Accessing Axway Mobile Backend Service (MBS) from a Node.js Application

0 Flares 0 Flares ×

The Axway Appcelerator MBS also referred to as MBaaS (Mobile Backend as a Service), is a feature-rich set of over 20 cloud services for use with mobile applications, including Push Notification, Geofencing, Photo Storage, File Storage and a Database as a Service (DaaS). All services are accessible via a REST API. You can read more about the MBS here.

The services are intended for mobile applications, hence most of the time you will be making calls to the MBS from a mobile app. As such, there are client SDKs for Titanium, iOS and Android. But, you will also want to access the MBS from a non-mobile application, such as a CRM or other back office application. For example, when a marketing promotion is initiated, you may want to cause push notifications to be sent to one, some or all mobile app users. A back office app would need to do this. As such, a Node.js SDK is provided.

This blog post will describe how to use the Node.js SDK to access the MBS from a Node.js app.

Overview

The basic steps for accessing the MBS from Node.js are described below:

  1. Create an MBS App if you don’t already have one and get the app keys
  2. Install arrowbd npm in your Node.js project
  3. Use the MBS App Key and initialize an arrowdb instance
  4. Login to the MBS using the userLogin() method and a preexisting user account
  5. Access the MBS services using the methods as described in the online docs

Get The MBS App Keys


If you have a Titanium App already
Currently, when you create a Titanium application, a corresponding MBS app, with the same name is created automatically. In this case, you can find the App Keys in the Titanium tiapp.xml file. You can also find the MBS App Keys by going to the MBS app in the platform dashboard at https://platform.axway.com/ and clicking on Go To Dashboard. You will then see a list of all of your applications (Titanium, MBS, API Builder, …). If the list of applications is large, you can click on the Apps button in the navigation bar and enter the MBS app name as shown below.


MBS apps are denoted by the Type Mobile Backend Service in the app list. Also, MBS apps have a cloud+database icon.

Click on your MBS app.


If you don’t have a Titanium App already
If you don’t have a Titanium app or an existing MBS app, you can create one in the dashboard by clicking on the + button in the navigation bar and select Create Mobile Backend Services Datasource as shown below.


Follow the prompt to name your app and you will be brought to the MBS app main page as shown below.



Find your App Keys
Click on the Configuration button (on the left) to see your App Keys for Development and Production as shown below.



You will need these to continue.

Install arrowdb npm in your Node.js project

Either create a new Node.js app or go to your existing Node.js app and install the arrowdb npm using:

npm install arrowdb

Edit your Node.js app and add the following lines:

var ArrowDB = require('arrowdb'),
 arrowDBApp = new ArrowDB(<YOUR MBS APP KEY>);

Login to the MBS

In order to make MBS calls, you need to have your app login (as a user of the MBS). The most straightforward way to do this is to use the platform dashboard and create a user.

Click on the Manage Data navigation button as follows:


Note: make sure you select Production or Development appropriately depending on which environment you are connecting to.

Click on Users link on the lower right-hand side of the list of objects to navigate to the Users page.


Click on the Create User button in the top right-hand corner and fill in the username, password and email address. You may want to make the user an admin as several MBS features are only accessible to admin users. For now, we can leave as a non admin user. Note that the user I am creating has a username of ‘a’ and a password of ‘1234’. Click Save Changes.


Now that we have a user, let’s log in using the code fragment provided in the MBS User online docs and the user we created above by editing our Node.js project’s index.js file as follows:

var ArrowDB = require('arrowdb'),
    arrowDBApp = new ArrowDB('VzkVRbN7SlBJaDWQyYuXNcX9FMIYU2Aw');
arrowDBApp.usersLogin({
    login: 'a',
    password: '1234'
}, function(err, result) {
    if (err) {
        console.error(err.message);
    } else {
        console.log(result.body.response.users[0]);
    }
});

Note: you will need to click on the Node.js SDK tab in the code samples section of the docs

Run the node app by typing node index.js in your terminal and view the console, which should look similar to the following:

{ id: '5baa8a0693fb03022010ae6a',
created_at: '2018-09-25T19:18:30+0000',
updated_at: '2018-09-25T21:00:04+0000',
external_accounts: [],
confirmed_at: '2018-09-25T19:18:30+0000',
username: 'a',
email: 'a@a.com',
admin: 'false',
stats: { photos: { total_count: 0 }, storage: { used: 0 } },
friend_counts: { requests: 0, friends: 0 } }

You can see the valid response which returns details for the logged in user.

Access the MBS Services

We’ve actually already accessed the MBS User service but let’s use another service. If the user logs in properly, let’s upload a photo and then let’s retrieve a list of photos. We’ll use the Photos Create and Photos Query methods. In the success callback of the usersLogin() method, we’ll make a call to the photosCreate() method.

If we look at the code sample for photosCreate, we see it’s quite simple:

fs = require('fs');
arrowDBApp.photosCreate({
    photo: fs.createReadStream('photo.jpg')
}, function(err, result) {
    if (err) {
        console.error(err.message);
    } else {
        console.log(result.body.response.photos[0]);
    }
});

We’ll need to include a photo.jpg in our project folder. Also, I’ll wrap the code above in a callable method, called uploadPhoto(). Our index.js is now as follows:

