$fh.web

$fh.web(options, callback(err, res))

Description

Perform an external web request

Arguments

options

  • type : object - Set of key/value pairs for configuration external web requests. Possible keys:
  • keys:
    • url
      • type: string - Target url
      • mandatory : yes
    • method
      • type: string - Method used for the request.
      • mandatory : yes
      • default : GET
    • contentType
      • type : string - Type of content in request body. e.g. text/plain
      • mandatory : no
    • charset
      • type : string - Charset used for the response. e.g. UTF-8
      • mandatory : no
    • body
      • type : string - Message body. Only used if the method is NOT "GET".
      • mandatory : no
    • headers
      • type: array. An array of JSON object. Each JSON object contains the following fields:
        • name : The name of the header
        • value : The value for the header
      • mandatory : no
    • cookies :
      • type : array - An array of JSON object. Each JSON object contains the following fields:
        • name : Name of the cookie
        • value : Cookie value
      • mandatory : no
    • period
      • type : number - For how long the response data should be cached. In milliseconds.
      • mandatory : no

callback

  • type: function - Callback function that is called when the operation is completed
  • arguments:
    • err : A Error object contains relevant error information
      • type : object.
      • keys:
        • message
          • type: string - error message
    • res : The response of the web request
      • type : object
      • keys
        • status
          • type: number - The status code of the HTTP request
        • headers
          • type: array - An array of name/value pairs representing the response headers
        • body
          • type: string - The response data.
        • contentType
          • type: string - The content type value of the response.

Examples

$fh.web({
  url: "http://www.google.com",
  method: "GET",
  contentType: "text/html",
  charset: "UTF-8",
  period: 60000 //cache for 1 min
}, function(err, result) {
  if (err) {
    console.log("Error : " + err.message);
  } else {
    var data = result.body;
    console.log("Response is " + data);
  }
})

$fh.cache

$fh.cache(options, callback(err, res))

Description

Cache an object in the cloud for a period of time.

Arguments

options

  • type : object - Set of key/value pairs to configure the cache operation. Possible keys:
  • keys
    • act
      • type : string - Possible values:
        • save : Save an object to the cache
        • load : Read an object from the cache
        • remove : Delete an object from the cache
      • mandatory : yes
    • key
      • type : string - The key associated with the object
      • mandatory : yes
    • value
      • type : serializable - The value to be cached.
      • mandatory : no
    • expire
      • type : number - For how many seconds the object will be cached.
      • mandatory : no

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • keys
        • message
          • type : string - the error message
    • res : The value to be saved/loaded/removed
      • type : serializable

Examples

//save a value
var key = "foo";
var value = "bar";
$fh.cache({
  act: "save",
  key: key,
  value: value
}, function(err, res) {
  if (err) {
    console.log(err.toString());
  } else {
    console.log(res.toString());
  }
})

//load
$fh.cache({
  act: "load",
  key: key
}, function(err, res) {
  if (err) {
    console.log(err.toString());
  } else {
    console.log(res.toString());
  }
})

//remove
$fh.cache({
  act: "remove",
  key: key
}, function(err, res) {
  if (err) {
    console.log(err.toString());
  } else {
    console.log(res.toString());
  }
})

$fh.feed

$fh.feed(options, callback(err, res))

Description

Reading RSS feeds from a link.

Arguments

options

  • type : object - A set of key/value pairs for configure reading RSS feeds. Possible keys:
  • keys
    • link
      • type : string - The url link of the feed
      • mandatory : yes
    • list-max
      • type : number - The maximum number of feed entries to read
      • mandatory : yes

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • keys
        • message
          • type : string - the error message
    • res : An object
      • type : object
        • statusCode : string - Status code of response
        • body : string - Body of the response
        • Parsing the body using JSON.parse() gives and object with the following
          • list : array - Array of feed entries, where each feed entry object contains a object called "fields" with the following attributes:
            • author : string - The author of the field
            • title : string - The title of the field
            • description : string - The content of the feed

Examples

$fh.feed({
  'link': "http://www.feedhenry.com/feed",
  'list-max': 10
}, function(err, result) {
  if (err) {
    console.log("Error is : " + err.message)
  } else {
    entries = JSON.parse(result.body).list;
    for (var i = 0; i < entries.length; i++) {
      console.log("Entry title : " + entries[i].fields.title + " : Content : " + entries[i].fields.description);
    }
  }
})

$fh.log

$fh.log(data, showHidden, depth)

Description

Log data to the console.

Arguments

data

  • type : object - The data to be logged to console
  • mandatory : yes

showHidden

  • type : boolean - If this is set to true, the object's non-enumerable properties will be shown
  • mandatory : no
  • default : false

depth

  • type : number - How many times to recurse while formatting the object. Pass null to recurse indefinitely
  • mandatory : no
  • default : 2

Example

$fh.log({
  "key": "value"
});

$fh.push

$fh.push(options, callback(err, res))

Description

Send messages to Urbanairship from the cloud side.

Arguments

