npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hai.dinh/service-libraries

v1.1.0

Published

Utilized libraries for services

Downloads

6

Readme

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 - [email protected] [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)