Chinese Documentation : Tutorial: push notifications - LoopBack app

This is part one of a four-part tutorial on setting up a mobile application on Amazon EC2 that can send push notification to iOS and Android client applications.  This article (part one) shows how to use the slc command-line tool to create a LoopBack application running on Amazon EC2 to send push notifications.

Overview 

Push notifications enable server applications (known as providers in push parlance) to send information to mobile apps even when the app isn’t in use.  The device displays the information using a "badge," alert, or pop up message.  A push notification uses the service provided by the device's operating system:

  • iOS - Apple Push Notification service (APNS)
  • Android - Google Cloud Messaging (GCM)

For an overview of the LoopBack Push Notification component, see Push notifications.

Prerequisites

Before starting this tutorial:

Set up mobile backend server on Amazon

Launch the instance 

  1. To follow along you will need to have an Amazon AWS account.
  2. To find the StrongLoop AMI, simply log into the AWS Console and select “EC2.” Browse images by selecting “AMIs” under the “Images” drop down.  Make sure the filtering shows “Public Images” , “All Images” and “All Platforms”.  From here you can simply search “StrongLoop" and select the latest version. Current - StrongLoop-slc v2.5.2 (node v0.10.26)
  3. Launch a new instance from the console using this AMI. Once the instance is up and running, you can remote ssh into your newly created server instance using the same ec2-keypair and the machine instance ID. 

    $ssh -i ec2-keypair ec2-user@ec2-54-222-22-59.us-west-1.compute.amazonaws.com

Create the application

Icon

StrongLoop Controller (slc) and MongoDB are pre-installed in the StrongLoop AMI. To run MongoDB, use ~/mongodb/bin/mongod &. You may need to use sudo

 

  1. Use the slc loopback command to create a LoopBack application:

    $ slc loopback
    [?] Enter a directory name where to create the project: push
    [?] What's the name of your application? push
  2. Add the loopback-component-push and loopback-connector-mongodb modules as dependencies in package.json:

     "dependencies": {
        "loopback": "~1.7.0",
        "loopback-component-push": "~1.2.0",
        "loopback-connector-mongodb": "~1.2.0"
      },
  3. Install dependencies:

     npm install 
  4. Add the mongo connection string in /server/datasources.json:

     "db": {
        "defaultForType": "db",
        "connector": "mongodb",
        "url": "mongodb://localhost/demo"
      },

    Try it with an example

    Icon

    To try out an example, you can replace the server.js file in your application with this. You will also need the model-config.js file to save your configurations. Alternatively, to enable push notifications for your own application using the loopback-component-push module, follow the steps below (5-8)

  5. Create a push model 

    1. To send push notifications, you must create a push model.  The code below illustrates how to do this with a database as the data source. The database is used to load and store the corresponding application/user/installation models.

       

      var loopback = require('loopback');
      var app = loopback();
      ...
      var Notification = app.models.notification;
      var Application = app.models.application;
      var PushModel = app.models.push;
      
  6. Register a mobile(client) application

    1. The mobile application needs to register with LoopBack so it can have an identity for the application and corresponding settings for push services. Use the Application model's register() function for sign-up. 

      For information on getting API keys, see:

       

      Application.register('put your developer id here',
          'put your unique application name here',
          {
            description: 'LoopBack Push Notification Demo Application',
            pushSettings: {
              apns: {
                certData: readCredentialsFile('apns_cert_dev.pem'),
                keyData: readCredentialsFile('apns_key_dev.pem'),
       
                pushOptions: {
                },
                feedbackOptions: {
                  batchFeedback: true,
                  interval: 300
                }
              },
              gcm: {
                serverApiKey: 'your GCM server API Key'
              }
            }
          },
          function(err, app) {
            if (err) return cb(err);
            return cb(null, app);
          }
        );
       
      function readCredentialsFile(name) {
       return fs.readFileSync(
         path.resolve(__dirname, 'credentials', name),
         'UTF-8'
       );
      }
  7.  Register a mobile device

    1. The mobile device also needs to register itself with the backend using the Installation model and APIs. To register a device from the server side, call theInstallation.create() function, as shown in the following example:

      Installation.create({
          appId: 'MyLoopBackApp',
          userId: 'raymond',
          deviceToken: '756244503c9f95b49d7ff82120dc193ca1e3a7cb56f60c2ef2a19241e8f33305',
          deviceType: 'ios',
          created: new Date(),
          modified: new Date(),
          status: 'Active'
      }, function (err, result) {
          console.log('Registration record is created: ', result);
      });

      Most likely, the mobile application registers the device with LoopBack using REST APIs or SDKs from the client side, for example

      POST http://localhost:3010/api/installations
          {
              "appId": "MyLoopBackApp",
              "userId": "raymond",
              "deviceToken": "756244503c9f95b49d7ff82120dc193ca1e3a7cb56f60c2ef2a19241e8f33305",
              "deviceType": "ios"
          }

     

  8. Send push notifications

    1. Send out the push notification

      LoopBack provides two Node.js methods to select devices and send notifications to them:

      • notifyById(): Select a device by registration ID and send a notification to it.
      • notifyByQuery(): Get a list of devices using a query (same as the where property for Installation.find()) and send a notification to all of them.

      For example, the code below creates a custom endpoint to send out a dummy notification for the selected device:

       

      var badge = 1;app.post('/notify/:id', function (req, res, next) {
       var note = new Notification({
         expirationInterval: 3600, // Expires 1 hour from now.
         badge: badge++,
         sound: 'ping.aiff',
         alert: '\uD83D\uDCE7 \u2709 ' + 'Hello',
         messageFrom: 'Ray'
       });
       
       PushModel.notifyById(req.params.id, note, function(err) {
         if (err) {
           // let the default error handling middleware
           // report the error in an appropriate way
           return next(err);
         }
         console.log('pushing notification to %j', req.params.id);
         res.send(200, 'OK');
       });
      });
      

       

      To select a list of devices by query, use the PushModel.notifyByQuery(), for example:

      PushModel.notifyByQuery({userId: {inq: selectedUserIds}}, note, function(err) {   console.log('pushing notification to %j', selectedUserIds);
       });

Next steps

  • To setup and create an Android app to receive push notifications go to Part two
  • To setup and create an iOS app to receive push notifications go to Part three 
  • To use LoopBack's swagger REST API and send/receive push notifications on your Android and iOS devices got to Part four 

Attachments:

EC2.png (image/png)