options

  • type : object - A set of key/value pairs to configure push notification. Possible keys:
  • keys
    • act
      • type: string - Should be one of register, push or broadcast
        • register : Register a device with Urbanairship.
        • push : Send a message to Urbanairship's push API.
        • broadcast : Send a message to Urbanairship's broadcast API.
      • mandatory : yes
    • type
      • type : string - Which environment the app is running as. Should be either dev or prod
        • dev : Development environment. The development keyset will be used.
        • prod : Production environment. The production keyset will be used.
      • mandatory : yes
    • params:
      • type : object - Extra parameters for an action.
        • If act is register:
          • id : string - The unique id of the device. It should be the deviceToken for iOS devices, or the apid for Android devices or the devicePIN for Blackberry devices.
            See < a gen - link = "api_client_hybrid#$fh.push" > FeedHenry client Push API < /a> for more details.
          • platform : string - Which platform the device is running on. Should be one of "ios", "android" or "blackberry".
        • If act is push :
          • object - This is the data which will be sent to Urbanairship's push API. See Urbanairship Push API for data format
        • If act is broadcast:

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • keys
        • message
          • type : string - the error message
    • res : the result of the operation
      • type : object
      • keys
        • result : string - Response from Urbanairship
        • status : number - The status code returned from Urbanairship
        • error : string - Error message return from Urbanairship (if any)

Examples

//register a device
var token = params.token; //the is returned by $fh.push on client side
var platform = params.platform;
$fh.push({
  'act': 'register',
  'type': 'dev',
  'params': {
    'id': token,
    'platform': platform
  }
}, function(err, res) {
  if (err) {
    console.log(err.toString())
  } else {
    console.log("status from UA : " + res.status);
  }
});

//push a message to a device
var message = "hello from FH";
var deviceToken = "xxxxxxxxxxxxxxxxxxxxxx";
var ios_message = {
  'device_tokens': [deviceToken],
  'aps': {
    'alert': message
  }
};
$fh.push({
  'act': 'push',
  'type': 'dev',
  'params': ios_message
}, function(err, res) {
  if (err) {
    console.log(err.toString())
  } else {
    console.log("status from UA : " + res.status);
  }
});

//broadcast a message
var message = "hello from FH";
var android_message = {
  'android': {
    'alert': message
  }
};
$fh.push({
  'act': 'broadcast',
  'type': 'dev',
  'params': android_message
}, function(err, res) {
  if (err) {
    console.log(err.toString())
  } else {
    console.log("status from UA : " + res.status);
  }
});

$fh.session

$fh.session.set(sessionid, sessiondata, expireafter, callback(err, res))
$fh.session.get(sessionid, callback(err, res))
$fh.session.remove(sessionid, callback(err, res))

Description

Manage sessions in the cloud

Methods

set(sessionid, sessiondata, expireafter, callback(err, res))

Start a session

get(sessionid, callback(err, res))

Retrieve a session

remove(sessionid, callback(err, res))

Remove a session

Arguments

sessionid

  • type : string - identifier for the session
  • mandatory : yes

sessiondata

  • type : string - representation of a JSON object
  • mandatory : yes

expireafter

  • type : number - The number of seconds to keep the session active. Use 0 for no timeout
  • mandatory : yes

callback

  • type : function - Callback function to be executed after the operation is completed
  • mandatory : yes
  • arguments:
    • err
      • type : string - the error message
    • res : the result of the operation. Based on the method, different results are generated:
      • If method is set:
        • the result is the session id
      • If method is get:
        • the result is the session data
      • If method is remove:
        • the result is a boolean indicate if the operation is successful

Examples

var sessionData = JSON.stringify({
  "foo": "bar"
});
var sessionId = "randomId000000";

//save a new session
$fh.session.set(sessionId, sessionData, 0, function(err, res) {
  if (err) {
    console.log(err)
  } else {
    console.log("Session saved. Session id is " + res)
  }
})

//load an existing session
$fh.session.get(sessionId, function(err, res) {
  if (err) {
    console.log(err)
  } else {
    console.log("Session loaded. Session data is " + res)
  }
})

//remove a session
$fh.session.remove(sessionId, function(err, res) {
  if (err) {
    console.log(err)
  } else {
    if (res) {
      console.log("Session " + sessionId + " removed.");
    } else {
      console.log("Failed to remove session " + sessionId);
    }
  }
})

$fh.db

$fh.db(options, callback(err, res))

Description

Access to hosted data storage. It supports CRUDL (create, read, update, delete, list) and index operations. It also supports deleteall, which deletes all the records in the specified entity.

'create' Arguments

options

  • type : object - a set of key/value pairs to configure the create operation. Possible keys:
  • keys
    • act
      • type : string - The operation to perform. Should be create
      • mandatory : yes
    • type
      • type : string - The entity to perform the operation on. An entity is analogous to "Table" in MySql or "Collection" in MongoDB.
      • mandatory : yes
    • fields : object - The structure of the data. A data is analogous to "Row" in MySql or "Documents" in MongoDB
      • mandatory : yes

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • keys
        • message
          • type : string - the error message
    • res : The data that has been created
      • If only create one data, properties include
        • fields : object - The fields of the data
        • guid : string - A unique identifier of the data
        • type : string - The entity type of the data
      • If multiple data are created, properties include
        • status : string - The overall result of the create operation
        • count : number - How many rows of data has been created

