Index

Quick Overview

Important Changes

  • Built.io Backend has deprecated the use of GroupMultiple. For a detailed explaination please read this blog.

Intro

This document covers the details of JavaScript based SDK provided by Built.io Backend. The SDK is available both for Browser and Node.js environments.

Node.js

To use this SDK on Node.js follow the below given steps.

  • Download the buit.io SDK from npm repository.

    npm install built.io
  • Require the SDK module in your application.

    var Built = require('built.io'); 

Browser

To use this SDK on browser follow the below given steps.

  • Download the SDK package from here.

  • Extract the zip package to get the built_rt.min.js file and include it in a script tag as shown below.

    <script type="text/javascript" src="built_rt.min.js"></script>
  • After the file is included a Built object would be avaliable globally for use as shown below.

    var app = Built.App('blt5d4sample2633b');

Basic structure

The structure followed by SDK logically resembles the application structure on Built.io Backend. Once you're done with the basic setup explained in Installation section, you have a Built object with you, which you can then use to initialize different modules.

Initialization process for each module is explained briefly below.

  • Application

    To initialize an app, use the App constructor on the Built object and supply it the application's api key.

    var app = Built.App('blt5d4sample2633b');
  • Class

    An application can have multiple classes. Similarly, an application instance has a class constructor which accepts the uid of the class whose instance is to be created.

    var ProjectClass = app.Class('project');               
  • Object

    Object is an instance of a Class. SDK follows this by providing a 'Object' constructor on the class instance. The object constructor accepts an existing object's uid or data to initialize a new object.

    var Project = ProjectClass.Object;
    var project  = Project({
       name : 'Super Project #41!'
    });
  • Query

    Query is used to retrieve objects of class based on some condition. SDK provides a Query constructor on the class instance which when executed would retrieve objects of that class.

    var query = ProjectClass.Query();
  • Upload

    The Upload constructor can be accessed on the App instance.

    var upload = app.Upload();

Cache Policies

SDK supports caching and uses browsers 'localStorage' to maintain it. A set of cache policies are avaliable for use which are listed below.

  • ONLY_NETWORK (Default)

    This is the default cache policy which will always get the data from an network call.

  • CACHE_ELSE_NETWORK

    This policy will try to first get the data from cache, on failure would make a network call.

  • NETWORK_ELSE_CACHE

    It will try to make a network call, on failure would fetch it from cache.

  • CACHE_THEN_NETWORK

    This policy would first get the data from cache as well would make a network call to get the updated copy.

    Cache policy can be set for the entire application as follows, which means all queries built using this application instance would follow the cache policy.

      var app = Built.App('api_key').setCachePolicy(Built.CachePolicy.CACHE_ELSE_NETWORK);

    Cache policy can also be set on individual queries as follows.

      var query = Built.App('api_key').Class('project').Query();
      query = query.setCachePolicy(Built.CachePolicy.CACHE_ELSE_NETWORK);

Transforms

Transforms allows you to get the objects returned from a query in format other than the default. For example, you can choose to get a Backbone.js collection instead of an array of objects.

The transforms avaliable are listed below.

  • toJSON()

    This transform would return the query result as an array of plain javascript objects

    var query = Built.App('api_key').Class('project').Query();
    query
    .where('name','Super Project #41!')
    .toJSON()
    .exec()
    .then(function(objects){
       console.log(objects); // array of plain javascript objects
    });
  • toBackbone()

    This transform would return the query result as a Backbone.js collection

    var query = Built.App('api_key').Class('project').Query();
    query
    .where('name','Super Project #41!')
    .toBackbone()
    .exec()
    .then(function(collection){
       console.log(collection); // Backbone.js collection
    });

Immutability

The SDK follows the concept of immutability. This means any operation that intends to modify the state of an object results into the creation of a new object with the intended modification. The state of the existing object is maintained.

The advantages of immutability are explained below.

1] Suppose you want to upload 3 files on Built.io Backend and all of them share the same ACL. The code for this is simplified because of immutability.

  • Create an ACL object with the intended permission.

    var acl = Built.ACL();
    // Returns a new ACL object with read permission
    acl  = acl.setPublicReadAccess(true); 
  • Create an upload object and apply ACL to it.

    // Returns a new upload object with public read access.
    var upload = Built.App('api_key').Upload() 
                 .setACL(acl);   
  • We can now create multiple uploads using the existing upload object.

    var upload1 = upload.setFile('/home/Super Project #41!/Pictures/tiger.gif');
    
    var upload2 = upload.setFile('/home/Super Project #41!/Pictures/duck.gif');
    
    var upload3 = upload.setFile('/home/Super Project #41!/Pictures/dolphin.gif');

