microsjs

The simple functional NodeJS microservice framework.

Usage no npm install needed!

<script type="module">
  import microsjs from 'https://cdn.skypack.dev/microsjs';
</script>

README

microsjs

Easy microservices
The simple functional NodeJS microservice framework.

Table of Contents

Features

  • object validation: easily verify that data called to a service matches a schema
  • configurable: specify how you want your service to run
  • small api: create commands with only 3 lines of code
  • event based: update your interface as commands are being processed
  • integratable: all you need is an object

Installation

$ npm install microsjs

Guide

At its core, microsjs follows a simple setup. Each service has a configuration object which tells it what commands can be called, and what objects are available to be validated. These are separated into two sections: objects and messaging.

The Configuration object

Each object uses JSON schema in order to validate. They each need their own unique identifier, but you can choose to validate it however you would like using a schema.

"objects": {
    "Email": { "type": "string", "pattern": "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}quot; }
}

To keep everything tidy, you can reference an object from inside of an object by using a prefix.

"objects": {
    "Email": { "type": "string", "pattern": "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}quot; },
    "User": {
        "type": "object",
        "properties": {
            "email": ":Email",  // <--
            "password": { "type": "string", "optional": true }
        }
    }
}

Defining commands and events are just as simple as defining objects. It should be noted that messages must follow this pattern.

command(argument: Object, second)

arg argument will be validated against the Object object.

arg second doesn't have a set object, so the service will only check that it is not undefined.

In the configuration object, every command must have an event. The arguments that are called to a command will be validated according to the arguments. Same goes for the event when the callback function is called.

"messaging": {
    "registerUser(user: User, password)": {                // <-- will be validated in call
        "event": "registerUserResponse(response: string)"  // <-- will be validated in callback
    }
}

The Service Class

Now that you have the configuration, you only need the class to finish this service. You can use super to link a configuration file, or just a normal object.

var ms = require('microsjs')

class MyService extends ms {
    constructor() {
        super('./path/to/config.file')
    }
}

Then, you need to define the business logic for each command.

    registerUser(event, callback) {
        // ..
        callback('Registered user with email' + event.user.email + '!')
        // registerUserResponse(response: string)
    }

event is the arguments that will be passed into the command which are given as they are called.

callback is the function that should be called when the function is completed.

In some special cases, you can update the status of a message call and display it however you would like. This is especially handy for things like model training or tasks that take a long time to execute.

    registerUser(event, callback) {
        // ..
        callback.update('50% complete')
        // ..
        callback('Registered user with email' + event.user.email + '!')
    }

Finally, you need to register the function to the specified command.

    constructor() {
        super('./path/to/config.file')
        this.register(this.registerUser, 'registerUser')
    }

Calling the Service

The two different ways you can call a service is by using ms.call() and ms.promiseCall() which can be called like this.

// registerUser(user: User, password)
ms.call({
    registerUser: {
        user: {
            email: 'guy@gmail.com',
            password: ''
        },
        password: 'password123'
    }
}, function(response) { console.log(response) })

The only difference between the two functions is that promiseCall will return a Promise object instead of a message id. This means you can use await instead of having to rely on a callback.

var data = (async () => {
    return await ms.promiseCall({ registerUser: /* ... */ })
})()

Now, use the ms.didUpdate function to use the benefits of the callback.update() function that is used in the command definition.

var id = ms.call({ /* ... */ })
ms.didUpdate(function(status) { console.log(status) }, id) // executed when `callback.update()` is called.

Or, use ms.poll to retrieve the status of a command.

var status = ms.poll(id)

Coming full circle

Here's the service we just wrote in its entirety.

# ./service.js
var ms = require('microsjs')

class MyService extends ms {
    constructor() {
        super('./configuration.json')
        this.register(this.registerUser, 'registerUser')
    }

    registerUser(event, callback) {
        // ..
        callback.update('50% complete')
        // ..
        callback('Registered user with email' + event.user.email + '!')
    }
}
# ./configuration.json
{
    "service": "example",
    "objects": {
        "Email": { "type": "string", "pattern": "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}quot; },
        "User": {
            "type": "object",
            "properties": {
                "email": ":Email",
                "password": { "type": "string", "optional": true }
            }
        }
    },
    "messaging": {
        "registerUser(user: User, password)": {
            "event": "registerUserResponse(response: string)"
        }
    }
}

Documentation

'ms.register(func, command)'

Use this to register your business logic to a specified command. event, and callback are the default parameters that should be used in the function.

'ms.call(object)'

Use this to call a command with arguments to a service. This will be validated according to the list of arguments in the configuration object.

'ms.promiseCall(object)'

This is an extension of ms.call that will return a Promise instead of a message id.

'ms.didUpdate(func, id)'

Call this to set the handler for when a message is updated. It should be executed with the result of ms.call()

'ms.poll(id)'

Poll for the status of a specified message.