Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Moving App Logic to the Server

DZone's Guide to

Moving App Logic to the Server

This article takes you through the how-to for querying the database from appery.io server code script.

· Mobile Zone
Free Resource

Get gorgeous, multi-touch charts for your iOS application with just a few lines of code.

An Appery.io developer posted a question on the Appery.io Facebook page on how to write a Server Code script to query two different collections in the database. This post will show you how to do that.

In general, querying two database collections is better to do on the server-side than from the client. Doing it on the server is a lot faster and provides you with the option to update the search without impacting the client. Plus, you can add any logic when needed. Doing it from the client would require two REST API calls to the database.

First, there are two collections in the Appery.io Database.

This is the ProductName collection:

Screen Shot 2016-05-24 at 4.42.32 PM 

This collection is simple. It has a name and a code.

This is the ProductData collection:

Screen Shot 2016-05-24 at 4.44.33 PM.png


The code in this collection links the product name to the actual product (Android or iOS device).

The input to the script is the product type: Android or iOS. Based on the input, you look up the code for the product (a or i) and then run a second query to find all iOS or Android phones in the ProductData collection. Here is the script:

var product = request.get("type");
var dbId = "367e9e77......";
var params = {};
var result = [];

// Search for object with the provided 'type' (iOS or Android)
params.criteria = {
 "name": {
 "$eq": product
 }
};
result = Collection.query(dbId, "ProductName", params);

// Find all objects with code 'i' or 'a'
params.criteria = {
 "code": {
 "$eq": result[0].code // Either 'i' or 'a'
 }
};
// Run the query
result = Collection.query(dbId, "ProductData", params);
// Script response (API response)
Apperyio.response.success(result, "application/json");


This script first searches the ProductName collection to find the id for iOS or Android devices. Then it searches the ProductData collection to find the actual devices.

Moving this logic to the server is a good idea as you query two collections (or even more) with a single request from the client.

If you want to learn more about Server Code, check out our YouTube channel Server Code playlist.

.Net developers: use Highcharts, the industry's leading interactive charting library, without writing a single line of JavaScript.

Topics:
server ,devices ,code ,script ,developer ,appery.io

Published at DZone with permission of Max Katz, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}