Examples

Soon or later you will need to add your own service to the ecosystem, and Microbase is build on top of a a small framework developed as a Node.js module to define and call services, and give basic utilities like config, logging, jobs, cache and MongoDB access. It really can be used as a base to implement any application with a microservices style architecture.

The following examples can be found in the examples folder.

Create a project from scratch

Be sure to have followed the instructions to create the NPM repository environment variables as described here

Create a new directory, create a project and install microbase:

cd /tmp
mkdir test
cd test
npm init
npm i -S microbase

Create the service entrypoint

Create an index.js file with the following content:

cat >index.js<<EOF
const MicroBase = require('microbase');
const base = new MicroBase({
  configPaths: [{
    servicePath: __dirname
  }]
});
EOF

Create the configuration files

Create a default configuration file under the config directory

mkdir config
cat >config/defaults.json<<EOF
{
  "services": {
    "name": "test",
    "version": "v1",
    "style": "RPC"
  }
}
EOF

Create another configuration file to be used only in the local development environment

cat >config/development.json<<EOF
{
  "logger": {
    "level": "debug"
  }
}
EOF

Implement an operation

Ceate a file under the operations directory

mkdir operations
cat >operations/vat.js<<EOF
module.exports = class {
  constructor(base) {
    this.base = base;
    this.logger = base.logger;
  }
  handler(params, reply) {
    if (!params.gross) {
      return reply(this.base.utils.genericResponse(null, this.base.utils.Error('gross_not_provided')));
    }
    return reply(this.base.utils.genericResponse({ 
      gross: params.gross,
      vat: params.gross * 0.21 
    }));
  }
}
EOF

Start the application

node index.js

Access the service operations

Make a call to the operation using curl

curl --request POST \
  --url http://localhost:3000/services/test/v1/vat \
  --header 'content-type: application/json' \
  --header 'accept: application/json' \
  --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL21pY3JvYmFzZS5pbyIsInN1YiI6ImNsaWVudC9pbnRlcm5hbCIsInNjb3BlIjpbIklOVEVSTkFMIl0sImp0aSI6IjgyM2Y1MjY2LWEzYjEtNDkzNi1hMDk4LTc1Y2EzYzJlMmZmZSIsImlhdCI6MTQ5ODIwNTUwMX0.z3z2U_xTSSkLbB2e6WqV7ipidvGny7x6bZVm-mxMbU4' \
  --data '{"gross": 100}'

Verify the response

{
  "ok": "true",
  "gross": 100,
  "vat": 21
}

eComm service extension

If you want to extend an eComm service (like the Catalog Service) you need to require the service and instantiate it adding your confguration folder.

const Service = require('micro-catalog-service');
const service = new Service()
  .addConfigPath('appPath', __dirname)
  .init();