'create' Examples

//create a data record for entity "myFirstEntity"
$fh.db({
  "act": "create",
  "type": "myFirstEntity",
  "fields": {
    "firstName": "Joe",
    "lastName": "Bloggs",
    "address1": "22 Blogger Lane",
    "address2": "Bloggsville",
    "country": "Bloggland",
    "phone": "555-123456"
  }
}, function(err, data) {
  if (err) {
    console.log("Error " + err)
  } else {
    console.log(JSON.stringify(data))
    /*
     The output will be something similar to this
     {
      "fields": {
        "address1": "22 Blogger Lane",
        "address2": "Bloggsville",
        "country": "Bloggland",
        "fistName": "Joe",
        "lastName": "Bloggs",
        "phone": "555-123456"
      },
      "guid": "4e563ea44fe8e7fc19000002",
      "type": "myFirstEntity"
    }
    */
  }
});

//create multipe records a time
$fh.db({
  "act": "create",
  "type": "myCollectionType",
  "fields": [{
    "id": 1,
    "name": "Joe"
  }, {
    "id": 2,
    "name": "John"
  }]
}, function(err, data) {
  if (err) {
    //print out error
  } else {
    console.log(JSON.stringify(data))
    /*
         The output will be something similar to this
         {
            "Status":"OK",
            "Count":2
         }
        */
  }
});

'read' Arguments

options

  • type : object - A set of key/value pairs to configure the read operation. Possible keys:
  • key
    • act
      • type : string - The operation to perform. Should be one read
      • mandatory : yes
    • type
      • type : string - The entity to perform the operation on. An entity is analogous to "Table" in MySql or "Collection" on MongoDB.
      • mandatory : yes
    • guid
      • type : string - A global unique id of the data. A data is analogous to "Row" in MySql or "Document" in MongoDB.
      • mandatory : yes

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • keys
        • message
          • type : string - the error message
    • res : The data that has been read
      • keys
        • fields : object - The data fields
        • guid : string - The global unique id of the data
        • type : string - The entity type
        • If no entity exists for the guid specified, it will be empty

'read' Examples

$fh.db({
  "act": "read",
  "type": "myFirstEntity",
  "guid": "4e563ea44fe8e7fc19000002"
}, function(err, data) {
  /* Sample output 
    {
      "fields": {
        "address1": "22 Blogger Lane",
        "address2": "Bloggsville",
        "country": "Bloggland",
        "fistName": "Joe",
        "lastName": "Bloggs",
        "phone": "555-123456"
      },
      "guid": "4e563ea44fe8e7fc19000002",
      "type": "myFirstEntity"
    }
    */
});

'update' Arguments

options

  • type : object - A set of key/value pairs to configure update operation. Possible keys:
  • keys
    • act
      • type : string - The operation to perform. Should be update
      • mandatory : yes
    • type
      • type : string - The entity to perform the operation on. An entity is analogous to "Table" in MySql or "Collection" on MongoDB.
      • mandatory : yes
    • guid
      • type : string. A global unique id of the data. A data is analogous to "Row" in MySql or "Document" in MongoDB.
      • mandatory : yes
    • fields :
      • type : object. The structure of the data.
      • mandatory : yes

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • keys
        • message
          • type : string - the error message
    • res : The data that has been updated
      • keys
        • fields : object - The data fields
        • guid : string - The global unique id of the data
        • type : string - The entity type

Note

The update call updates the entire entity. It will replace all the existing fields with the new fields passed in.

'update' Examples

//update
$fh.db({
  "act": "update",
  "type": "myFirstEntity",
  "guid": "4e563ea44fe8e7fc19000002",
  "fields": {
    "fistName": "Jane",
  }
}, function(err, data) {
  if (err) {
    //process error
  } else {
    console.log(JSON.stringify(data))
    /* Output:
    {
      "fields": {
        "fistName": "Jane"   //only one field now
      },
      "guid": "4e563ea44fe8e7fc19000002",
      "type": "myFirstEntity"
    }
    */
  }
});

//To update a single field, read it first
$fh.db({
  "act": "read",
  "type": "myFirstEntity",
  "guid": "4e563ea44fe8e7fc19000002"
}, function(err, entity) {
  var entFields = entity.fields;
  entFields.firstName = 'Jane';

  $fh.db({
    "act": "update",
    "type": "myFirstEntity",
    "guid": "4e563ea44fe8e7fc19000002",
    "fields": entFields
  }, function(err, data) {
    /*output
        {
          "fields": {
            "address1": "22 Blogger Lane",
            "address2": "Bloggsville",
            "country": "Bloggland",
            "firstName": "Jane",
            "lastName": "Bloggs",
            "phone": "555-123456"
          },
          "guid": "4e563ea44fe8e7fc19000002",
          "type": "myFirstEntity"
        }
        */
  });
});

'delete' Arguments

