stackmobconnect

a REST based node.js StackMob client.

npm install stackmobconnect
4 downloads in the last week
8 downloads in the last month

StackMobConnect -- a REST based node.js StackMob client

Install

From npm (recommended):

$ npm install stackmobconnect

From source:

$ git clone git@github.com:jonasonline/StackMobConnect.git
$ cd StackMobConnect
$ npm install

Background

StackMob is a cloud based backend service. It makes storing data and authenticating users in web and mobile applications simple and it comes with a very attractive price tag.

StackMobConnect makes it easy to authenticate against StackMob backend and to store, update and retrieve data using the StackMob REST api.

The HTTP methods (GET, PUT, POST and DELETE) are wrapped inside javascript functions which accepts input in the form of an "options" object and a callback function.

Functions

authorize(version, publicKey, userAgent, userName, password, callback)

Use this function to use OAuth 2.0. Callback should return "access token" and "MAC key". For more information, see StackMob REST API Reference.

get(options, callback)

possible keys (properties) in options object

  • entityName -- required -- The name of the entity
  • primaryKey -- optional -- The key for the object
  • filter -- optional -- search filters, see https://developer.stackmob.com/sdks/rest/api#a-get_-_expanding_relationships:_get_full_objects__not_just_ids
  • expandRelatedObjects -- optional -- includes related objects instead of just primary keys. Defined as level 1 - 3.
  • selectFields -- optional -- return only defined fields
  • orderBy -- optional -- sort order
  • range -- optional -- enables pagination by defining a range of objects to return
  • environmentVersion -- required -- defines which version of the backend to be used, ex. 0 = dev, 1 = prod
  • publicAPIKey -- required -- your public api key
  • access_token -- optional -- include access token to use OAuth2
  • MAC_key -- optional -- include MAC_Key to use OAuth2

post(options, callback)

possible keys (properties) in options object

  • entityName -- required -- The name of the entity
  • primaryKey -- optional -- The key for the object
  • environmentVersion -- required -- defines which version of the backend to be used, ex. 0 = dev, 1 = prod
  • StackMobRelations -- optional -- defines relations between schema and object in a json tree. For example 'author=user' explains that the field author relates to the schema 'user'. IMPORTANT! Use lower case letters for names.
  • publicAPIKey -- required -- your public api key
  • access_token -- optional -- include access token to use OAuth2
  • MAC_key -- optional -- include MAC_Key to use OAuth2

put(options, callback)

possible keys (properties) in options object

  • entityName -- required -- The name of the entity
  • primaryKey -- optional -- The key for the object
  • environmentVersion -- required -- defines which version of the backend to be used, ex. 0 = dev, 1 = prod
  • publicAPIKey -- required -- your public api key
  • access_token -- optional -- include access token to use OAuth2
  • MAC_key -- optional -- include MAC_Key to use OAuth2

del(options, callback)

possible keys (properties) in options object

  • entityName -- required -- The name of the entity
  • primaryKey -- optional -- The key for the object
  • environmentVersion -- required -- defines which version of the backend to be used, ex. 0 = dev, 1 = prod
  • publicAPIKey -- required -- your public api key
  • access_token -- optional -- include access token to use OAuth2
  • MAC_key -- optional -- include MAC_Key to use OAuth2
  • filter -- optional -- search filters, see https://developer.stackmob.com/sdks/rest/api#a-get_-_expanding_relationships:_get_full_objects__not_just_ids
  • cascadeDelete -- optional -- Deletes related entities default is "true"
  • relatedFieldName -- optional -- Name of the relation
  • listOfItemsToDelete -- optional -- List of related items to delete

Examples

The examples below requires that you have stackmobconnect installed as a module in your project folder. For more information on modules see: npmjs.org npm cheatsheet

GET with filter, using OAuth 2.0

Here is an example on how send a GET request with a filter using OAuth 2.0.

var stackMob = require('stackmobconnect').stackMob;
var testUserName = 'a username';
var testPassword = 'a password';
var stackMobPublicAPIKey = 'a public StackMob API key';
stackMob.authorize(0, stackMobPublicAPIKey, 0, testUserName, testPassword, function(err, response, body){
    if(err) return err;
    var objResponse = JSON.parse(body);
    stackmobAccessToken = objResponse.access_token;
    stackmobMacKey = objResponse.mac_key;
    var options = { 
        entityName: 'TestEntity',
        environmentVersion: 0,
        publicAPIKey: stackMobPublicAPIKey,
        access_token: stackmobAccessToken,
        MAC_key: stackmobMacKey,
        filter: 'title=TestTitle3' };
        stackMob.get(options, function(err, response){
            response.should.have.status(200);
        });
});

