Code Explanation - S1
Introduction
The following page provides samples and code walkthrough for both the config.js and the index.js that together make up the S1 service.
Configuration File
This file contains the configuration needed to register a service in SOAJS, and to instruct the IMFV engine of mechanism to use to fetch and validate inputs during runtime for the APIs being invoked.
'use strict'; module.exports = { type: 'service', //either service or deamon prerequisites: { //object that is used when deploying the service or daemon in HA mode cpu: '', memory: '' }, serviceVersion: 1, //service version serviceName: "jsconf1", //service name serviceGroup: "JSConf", //service group name servicePort: 4111, //service port requestTimeout: 30, //time needed before timeout requestTimeoutRenewal: 5, //how many retries before eventually giving up on the request extKeyRequired: false, //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 schema: { //object that contains the APIs schema "/hello": { //one API "_apiInfo": { //API labels "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" } } } } };
The above defines a service that listens on port 4111, and does not require a tenant key or an access token to be accessible.
The service has one API "hello", that accepts up to 2 parameters name and email. we also see that he name parameter has a default value.
Index File
This file contains the service code. Here you create a new SOAJS service instance, pass on the above configuration file and write the business logic for the APIs you defined in config.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 jsconfSRV.init(function () { //initialize the 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.start(); //Start the service });
The business logic of this API reads 2 inputs from the IMFV engine, formulates a string message and returns it in the response.
Notice how easy it is to read inputs from the IMFV engine since they are both consolidated in the same inputmaskData object.
Also notice that even if the name input is not provided, we still treat the code as if it is since the IMFV will provide us with the default value in this case.