@jenius2/j2-http-connector
HTTP Connector for Jenius 2
Last updated 3 years ago by j2techlead .
Repository · Original npm · Tarball · package.json
$ cnpm install @jenius2/j2-http-connector 
SYNC missed versions from official npm registry.

node-j2-http-connector build status coverage report

Talk HTTP to anything, with special sauce for Jenius 2.

Lean and simple promise based HTTP connector:

const http = new HTTPConnector({
  secure: false,
  hostname: 'mock-idm',
  port: 5000
  withRefNo: 1 // enables custom request header to the added
});

http.request('/healthcheck')
.then((response) => {
  console.log(`Healthcheck version: ${response.body.version}`);
});

The response is a request response. Use the request docs to understand the API.

Table of Contents

Install

npm install @jenius2/j2-http-connector

Usage

The general pattern we are striving for is:

  1. For each system you need to communicate with, create the required HTTP configuration.
  2. On plugin registration, initiate the connector and inject it into the required models.
  3. In your models, use your injected connectors.

Here is an example for the following use case:

How do I add a downstream healthcheck to the IDM service in my microservice?

Step 1: Add the config

Update the project config:

const config = {
  // ...usual config
  resources: {
    idmService: {
      secure: false,
      withCredentials: true,
      pathname: 'some/path', // optional
      hostname: process.env.IDM_SERVICE_HOST || 'idm-service',
      port: process.env.IDM_SERVICE_PORT || 5000,
      timeout: process.env.IDM_SERVICE_TIMEOUT || 10000
    }
  }
}

Step 2: Create the connector when your plugin starts up, make it available in requests

In your Hapi plugin for your domain, set up your model(s) with HTTPConnector instances configured from the config above.

const HttpConnector = require('@jenius2/j2-http-connector');
const Users = require('../../models/users');

// Plugin registration function.
exports.register = (server, opts, next) => {
  //  Create our model, passing in our configured connector.
  const users = new Users({
    http: new HttpConnector(opts.config.resources.idmService)
  });

  //  Add our services to the plugin.
  server.ext('onPreHandler', (req, reply) => {
    req.server.users = users; // eslint-disable-line
    reply.continue();
  });

};

Step 3: Use your connector in your model

Your models now have a ready-to-go connector. This is also easy to mock/stub in model tests.

class Users {
  constructor(opts) {
    Object.assign(this, opts);

    if (!this.http) { utils.throwIfMissing('http'); }
  }

  // Resolves with true if healthy, false otherwise.
  healthy() {
    http('/healthcheck')
    .then((response) => {
      logger.info(`Healthy downstream, version ${response.body.version}`);
      return true;
    })
    .catch((err)) => {
      logger.info('Downsteam IDM not healthy', err);
      return false;
    });
    )
  }
}

How do I handle a custom error?

Step 1: Declare your errorMapper with proper status codes

this.openam = new HTTPConnector(opts.openam);
this.openam.errorMapper = {
  302: () => { throw new RedirectionError(); }
};

Step 2: The request method should have errorMapper be injected every time you call

this.openam.request(url, {
  method: 'POST',
  form: payload,
  headers
});

Is there a way we can inject calculated headers at runtime (when request is made) ?

Method 1:

  • Manually inject headers element when request is made
  this.openam.request(url, {
    method: 'POST',
    form: payload,
    headers: {
      'header-name': 'header-value',
      'other-header': getXHeader()
    }
  });

Method 2:

  • If you happen to use this request with well-known BTPN systems then you must be familar with (X-Reference-No or X-Transmission-Date-Time) then configure http connector to calcuate header values automatically upon request
  // config
  const http =  new HttpConnector({
    secure: false,
      hostname: '0.0.0.0',
      port: 80,
      withRefNo: 1,
      headers: {
        X-Channel-Id: '12345'
      }
  });

  // request 
  http.request('/test');
  // => headers : { X-Reference-No: $calculated_value, X-Channel-Id: '12345' }

Structure

Uses Node LTS. Source in lib, tests in test.

Files and Directory Structure

    .
    ├── README.md               # this file
    ├── artifacts/              # generated reports etc
    ├── lib                     # source code for the module
    ├── package.json            # description of this package for npm, including dependency lists
    └── test                    # all specs

What's Included?

Developer Guide

Easy commands for good times:

Command Usage
npm run lint Lint the code.
npm test Run tests.
npm run test:cov Run test with coverage written to ./artifacts/coverage.
npm run debug Debug tests. Add a debugger statement to break at the right time.
npm version patch && git push tags Create a release. The pipeline will publish the module.

Current Tags

  • 0.10.6                                ...           latest (3 years ago)

17 Versions

  • 0.10.6                                ...           3 years ago
  • 0.10.5                                ...           3 years ago
  • 0.10.4                                ...           3 years ago
  • 0.10.3                                ...           3 years ago
  • 0.10.2                                ...           3 years ago
  • 0.10.1                                ...           3 years ago
  • 0.10.0                                ...           3 years ago
  • 0.9.0                                ...           3 years ago
  • 0.8.0                                ...           3 years ago
  • 0.7.0                                ...           3 years ago
  • 0.6.1                                ...           3 years ago
  • 0.5.1                                ...           3 years ago
  • 0.5.0                                ...           3 years ago
  • 0.4.0                                ...           3 years ago
  • 0.3.1                                ...           3 years ago
  • 0.2.0                                ...           3 years ago
  • 0.3.0                                ...           3 years ago

Copyright 2014 - 2016 © taobao.org |