options

  • type : object - A set of key/value pairs to configure delete operation. Possible keys:
  • keys
    • act
      • type : string - The operation to perform. Should be one delete.
      • mandatory : yes
    • type
      • type : string - The entity to perform the operation on. An entity is analogous to "Table" in MySql or "Collection" on MongoDB.
      • mandatory : yes
    • guid
      • type : string - A global unique id of the data. A data is analogous to "Row" in MySql or "Document" in MongoDB.
      • mandatory : yes

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • keys
        • message
          • type : string - the error message
    • res : The data that has been deleted
      • keys
        • fields : object - The data fields
        • guid : string - The global unique id of the data
        • type : string - The entity type
        • If no entity exists for the guid specified, it will be empty

'delete' Examples

$fh.db({
  "act": "delete",
  "type": "myFirstEntity",
  "guid": "4e563ea44fe8e7fc19000002"
}, function(err, data) {
  /* output
    {
      "fields": {
        "address1": "22 Blogger Lane",
        "address2": "Bloggsville",
        "country": "Bloggland",
        "fistName": "Jane",
        "lastName": "Bloggs",
        "phone": "555-123456"
      },
      "guid": "4e563ea44fe8e7fc19000002",
      "type": "myFirstEntity"
    }
    */
});

'deleteall' Arguments

Warning

This operation will delete all the records in the specified entity

options

  • type : object - A set of key/value pairs to configure delete operation. Possible keys:
  • keys
    • act
      • type : string - The operation to perform. Should be one deleteall.
      • mandatory : yes
    • type
      • type : string - The entity to perform the operation on. An entity is analogous to "Table" in MySql or "Collection" on MongoDB.
      • mandatory : yes

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • key
        • message : string - the error message
    • res
      • type : object
      • keys
        • status : string - The overall result of the deleteall operation
        • count : number - How many records of data have been deleted

'deleteall' Examples

$fh.db({
  "act": "deleteall",
  "type": "myFirstEntity"
}, function(err, data) {
  /* output
      {
        status: "ok",
        count: 5
      }
    */
});

'list' Arguments

options

  • type : object - A set of key/value pairs to configure the list operation. Possible keys:
  • keys
    • act
      • type : string - The operation to perform. Should be list.
      • mandatory : yes
    • type
      • type : string - The entity to perform the operation on. An entity is analogous to "Table" in MySql or "Collection" on MongoDB.
      • mandatory : yes
    • eq
      • type : object - A set of key/value pairs to specify the query restrictions
      • is equal to
      • mandatory : no
    • ne
      • type : object - A set of key/value pairs to specify the query restrictions
      • not equal to
      • mandatory : no
    • It
      • type : object - A set of key/value pairs to specify the query restrictions
      • less than
      • mandatory : no
    • le
      • type : object - A set of key/value pairs to specify the query restrictions
      • less than or equal
      • mandatory : no
    • gt
      • type : object - A set of key/value pairs to specify the query restrictions
      • greater than
      • mandatory : no
    • ge
      • type : object - A set of key/value pairs to specify the query restrictions
      • greater than or equal
      • mandatory : no
    • like
      • type : object - A set of key/value pairs to specify the query restrictions
      • Match some part of the field. Based on Mongo regex matching logic
      • mandatory : no
    • in
      • type : object - A set of key/value pairs to specify the query restrictions
      • The same as $in operator in MongoDB, to select documents where the field (specified by the key) equals any value in an array (specified by the value)

List operations can use as many or as few of the restrictions.

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • keys
        • message
          • type : string - the error message
    • res : A list of data that matches the restriction
      • keys
        • count : number - Total number of matched data
        • list : array - The array of the matched data

'list' Examples

//simple list
$fh.db({
  "act": "list",
  "type": "myFirstEntity",
}, function(err, data) {
  /* output 
    {
      "count": 1,
      "list": [{
        "fields": {
          "address1": "22 Blogger Lane",
          "address2": "Bloggsville",
          "country": "Bloggland",
          "fistName": "Joe",
          "lastName": "Bloggs",
          "phone": "555-123456"
        },
        "guid": "4e563ea44fe8e7fc19000002",
        "type": "myFirstEntity"
      }]
    }
    */
});

//Geo search
$fh.db({
  act: "list",
  type: "collectionName",
  "geo": {
    "employeeLocation": { //emplyeeLocation has been indexed as "2D"
      center: [-83.028965, 42.542144],
      radius: 5 //km
    }
  }
}, function(err, data) {

})

//multiple restrictions
$fh.db({
  "act": "list",
  "type": "myFirstEntity",
  "eq": {
    "lastName": "Bloggs"
  },
  "ne": {
    "firstName": "Jane"
  },
  "in": {
    "country": ["Bloggland", "Janeland"]
  }
}, function(err, data) {

});

//restricting fields returned
$fh.db({
  "act": "list",
  "type": "myFirstEntity",
  "eq": {
    "lastName": "Bloggs",
    "country": "Bloggland"
  },
  "ne": {
    "firstName": "Jane"
  },
  "fields": ["address1", "address2"]
}, function(err, data) {
  /* output 
    {
      "count": 1,
      "list": [{
        "fields": {
          "address1": "22 Blogger Lane",
          "address2": "Bloggsville"
        },
        "guid": "4e563e874fe8e7fc19000001",
        "type": "myFirstEntity"
      }]
    }
    */
});

