Code Explanation - S2

Let's have a look at the config.js and index.js files of S2.

config.js
'use strict';

module.exports = {
   type: 'service',		//either a service or a daemon
   prerequisites: {		//object that is used when deploying service or daemon in HA mode
      cpu: '',
      memory: ''
   },
   serviceVersion: 1,			//service version
    serviceName: "jsconf2",		//service name
    serviceGroup: "JSConf",		//service group
    servicePort: 4112,			//service port
    requestTimeout: 30,			//time needed before timeout
    requestTimeoutRenewal: 5,	//how many retires before giving up on the request
    extKeyRequired: true,		//set to true if the service is multi-tenant
	oauth: false,				//set to true if service is secured by oauth
    "errors": {					//object that contains the error codes of the service
       600: "Database Error"
    },
    "schema": {						//object that contains the APIs schema
        "/hello": {					//one API
            "_apiInfo": {		//API label
                "l": "Hello World",
                "group": "Hello",
                "groupMain": true
            },
           "name": {			//API input
              "source": ['query.name'],
              "required": false,
              "default": "John Doe",
              "validation": {
                 "type": "string"
              }
           },
            "email": {		//API input
                "source": ['query.email'],
                "required": true,
                "validation": {
                    "type": "string",
                    "format": "email"
                }
            }
        },
       "/standalone/add": {
          "_apiInfo":{
             "l": "Add Info to Standalone DB",
             "group": "Information",
             "groupMain": true
          },
          "username": {
             "source": ['body.username'],
             "required": true,
             "validation": {
                "type": "string",
                "minLength": 4,
                "maxLength": 8,
                "pattern": /^[a-zA-Z][0-9a-zA-Z_\-]+$/
             }
          },
          "name": {
             "source": ['body.name'],
             "required": false,
             "default": "anonymous",
             "validation": {
                "type": "string"
             }
          },
          "email": {
             "source": ['body.email'],
             "required": true,
             "validation": {
                "type": "array",
                "items": {
                   "type": "object",
                   "properties": {
                      "address": {"type": "string", "format": "email", "required": true},
                      "primary": {"type": "boolean", "required": true}
                   }
                },
                "minItems": 1,			//minimum number of items allows
                "maxItems": 5,			//maximum number of items allowed
                "uniqueItems": true		//set to true to prevent duplicates
             }
          }
       }
    }
};

A few noticeable differences from previous config files, we are specifying the minimum and maximum length for the username field. Not just that, SOAJS supports the use of regular expressions to determine whether or not an input is valid.

Another addition to this config file is the uniqueItems field. As the name suggests, this will allow or prevent duplicate input values.

index.js
'use strict';
var soajs = require('soajs');						//require soajs
var config = require('./config.js');
var jsconfSRV = new soajs.server.service(config);	//create new service instance

/**
 * Declare a global variable, usage is below
 */
var myMongo;

jsconfSRV.init(function () {						//initialize service

   jsconfSRV.get("/hello", function (req, res) {	//implement the API business logic

      var txt = req.soajs.inputmaskData.name + " <" + req.soajs.inputmaskData.email + "> ";

      return res.json(req.soajs.buildResponse(null, txt)); //generate API response
   });

   jsconfSRV.post("/standalone/add", function(req, res){

      if(!myMongo){
         /**
          * Initializing DB Connection
          */
         req.soajs.log.debug("Creating new DB connection to 'myDatabase' database."); //output to logs
         var dbConfiguration = req.soajs.registry.coreDB.myDatabase;
         myMongo = new soajs.mongo(dbConfiguration);
      }
      else{
         req.soajs.log.debug("Mongo Instance already created, reusing existing connection.");
      }

      /**
       * Formulating Document to insert
       */
      req.soajs.log.debug("Formulating new record: " + JSON.stringify(req.soajs.inputmaskData));
      var record = {
         'username': req.soajs.inputmaskData.username,
         'name': req.soajs.inputmaskData.name,
         'email': req.soajs.inputmaskData.email
      };

      myMongo.insert("data", record, true, function (error) {
         if (error) {
            req.soajs.log.error(error);
            return res.jsonp(req.soajs.buildResponse({'code': 600, 'msg': config.errors[600]}));
         }

         return res.json(req.soajs.buildResponse(null, true));
      });
   });

   jsconfSRV.start(); //start service
});

In addition to the "hello" route from S1, we see that we have a new route of type post.

In this service, we are adding the capability of saving a record to a Mongo database. 

We initialize a Mongo connector the first time, then reuse this connection for any subsequent Mongo request. 

SOAJS makes establishing a mongo connection so easy! We simply tell the framework the config of the database we want to connect to (That is saved in the dbConfiguration variable) and we then simply create a mongo connection with that variable!