All Projects → banzaicloud → Service Tools

banzaicloud / Service Tools

Licence: apache-2.0
Prepare your Node.js application for production

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Service Tools

Grant
OAuth Proxy
Stars: ✭ 3,509 (+3842.7%)
Mutual labels:  middleware, express, koa
Kona
a node.js service framework built on koa.js (generators)
Stars: ✭ 23 (-74.16%)
Mutual labels:  middleware, express, koa
Graphql Upload
Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.
Stars: ✭ 1,071 (+1103.37%)
Mutual labels:  express, koa
Rainbow
An Express router middleware for RESTful API base on file path.
Stars: ✭ 53 (-40.45%)
Mutual labels:  middleware, express
Vue Socket.io Chat
💬 TypeScript + Vue + Express/Koa + Socket.io
Stars: ✭ 61 (-31.46%)
Mutual labels:  express, koa
Angela
🙂angela (安其拉):react ssr router redux; react同构框架
Stars: ✭ 15 (-83.15%)
Mutual labels:  express, koa
Apicache
Simple API-caching middleware for Express/Node.
Stars: ✭ 957 (+975.28%)
Mutual labels:  middleware, express
Http Proxy Middleware
⚡ The one-liner node.js http-proxy middleware for connect, express and browser-sync
Stars: ✭ 8,730 (+9708.99%)
Mutual labels:  middleware, express
Vue Chat
👥Vue全家桶+Socket.io+Express/Koa2打造一个智能聊天室。
Stars: ✭ 887 (+896.63%)
Mutual labels:  express, koa
Express Joi Validation
validate express application inputs and parameters using joi
Stars: ✭ 70 (-21.35%)
Mutual labels:  middleware, express
Trafficlight
🚦 Flexible NodeJS Routing Decorators for API Routing
Stars: ✭ 69 (-22.47%)
Mutual labels:  express, koa
Vox
Simple and lightweight Go web framework inspired by koa
Stars: ✭ 74 (-16.85%)
Mutual labels:  express, koa
Deprecated
🚀 Framework for building universal web app and static website in Vue.js (beta)
Stars: ✭ 858 (+864.04%)
Mutual labels:  express, koa
Outputcache
Cache api responses using Redis, Memcached or any cache provider for NodeJS
Stars: ✭ 9 (-89.89%)
Mutual labels:  middleware, express
Webpack Isomorphic Dev Middleware
The webpack-dev-middleware, but for isomorphic applications
Stars: ✭ 38 (-57.3%)
Mutual labels:  middleware, express
Koa Useragent
Koa user-agent middleware
Stars: ✭ 54 (-39.33%)
Mutual labels:  middleware, koa
Redirect Ssl
Connect/Express middleware to enforce https using is-https
Stars: ✭ 81 (-8.99%)
Mutual labels:  middleware, express
Cabin
🌲 Cabin is the best JavaScript and Node.js logging service and logging npm package
Stars: ✭ 622 (+598.88%)
Mutual labels:  express, koa
Koa2 Api Scaffold
一个基于Koa2的轻量级RESTful API Server脚手架。
Stars: ✭ 694 (+679.78%)
Mutual labels:  express, koa
Koatty
Koa2 + Typescript = Koatty. Use Typescript's decorator implement IOC and AOP.
Stars: ✭ 67 (-24.72%)
Mutual labels:  middleware, koa

Node.js Service Tools

Prepare your Node.js application for production!

This library provides common functionalities, like graceful error handling & shutdown, structured JSON logging and several HTTP middleware to make your application truly ready for modern containerised environments, like Kubernetes.

Installation

npm i @banzaicloud/service-tools
# or
yarn add @banzaicloud/service-tools

Usage & Examples

This library is written in TypeScript, refer to the published types or the source code for argument and return types.

Examples are available for Express and Koa frameworks. Check out the examples folder!

Main exports

catchErrors(options)

Catch uncaught exceptions and unhandled Promise rejections. It is not safe to resume normal operation after 'uncaughtException'.

const { catchErrors } = require('@banzaicloud/service-tools')

// ...

// the handlers return a Promise
// the handlers are called in order
catchErrors([closeServer, closeDB])

// the error will be caught and the handlers will be called before exiting
throw new Error()

gracefulShutdown(handlers, options)

Graceful shutdown: release resources (databases, HTTP connections, ...) before exiting. When the application receives SIGTERM or SIGINT signals, the close handlers will be called. The handlers should return a Promise.

const { gracefulShutdown } = require('@banzaicloud/service-tools')

// ...

// the handlers return a Promise
// the handlers are called in order
gracefulShutdown([closeServer, closeDB])

logger

A pino structured JSON logger instance configured with config.pino.

const { logger } = require('@banzaicloud/service-tools')

logger.info({ metadata: true }, 'log message')
// > {"level":30,"time":<ts>,"msg":"log message","pid":0,"hostname":"local","metadata":true,"v":1}
Use provided logger instead of console

Globally overwrite the console and use the logger provided by the library to print out messages.

const { logger } = require('@banzaicloud/service-tools')

console.log('log message')
// > log message

logger.interceptConsole()

console.log('log message')
// > {"level":30,"time":<ts>,"msg":"log message","pid":0,"hostname":"local","v":1}