'index' Arguments

options

  • type : object - A set of key/value pairs to configure the index operation. Possible keys:
  • keys
    • act
      • type : string - The operation to perform. Should be index.
    • type
      • type: string - The entity to perform the operation on. An entity is analogous to "Table" in MySql or "Collection" on MongoDB.
    • index
      • object - The fields the index should be added to.
        • The index type of a field could be one of following:
          • ASC : the index is ascending
          • DESC : the index is descending
          • 2D : The index is Geo indexation. It requires that the specified fields meets following conditions:
            • It is a [Longitude, Latitude] array
            • Longitude should be between [-180, 180]
            • Latitude should be between [-90, 90]
            • Latitude or longitude should NOT be null

callback

  • type : function - Callback function to be executed after the operation is completed
  • arguments:
    • err : A error object contains the relevant error information
      • type : object
      • keys
        • message
          • type : string - the error message
    • res : The result of the operation
      • keys
        * status: string - The overall result * indexName: string - The name of the added index

'index' Examples

$fh.db({
  "act": "index",
  "type": "employee",
  "index": {
    "employeeName": "ASC" // Index type
    "location": "2D"
  }
}, function(err, data) {
  /* output
    {
        "Status":"OK",
        "indexName":"employeeName_1_location_2d"
    }
    */
})

$fh.act

$fh.act(options,callback)

Description

Make cloud calls to your other apps allowing them to share data and functionality. The guid of your app can be retrieved with the shortcut ctrl+alt+g from the studio or from the fhc command line tool using the apps command.

'list' Arguments

options

  • type : object - A set of key/value pairs to configure the act operation. Possible keys:
    • keys
      • guid
        • type : string - This is the identifier of one of your other Feedhenry apps that you wish to call.
        • mandatory : yes
      • endpoint
        • type : string -This is the name of the remote app's function in the cloud
        • mandatory : yes
      • params
        • type : object - This contains key value pairs which will be passed to the remote app's function in the params object
        • mandatory : no
      • live
        • type boolean - This is a flag for choosing whether you wish to call a development apps endpoint or a live apps endpoint, it defaults to false.
        • mandatory : no

callback

  • type : function - Callback function to be executed after the operation is completed
    • arguments:
      • err : contains the relevant error information
        • type : string
      • res : The result of the remote apps endpoint.
        • type : returned result of the remote apps cloud function

Examples

App1: main.js
exports.doSomething = function(params, callback) {
  return callback(null, {
    msg: "I did something",
    iwassent: params.somekey
  });
};

App2: main.js
exports.makeAppCall = function(params, callback) {
  $fh.act({
    guid: "123456789erghjtrudkirejr",
    endpoint: "doSomething",
    params: {
      somekey: "someval"
    }
  }, function(err, data) {
    if (err) console.log(err);
    return callback(err, data);
  });
};

$fh.stats

$fh.stats.inc(counter_name)

Description

Increment a counter

Arguments

counter_name

  • type : string - The name for the counter you want to increment. If this doesn't exist, it is created.
  • mandatory : yes

Example

$fh.stats.inc('counter_name');

$fh.stats.dec(counter_name)

Description

Decrement a counter

Arguments

counter_name

  • type : string - The name for the counter you want to decrement.
  • mandatory : yes

Example

$fh.stats.dec('counter_name');

$fh.stats.timing(timer_name, milliseconds)

Description

Records the value for a timer.

Arguments

timer_name

  • type: number - The name for the timer you want to record a value for. If it doesn't exist, it is created.
  • mandatory: yes

milliseconds

  • type: string - Timing in milliseconds of the interval you wish to record (e.g. time difference between a timer start and end)
  • mandatory: yes

Example

// Action took 500ms, record this
$fh.stats.timing('my_timer', 500);

$fh.sync

The cloud sync framework requires handler functions to be defined which provide access to the back end data & manage data collisions. These are specified in the handleXXX() functions. Each unique dataset being managed is identified by a dataset_id which must be specified as the first parameter when calling any function of the sync framework.

$fh.sync.init(dataset_id, options, callback)

Description

Initialise cloud data sync service for specified dataset.

Arguments

dataset_id

  • type: string - Unique Id for the dataset to initialise.
  • mandatory: yes

options

  • type: object - JSON Object of configuration options
    • sync_frequency
      • type: number - How often to synchronise data with the back end data store in seconds.
      • default: 10
      • mandatory: no

callback(err)

  • type: function - the function to call once the dataset has been initialised
    • err - Any error thrown during initialisation

$fh.sync.invoke(dataset_id, params, callback)

Description

Invoke the Sync Server. This should be called from a cloud “act” function. TODO - this is not still the case!

Arguments

dataset_id

  • type: string - Unique Id for the dataset to manage. The value for dataset_id is the name of the act function which is calling fh.sync.invoke()