2] Suppose you want create two app instances which are exactly similar to each other but belong to different tenants. The code for this is simplified because of immutability.

var app = Built.App('api_key')
            .setCachePolicy(Built.CachePolicy.CACHE_ELSE_NETWORK);

var app1 = app.setTenant('Super Project #41!'); 

var app2 = app.setTenant('xyz');

Group

A group, is a collection of fields. You can have several fields under one particular group field. An example of a group would be an 'Address' field, which may further have several other fields, such as Street name, City, Zip Code, and so on.

  • Built.Group

    Built.Group is a module in SDK specially developed to represent a group field. Instance created using this module can be pass to methods which perform operations on group fields.

    Consider you have a group field 'team_lead' in our 'Project' class. We can represent this group using Built.Group module as follows

    var tlGrp = Built.Group('team_lead',{
       name: 'John',
       age: 32
    })
    
    var project = Built.App('api_key').Class('project').Object({
      name: 'Super Project #41'
    })
    
    project.addGroup(tlGrp)
    
    project
    .save()
    .then(function(project){
       console.log(project.toJSON())
    })
    • Built.GroupMultiple

    Built.GroupMultiple is used to represent a group field marked multiple.

    var tls = Built.GroupMultiple('team_leads',[{
       name: 'John',
       age: 32
    },{
       name: 'Jack',
       age: 42
    }]) 
    
    var project = Built.App('api_key').Class('project').Object({
       name: 'Super Project #41'
    })
    
    project.addGroup(tls)
    
    project
    .save()
    .then(function(project){
       console.log(project.toJSON())
    })

Promises

SDK uses promises for handling all of its async operations. Few examples are shown below.

  • Saving an object

    To save an object on Built.io Backend is an async task, therefore the save() method returns a promise which resolves with saved object.

    // Project is object constructor
    Project({             
       name : 'Super Project #41!'
    })
    .save()
    .then(function(object){
       // object returned from Built.io Backend
    });
  • Executing a query

    Executing a query on Built.io Backend is also an async task, therefore exec() method returns a promise which resolves with all the objects which fulfils the query condition.

    ProjectClass
    .Query()
    .where('name','Super Project #41!')
    .exec()
    .then(function(objects){
       // All projects having name as 'Super Project #41!'
    }); 

Realtime Functionality

