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

@huz-com/middleware-core

v1.0.13

Published

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

Downloads

24

Readme

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) => {...});