2.3.26 • Published 6 years ago

jala-simple-web-service v2.3.26

Weekly downloads
4
License
COMMERCIAL
Repository
-
Last release
6 years ago

Simple Web Service

The easiest way to implement web services on Node. All infrastructure to deploy a web service is ready to use.

Prerequisites

  • Node: ^6.2.1
  • Npm: ^3.9.3

Installation

  $> npm --registry http://10.31.2.174:4873 install jala-simple-web-service --save

Available Features

  • It is possible to add components, they must be organized in folders inside folder called: components.
  • It is possible to register ExpressJs middleware. For doing it you should have a folder called: boot-express.
  • It is possible to register custom components (own modules or utilitaries).
  • It is possible to use library components ($logger, $expressRouter).
  • It is possible to get component's objects in any place.
  • It is possible use lambda expression in the component routers.

Available Modules

How to use

Include the jala-simple-web-service in your main file. A file structure of custom web service will looks like, the components will be loaded in name order:

my-web-service/
  ├── lib/
  |   ├── boot-express
  |   │   └── contex.js
  |   └── components
  |       ├── employees
  |       │   └── index.js
  |       └── system
  |           └── index.js
  ├── README.md
  ├── LICENSE
  ├── index.js
  ├── .eslintrc
  ├── .editorconfig
  ├── package.json
  └── .gitignore

Options to start service

  • port: setting service port by default is 3000
  • protocol: service protocol by default is http without security
  • middlewarePath: custom middleware path, it can be single string or an array of string paths.
  • componentsPath: custom components path, it can be single string or an array of string paths.
  • maximumRequestBodySize: controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. by defaults to '100kb'
  • secure: self-signed certificates
    • key: Buffer of key
    • cert: Buffer of certificate

To initialize the web service you should include the jala-simple-web-service library in your main file:

// my-web-service/index.js
const fs = require('fs');
const server = require('jala-simple-web-service');

const options = {
  port: {SERVICE_PORT},
  protocol: "https",
  secure: {
    key: fs.readFileSync({YOUR_KEY_PATH}),
    cert: fs.readFileSync({YOUR_CERT_PATH})
  },
  maximumRequestBodySize: '5mb'
}
// starts web service
server.start(options);

To register ExpressJs middleware you should include the following code:

// my-web-service/lib/boot-express/contex.js
const application = require('jala-simple-web-service').App;
// if you not define route path by default is '/',
// the callback has access to req, res and next by using 'this' scope (example: this.req, this.res, this.next),
//can also get the entity objects by setting them up as parameter in the callback function.
application
  .middleware(function(systemObject) {
    this.req.context = {
      userId: '772F1677-B3EC-4642-A362-EAAA36813CBD'
    };

    systemObject.getUptime()
      .then(response => console.info(response))
      .catch(error => console.error(error));
    
    this.next();
  });

To register a custom module (own libraries), you should include the following code:

// my-web-service/lib/boot-express/custom-date.js
const application = require('jala-simple-web-service').App

// to register a utility
application.module('customDate', Date);

To get utilities, you should include the following code in any place:

const application = require('jala-simple-web-service').App

let customDate = application.module('customDate');
let logger = application.module('$logger');

To initialize the component you should include the following code:

// my-web-service/lib/components/employees/index.js
const application = require('jala-simple-web-service').App
// define system object entity
class EmployeeObject {
  validateSession() {
    return new Promise((resolve, reject) => {
      resolve({});
    });
  }
  getAll() {
    return new Promise((resolve, reject) => {
      resolve([{
        name: 'Isacc',
        lastName: 'Newton'
      }]);
    });
  }
};
// setting component employee's artefacts
application.component('employee', [])
  .objects('employeeObject', EmployeeObject);
  .router(function($expressRouter, $logger, $httpStatus, employeeObject) {
    $expressRouter.get('/employees', function(req, res) {
      employeeObject.getAll()
        .then(users => {
          $logger.info('[get-employee]', 'Returns users:', users);
          res.status($httpStatus.OK).send(users);
        })
        .catch(error => res.status($httpStatus.INTERNAL_SERVER_ERROR).send(error.message));
    });
    return $expressRouter;
  });
// my-web-service/lib/components/system/index.js
const application = require('jala-simple-web-service').App
// define system object entity
class SystemObject {
  constructor() {
    this.employeeObject = null;
  }
  getUptime() {
    return new Promise((resolve, reject) => {
      this.employeeObject.validateSession()
        .then(() => resolve(process.uptime())
        .catch(error => reject(error));
    });
  }
  set Employee(employeeObject) {
    this.employeeObject = employeeObject;
  }
};
// setting component system's artefacts, can also set component dependencies.
application.component('system', ['employee'])
  .constant('HELLO', 'Hello')
  .constant('WORLD', 'world')
  .objects('systemObject', SystemObject, {Employee: 'employeeObject'})
  .router(($expressRouter, $logger, $httpStatus, systemObject, HELLO, WORLD, customDate) => {
    $expressRouter.get('/system', function(req, res) {
    systemObject.getUptime()
      .then(processUptime => {
        $logger.info('[get-uptime]', 'Returns process uptime:', processUptime, HELLO, WORLD);
        res.status($httpStatus.OK).send({
          date: new customDate(),
          uptime: processUptime
        });
      })
      .catch(error => res.status($httpStatus.INTERNAL_SERVER_ERROR).send(error.message));
    });
    return $expressRouter;
  });

Executed this URL on navigator.

  https://{SERVICE_HOST}:{SERVICE_PORT}/api/system

Enjoy this simple app, for more information you could review the example.

Environment development

  • Install dependencies
$> npm install
$> npm install gulp-cli -g
  • Shows availables gulp task:
gulp help