If you find any errors, typos or have general feedback, select the text and click CTRL+ALT+ENTER.

See the Server Code overview here.

Introduction

It’s a beneficial practice to place you code inside a try{...} catch (e) {...} block. If something goes wrong, you’ll see the exception. Structure of JavaScript exception:

Method Description
message Description of exception
code Code of exception

All Server Code methods except of Console can be used with Apperyio prefix as following:

This can help to avoid namespace conflicts.

Console

Console Used to print data for information or debugging purposes.

Method summary

The Console object has the following functions:

Method Description
log(data, data1, data2…) Writes specified data to trace. Accepts multiple numbers of arguments. If the first argument is a formatted string, the output will be formatted according to it.
data – any of the types: string, number, boolean, array, object.
dir(object) Displays object data into the trace.
assert(expression,message) Logs message only when expression is false.
time(label) Marks timer to log execution time.
timeEnd(label) Finishes timer, records output.
trace(label) Prints stack trace.

Examples

The following example determines whether the post_id parameter is in the request. If it is, it prints its value, or prints a message if it’s not. Also, execution time is calculated for this script via the time/timeEnd methods:

Collection

Collection Provides integration with the Appery.io database.

A token isn’t required if you added “token” in the request header.

Method summary

The Collection object has the following functions:

Method Description
getCollectionList(dbId) Returns a list of a collection info of a specific database.
createObject(dbId, collectionName, objectJSON[, token]) Creates an object in the specified collection.
retrieveObject(dbId, collectionName, objectId, include[, proj][, token]) Retrieves an object from the specified collection.
updateObject(dbId, collectionName, objectId, objectJSON[, token]) Updates object into the specified collection.
multiUpdateObject(dbId, collectionName, queryString, updateJSON, operationsJSON[, token]) Updates multiple objects by specified values.
deleteObject(dbId, collectionName, objectId[, token]) Deletes object from the specified collection.
multiDeleteObject(dbId, collectionName, criteria[, token]) Deletes multiple objects from the specified collection that matches specified criteria.
query(dbId, collectionName[, params][, token]) Queries a list of objects from a specified collection.
distinct(dbId, collectionName, columnName[, criteria][, token]) Queries a list of distinct values from a specified collection’s column.

See available error codes for Collection here.

getCollectionList

Returns a list of a collection name from a specified database:

getCollectionList(dbId)

Parameters

The function has the following input parameter(s):

  • dbId – string with database id.

Response

The function returns JSON objects with collections names:

Example

The following example shows how to get a collection list and save it to the response:


createObject

Creates an object in the specified collection.

createObject(dbId, collectionName, objectJSON[, token])

Parameters

The function has the following parameter(s):

  • dbId – string with database id.
  • collectionName – string with name of collection.
  • objectJSON – JSON object.
  • token – string with user token or database master key.

Response

JSON object which contains the id of the object created and the time the object was created:

Examples

The following examples show how to create an object in a chosen collection. Note that it is not necessary to define all of the object fields; it’s enough to specify at least one. This will create a new object: {"taskName":"Get some coffee","priority":"High"}:

This will create a new object with an empty priority field: {"taskName":"Get some coffee","priority":""}:

This won’t work because at least one column must be specified:


retrieveObject

Retrieves an object from the specified collection.

retrieveObject(dbId, collectionName, objectId, include[, proj][, token])

Parameters

The function has the following parameter(s):

  • dbId – string with database id.
  • token – string with user token or database master key.
  • collectionName – string with name of collection.
  • objectId – unique identifier of the object that should be retrieved.
  • include – parameter indicated should or shouldn’t include referenced object.
  • proj – JSON projection object that was built in accordance with the documentation of mongo quering.

Response

The function returns JSON object representing information about the retrieved object:

Examples

The following examples show how to retrieve a specific object and use an include parameter.

There are three fields in a current collection: taskName (string), priority (string) and owner (pointer).