params

  • type: object - The params passed to the “act” function

callback

  • type: function - The callback passed to the “act” function

e.g.:

exports.foo = function(params, callback) {
  return fh.sync.invoke(‘foo’, params, callback);
}

$fh.sync.stop(dataset_id, callback)

Description

Stop cloud data sync for the specified dataset_id. This will remove any reference to the dataset from the sync service. Any subsequent cloud calls to sync.invoke will fail with an unknown_dataset error. The dataset can be put back under control of the sync service by calling the sync.init() function again. Calling stop on a non-existent dataset has no effect. Calling stop multiple times on the same dataset has no effect.

Arguments

dataset_id

  • type: string - Unique Id for the dataset to stop managing.

callback

  • The callback to invoke once the dataset has been removed from the management of the service. There are no parameters passed to this callback.

$fh.sync.stopAll(callback)

Description

Stop cloud data sync service for ALL datasets. This will remove all reference to all datasets from the sync service. Any subsequent cloud calls to sync.invoke() will fail with an unknown_dataset error. Any of the datasets can be put back under control of the sync service by calling the sync.init() function again and passing the required dataset_id. Calling stop multiple times has no effect - except that the return data to the callback (an array of dataset_ids which are no longer being synced) will be different.

Arguments

callback(err, res)

  • type: function - the callback function to invoke once all datasets have been removed from the management of the service.
    • err - Any error thrown during the removal of the datasets
    • res - A JSON Array of Strings - representing the dataset_Ids which have been removed from the sync service

$fh.sync.handleList(dataset_id, function)

Description

Defines a handler function for listing data from the back end data source for a dataset

Arguments

dataset_id

  • type: string - Unique Id for the dataset to manage.

function

  • type: function - the function to invoke which will list data from the back end data store.

    • dataset_id - The dataset identifier that this function was defined for
    • params - JSON object representing query parameters passed from the client. These can be used to restrict the data set returned.
    • callback(err, res) - The callback into the sync service to store the dataset
      • err - Any error thrown during listing
      • res - A JSON Object - representing the data in the following format:
{
  uid_1 : {<JSON Object of data>},
  uid_2 : {<JSON Object of data>},
  uid_3 : {<JSON Object of data>},
  ...
}

It is recommended that the handleList function converts data from the back end format into a full JSON Object. This is a sensible approach when reading data from relational and nonrelational databases, and works well for SOAP and XML data. However, it may not always be feasible - e.g. when reading non structured data. In these cases, the recomened approach is to create a JSON object with a single key called “data” and set the value for this key to be the actual data. e.g. xml data

<dataset>
  <row>
    <userid>123456</userid>
    <firstname>Joe</firstname>
    <surname>Bloggs</surname>
    <dob>1970-01-01</dob>
    <gender>male</gender>
  </row>
</dataset>

{
  "123456" : {
    "userid" : "123456",
    "firstname" : "Joe",
    "surname" : "Bloggs",
    "dob" : "1970-01-01",
    "gender" : "male"
  }
}

e.g. non structured data

123456|Joe|Bloggs|1970-01-01|male

{
  "123456" : {
    "data" : "123456|Joe|Bloggs|1970-01-01|male"
  }
}

$fh.sync.handleCreate(dataset_id, function)

Description

Defines a handler function for creating a single row of data in the back end data source for a dataset.

Arguments

dataset_id

  • type: string - Unique Id for the dataset to associate the create handler with.

  • type: function - the function to invoke which will create a single row of data in the back end data store.

    • dataset_id - The dataset identifier that this function was defined for

    • data - Row of data to create

    • callback(err, res) - The callback into the sync service to store the dataset

      • err - Any error thrown during creation

      • res - JSON Object containing the following data

        • uid - Unique Identifier for row

        • data - The created data record - including any system or UID fields added during the create process

e.g:

{
  "uid": "1234",
  "data": {
    "userid": "1234",
    "name": "Jane Bloggs",
    "age": 27
  }
}

$fh.sync.handleRead(dataset_id, function)

Description

Defines a handler function for reading a single row of data from the back end data source for a dataset

Arguments

dataset_id

  • type: string - Unique Id for the dataset to associate the read handler with.

  • type: function - the function to invoke which will list data from the back end data store.

    • dataset_id - The dataset identifier that this function was defined for

    • uid - Unique Identifier for row.

    • callback(err, res) - The callback into the sync service to return the row of data

      • err - Any error thrown during reading the data

      • res - JSON Object representing the row of data

e.g:

{
  "userid": "1234",
  "name": "Jane Bloggs",
  "age": 27
}

$fh.sync.handleUpdate(dataset_id, function)

Description

Defines a handler function for updating a single row of data from the back end data source for a dataset. The sync service will verify that the update can proceed (i.e. collision detection) before it invokes the update function.

Arguments

dataset_id

  • type: string - Unique Id for the dataset to associate the update handler with.

  • type: function - the function to invoke which will update a single row of data in the back end data store.

    • dataset_id - The dataset identifier that this function was defined for

    • uid - Unique Identifier for row.

    • data - Row of data to update

    • callback(err, res) - The callback into the sync service to return the updated row of data

      • err - Any error thrown during reading the data

      • res - JSON Object representing the updated row of data