Config

Load configurations dynamically.

config.environment

Uses the NODE_ENV environment variable, with accepted values of: production, development, test.

const { config } = require('@banzaicloud/service-tools')
// validates the NODE_ENV environment variable
console.log(config.environment)
// > { nodeEnv: 'production' }

config.pino

Used by the provided logger. Uses the LOGGER_LEVEL and LOGGER_REDACT_FIELDS environment variables. The LOGGER_LEVEL can be one of the following: fatal, error, warn, info, debug, trace. LOGGER_REDACT_FIELDS is a comma separated list of field names to mask out in the output (defaults to: 'password, pass, authorization, auth, cookie, _object').

const pino = require('pino')
const { config } = require('@banzaicloud/service-tools')

const logger = pino(config.pino)

logger.info({ metadata: true, password: 'secret' }, 'log message')
// > {"level":30,"time":<ts>,"msg":"log message","pid":0,"hostname":"local","metadata":true,"password":"[REDACTED]","v":1}

Middleware (Koa)

Several middleware for the Koa web framework.

errorHandler(options)

Koa error handler middleware.

const Koa = require('koa')
const { koa: middleware } = require('@banzaicloud/service-tools').middleware

const app = new Koa()

// this should be the first middleware
app.use(middleware.errorHandler())

healthCheck(checks, options)

Koa health check endpoint handler.

const Koa = require('koa')
const Router = require('koa-router')
const { koa: middleware } = require('@banzaicloud/service-tools').middleware

// ...

const app = new Koa()
const router = new Router()

// the checks return a Promise
router.get('/health', middleware.healthCheck([checkDB]))

app.use(router.routes())
app.use(router.allowedMethods())

prometheusMetrics(options)

Koa Prometheus metrics endpoint handler. By default it collects some default metrics.

const Koa = require('koa')
const Router = require('koa-router')
const { koa: middleware } = require('@banzaicloud/service-tools').middleware

// ...

const app = new Koa()
const router = new Router()

router.get('/metrics', middleware.prometheusMetrics())

app.use(router.routes())
app.use(router.allowedMethods())

requestValidator(options)

Koa request validator middleware. Accepts Joi schemas for body (body parser required), params and query (query parser required). Returns with 400 if the request is not valid. Assigns validated values to ctx.state.validated.

const joi = require('@hapi/joi')
const qs = require('qs')
const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const { koa: middleware } = require('@banzaicloud/service-tools').middleware

// ...

const app = new Koa()
const router = new Router()

const paramsSchema = joi
  .object({
    id: joi
      .string()
      .hex()
      .length(64)
      .required(),
  })
  .required()

const bodySchema = joi.object({ name: joi.string().required() }).required()

const querySchema = joi.object({ include: joi.array().default([]) }).required()

router.get(
  '/',
  middleware.requestValidator({ params: paramsSchema, body: bodySchema, query: querySchema }),
  async function routeHandler(ctx) {
    const { params, body, query } = ctx.state.validated
    // ...
  }
)

app.use(bodyParser())
// query parser
app.use(async function parseQuery(ctx, next) {
  ctx.query = qs.parse(ctx.querystring, options)
  ctx.request.query = ctx.query
  await next()
})
app.use(router.routes())
app.use(router.allowedMethods())

requestLogger(options)

Koa request logger middleware. Useful for local development and debugging.

const Koa = require('koa')
const { koa: middleware } = require('@banzaicloud/service-tools').middleware

// ...

const app = new Koa()

// this should be the second middleware after the error handler
// ...
app.use(middleware.requestLogger())

Middleware (Express)

Several middleware for the Express web framework.

errorHandler(options)

Express error handler middleware.

const express = require('express')
const { express: middleware } = require('@banzaicloud/service-tools').middleware

const app = express()

// this should be the last middleware
app.use(middleware.errorHandler())

healthCheck(checks, options)

Express health check endpoint handler.

const express = require('express')
const { express: middleware } = require('@banzaicloud/service-tools').middleware

// ...

const app = express()

// the checks return a Promise
app.get('/health', middleware.healthCheck([checkDB]))

prometheusMetrics(options)

Express Prometheus metrics endpoint handler. By default it collects some default metrics.

const express = require('express')
const { express: middleware } = require('@banzaicloud/service-tools').middleware

// ...

const app = express()

app.get('/metrics', middleware.prometheusMetrics())

requestValidator(options)

Express request validator middleware. Accepts Joi schemas for body (body parser required), params and query. Returns with 400 if the request is not valid. Assigns validated values to req.

const joi = require('@hapi/joi')
const express = require('express')
const { express: middleware } = require('@banzaicloud/service-tools').middleware

// ...

const app = express()

const paramsSchema = joi
  .object({
    id: joi
      .string()
      .hex()
      .length(64)
      .required(),
  })
  .required()

const bodySchema = joi.object({ name: joi.string().required() }).required()

const querySchema = joi.object({ include: joi.array().default([]) }).required()

app.use(express.json())
app.get(
  '/',
  middleware.requestValidator({ params: paramsSchema, body: bodySchema, query: querySchema }),
  function routeHandler(req, res) {
    const { params, body, query } = req
    // ...
  }
)
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].