1.1.0 • Published 4 years ago

sanar-ms v1.1.0

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

sanar-ms-cover-v3

sanar-ms

Framework to create Sanar Microservices. With this library you are able to quickly create a extensible microservice following the standards adopted by Sanar.

Features:

  • Setup Express Server: Quickly setup all API server
  • Logger: Pretty logging with multiple transports
  • Env Vars: Assert and Validate environment variables
  • Healthcheck: Customize how we know the service is health
  • Database Integration: Create and assert database connection
  • API Validator: Validating request body/queries/cookies/headers
  • API Pagination: Standardization of pagination in API

Basic Usage

import * as SanarMS from 'sanar-ms';

const ms = new SanarMS({
  name: 'questions',
});

ms.app.get('/hello', (req, res) => {
  res.json({ hello: 'world' });
});

ms.listen();

Documentation

Full options example

const opts = {
  name: 'my-service',
  middlewares: {
    push: [],
    unshift: [],
    overwrite: [],
  },
  logger: {
    transports: [
      new winston.transports.Console(),
    ],
    silent: false,
    level: 'info',
  },
  envs: [
    {
      name: 'MONGO_HOST',
      type: 'url',
      required: true,
    },
    {
      name: 'MONGO_PORT',
      type: 'port',
    },
  ],
  validator: ({ body, query }) => ({
    createUser: [
      body('name')
        .isString()
      query('enabled')
        .isBoolean()
    ],
  }),
}

Options

Basic Setup

  • name (String): Microservice name

Server Setup

  • middlewares.unshift (Array): Unshift/Prepend Express middleware before all default middlewares.
  • middlewares.push (Array): Push/Append Express middleware after all default middlewares.
  • middlewares.overwrite (Array): Overwrite all default Express. Note: when defined, unshift and push will be ignored.

Logger

  • logger.transports (Array): List of Logger transports (See more: winston-transports)
  • logger.level (String): Log only if logger.level less than or equal to this level
  • logger.silent (Boolean): If true, all logs are suppressed

Environment Variables

  • envs (Arrayenv): List of environment variable definitions

Environment Object Properties

  • env.name (String): Env variable name. Ex: MONGO_HOST
  • env.type (String): Env variable type. Ex: int. See below all types.
  • env.required (String): If true and not defined, the Microservie crashes.

Environment Variable Types

  • int: Parse int number. Example: 123
  • float: Parse float number. Example 12.8
  • string Parse string. Example 'Hello'
  • boolean. Parse boolean. Example: true
  • host. Parse host. Example: localhost
  • port. Parse port. Example: 3000
  • url. Parse url. Example: http://editorasanar.com.br

Healthcheck

  • health (Function): Custom function to assert the Microservice is healthy. Returns true healthy / false unhealthy

Database

  • database.enabled: Enable / Disable database
  • database.type: Database type. See the list of Database types below.

Database Types

  • mongo: MongoDB using Mongoose framework

    Note: Currently we are only giving support to mongo database.

Validator

  • database.validator: Function that should return a map of key => validationMiddlewares

Note: We use express-validator. See all validator types.


Examples

Example 1 - Extending middlewares with Unshift / Push:

const beforeMiddleware = (req: any, res: any, next: any) => {
  console.log('Before all default middlewares');
  next();
};

const afterAllMiddleware = (req: any, res: any, next: any) => {
  console.log('After all default middlewares');
  next();
};

const ms = new SanarMS({
  name: 'my-service',
  middlewares: {
    unshift: [
      beforeMiddleware,
    ],
    push: [
      afterAllMiddleware,
    ]
  }
});

Example 2 - Overwriting middlewares:

const ms = new SanarMS({
  name: 'my-service',
  middlewares: {
    overwrite: [
      bodyParser.json(),
    ],
  }
});

Example 3 - Custom Logger Transports:

const ms = new SanarMS({
  name: 'my-service',
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' }),
    new AwsCloudWatch(options),
  ],
});