e.g:

{
  "userid": "1234",
  "name": "Jane Ann Bloggs",
  "age": 27
}

$fh.sync.handleDelete(dataset_id, function)

Description

Defines a handler function for deleting a single row of data from the back end data source for a dataset. The sync service will verify that the delete can proceed (i.e. collision detection) before it invokes the delete function.

Arguments

dataset_id

  • type: string - Unique Id for the dataset to associate the delete handler with

function

  • type: function - the function to invoke which will delete a single row of data in the back end data store.

    • dataset_id - The dataset identifier that this function was defined for

    • uid - Unique Identifier for row.

    • callback(err, res) - The callback into the sync service to return the delete row of data

      • err - Any error thrown during reading the data

      • res - JSON Object representing the deleted row of data

e.g:

{
  "userid": "1234",
  "name": "Jane Ann Bloggs",
  "age": 27
}

$fh.sync.handleCollision(dataset_id, function)

Description

Defines a handler function for dealing with data collisions (i.e. stale updates). Typically a collision handler will write the data record to a collisions table which is reviewed by a user who can manually reconcile the collisions.

Arguments

dataset_id

  • type: string - Unique Id for the dataset to associate the collision handler with.

function

  • type: function - the function to invoke when a data collision occurs.

    • dataset_id - The dataset identifier that this function was defined for

    • hash - Unique hash value identifying the collision

    • timestamp - Date / time that update was created on client device

    • uid - Unique Identifier for row

    • pre - The data row the client started with

    • post - The data row the client tried to write

$fh.sync.listCollisions(dataset_id, function)

Description

Defines a handler function for returning the current list of collisions. This would usually be used by an administration console where a user is manually reviewing & resolving collisions.

Arguments

dataset_id

  • type: string - Unique Id for the dataset to associate the collision handler with.

function

  • type: function - the function to invoke which will return the current list of collisions.

    • dataset_id - The dataset identifier that this function was defined for

    • callback(err, res) - The callback into the sync service to return the delete row of data

      • err - Any error thrown while listing the collisions

      • res - JSON Object representing the list of collisions in the following format:

e.g.

{
  "collision_hash_1": {
    "uid": "<uid_of_data_row>",
    "timestamp": "<timestamp_value_passed_to_handleCollision_fn>",
    "pre": "<pre_data_record_passed_to_handleCollision_fn>",
    "post": "<post_data_record_passed_to_handleCollision_fn>"
  },
  "collision_hash_2": {
    "uid": "<uid_of_data_row>",
    "timestamp": "<timestamp_value_passed_to_handleCollision_fn>",
    "pre": "<pre_data_record_passed_to_handleCollision_fn>",
    "post": "<post_data_record_passed_to_handleCollision_fn>"
  },
  "collision_hash_2": {
    "uid": "<uid_of_data_row>",
    "timestamp": "<timestamp_value_passed_to_handleCollision_fn>",
    "pre": "<pre_data_record_passed_to_handleCollision_fn>",
    "post": "<post_data_record_passed_to_handleCollision_fn>"
  }...
}

Note: "collision_hash" is the hash value which uniquely identifies a collision. This value will have been passed as the "hash" parameter when the collision was originally created in the "handleCollision" function.

$fh.sync.removeCollision(dataset_id, function)

Description

Defines a handler function for deleting a collision from the collisions list.This would usually be used by an administration console where a user is manually reviewing & resolving collisions.

Arguments

dataset_id

  • type: string - Unique Id for the dataset to associate the collision handler with.

function

  • type - the function to invoke which will delete a collisions from the list.

    • dataset_id - The dataset identifier that this function was defined for

    • collision_hash - The hash value which uniquely identifies a collision. This value will have been passed as the "hash" parameter when the collision was originally created in the "handleCollision" function.

    • callback(err) - The callback into the sync service to return the delete row of data

      • err - Any error thrown while deleting the collisions

$fh.hash

$fh.hash(options, callback(err, res))

Description

Generate the hash value of a given input

Arguments

options

  • type : object - A set of key/value pairs to configure the hash operation. Possible keys:
  • keys:
    • algorithm
      • type : string - Supported hash algorithms:
        • MD5
        • SHA1
        • SHA256
        • SHA512
      • mandatory : yes
    • text
      • type : string - The input to be hashed
      • mandatory : yes

callback

  • type : function - Callback function to be executed after the operation is completed
    • arguments:
      • err : contains the relevant error information
        • type : string
      • res : A JSON object contains the hash value.
        • keys
          • hashvalue: the hash value of the input text

Examples

$fh.hash({
  algorithm: 'MD5',
  text: 'test string'
}, function(err, result) {
  if (err) {
    return console.log("Failed to generate hash value: " + err);
  } else {
    return console.log("Hash value is :" + result.hashvalue);
  }
});

$fh.sec

$fh.sec(options, callback(err, result))

Description

Key generation, data encryption/decryption.

Key Generation