var ArrowDB = require('arrowdb'),
    arrowDBApp = new ArrowDB('VzkVRbN7SlBJaDWQyYuXNcX9FMIYU2Aw');

arrowDBApp.usersLogin({
    login: 'a',
    password: '1234'
}, function(err, result) {
    if (err) {
        console.error(err.message);
    } else {
        console.log(result.body.response.users[0]);
        uploadPhoto();
    }
});

function uploadPhoto() {
  fs = require('fs');
  arrowDBApp.photosCreate({
      photo: fs.createReadStream('photo.jpg')
  }, function(err, result) {
      if (err) {
          console.error(err.message);
      } else {
          console.log(result.body.response.photos[0]);
      }
  });
}

Run this by typing node index.js in terminal. The console should look like:

{ id: '5baa8a0693fb03022010ae6a',
  created_at: '2018-09-25T19:18:30+0000',
  updated_at: '2018-09-26T15:53:05+0000',
  external_accounts: [],
  confirmed_at: '2018-09-25T19:18:30+0000',
  username: 'a',
  email: 'a@a.com',
  admin: 'false',
  stats: { photos: { total_count: 0 }, storage: { used: 0 } },
  friend_counts: { requests: 0, friends: 0 } }
{ id: '5babab62625c1b0219187822',
  filename: 'photo.jpg',
  size: 198318,
  md5: '8072e917205c41813a5ac677b1309bae',
  created_at: '2018-09-26T15:53:07+0000',
  updated_at: '2018-09-26T15:53:07+0000',
  processed: false,
  content_type: 'image/jpeg',
  user_id: '5baa8a0693fb03022010ae6a' }

You can see that the reply from the photosCreate indicates that the photo was uploaded properly. If we go back to the dashboard and click on Manage Data we can see 1 photo object where we had zero before.

Click on the Photo link and see the photo in the list and expand it as follows:


You can view the image if you click on the Original link.


Note that your image is most likely different, but not as beautiful as mine 🙂

Now, let’s retrieve a list of photos after we upload our photo. We’ll use the photosQuery for this. The code sample provided in the online docs is as follows:

arrowDBApp.photosQuery({
    limit: 10,
    where: {
        coordinates: {
            '$nearSphere': [-122.23,37.12],
            '$maxDistance': 0.00126
        }
    }
}, function(err, result) {
    if (err) {
        console.error(err.message);
    } else {
        result.body.response.photos.forEach(function (photo) {
            console.log(photo);
        });
    }
});

The query above looks for 10 (limit:10) photos that are within a certain radius of a location. We’re not going to do a geo search, but we’ll just get up to the last 10 uploaded photos. Also, we’ll wrap the code in a method called getPhotos() and call it from the uploadPhoto() method. I’m also going to comment out the userLogin() and uploadPhoto() console logging and only print the photosQuery() console logging.

The index.js file now looks like the following:


var ArrowDB = require('arrowdb'),
    arrowDBApp = new ArrowDB('VzkVRbN7SlBJaDWQyYuXNcX9FMIYU2Aw');

arrowDBApp.usersLogin({
    login: 'a',
    password: '1234'
}, function(err, result) {
    if (err) {
        console.error(err.message);
    } else {
        // console.log(result.body.response.users[0]);
        uploadPhoto();
    }
});

function uploadPhoto() {
  fs = require('fs');
  arrowDBApp.photosCreate({
      photo: fs.createReadStream('photo.jpg')
  }, function(err, result) {
      if (err) {
          console.error(err.message);
      } else {
          // console.log(result.body.response.photos[0]);
          getPhotos();
      }
  });
}

function getPhotos() {
  arrowDBApp.photosQuery({
    limit: 10
  }, function(err, result) {
    if (err) {
      console.error(err.message);
    } else {
      result.body.response.photos.forEach(function (photo) {
        console.log(photo);
      });
    }
  });
}

When I run the Node.js project I get the following console logging, which shows the two uploaded photos:

{ id: '5babb0c1b6d895022016b894',
  filename: 'photo.jpg',
  size: 198318,
  md5: '8072e917205c41813a5ac677b1309bae',
  created_at: '2018-09-26T16:16:01+0000',
  updated_at: '2018-09-26T16:16:01+0000',
  processed: false,
  content_type: 'image/jpeg',
  user_id: '5baa8a0693fb03022010ae6a' }
{ id: '5babb0b9eb0ec602191967e7',
  filename: 'photo.jpg',
  size: 198318,
  md5: '8072e917205c41813a5ac677b1309bae',
  created_at: '2018-09-26T16:15:54+0000',
  updated_at: '2018-09-26T16:15:54+0000',
  processed: true,
  urls:
   { original: 'https://s3-us-west-1.amazonaws.com/storage-platform.cloud.appcelerator.com/CHftZFD3VPkMuUlxIy4rX9JhPBa9d3t5/photos/9b/ae/5babb0baeb0ec602191967e8/photo_original.jpg' },
  content_type: 'image/jpeg',
  user_id: '5baa8a0693fb03022010ae6a' }

Conclusion

In this blog post, we saw how easy it is to access the Axway MBS from a Node.js app. We simply need the App Key for our MBS application – and then we can copy and paste from the code samples provided for each service method.

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 0 Flares ×

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign up for our blog!

computer and tablet showing Appcelerator software
Start free, grow from there.
0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 0 Flares ×