@huz-com/middleware-core
TypeScript icon, indicating that this package has built-in type declarations

1.0.13 • Public • Published

Huz.Com > Component > Middleware Core

helmet, cors, body, cookie, header, query, default endpoints and most-used middlewares

Standards

  • Language: TS
  • Eslint: Yes
  • Static Code Analysis: Yes IntelliJ Code Inspections
  • DDD - Document Driven: Yes
  • EDD - Exception Driven: Yes
  • TDD - Test Driven: Yes go to test folder
  • Standards Complied: Huz Standards

Commands

  • npm run clear // clears "dist" folder
  • npm run lint // runs eslint for static code analysis
  • npm run test // runs test files in "test" folder
  • npm run build // builds JS files at "dist" folder
  • npm publish or npm run publix // publishes "dist" folder to npm

Install

npm i @huz-com/middleware-core

Sample - Easy

const {MiddlewareCore} = require('@huz-com/middleware-core');
// ES6: import {middlewareCore} from "@huz-com/middleware-core";

const app = express();
const middlewareCore = MiddlewareCore.with(app);

middlewareCore.initDefaultHandlers();
/*
it calls: 
    .helmet().cors().urlEncode() // for security
    .json().cookie().queryString().toHeader().requestCustom() // for formatting
    .readiness().liveness().status() // for default endpoints
    .count() // processors (call counter)
    ;
*/ 

// ...................................................
// Your custom codes (other middlewareCores, other routes)
// ...................................................

middlewareCore.finalDefaultHandlers();
/*
it calls: 
    empty().notFound().generalError() // for error handling
    ;
*/ 

Sample - Detailed

const {MiddlewareCore, ProcessExitType} = require('@huz-com/middleware-core');
// ES6: import {middlewareCore} from "@huz-com/middleware-core";

const app = express();
const middlewareCore = MiddlewareCore.with(app);

//initializer functions
middlewareCore
    .helmet() // (options), def: null, ie: ##helmet
    .cors() // (options), def: null, ie: ##cors
    .urlEncode() // (options), def: { extended: false }, ##body-parser
    .json() // (options), def: null, ##body-parser
    .cookie() // (secret, options), ie: ##cookie-parser
    .queryString() // (options), def: {depth: 12}, ##qs
    .toHeader() // (options), def: {prefix: '__'}
    .requestCustom() // (value), def: {}  
    .readiness((req) => null) // if success callback should return null, else error message
    .liveness((req) => null) // // if success callback should return null, else error message
    .status() // (path: string), def: status
    .count() // counts endpoint calls
    
    // other middlewares
    // calculates endpoint duration
    .duration((req, path, msec) => console.log(`>> ${path} consumes ${msec}`)) // it takes async function to process duration
    // catches all method:options calls
    .corsOptions() // (path, options), def: ('*', null) ie: ##cors
    ;

// ...................................................
// Your custom codes (other middlewareCores, other routes)
// ...................................................

//finalizer functions
middlewareCore
    .empty() // Throws when empty endpoint or route
    .notFound() // (...ignoredPaths: Array<string>) you can give ignored paths like ('c-panel', 'admin')
    .generalError() // Throws when unhandled error
    .onExit({ // triggers on exit, you can set events which you need
        beforeExit: (type, ...args) => {}, // triggers before exit
        afterExit: (type, ...args) => {}, // triggers after exit (after below)
        uncaughtException: (type, ...args) => {}, // when error
        exit: (type, ...args) => {}, // any exit
        SIGINT: (type, ...args) => {}, // ctrl+c event or normally exit
        SIGUSR1: (type, ...args) => {}, // kill process
        SIGUSR2: (type, ...args) => {}, // kill process
        SIGTERM: (type, ...args) => {}, // administratively terminate a process
        SIGQUIT: (type, ...args) => {}, // kill process with dumps core
    })
    ;

Dependency

middlewareCore.helmet

  • Initializer add before your custom routers or middlewareCores
  • Npm Package helmet

It enables small security middlewareCores

  1. contentSecurityPolicy: CSP: Content Security Policy by Mozilla
    • sets Content-Security-Policy
    • sets Content-Security-Policy-Report-Only
  2. dnsPrefetchControl: X-DNS-Prefetch-Control by Mozilla
  3. expectCt: Expect-CT by Mozilla
  4. frameGuard: X-Frame-Options by Mozilla
  5. hidePoweredBy: X-Powered-By by Mozilla
  6. hsts: HSTS: HTTP Strict Transport Security by Mozilla
  7. ieNoOpen: X-Download-Options by NWebsec
  8. noSniff: X-Content-Type-Options by Mozilla
  9. permittedCrossDomainPolicies: X-Permitted-Cross-Domain-Policies by OWASP
  10. referrerPolicy: Referrer-Policy by Mozilla
  11. xssFilter: XSS: Cross-Site Scripting by OWASP

middlewareCore.cors

  • Initializer add before your custom routers or middlewareCores
  • Npm Package cors

It enables that CORS (Cross-Origin Resource Sharing)

middlewareCore.cookie

  • Initializer add before your custom routers or middlewareCores
  • Npm Package cookie-parser

Parse "Cookie" header and populate req.cookies with an object keyed by the cookie names

middlewareCore.urlEncode

  • Initializer add before your custom routers or middlewareCores
  • Npm Package body-parser

it parses if content-type is application/x-www-form-urlencoded

middlewareCore.json

  • Initializer add before your custom routers or middlewareCores
  • Npm Package body-parser

it parses if content-type is application/json

middlewareCore.queryString

  • Initializer add before your custom routers or middlewareCores
  • Npm Package qs

it parses query string and converts it to json object

Sample: foo[bar]=baz ===> {foo: {bar: 'baz'}}

middlewareCore.readiness

  • Initializer add before your custom routers or middlewareCores
  • Tutorial Kubernetes

Creates an endpoint for Kubernetes readinessProbe

middlewareCore.liveness

  • Initializer add before your custom routers or middlewareCores
  • Tutorial Kubernetes

Creates an endpoint for Kubernetes livenessProbe

middlewareCore.toHeader

  • Initializer add before your custom routers or middlewareCores
  • Custom solution for Huz

It parses query string and moves some keys to headers

Sample: ?__silent=true&__token=foo-bar ==> {silent: true, token: 'foo-bar'}

middlewareCore.duration

  • Initializer add before your custom routers or middlewareCores
  • Custom solution for Huz

It calculates consumed time by called endpoint

middlewareCore.empty

  • Finalizer add after your custom routers or middlewareCores
  • Custom solution for Huz

Handles empty endpoint and throws an error

app.get('/', (req, res) => {...});

middlewareCore.notFound

  • Finalizer add after your custom routers or middlewareCores
  • Custom solution for Huz

Handles not-found endpoint and throws an error

app.use((req, res) => {...});

middlewareCore.generalError

  • Finalizer add after your custom routers or middlewareCores
  • Custom solution for Huz

Handles any unknown error and throws an error

app.use((e, req, res, next) => {...});

Package Sidebar

Install

npm i @huz-com/middleware-core

Weekly Downloads

0

Version

1.0.13

License

ISC

Unpacked Size

53 kB

Total Files

23

Last publish

Collaborators

  • demiremrece