options

  • type : object - A set of key/value pairs to configure the key generation operation. Possible keys:
  • keys
    • act
      • type : string - The operation to perform. Should be keygen
      • mandatory : yes
    • params
      • type : object - The parameters for the operation
        • algorithm : string - The key generation algorithm. Should be either RSA or AES
        • keysize : number - The key size.
          • For RSA, 1024 or 2048 is supported
          • For AES, 128 or 256 is supported
      • mandatory : yes

callback

  • type : function - Callback function to be executed after the operation is completed
    • arguments:
      • err : contains the relevant error information
        • type : string
      • result: A JSON object contains the generated keys
        • For RSA, the following properties are included:
          • public : Hex value of the public key
          • private : Hex value of the private key
          • modulu : Hex value of the modulu
        • For AES, the following properties are included:
          • secretkey : Hex value of the secret key
          • iv: Hex value of the initial vector

Examples

//generate a pair of RSA key
$fh.sec({
  act: 'keygen',
  params: {
    algorithm: "RSA",
    keysize: 1024
  }
}, function(err, res) {
  if (err) {
    return console.log("RSA key generation failed. Error: " + err);
  }
  return console.log("Public key is " + res.public + " Private key is " + res.private);
});

//generate a AES key
$fh.sec({
  act: 'keygen',
  params: {
    algorithm: "AES",
    keysize: 128
  }
}, function(err, res) {
  if (err) {
    return console.log("AES key generation failed. Error: " + err);
  }
  return console.log("AES secret key is " + res.secretkey + " iv is " + res.iv);
});

Data Encryption

options

  • type : object - A set of key/value pair to configure data encryption
  • keys
    • act
      • type : string - The operation to perform. Should be encrpty
      • mandatory : yes
    • params
      • type : object - The parameters for the operation
        • algorithm : string - The encryption algorithm. Both RSA and AES are supported
        • plaintext : string - The data to be encrypted
        • key : string - Public key hex value for RSA encryption or secret key hex value for AES encryption
        • iv: string - AES encryption only. The hex value of the initial vector.
      • mandatory : yes

operation modes

  • AES encryption
    • mode : CBC
    • padding: PKCS#5
  • RSA public key encryption
    • padding: PKCS#1

callback

  • type : function - Callback function to be executed after the operation is completed
    • arguments:
      • err : contains the relevant error information
        • type : string
      • result: object - The result of the encrption. It contains the following properties:
        • ciphertext: Hex value of the encrypted data.

Examples

//generate an AES key first then encrypt some data
$fh.sec({
  act: 'keygen',
  params: {
    algorithm: "AES",
    keysize: 256
  }
}, function(err, keys) {
  if (err) {
    return console.log("Key generation failed: " + err);
  }
  var pt = "test";
  $fh.sec({
    act: 'encrypt',
    params: {
      algorithm: "AES",
      plaintext: pt,
      key: keys.secretkey,
      iv: keys.iv
    }
  }, function(err, result) {
    if (err) {
      return console.log("Encryption failed: " + err);
    }
    return console.log("Encrypted data is " + result.ciphertext);
  });
});

Data Decryption

options

  • type : object - A set of key/value pair to configure data decryption
  • keys
    • act
      • type : string - The operation to perform. Should be decrypt
      • mandatory : yes
    • params
      • type : object - The parameters for the operation
        • algorithm : string - The encryption algorithm. Both RSA and AES are supported
        • ciphertext : string - The data to be decrypted
        • key : string - Private key hex value for RSA decryption or secret key hex value for AES decrytion
        • iv: string - AES decryption only. The hex value of the initial vector.
      • mandatory : yes

operation modes

  • AES decryption
    • mode : CBC
    • padding: PKCS#5
  • RSA private key decryption
    • padding: PKCS#1

callback

  • type : function - Callback function to be executed after the operation is completed
    • arguments:
      • err : contains the relevant error information
        • type : string
      • result: object - object - The result of the decryption. It contains the following properties:
        • plaintext: Decrypted data in plain text

Examples

//generate an AES secret key
$fh.sec({
  act: 'keygen',
  params: {
    algorithm: "AES",
    keysize: 256
  }
}, function(err, keys) {
  if (err) {
    return console.log("Key generation failed: " + err);
  }
  //use the generated secret key to encrypt data
  var pt = "test";
  $fh.sec({
    act: 'encrypt',
    params: {
      algorithm: "AES",
      plaintext: pt,
      key: keys.secretkey,
      iv: keys.iv
    }
  }, function(err, result) {
    if (err) {
      return console.log("Encryption failed: " + err);
    }
    console.log("Encrypted data is " + result.ciphertext);
    //decrypt the encrypted data using the same secret key
    $fh.sec({
      act: 'decrypt',
      params: {
        algorithm: "AES",
        ciphertext: result.ciphertext,
        key: keys.secretkey,
        iv: keys.iv
      }
    }, function(err, result) {
      if (err) {
        return console.log("Decryption failed: " + err);
      }
      return console.log("Decryption data is " + result.plaintext);
    });
  });
});

Key Management

See Security Keys Management.