The following code will retrieve all of the object fields with ID 5278ef59e4b01085e4b79480 but without associated objects:

The following code will retrieve all of the object fields and associated objects defined in the column owner:

You can also provide a token:


updateObject

Updates an object with new values.

updateObject(dbId, collectionName, objectId, objectJSON[, token])

Parameters

The function has the following parameters:

  • dbId – string with database id.
  • token – string with user token or database master key.
  • collectionName – string with name of collection.
  • objectId – unique identifier of object that should be retrieved.
  • objectJSON – JSON object.

Response

The function returns the time stamp when the object was modified:

Examples

The following examples show ways to update an object. Note that it is not necessary to define all of the object fields; it’s enough to specify at least one. A field (column) that is not included will not be updated.

Predefined collections cannot be updated in this way. Use the following approach.

The following code will update two fields (taskName and priority) of the object 5278ef59e4b01085e4b79480:

It is not necessary to specify all of the object fields. This will update only the taskName field:

The following code will update only the priority field. You can also provide a token:


multiUpdateObject

Updates multiple objects by specified values.

multiUpdateObject(dbId, collectionName, queryString, updateJSON, operationsJSON[, token])

Parameters

The function has the following parameters:

  • dbId – string with database id.
  • token – string with user token or database master key.
  • collectionName – string with name of collection.
  • queryString – JSON query object that was built in accordance with the documentation of mongo quering.
  • updateJSON – JSON object with fields of object that should be updated.
  • operationsJSON – JSON update object with native MongoDB operations and fields of object that should be updated. The object was built in accordance with the documentation of mongo set operations. If <operations> object specified than update <updateJSON> param fully ignored. Their functionality cannot be used simultaneously. The following operations are supported:
    • $set
    • $unset
    • $inc (Number type only)
    • $mul (Number type only)
    • $min (Number and Date type only)
    • $max (Number and Date type only)

Predefined collections cannot be updated in this way. Use the following approach.

Examples

This example finds all objects with productName equal to iPhone and updates the productLabel in these objects to iPhone 7.  If the search finds seven objects, then all seven objects will be updated with the new label.

This example performs the same update as above but using the native MongoDB operations (operationsJSON):


deleteObject

Deletes an object from the specified collection.

deleteObject(dbId, collectionName, objectId[, token])

Parameters

The function has the following parameters:

  • dbId – string with database id.
  • token – string with user token or database master key.
  • collectionName – string with name of collection.
  • objectId – unique identifier of object that should be deleted.

Response

This function returns no data.

Examples

The following example shows how to delete an object from the specified collection:


multiDeleteObject

Deletes multiple objects from the specified collection that matches specified criteria

multiDeleteObject(dbId, collectionName, criteria[, token])

Parameters

  • dbId – string with database id.
  • token – string with user token or database master key.
  • collectionName – string with name of collection.
  • criteria – JSON query object that was built in accordance with the Mongo querying documentation.

query (search)

Queries a list of objects from a specified collection.

query(dbId, collectionName[, params][, token])

Parameters

The function has the following parameters:

  • dbId – string with database id.
  • token – string with user token or database master key.
  • collectionName – string with name of collection.
  • params – JSON object that contains request parameters:
    • criteria – JSON – queries the object that was built in accordance with the mongo querying documentation.
    • skip – integer – parameter indicating how many objects should be skipped before including objects into the response.
    • limit – integer – parameter indicating how many objects should be included in response.
    • count – boolean – parameter indicating whether to include or not include the number of selected objects in the response;
    • sort – string – list of fields names split by commas that indicate order of objects in response.
    • include – string – parameter indicating whether the referenced object should or shouldn’t be included.
    • proj – JSON projection object that was built in accordance with the documentation of mongo quering.Here is an example of JSON structure:

Response

A JSON object with a list of objects contained in the collection according to the request:

Examples