For more basic examples see test suits in the repository test folder.

Using StackMobConnect with IronWorker

This example shows how to use StackMobConnect with IronWorker. IronWorker is a great service from Iron.io. It enables you to schedule programs (workers) to run on iron.io's servers. This makes it really easy to, for example, automate loading of data into the StackMob data store from different sources. In this example we will store tweets from your Twitter home timeline in your backend on StackMob. Don't ask me why you would want to do that but there are people who collect stranger and mote useless stuff than that so why not...

This example requires that you have Ruby 1.9 installed on your computer. It also requires that you register as a developer at https://dev.twitter.com and register an application for this test purpose.

Create new application

Log in to Stackmob and create a new application. Add a new user to the application. This user account will be used when connecting to Stackmob. Go to the applications modules and add "IronWorker". Follow the guide to register at iron.io and create a new project for your worker.

Install CLI

Install the IronWorker Command Line Interface.

$ gem install iron_worker_ng

Create the worker

Create a new folder for your worker. In this example we will call the test application "TwitterHarvester". In that folder, create a file called iron.json with the following content :

{
"project_id": "INSERT YOUR IRONWORKER PROJECT ID HERE",
"token": "INSERT YOUR IRONWORKER TOKEN HERE"
}

Create a file called TwitterHarvester.worker with the following content:

runtime "node"
exec "TwitterHarvester.js"
dir "node_modules"

Create a file called TwitterHarvester.js with the following content and paste in your credentials from Stackmob and Twitter:

var stackMob = require('stackmobconnect').stackMob;
var twitter = require('ntwitter');

//Replace with your credentials
var testUserName = 'Your Stackmob user account';
var testPassword = 'The password for your Stackmob user account';
var stackMobPublicAPIKey = 'Your public Stackmob API key';

//Replace with your credentials
var twit = new twitter({
    consumer_key: 'Your Twitter consumer key',
    consumer_secret: 'Your Twitter consumer secret',
    access_token_key: 'Your Twitter access token key',
    access_token_secret: 'Your Twitter access token secret'
});

twit.getHomeTimeline(null, function(err, data) {
    if(!err){
        var listOfTweetsToStore = [];
        for(var itemNo in data){
            nextTweet = null;
            nextTweet = {
                tweets_id: data[itemNo].id.toString(),
                Name: data[itemNo].user.name,
                text: data[itemNo].text,
                creationDateTime: data[itemNo].created_at
            }
        listOfTweetsToStore.push(nextTweet);
    }

    stackMob.authorize(0, stackMobPublicAPIKey, 0, testUserName, testPassword, function(err, response, body){
        if(!err){
            var objResponse = JSON.parse(body);
            var stackmobAccessToken = objResponse.access_token;
            var stackmobMacKey = objResponse.mac_key;
            var options = { 
                entityName: 'Tweets',
                entityJSONObject: listOfTweetsToStore,
                environmentVersion: 0,
                publicAPIKey: stackMobPublicAPIKey,
                access_token: stackmobAccessToken,
                MAC_key: stackmobMacKey 
                };
            stackMob.post(options, function(err, response, body){
                console.log(body)
            });
        }
    });
}
});

Install dependencies

Before we can upload the worker we need to install the modules we depend on. From your worker folder run:

$ npm install stackmobconnect
$ npm install ntwitter

Upload the worker

From your worker folder run:

$ iron_worker upload TwitterHarvester

Try the worker

$ iron_worker queue TwitterHarvester

Now log in to the Iron.io dashboard and view the workers for your test project. Under "tasks" you can see some statistics for our new worker and hopefully you see one successfully completed execution. Log in to your Stackmob dashboard and view your collected tweets. The "tweets" schema was automatically created because we used the development environment. For production use I recommend that you create the schemas manually and set adequate permissions. You can read more about scheduling of IronWorker tasks on the Iron.io Dev Center.

Tests

The repository contains a number of unit tests. The test framework used for the tests is mocha and should. There are far from complete code coverage but there are tests for essential cases. Don't hesitate to contribute with more tests... Or any code for that matter...

Running the tests

To run the tests, first go to the stackmobconnect folder and install the developer dependencies

$ npm install

Then paste credentials for your Stackmob account and a user account from your database into the file TestSuit01.js in the "test" folder

var testUserName = 'a username';
var testPassword = 'a password';
var stackMobPublicAPIKey = 'a StackMob public API key';

Now you can run the tests.

$ make test

Contact

Any questions? Send me an email or ping me on twitter!

npm loves you