Using the JavaScript SDK in Cloud Code

Using the JavaScript SDK in Cloud Code

The Backend Services JavaScript SDK that is available in hybrid and native apps can also be used in Cloud Code. Note that although usage is mostly the same, a few differences apply, including in how operations are invoked.

The article Sending Push Notifications represents a case study of leveraging the JavaScript SDK to send push notifications.

Initialization

The SDK is available through the Sdk field of the global Everlive object.

The SDK provides three ways for creating new instances:

  • new Everlive.Sdk(options) - the standard way for creating new instances. It is described here.

  • Everlive.Sdk.withMasterKey() - creates a new instance with Master Key authorization for the current app. This instance will give you unrestricted access to the API.

  • Everlive.Sdk.fromContext() - takes the authorization context from the current user. If the current request to the Cloud code is made by an authenticated user then the operations made by the SDK instance will be personalized with her identity. For example, if you create a new item with the SDK from the Cloud Code the item will have its Owner set to the Id of the current user making the request to the API.

Do not forget to add ".Sdk" to the Everlive global variable when using the SDK inside the cloud code.

The difference between the three ways of initialization stands in the mechanism used for authentication and authorization.

When you need to override some type level or item level permissions and operate over other content types without restrictions, initialize the Everlive instance with the new Everlive.Sdk.withMasterKey() constructor.

When you want to keep the context for the current user making the request to the API, create an instance with the fromContext() constructor. Such instance impersonates the current user and adheres to the permissions of the user's role. It may not be able to make CRUD operations over other content types as this depends of the role of the current user making the request. For example, if a content type is with Shared permissions, a user can delete only the items she "owns".

The standard Everlive.Sdk() instance can execute CRUD operations only over content types with Public permissions.

Basic Usage

The following code sample effectively replaces the result of a 'GET' request to a given type with the data of another type.

Everlive.Events.afterRead(function(request, response, context, done) {
    Everlive.Sdk.$.data('type-name').get(null, // filter
        function(error, data) {
            if (error){
          // When using content type cloud code you need to set the result like so:
                Everlive.Response.setErrorResult(error);
            } else {
          // When using content type cloud code you need to set the result like so:
                Everlive.Response.setObjectResult(data.result, 200, { Count: data.count });
            }
            done();
        });
});

The same code can also be invoked from a cloud function, where the syntax is almost the same:

Everlive.CloudFunction.onRequest(function(request, response, done) {
    Everlive.Sdk.$.data('type-name').get(null, // filter
        function(error, data) {
            if (error) {
                // When using cloud functions you need to set the result like so:
                response.body = error;
                response.statusCode = 500;
            } else {
                // When using cloud functions you need to set the result like so:
                response.body = data.result;
            }
            done();
        });
});

Querying

To initialize the Query object of the Everlive instance use the following syntax:

var query = new Everlive.Sdk.Query();
query.where().eq('name', 'Joe');

var data = Everlive.Sdk.$.data('type-name');
data.get(query, function (err, items) {
    if (err) {
        // handle the error result
        done();
    } else {
      // handle the success result
        done();
    }
});

Accessing Content Types

Very often you would like to update a content type with the information about a newly-created item in another content type. Here is a sample code that updates the "Library" and "Authors" content types when a "Book" item is created.

Everlive.Events.afterCreate(function (request, response, context, done) {
    var authorId = request.data.Book.AuthorId;
    var newBook = request.data.Book;

    var query = new Everlive.Sdk.Query();
    query.where('Id', authorId);

    var library = Everlive.Sdk.$.data('Library');

    library.create(newBook).then(
        function (data) {
            var createdBookId = data.result.Id;

            var authors = Everlive.Sdk.$.data('Authors');
            authors.rawUpdate({
                $addToSet: {
                    Books: createdBookId
                }
            }, authorId).then(function (data) {
                Everlive.Response.setObjectResult({
                    "Id": createdBookId
                }, 201);
                done();
            }, function (err) {
                Everlive.Response.setErrorResult("Failed ....", 100011, 400);
                done();
            });
        },
        function (err) {
            Everlive.Response.setErrorResult("Failed ....", 100006, 400);
            done();
        }
    );
});

Unsupported Features

The following features of the SDK are not supported inside Cloud Code:

  • Uploading and downloading of files.
  • The integration with Kendo UI.
  • Registration of devices for push notifications.

The cloud code execution is time restricted. A single event execution can last no longer than 5 seconds. If this happens, the request will fail and return a timeout error to the client. Too many timeouts for a limited time interval will result in disabling the cloud code execution for this content type automatically by the cloud infrastructure. Trying to call the cloud code for a type will return a "Custom cloud code is disabled for this type" error from the server.

Start a free trial Request a demo
Contact us: +1-888-365-2779
sales@telerik.com
Copyright © 2016-2017, Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.