Progress will discontinue Telerik Platform on May 10th, 2018. Learn more

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. Although usage is mostly the same, a few differences apply, including how operations are invoked.

Cloud Code embeds the Backend Services JavaScript SDK so you don't need to include the SDK before calling its APIs. The current embedded version is 1.6.9.

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

In this article:

Initialization

When used for writing Cloud Code, the Backend Services JavaScript SDK is available through the Sdk field of the global Everlive object.

There are three ways for creating new instances. The difference between them stands in the mechanism used for authentication.

  • new Everlive.Sdk(options)—the standard way for creating new instances. It is described in Getting Started with the Backend Services JavaScript SDK.
  • Everlive.Sdk.withMasterKey()—creates a new instance with Master Key authorization for the current app. Such an instance gives you unrestricted access to the Backend Services 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 all operations made with the SDK instance are personified accordingly, adhering to the user's permissions.

    For example, if you create a new item from Cloud Code, the item will have its Owner set to the Id of the current user making the request to the API.

Don't forget to add .Sdk to the Everlive global variable when using the SDK inside Cloud Code.

The standard Everlive.Sdk() instance is acting as an anonymous user and can execute CRUD operations only over content types with Public permissions for the respective operation.

Basic Usage

Most often, using Cloud Code means acting on the request, response, and context objects bound to every content type operation. Naturally, especially with Cloud Functions, you can write server-side logic that operates on external data or data passed as query parameters, and has nothing to do with Telerik Platform content types.

The following code, when placed in the Users content type's Cloud Code (Users.js), effectively replaces the result of a read request to Users with the all data from the Products content type.

Everlive.Events.afterRead(function(request, response, context, done) {
    Everlive.Sdk.$.data('Products').get(null, // filter
        function(error, data) {
            if (error){
          // When using Cloud Code for Data you need to set the result like so:
                Everlive.Response.setErrorResult(error, 40033, 400);
            } else {
          // When using Cloud Code for Data you need to set the result like so:
                Everlive.Response.setObjectResult(data.result, 200, null);
            }
            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('Products').get(null, // filter
        function(error, data) {
            if (error) {
                // When using Cloud Functions you need to set the result like so:
                response.error = error;
                response.statusCode = 400;
            } else {
                // When using Cloud Functions you need to set the result like so:
                response.body = data.result;
                response.statusCode = 200;
            }
            done();
        });
});

Querying

You query data from Cloud Code using the Backend Services JavaScript SDK. For details and examples, see Introduction to Querying.

The following example initializes the Query object of the Everlive instance and then declares a filter to look for users whose first name is Joe. Finally, it uses the data.get() method to read the filtered data.

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

Often, you may need to update a content type with 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
  • 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.

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