The first example shows how to search column name studentName for Sarah:

Here is a more advanced example. In the beginning, the user is logged into the database. Then, two queries with different parameters are performed:

You can find a full description of query possibilities here.


distinct

Queries a list of distinct values from a specified collection’s column.

distinct(dbId, collectionName, columnName[, criteria][, token])

Parameters

This function has the following parameters:

  • dbId – string with database id.
  • token – string with user token or database master key.
  • collectionName – string with name of collection.
  • columnName – string with name of collection column where distinct values need to be retrieved.
  • criteria – JSON query object that was built in accordance with the Mongo querying documentation.

Response

A JSON object with a list of distinct values contained in the collection’s column according to the request:

Examples

The first example will retrieve all distinct values from cityName column:

distinct returns only data from the specified column. In other words, other collection data (columns) are not returned.

This example will retrieve distinct values from column named count but only for values greater than 10:

More examples

This section provides more examples connecting to the database from Server Code script.

Video example

This short video shows how to return all the records from a collection (query API is used): How to Integrate with the Database from Server Code Script

Basic functions example

The following example uses a basic function of the Collection API:

The user is logged in and the received token is stored to the result object. The next step is to call the getCollectionList method, and save its response (which is a list of all collections) to the result object as well. Then, via the createObject method, a new object is created and its ID is stored to the ID variable and to the result object. Using a retrieveObject method and the just-gotten ID, this object is saved to the result object. Then the newly created object is updated with the new data. The updated object is saved to the result object. In the end, the updated object is deleted via the deleteObject method:

Sample data that can be used as a request for the following example:

Parameter Value
DB_id: 526fdbd8e4b07c3286b537f1
userName: Dan
userPass: another_password
priority: Middle
taskName: Play the music
collection: todo

Database user

DatabaseUser Provides integration with the Users collection from Appery.io database (sign up, log in, log out, update, retrieve and delete users).

Token is not required if the user added “token” to the request header (click “obtain token” on the server code Test tab).

Method summary

Method Description
login(dbId, userName, password[, masterKey]) Logs in to the database and gets a session token for next actions.
logout(dbId, token) Logs out from the database and destroys current session token.
signUp(dbId, userJSON) Signs up user to the database.
update(dbId, objectId, userJSON[,token]) Updates info about the user in the database.
retrieve(dbId, objectId, include[,token]) Retrieves info about the user in the database.
remove(dbId, objectId[, token]) Deletes the user from the database.
query(dbId, params[, token]) Queries users from the database.

See available error codes for DatabaseUser here.

login

Logs in to the database and gets a session token for next actions.

login(dbId, userName, password[, masterKey])

Parameters

  • dbId – string with database id.
  • userName – string with user name.
  • password – string with user password.
  • masterKey – string with database master key, if specified than the password value is ignored.

Response

JSON object with session token:


logout

Logs out from the database and destroys current session token.

logout(dbId, token)

Parameters

  • dbId – string with database id.
  • token – string with user token.

signUp

Signs up user to the database.

signUp(dbId, userJSON)

Parameters

  • dbId – string with database id.
  • userJSON – user JSON object:

Response


update

Updates info about the user in the database.

update(dbId, objectId, userJSON[,token])

Parameters

  • dbId – string with database ID.
  • token – string with user token.
  • objectId – unique identifier of the user that should be updated.
  • userJSON – user JSON object

Response


retrieve

Retrieves info about the user in the database.

retrieve(dbId, objectId, include[,token])

Parameters

  • dbId – string with database id.
  • token – string with user token.
  • objectId – unique identifier of the user that should be updated.
  • include – parameter that indicates whether the referenced object should be included.

Response


remove

Deletes the user from the database.

remove(dbId, objectId[, token])

Parameters

  • dbId – string with database id.
  • token – string with user token.
  • objectId – unique identifier of the user that should be updated.

query

Queries users from the database.

query(dbId, params[, token])

