Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@hai.dinh/service-libraries

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@hai.dinh/service-libraries

Utilized libraries for services

latest
Source
npmnpm
Version
1.1.0
Version published
Maintainers
1
Created
Source

Service Libraries

Build Status License: MIT

A collection of utilities for services in mircoservice-poc

Installation

The easiest way to install service-libraries is using NPM. If you have Node.js installed, it is most likely that you have NPM installed as well.

$ npm install @hai.dinh/service-libraries

Usage

httpHandler

Being inspired by AWS Lambda response for API Gateway styling, this function retrieves your response, which being like AWS Lambda response, then transform to express response

function simpleResponse(req) {
  return {
      statusCode: 200,
      body: {
          message: 'Hello World !'
      },
      headers: {
          'Content-Type': 'application/json'
      }
  }
}

...
import express from 'express';
import { httpHandler } from '@hai.dinh/service-libraries';

const app = express();

app.get('/hello-world', httpHandler(simpleResponse))

schemaValidator

schemaValidator is basically instance of ajv (to validate data with the corresponding schema), including pre-defined basic configuration.

To use schemaValidator, follow the instruction

import { schemaValidator } from '@hai.dinh/service-libraries';

const validator = schemaValidator.compile(schema);
const isValid = validator(yourData);

if (!isValid) {
    console.log('Your data is invalid.', validator.errors)
}

ServiceClientFactory

Taking file service-env.json (render by service-registry-cli pull) as input, ServiceClientFactory acts as service discovery in microservice system to find the endpoint of targeted service. To use this, do the following:

import { ServiceClientFactory } from '@hai.dinh/service-libraries';

...

const serviceClient = await ServiceClientFactory.create(<service-id>);

const response = await serviceClient.request(config)

ServiceClientFactory API

  • serviceClient.request(config: AxiosConfig)
    // Send a POST request
    const res = await serviceClient.request({
        method: 'post',
        url: '/user/12345',
        data: {
            firstName: 'Fred',
            lastName: 'Flintstone'
        }
    });

ServiceClientFactory uses axios behind the scene. For full configuration, you can get in here.

StorageClient

import { StorageClient } from '@hai.dinh/service-libraries';

API

  • create
    const storageClient = await StorageClient.create();

    const record = await storageClient.create(documentPath, {
        "Content": documentContent,
        "Type": documentType,
        "Attributes": documentAttributs,
    })
  • get
    const storageClient = await StorageClient.create();

    const record = await storageClient.get(documentPath)
  • list
    const storageClient = await StorageClient.create();

    const record = await storageClient.list(options)
  • update
    const storageClient = await StorageClient.create();

    const record = await storageClient.update(documentPath, {
        "Content": documentContent,
        "Type": documentType,
        "Attributes": documentAttributs,
    })
  • delete
    const storageClient = await StorageClient.create();

    const record = await storageClient.delete(documentPath)

Middlewares

traceRequest

traceRequest middleware allow Express application to capture and foward X-Request-ID from original request headers, then set it to process environment variable for other libraries(logger, http client ...) can consume it

  • Usage
import { traceRequest } from '@hai.dinh/service-libraries/middlewares';

...
// in your service (Express)
const app = express();

app.use(traceRequest)

console.log(process.env['X-Request-Id'])

useInstrumentation

useInstrumentation provides instrumentation to support logging for application. Log will be streamed to stdout and saved to file log/app.log

import { useInstrumentation } from '@hai.dinh/service-libraries/middlewares';

...
// in your service (Express)
const app = express();

app.use(useInstrumentation)

// get instrumentation from your request
app.get('/', (req, res) => {
    const { instrumentation } = res;
})
Instrumentation API
  • trace
instrumentation.trace('Process started!');
// Output
// If X-Request-ID is NA
// [2010-01-17 11:43:37.987] [TRACE] - - Process started!
// IF X-Request-ID is available (by useTraceRequest)
// [2010-01-17 11:43:37.987] [TRACE] 1212121 - Process started!
  • debug
instrumentation.debug('Got notification');
// Output
// If X-Request-ID is NA
// [2010-01-17 11:43:37.987] [DEBUG] - - Got notification!
// IF X-Request-ID is available (by useTraceRequest)
// [2010-01-17 11:43:37.987] [DEBUG] 1212121 - Got notification!
  • info
instrumentation.info('Hello World!');
// Output
// If X-Request-ID is NA
// [2010-01-17 11:43:37.987] [INFO] - - Hello World!
// IF X-Request-ID is available (by useTraceRequest)
// [2010-01-17 11:43:37.987] [INFO] 1212121 - Hello World!
  • warn
instrumentation.warn('Warn!');
// Output
// If X-Request-ID is NA
// [2010-01-17 11:43:37.987] [WARN] - - Warn!
// IF X-Request-ID is available (by useTraceRequest)
// [2010-01-17 11:43:37.987] [WARN] 121313 - Warn!
  • error
instrumentation.error('Error!');

// Output
// If X-Request-ID is NA
// [2010-01-17 11:43:37.987] [ERROR] - - Error!
// IF X-Request-ID is available (by useTraceRequest)
// [2010-01-17 11:43:37.987] [ERROR] 123212 - Error!

useHttpLogger

useHttpLogger allow your Express server to log http as CSL format.

Below is the example of log

127.0.0.1 - haidv@gmail.com [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326 "http://referer.com" "PostmanRuntime/7.23.0" vxve23sdgs45sdvw


log-format = %(addr) %(ident) %(user) [%(ltime)] "%(method) %(uri) %(proto)" %(status) 
%(size) "%(referer)" "%(uagent)" %(requestid)
  • Usage:
import { useHttpLogger } from '@hai.dinh/service-libraries/middlewares';

...
// in your service (Express)
const app = express();

app.use(useHttpLogger)

Keywords

microservice

FAQs

Package last updated on 27 Mar 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts