0.1.0 • Published 1 year ago

janis-integration-kit v0.1.0

Weekly downloads
-
License
ISC
Repository
bitbucket
Last release
1 year ago

Janis Integration Kit version 0.0.1

Set of tools, functions, classes, and objects to simplify the development of integration services to extend and customize Janis functionality and behaviour.

What it's included in this module:

  • Janis API Client (Legacy & v2)
  • Config helper function: getConfig
  • Janis Event Handler & response factory
  • Authorizer
  • AWS Service
  • Webhook setup utility

Install

First at all you have to set the token that you are going to use to authenticate to eudax organization in NPM Repository.

Set NPM_TOKEN using export

  export NPM_TOKEN=<npm_token>

Set NPM_TOKEN permanently using bashrc

If you set the variable using bashrc, you don't need to set it again when you need it in different consoles or when you reboot your system.

  echo "NPM_TOKEN=<npm_token>" > ~/.bashrc
  source ~/.bashrc

Create npm configuration to access to the package

You must to create a .npmrc file with the token in the root of your project.

  touch .npmrc && echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc 
  npm i @eudax/janis-integration-kit

Usage on Pipelines

To use the package on Pipelines you have to add NPM_TOKEN as an enviroment variable on your CI/CD Tool and add the following instruction in your pipeline before the npm install instruction

  touch .npmrc && echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc 

Janis API Client

Initialize

const { createJanisApiClient } = require('@eudax/janis-integration-kit');

const janisApiClient = createJanisApiClient(
    await config.janis.apiKey,
    await config.janis.apiSecret,
    await config.janis.client,
    await config.janis.environment
);

Call service method

const orderJanis = await janisApiClient.oms.getOrder(id);

Janis Legacy API Client

Initialize

const { janisLegacyApiClient } = require('@eudax/janis-integration-kit');

const janisLegacyApiClient = createJanisLegacyApiClient(
    await config.janisLegacy.apiKey,
    await config.janisLegacy.apiSecret,
    await config.janisLegacy.client,
    await config.janisLegacy.environment
);

Call service method

const { data } = await janisLegacyApiClient.legacy.getOrder({ seqId: sequentialId });

Config

Set SOME_CONFIG as env var or AWS secret called 'secrets'.

Define config module in project:

const { getConfig } = require('@eudax/janis-integration-kit');

const Config = {
    someConfig: getConfig('SOME_CONFIG', 'defaultValue'),
    otherConfig: getConfig('OTHER_CONFIG')
};

module.exports = Config;

Read value:

const config = require('./config');
const someConfig = await config.someConfig;

Janis Event Handler

This module helps handling of Janis notifications requests.

Extend JanisEventHandler to define the behaviour of the integration on specified event.

const { JanisEventHandler, JanisConstants } = require('@eudax/janis-integration-kit');

class OrderInvoicedEventHandler extends JanisEventHandler {
    constructor(responseFactory) {
        // Define service, entity and event to handle
        super(
            JanisConstants.services.Oms.name, 
            JanisConstants.services.Oms.entities.Order, 
            JanisConstants.services.Oms.events.Invoiced);
        
        this.responseFactory = responseFactory;
    }

    async handle(event) {
        // Do some stuff on event
        return this.responseFactory.ok('OK');
    }
}

module.exports = OrderInvoicedEventHandler;

Then use JanisNotificationsHandler in the notifications endpoint handler, i.e. SERVICE_BASE_URL/janis/notifications.

const responseFactory = require('@eudax/janis-integration-kit');
const OrderInvoicedEventHandler = require('./handlers/OrderInvoicedEventHandler');

module.exports.handler = async (event) => {
    // Instantiate notifications handler
    const janisNotificationsHandler = new JanisNotificationsHandler(responseFactory);

    // Register event handlers
    const orderInvoicedEventHandler = new OrderInvoicedEventHandler(responseFactory);
    janisNotificationsHandler.registerHandler(orderInvoicedEventHandler);

    .
    .
    .

    // Invoke notifications handler with the event
    return await janisNotificationsHandler.handle(event);
};

Authorizer helper

If the projects uses API Gateway, then create a authorizer handler like this:

const { Authorizer } = require('@eudax/janis-integration-kit');

module.exports.handler = Authorizer([await config.validToken, await config.anotherValidtoken]);

and in serverless.yml:

provider:
  name: aws
  runtime: nodejs16.x
  logs:
    httpApi: true
  httpApi:
    authorizers:
      authorizer:
        type: request
        functionName: authorizer
        enableSimpleResponses: true

.
.
.

functions:
  authorizer:
    handler: src/authorizer.handler

  janisNotifications:
    handler: src/janisNotifications.handler
    timeout: 15
    events:
      - httpApi:
          path: /janis/notifications
          method: post
          authorizer:
            name: authorizer

If using function urls instead of api gateway then a top of function:

const { AuthorizerService, responseFactory } = require('@eudax/janis-integration-kit');

module.exports.handler = async (event) => {
    const service = AuthorizerService([await config.validToken]);

    const token = event.headers.Authorization || event.headers.authorization;
    if (await service.isValid(token) !== true) { 
        console.error('Invalid token');
        return responseFactory.unauthorized();
    }

...

and there is no need to add something extra to serverless.yml.

AWS Service

AWSService is a helper factory that will return mockups version if our current environment is 'local'.

Can be used like this:

const { AWSService } = require('@eudax/janis-integration-kit');

// To get a S3 instance
const s3 = await AWSService.getS3(config);

Mockup version of S3 will look for files in local directory called 'local-bucket' in the root of thw project.

AWSService also has a factory method for SQS.

// To get a SQS
const sqs = await AWSService.getSQS(config, worker);

in this case the worker handler is need in order to execute events locally.

Webhook setup utility

This script help automation of Janis webhooks configuration. Can be used in pipeline to ensure our service will listen to the expected events.

Create a file with desired triggers, i.e. triggers.js:

const { JanisConstants } = require('@eudax/janis-integration-kit');

module.exports = [
                {
                    service: JanisConstants.services.Oms.name,
                    entity: JanisConstants.services.Oms.entities.Order,
                    eventName: JanisConstants.services.Oms.events.ReadyForInvoice,
                    status: JanisConstants.services.Webhooks.status.Active
                },
                {
                    service: JanisConstants.services.Oms.name,
                    entity: JanisConstants.services.Oms.entities.Order,
                    eventName: JanisConstants.services.Oms.events.Invoiced,
                    status: JanisConstants.services.Webhooks.status.Active
                },

                .
                .
                .

];

Then run

$ npx janis-setup ./triggers.js

This script will get Janis credentials and configs from env vars:

  • JANIS_ENVIRONMENT
  • JANIS_NOTIFICATIONS_URL
  • JANIS_WEBHOOK_TOKEN
  • JANIS_API_KEY
  • JANIS_API_KEY
  • JANIS_API_SECRET
  • JANIS_CLIENT

and will try to get base url from API_DOMAIN or from serverless.

Development info

For new development and maintance of this package:

New Release

Please read RELEASING.md to do a new release of the Package

Running Tests

To run tests, run the following command

  npm run test