Several applications such as chat, sock updates, alarm system, etc. require data to be fetched and pushed to and forth from the server in a matter of seconds. To support these requirements, Built.io Backend provides realtime functionality. In this, a socket connection is established between the client and the server, which enhances the speed of communication between the two.

  • Usage

    To establish a socket connection with Built.io Backend you need use enableRealtime() as shown below

     var app = Built.App('blt5d4sample2633b').enableRealtime();
  • API

    Built.io Backend uses events to notify the users when a particular action is performed. To listen to these events, we must first setup event listeners.

    The SDK provides several handy functions that help you manege the realtime functionality better. These functions are explained below in detail.

  • on

    This function is available on constructors as well as instances. It takes two arguments: the event on which we would like to listen to, and the listener to be invoked when the event is triggered. Below is a example where we setup a listener on Object constructor and its instance. Setting up a listener on instance requires read permission on it. (Refer actual documentation for more detailed explaination)

    //'blt5d4sample2633b' is a dummy Application API key
    // app.Class('class_name').Object returns a Object constructor
    // 'project' is a uid of a class on Built.io Backend
    // 'blt211sample241c' is uid of an object on Built.io Backend
    
    var app = Built.App('blt5d4sample2633b').enableRealtime();
    
    var Project = app.Class('project').Object; 
    
    var project = Project('blt211sample241c'); 
    
    Project.on('update',updateCB);
    
    project.on('update',updateCB);   
    
    function updateCB(project){
       console.log(project.toJSON()); 
    }
  • off

    As the name suggests, this method is used to stop a user from listening to event notifications. Similar to on( ) function, it takes two arguements, both of which are optional.

    1. A specific listener could be turned off as shown below.

       //'blt5d4sample2633b' is a dummy Application API key
       // app.Class('class_name').Object returns a Object constructor
       // 'project' is a uid of a class on Built.io Backend
       var app = Built.App('blt5d4sample2633b').enableRealtime();
      
       var Project = app.Class('project').Object; 
      
       Project.on('update', updateCB);
      
       Project.on('create', updateCB);
      
       //turns off listener for update only
       Project.off('update',updateCB); 
      
       function updateCB(project){
          console.log(project.toJSON()); 
       }
    2. All listeners attached to a resource could be removed as shown below.

       //'blt5d4sample2633b' is a dummy Application API key
       // app.Class('class_name').Object returns a Object constructor
       // 'project' is a uid of a class on Built.io Backend
       var app = Built.App('blt5d4sample2633b').enableRealtime();
      
       var Project = app.Class('project').Object; // Object constructor
      
       Project.on('update', updateCB);
      
       Project.on('create', updateCB);
      
       Project.off(); //turns off all listener attached on Project
      
       function updateCB(project){
          console.log(project.toJSON()); 
       }
    3. All listeners attached to a given event on a resource coule be removed as shown below.

       //'blt5d4sample2633b' is a dummy Application API key
       // app.Class('class_name').Object returns a Object constructor
       // 'project' is a uid of a class on Built.io Backend
       var app = Built.App('blt5d4sample2633b').enableRealtime();
      
       var Project = app.Class('project').Object;
      
       Project.on('update', printJSON);
      
       Project.on('update', printObject);
      
       Project.on('create', printJSON);
      
       //turns off all listener attached on Project for update event.
       Project.off('update');       
      
       function printJSON(project){
          console.log(project.toJSON()); // updated object
       }
      
       function printObject(project){
          console.log(project); // updated object
       }
  • broadcast

    Built.io Backend allows you to broadcast message that could be listened by others by setting up listeners for it. Broadcast method should be used to broadcast message and is available on constructors as well as instance. Update permission is required on the resource to be able to broadbast a message. The example given below demonstrates the syntax.

  //'blt5d4sample2633b' is a dummy Application API key
  // app.Class('class_name').Object returns a Object constructor
  // 'project' is a uid of a class on Built.io Backend
  var app = Built.App('blt5d4sample2633b').enableRealtime();

  var Project = app.Class('project').Object; 

  Project.broadcast('Hello Built.io Backend');

  //Subscriber

  var app = Built.App('blt5d4sample2633b').enableRealtime();

  var Project = app.Class('project').Object; // Object constructor

  Project.on('broadcast',function(message){
     console.log(message);
  });
  • Presence

    This feature helps you determine if a certain application user is currently online or offline. It stores the "last seen" timestamp of the user, which is especially useful for chat applications. Additionally, it allows you to store a "state" associated with your profile (you could use it to store chat statuses, for example).

    Here is a list of some handy functions that will help you the presence feature better.

    • getPresence

      1] To get the logged-in user's presence details, the SDK provides getPresence() on User constructor, which returns a promise that eventually resolves with instance of presence module. (Refer to the actual documentation for details about presence module).

      //'blt5d4sample2633b' is a dummy Application API key
      // Assuming user has already logged-in
      var app = Built.App('blt5d4sample2633b').enableRealtime();
      var User = app.User;
      User
      .getPresence() 
      .then(function(presence){
         console.log(presence.toJSON());
         // modifying the user's presence to be accesible publicly.
         presence
         .setPublic(true)
         .save()
         .then(function(presence){
            console.log(presence);
         });
      });

      2] To get the presence details of some other application user, the SDK provides getPresence method on user instance.

      The below given example demonstrates the syntax.

      / You would be able access the presence details of a user only if the user has allowed his/her presence details to be publicly visible or has shared it with you, by adding you in the whitelist. /

      //'blt5d4sample2633b' is a dummy Application API key
      // 'blt211sample241c' is uid of an object on Built.io Backend
      var app = Built.App('blt5d4sample2633b').enableRealtime();
      var user = app.User('blt211sample241c');
      user
      .getPresence(true)
      .then(function(presence){
         console.log(presence.toJSON());
      });
  • requestPresenceAccess

    In some chat applications, you may want to put a functionality that allows you to access other users' presece details by requesting access. We provide a similar functionality with requestPresence function. You can request a certain user to access his presence.

    Example below demonstrates the syntax.

    //'blt5d4sample2633b' is a dummy Application API key
    // 'blt211sample241c' is uid of an object on Built.io Backend
    var app = Built.App('blt5d4sample2633b').enableRealtime();
    var user = app.User('blt211sample241c');
    user
    .requestPresenceAccess()
    .then(function(){
       // done
    });