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:
1 |
Apperyio.request.get() |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
console.time('Elapsed time'); //start to calculate the execution time if (request.has("post_id")) { // prints out "Post: 202" if the request looks like this - // https://api.appery.io/rest/1/code/<scriptGUID>/exec?post_id=202 console.log("Post: " + request.get("post_id")); } else { // prints out "No post specified" if the request looks like this - // https://api.appery.io/rest/1/code/<scriptGUID>/exec console.log("No post specified"); } console.timeEnd('Elapsed time'); //stop the calculate. Prints out: "Elapsed time: 1ms" (Or other ms value) |
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:
1 |
[{"name": "collection_name1" }, {"name": "collectoin_name2"} ] |
Example
The following example shows how to get a collection list and save it to the response:
1 2 |
var collections = Collection.getCollectionList("526fdbd8e4b07c3286b537f1"); response.success(collections); |
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:
1 2 3 4 |
{ "_id": <object_id>, "_createdAt":<datetime> } |
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"}
:
1 2 |
var result = Collection.createObject("526fdbd8e4b07c3286b537f1", "todo", {"taskName":"Get some coffee","priority":"High"}); console.log(result); |
This will create a new object with an empty priority
field: {"taskName":"Get some coffee","priority":""}
:
1 |
Collection.createObject("526fdbd8e4b07c3286b537f1", "todo", {"taskName":"Get some coffee"})._id; |
This won’t work because at least one column must be specified:
1 |
Collection.createObject("526fdbd8e4b07c3286b537f1", "todo", {})._id; |
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:
1 2 3 4 5 6 |
{ "_id":<object_id>, "column1":"value1","column2":"value2", "_createdAt":{"$date":<create_date>}, "_updatedAt":{"$date":<update>} } |
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:
1 2 |
var result = {}; result = Collection.retrieveObject(DB_id, collectionName, "5278ef59e4b01085e4b79480"); |
The following code will retrieve all of the object fields and associated objects defined in the column owner
:
1 |
result = Collection.retrieveObject(DB_id, collectionName, "5278ef59e4b01085e4b79480", "owner"); |
You can also provide a token:
1 |
result = Collection.retrieveObject(DB_id, collectionName, "5278ef59e4b01085e4b79480", "owner", 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:
1 2 3 |
{ "_updatedAt":{"$date":<update>} } |
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
:
1 2 |
var result = {}; result = Collection.updateObject(dbId, collectionName, "5278ef59e4b01085e4b79480", {"taskName":"Build a second app", "priority":"Middle"}); |
It is not necessary to specify all of the object fields. This will update only the taskName
field:
1 |
result.obj = Collection.updateObject(dbId, collectionName, "5278ef59e4b01085e4b79480", {"taskName":"Build a second app"}); |
The following code will update only the priority
field. You can also provide a token:
1 |
result.obj = Collection.updateObject(dbId, collectionName, "5278ef59e4b01085e4b79480", {"priority":"Middle"}, 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.
1 |
var result = Collection.multiUpdateObject(dbId, collectionName, '{productName: "iPhone"}', {"productLabel":"iPhone 7"}); |
This example performs the same update as above but using the native MongoDB operations (operationsJSON
):
1 |
var result = Collection.multiUpdateObject(dbId, collectionName, '{productName:"iPhone"}', null, {"$set":{"productLabel":"iPhone 7"}}); |
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:
1 |
Collection.deleteObject("526fdbd8e4b07c3286b537f1", "todo", "5278ef59e4b01085e4b79480"); |
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:
123456789{["criteria":<criteria>,]["skip":<skip>, ]["limit":<limit>, ]["count":<count>, ]["sort":<sort>, ]["include":<include> ]["proj":<proj> ]}
Response
A JSON object with a list of objects contained in the collection according to the request:
1 2 3 4 5 6 |
[{ "_id":<object_id>, <colName>:<value>, "_createdAt":{"$date":<create_date>}, "_updatedAt":{"$date":<update>} }, ... ] |
Examples
The first example shows how to search column name studentName
for Sarah
:
1 2 3 4 5 6 7 8 |
var params = {}; params.criteria = { "studentName": { "$eq": "Sarah" } }; var result = Collection.query(dbId, "studentName", params); |
Here is a more advanced example. In the beginning, the user is logged into the database. Then, two queries with different parameters are performed:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
//Specify the suppression of the field.var DB_id = request.get("DB_id"); //Get the "DB_id" parameter from the request and store it params.proj = {'colNumber' : 0}; var userName = request.get("userName"); //Store the user name var userPass = request.get("userPass"); //and its password var collectionName = request.get("collection"); //Collection name that will be used try { result = {}; var token = DatabaseUser.login(DB_id, userName, userPass).sessionToken; //Login the user and save its sessionToken to the variable var params = {}; //Define parameters object params.criteria = { //Query criteria: 'studentId': { //field "studentId" "$gt": 10 //greater than 10. Only records where the value of the studentId field greater than 10 will be shown. } }; //Define other parameters params.skip = 3; //Skip first 3 records. params.limit = 6; //Show maximum 6 records params.sort = "studentId"; //Ascending sort by field "studentId" params.proj = {'_id' : 0}; //Remove _id column from the result result.query = Collection.query(DB_id, collectionName, params, token); //Make the query and save it to the result object result.distinct = Collection.distinct(DB_id, collectionName, 'studentId', { //Another query with "distinct" method "studentId": { //Show only studentId column "$gt": 50 //Where the field value greater than 50 }, }, token); response.success(result); } catch (e) { response.success("message: " + e.message + "ncode: " + e.code); } |
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:
1 |
[value1, value2, value3, ... ] |
Examples
The first example will retrieve all distinct values from cityName
 column:
1 |
Collection.distinct(dbId, collectionName, "cityName"); |
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
:
1 |
Collection.distinct(DB_id, collectionName, 'count', {"count":{"$gt":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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
var DB_id = request.get("DB_id"); //Get the "DB_id" parameter from the request and store it var userName = request.get("userName"); //Store the user name var userPass = request.get("userPass"); //and its password var collectionName = request.get("collection"); //Collection name that will be used var object = { // object, that will be created "priority": request.get("priority"), //Get the "priority" parameter from the request and store it "taskName": request.get("taskName") //Get the "taskName" parameter from the request and store it } try { result = {}; var token = DatabaseUser.login(DB_id, userName, userPass).sessionToken; //Login the user and save its sessionToken to the variable result.token = token; //Save it token to the result too result.collectionsList = Collection.getCollectionList(DB_id, token); //Call the getCollectionList and save its response to the result var id = Collection.createObject(DB_id, collectionName, object)._id; //Create new object. Save the gotten object id to the id variable result.id = id; //And to the result result.retrievedOldObject = Collection.retrieveObject(DB_id, collectionName, id, null); //Get the object, that just been created and save it to the result object.priority = "Low"; //Change the "priority" value object.taskName = "Play the jazz music"; //Change the "taskName" value Collection.updateObject(DB_id, collectionName, id, object); //Update the object with a new data result.retrievedNewObject = Collection.retrieveObject(DB_id, collectionName, id, null); //Get the updated object and save it to the result Collection.deleteObject(DB_id, collectionName, id); //Delete the object that have been used. response.success(result); //Pass the result object to the response. } catch (e) { response.success("message: " + e.message + "ncode: " + e.code); //If something goes wrong error message will appear } |
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:
1 2 3 4 |
{ "_id": <some_id>, "sessionToken": <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:
1234{"username": <username>,"password": <password>}
Response
1 2 3 4 5 6 7 |
{ "username":<username>, "_createdAt":<datetime>, "_updatedAt":<datetime>, "_id":<user_id>, "sessionToken":<session_token> } |
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
1234{"username": <username>,"password": <password>}
Response
1 2 3 4 5 6 |
{ "username":<username>, "_createdAt":<datetime>, "_updatedAt":<datetime>, "_id":<user_id> } |
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
1 2 3 4 5 6 |
{ "username":<username>, "_createdAt":<datetime>, "_updatedAt":<datetime>, "_id":<user_id> } |
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:
12345678{["criteria":<criteria>,]["skip":<skip>, ]["limit":<limit>, ]["count":<count>, ]["sort":<sort>, ]["include":<include> ]}
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
1 2 3 4 5 6 |
[{ "username": <username > , "_createdAt": <datetime > , "_updatedAt": <datetime > , "_id": <user_id > }, ...] |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
var dbId = "52776916a044652b54f1f976"; var username = "testUser10"; var password = "testUser10"; var id = DatabaseUser.signUp(dbId, { "username": username, "password": password })._id; var token = DatabaseUser.login(dbId, username, password).sessionToken; // or login with masterKey // var masterKey = "8e4cf6ee-5081-4c58-8ee6-e3aa113f9de5"; // var token = DatabaseUser.login(dbId, username, null, masterKey).sessionToken; var user = DatabaseUser.retrieve(dbId, id, null, token); var updated = DatabaseUser.update(dbId, id, { "username": "testUserNew", "password": "testUserNew" }, token); var query = DatabaseUser.query(dbId, { "skip": 1, "limit": 1 }, token); DatabaseUser.remove(dbId, id, token); |
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:
1 2 3 4 5 |
Apperyio.PN.send("ffbe3bb4-3ea0-4ee6-b9db-587e43cfdb31", { payload: { "message": "Notification sample", }, }); |
Send push notification using channels
The following example sends push notifications to the devices by using channels. Also, badge
(iOS parameter only) is specified.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Apperyio.PN.send("ffbe3bb4-3ea0-4ee6-b9db-587e43cfdb31", { payload: { "message": "Notification sample", "badge": 1 }, filter: {"channels": {"$in":[1,2]}}, schedule: { scheduledTime: 1484870400000, timeZone: 120 } }); |
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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var responseBody = {}; //Object for storing response var requestParams = {}; //This object will contain values of the request parameters var paramKeys = request.keys(); // Returns array of the request parameters: ["Db_id", "collection"] for (var key = 0; key < paramKeys.length; key++) { //From 0 to number of request parameters (2 in this case) requestParams[paramKeys[key]] = request.get(paramKeys[key]); // returns value of request parameter by its name } //Now the paramKeys contains parameter names: ["Db_id", "collection"] //And the requestParams contains parameter values: ["526fdbd8e4b07c3286b537f1", "todo"] responseBody.requestBody = request.body(); // responseBody.requestBody now contains "some useful information" responseBody.requestParams = requestParams; // responseBody.requestParams now contains object ["526fdbd8e4b07c3286b537f1", "todo"] responseBody.method = request.method; // responseBody.method now contains string "GET" or "POST". response.success(responseBody, "application/json"); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
var DB_id = request.get("DB_id"), collectionName = request.get("collection"), id = request.get("id"); try { result = {}; result.retrievedObject = Collection.retrieveObject(DB_id, collectionName, id, null); response.success(result); } catch (e) { // Return error message and error code to user response.success("message: " + e.message + "ncode: " + e.code); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var secureCode = request.get("secureCode"); if (validateCode(secureCode)) { try { // Send binary data response.binary([80, 75, 5, 6, 0, 0], "application/zip"); } catch (e) { // Redirect to error page response.redirect("http://error.page.com"); } } else { // Respond with error message and code response.error("Secure code is not valid", "Unauthorized"); //It's possible to use error code instead of its name //response.error("Cannot find an article", 401) //Works the same } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var DB_id = request.get("DB_id"), collectionName = request.get("collection"), id = request.get("id"); var retrievedObject = {}; //object to store retrieved data try { retrievedObject = Collection.retrieveObject(DB_id, collectionName, id, null); response.success({ studentName: retrievedObject.studentName, studentId: retrievedObject.studentId }); } catch (e) { // Return error message and error code to user response.success("message: " + e.message + "\ncode: " + e.code); } |
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:
1 |
{"studentId":90,"studentName":"Jacob"} |
The same can be performed via the underscore.pick
method:
1 |
response.success(_.pick(retrievedObject, 'studentName', 'studentId')); |
The
Underscore
library must be included on theDependencies
tab.
Another way to pass only the specific columns to the result is to delete any unneeded columns via the delete
command:
1 2 3 4 |
delete retrievedObject._createdAt; delete retrievedObject._updatedAt; delete retrievedObject._id; response.success(retrievedObject); |
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:
1 2 3 4 5 6 |
{ "body":<body>, "mimeType":<mimeType>, "status":<status>, "redirectLocation":<redirectLocation> } |
Examples
Simple script call
The following example shows how to call one script from another. The called script should look like:
- Name –
ShowAlertScript
- Alias –
alert_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:
1 2 3 4 5 6 7 8 9 10 |
try { var res = ScriptCall.call("e1e530d1-3f67-478e-9a5a-5b8b819d819b", {"key":"value"}, "body text", "text/plain"); //Call the script by GUID //var res = ScriptCall.call("alert_script", {"key":"value"}, "body text", "text/plain"); //Call the same script by Alias response.success(res); } catch (e) { response.success("message: " + e.message + "ncode: " + e.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 forXHR2
andXHR
:
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:
123456789101112131415{["parameters":{[ <param1> : <value1>, ][ <param2> : <value2>, ... ]},]["headers":{[ <header1> : <value1>, ][ <header2> : <value2>, ... ]},]["body": <request_body> ,]["isRawRequest": <boolean>, ]["isRawResponse": <boolean>]}- 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 totrue
. - 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:
1 2 3 4 5 6 7 8 |
{ "status" : <response_status>, "headers" : { [ <header1> : <value1>, ] [ <header2> : <value2>, ... ] }, "body" : <response_body> } |
- 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
isapplication/json
and response body is a valid JSON object. It can be byte array ifisRawResponse
is set totrue
.
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):
1 2 3 4 |
var XHRResponse = XHR2.send("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false", {}); result = "status: " + XHRResponse.status; result += "body: " + XHRResponse.body; response.success(result, "text/plain"); |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
var XHRResponse = XHR2.send("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false", {}); //The same request var resultObject = {}; //Variable to store the new converted object var latLngArray = []; //Array for lat/lng values resultObject = JSON.parse(XHRResponse.body); //Conevrting the XHRResponse.body (which is string) in to the JSON object for (var i in resultObject.results) //All data is wrapped in the "results" tag. { latLngArray[i] = resultObject.results[i].geometry.location; //lat/lng values is placed by this hierarchy } response.success(latLngArray, "text/plain"); |
In the response, you’ll get an array with objects. Every one of them will contain “lng” and “lat” parameters, as in the following:
1 |
[{"lng":-122.0839544,"lat":37.4219985}] |
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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var XHRResponse = XHR2.send("POST", "http://requestb.in/py61zlpy", { //Change RequestBin URL to yours "parameters": { 'requestParameter' : 'Request parameter value', 'secondRequestParameter' : 'Second request parameter value' }, "headers": { 'X-Appery-Database-Id' : '517gdbd3e2b07c3286b537g5', 'X-Appery-Session-Token' : 'zxkgjjkasghag32-w315qwg2356-weg', }, "body": "Request body" }); |
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
:
1 2 3 4 5 6 7 8 9 10 |
var XHRResponse = XHR.send("GET", "https://api.appery.io/rest/1/db/users", { "headers": { "X-Appery-Database-Id": "51b2c9a7e4b0e832dd8fa123", "X-Appery-Master-Key": "fa5b2bf9-b329-49eb-8806-ed8967565f234" }, "parameters": { "where": '{"_id":"529c99bfe4b06de3a99fb2f1"}' } }); response.success(XHRResponse.body, "text/plain"); |
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 theXMLHttpRequest
object. We are working on adding a special script API to accessUsers
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var someValue = 'Value that should be stored in memory'; IMD.put("key", someValue); //Store someValue variable console.log(IMD.get("key")); //'Value that should be stored in memory' IMD.put("key", "New value"); //Rewrite value for "key" IMD.put("key2", "Another value"); //Store another value with different key console.log("keys: " + IMD.keys()); //Lists all the stored keys: [key2, key] console.log("length: " + IMD.length()); //Return number of stored keys: length: 2 IMD.remove("key"); //Remove "key" and its value console.log("keys: " + IMD.keys()); //keys: [key2] console.log("length: " + IMD.length());//length: 1 console.log("contains key2: " + IMD.contains("key2")); //contains key2: true response.success(IMD.keys()); //Add all the keys to response |