Parameters

  • dbId – string with database id.
  • token – string with user token.
  • params – JSON object that contains request parameters:
    criteria – JSON – query object built in accordance with the mongo querying;
    skip – integer – parameter indicating how much objects should be skipped before including objects into response;
    limit – integer – parameter indicating how many objects should be included in response;
    count – boolean – parameter indicating whether the number of selected objects should be included in response;
    sort – string – list of fields names split by comma that indicates the order of objects in response;
    include – string – parameter that indicates whether the referenced object should be included.

Response

JSON object with a list of users

Examples

This section provides a number of examples using Database User API.

User registration form

This example shows how to use Server Code script and Pointer data type to setup user registration – Learn How to Create a User Registration Form with the Appery.io Database and Server Code

User login

This example signs up a user/makes the user log in. Then it retrieves information about the user, and updates user data. Finally, the user is removed from database:

Push Notifications

PN Used to send Push Notifications messages

If you are new to push notifications, we strongly recommend you read this page.

Method summary

Method Description
send(pushAPIKey, messageData) Sends push notifications.
listScheduled(pushAPIKey) Returns the list of scheduled push notifications that haven’t already been sent.
deleteScheduled(Push_id) Deletes scheduled push that hasn’t been already sent. In other case it returns an error.

See available error codes for PN here.

send

Sends push notification.

send(pushAPIKey, messageData)

Parameters

  • pushAPIKey – string with unique key, issued by server.
  • messageData – notification message data object. All the available fields are described in Push Notification REST API doc.

listScheduled

Returns the list of scheduled push notifications that haven’t already been sent.

listScheduled(pushAPIKey)

Parameters

  • pushAPIKey – string with unique key, issued by server.

deleteScheduled

Deletes scheduled push that hasn’t been already sent. In other case it returns an error.

deleteScheduled(Push_id)

Parameters

  • Push_id — unique identifier of the Push Notification.

Examples

This section contains a number of examples sending Push Notifications.

Sending a Push Notification

The following example sends push notifications to all devices:

Send push notification using channels

The following example sends push notifications to the devices by using channels. Also, badge (iOS parameter only) is specified.

Request

Request Holds request (input) information for the script.

Method summary

Method Description
keys() Lists provided URL parameter names.
get(name) Gets URL parameter with specified name.name – string.
has(name) Signals whether URL parameter with specified name exists in request.name – string.
body() Returns request body or null for GET requests.
mimeType() Returns body mimetype or null for GET requests.

Properties summary:

Property Description Form
headers JSON object – provides header values
params JSON object – provides URL parameters.
user JSON object – provides information about the logged user.
method String – name of request method (GET or POST).

Examples

Retrieve request parameters and body

The following example retrieves request parameters and body. For example, the request contains two parameters: Db_id = 51bf5ec1975a2d55263801cd and collection = todo. Also, the request body contains a string: some useful information.

Response

Response Used as a response (answer) for the request.

Method summary

Method Description
success() Returns successful response without body.
success(body) Returns successful response with specified body.
success(body, mimetype) Returns successful response with specified body and MIME type.
binary(body) Returns successful response with binary data in body and MIME type “application/octet-stream.”
binary(body, mimetype) Returns successful response with binary data in body and specified MIME type.
redirect(url) Returns redirect response with specified location URL.
error(body) Returns error response with specified body and error code (response status).
setHeader(name, value) Sets specified header value.

See available error codes for Response here.

success

Returns successful response without body.

success()


success(body)

Returns successful response with specified body.

success(body)

Parameters

  • body – string, number, boolean, array, object.

success(body, mimetype)

Returns successful response with specified body and MIME type.

success(body, mimetype)

Parameters

  • body – string, number, boolean, array, object.

binary(body)

Returns successful response with binary data in body and MIME type application/octet-stream.

binary(body)

Parameters

  • body – array of bytes (represented by integer numbers in range 0-255).

binary(body, mimetype)

Returns successful response with binary data in body and specified MIME type.

binary(body, mimetype)

Parameters

  • body – array of bytes (represented by integer numbers in range 0-255);
  • mimetype – any binary MIME type, e. g:
    • application/zip
    • application/pdf
    • image/jpeg

redirect

Returns redirect response with specified location URL.

redirect(url)

Parameters

  • url – string with absolute URL.

error

Returns error response with specified body and error code (response status).

error(body)

Parameters

  • body – object;
  • code – error code (string or number).

Examples

This section has a number of examples.

Simple response usage

The following example retrieves the request parameters such as DB_id, collection and object ID. Then the retrieveObject procedure is performed, and if it’s successful, the retrieved object is saved to the response. Otherwise, the error message will be saved to the response.

Using the binary and redirect methods

The following example shows how to use binary, redirect and error methods. In the beginning, some kind of a secureCode is saved to the variable. Then the code check procedure is performed. The validateCode is a function that can performs the check. If the secureCode variable that was retrieved as a request parameter is true, then the binary data is sent to the response. If this step causes any errors, then the redirect function (it is in a catch (e) block) performs. If the secureCode isn’t valid, an error message is sent to the user.

Including specific columns in the response

The following example shows how to return certain columns. This can be handy when services fields (such as _createdAt, _updatedAt) or any other fields aren’t needed in the response. There are several ways to do this.

Take a look at the example:

In the example above, the raw retrieved object doesn’t pass to response.success. Instead, a new object is created and it contains only the specific fields. The results of this example look like:

The same can be performed via the underscore.pick method:

The Underscore library must be included on the Dependencies tab.

Another way to pass only the specific columns to the result is to delete any unneeded columns via the delete command:

Script call

ScriptCall Used to call other scripts.

Method summary

Method Description
call(guid, params, body, bodyMimeType) Runs script.

See available error codes for ScriptCall here.

call

Runs script.

call(guid, params, body, bodyMimeType)

Parameters

  • guid – script GUID;
  • params – JSON object (map of params);
  • body – body text to pass into script;
  • bodyMimeType – body type.

Response

JSON objects with collections’ names:

Examples

Simple script call

The following example shows how to call one script from another. The called script should look like:

  • NameShowAlertScript
  • Aliasalert_script
  • GUID (generated automatically) – e1e530d1-3f67-478e-9a5a-5b8b819d819b
  • Script body – response.success('Hi, Dude!');

Also, this script saves a message to the success.

Caller script code:

XMLHttpRequest

XHR2 Used to send HTTP requests to web server and retrieve any type of data directly back into the script.

 

As new version of XHR was added to Appery.io, simultaneously two methods are available for now:

XHR2 A new version of XHR implementation. Supports additional HTTP methods such as HEAD, OPTIONS and TRACE. Works faster than old XHR implementation. Recommended to use.
XHR And old version of XHR implementation. In case of any problems with XHR2 you can switch back to XHR.

Method summary

Method Description
send(method, url, options) Makes synchronous HTTP requests.

send

Makes synchronous HTTP requests.

send(method, url, options)

Parameters

  • method – string with method name. Supported methods for XHR2 and XHR:
    XHR2 XHR
    • DELETE
    • GET
    • POST
    • PUT
    • HEAD
    • OPTIONS
    • TRACE
    • DELETE
    • GET
    • POST
    • PUT
  • url – string with resource url.
  • options – JSON object with additional request parameters. Structure of options:
    • parameters – JSON object with query request parameters. They will be added to URL.
    • headers – JSON object with request headers. You can find more information here.
    • body – string or JSON object with request body. It can be byte array if isRawRequest is set to true.
    • isRawRequest – if request body is binary data (optional). Default value – false.
    • isRawResponse – if response body is binary data (optional). Default value – false.

Response

JSON object with response information:

  • status – 3-digit integer result code of the attempt to understand and satisfy the request. You can find more information here.
  • headers – JSON object with response headers.
  • body – string with response body. It can be JSON object if value of header Content-Type is application/json and response body is a valid JSON object. It can be byte array if isRawResponse is set to true.

Examples

This section provides a number of examples using the XHR object.

Using the Google Geocoding via XHR:

The following example sends the XML HTTP request to the Google Geocoding services via the XHR request. XHRResponse.status will contain the status of the request. In the case of success, it will be to 200. XHRResponse.body will contain a string with all results (in this case, in JSON format):

You can find more about the Google Geocoding API here.

Let’s go a little deeper, and find out how to parse the response if you want to get a specific value. Let’s say you want to get all of the latitude/longitude values of every “location.” As the Geocoding responses are very sensitive to incoming data, there may be several “location” nodes. In this case, we need a “for” loop to run over them and store needed values. Before looking over the data, we need to convert the response to the JSON object. That’s where the JSON.parse method comes in handy; it turns the response string to the JSON object, which can then be easily parsed. Lets look at the code:

In the response, you’ll get an array with objects. Every one of them will contain “lng” and “lat” parameters, as in the following:

Send POST request via XHR

The following example sends the XML HTTP POST request with request parameters, headers and body. Following example uses RequestBin for informational purposes. To create your own RequestBin go to http://requestb.in/, click “Create a RequestBin” and copy Bin URL.

More examples using 3rd party APIs

This section has more examples using various 3rd party APIs.

Accessing predefined collections

Via the the XHR request, you can access one of the predefined collections such as Users, Devices, or Files. It’s useful when you need to store additional data in these collections. For example, the collection Users contains the additional field of email, which you want to access from the server code.

Since the predefined collections don’t have read-and-write permissions, you can use a “Master Key,” or you can turn on the “Read” permission for the collections. For security reasons, the latter is not recommended.

This code returns all data of the object with ID 529c99bfe4b06de3a99fb2f1:

There shouldn’t be any spaces in the where parameter.

You can parse this response and do some processing with the user’s email.

Access to predefined collections (Users, Devices, Files) is currently done using the XMLHttpRequest object. We are working on adding a special script API to access Users and other collections.

In Memory Data

IMD Allows to store any data in fast memory for 20 minutes. It works like a very fast cache.

Method summary

Method Description
put(key, value) Associates the specified value with the specified key in the cache.
get(key) Returns the value to which the specified key is mapped, or null if the cache contains no mapping for the key.
remove(key) Removes the mapping for a key from the cache if it is present.
contains(key) Returns true if the cache contains a mapping for the specified key.
length() Returns the number of key-value mappings in the cache.
keys() Returns an array of the keys contained in the cache.

See available error codes for IMD here.

put

Associates the specified value with the specified key in the cache. If the cache previously contained a mapping for the key, the old value will be replaced by the specified value.

put(key, value)

Parameters

  • key – key with which the specified value should be associated.
  • value – value that should associated with the specified key.

get

Returns the value to which the specified key is mapped, or null if the cache contains no mapping for the key.

get(key)

Parameters

  • key – the key whose associated value should be returned.

Response

value – the value to which the specified key is mapped, or null if this map contains no mapping for the key.


remove

Removes the mapping for a key from the cache if it is present.

remove(key)

Parameters

  • key – key whose mapping is should be removed from the cache.

contains

Returns true if the cache contains a mapping for the specified key.

contains(key)

Parameters

  • key – key whose presence in the cache is should be tested.

Response

true if the cache contains a mapping for the specified key.


length

Returns the number of key-value mappings in the cache.

length()

Response

The number of key-value mappings in this map.


keys

Returns an array of the keys contained in the cache.

keys()

Response

An array of the keys contained in the cache.

Examples

Simple usage of IMD:

The following example shows how store and retrieve data by using the IMD API: