GithubHelp home page GithubHelp logo

iamolegga / create-nestjs-middleware-module Goto Github PK

View Code? Open in Web Editor NEW
38.0 3.0 2.0 3.42 MB

NestJS configured middleware module made simple

License: MIT License

TypeScript 77.54% JavaScript 22.46%

create-nestjs-middleware-module's Introduction

create-nestjs-middleware-module

npm npm GitHub branch checks state Known Vulnerabilities Libraries.io Dependabot Supported platforms: Express & Fastify

NestJS configured middleware module made simple

What is it?

It is a tiny helper library that helps you create simple idiomatic NestJS module based on Express/Fastify middleware in just a few lines of code with routing out of the box.

Install

npm i create-nestjs-middleware-module

or

yarn add create-nestjs-middleware-module

Usage

Let's imaging you have some middleware factory, for example, simple logger:

export interface Options {
  maxDuration: number
}

export function createResponseDurationLoggerMiddleware(opts: Options) {
  return (request, response, next) => {
    const start = Date.now();

    response.on('finish', () => {
      const message = `${request.method} ${request.path} - ${duration}ms`;

      const duration = Date.now() - start;

      if (duration > maxDuration) {
        console.warn(message);
      } else {
        console.log(message);
      }
    });

    next();
  };
}

And you want to create an idiomatic NestJS module based on that middleware. Just pass this middleware factory to createModule function:

import { createModule } from 'create-nestjs-middleware-module';
import { Options, createResponseDurationLoggerMiddleware } from './middleware';

export const TimingModule = createModule<Options>(createResponseDurationLoggerMiddleware);

That's it, your module is ready. Let's see what API it has:

import { TimingModule } from './timing-module';
import { MyController } from './my.controller';

@Module({
  imports: [

    // 1. `.forRoot()` method accept params satisfying `Options` interface
    TimingModule.forRoot({ maxDuration: 1000 }),

    // 2. `.forRoot()` method accept additional optional routing params
    TimingModule.forRoot({
      maxDuration: 1000,

      // both `forRoutes` and `exclude` properties are optional
      // and has the same API as NestJS buil-in `MiddlewareConfigProxy`
      // @see https://docs.nestjs.com/middleware#applying-middleware
      forRoutes: [MyController],
      exclude: [{ method: RequestMethod.ALL, path: 'always-fast' }],
    }),

    // 3. `.forRootAsync()` method with only factory
    TimingModule.forRootAsync({
      useFactory: async () => {
        return { maxDuration: 1000 }
      }
    }),

    // 4. `.forRootAsync()` method with dependencies
    TimingModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => {
        return { maxDuration: config.maxDurationForAPIHandler }
      }
    }),

    // 5. `.forRootAsync()` method with routing
    TimingModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => {
        return {
          maxDuration: config.maxDurationForAPIHandler

          // both `forRoutes` and `exclude` properties are optional
          // and has the same API as NestJS buil-in `MiddlewareConfigProxy`
          // @see https://docs.nestjs.com/middleware#applying-middleware
          forRoutes: [MyController],
          exclude: [{ method: RequestMethod.ALL, path: 'always-fast' }],
        };
      }
    }),
  ]
  controllers: [MyController /*, ... */]
})
class App {}

More examples

See examples of usage in __tests__ folder or nestjs-session and nestjs-cookie-session packages

Notes

  1. createModule callback function can return not only one middleware, but array of it.
import { createModule } from 'create-nestjs-middleware-module';


interface Options {
  // ...
}

createModule<Options>((options) => {
  function firstMidlleware() { /* ... */ }
  function secondMidlleware() { /* ... */ }
  return [firstMidlleware, secondMidlleware]
});
  1. If your Options interface has not required properties it can be frustrating to force end-users of your module to call forRoot({}), and for better developer expirience you can cast createModule(...) result to FacadeModuleStaticOptional<Options>, then forRoot() could be called without arguments and without TS error. In such case createModule callback function will be called with empty object {}.
import { createModule, FacadeModuleStaticOptional } from 'create-nestjs-middleware-module';

interface Options {
  maxDuration?: number;
}

createModule<Options>((options) => {
  typeof options // always "object" even if not passed to `forRoot()`

  return (request, response, next) => {
    // ...
    next();
  };
}) as FacadeModuleStaticOptional<Options>;
  1. For better developer experience of end-users of your module you can also export interfaces of forRoot and forRootAsync argument:
import {
  AsyncOptions,
  SyncOptions,
} from 'create-nestjs-middleware-module';

interface Options {
  // ...
}

export type MyModuleOptions = SyncOptions<Options>;

export type MyModuleAsyncOptions = AsyncOptions<Options>;
  1. This library is tested against express and fastify. But you should be aware that middlewares of express are not always work with fastify and vise versa. Sometimes you can check platforms internally. Sometimes maybe it's better to create 2 separate modules for each platform. It's up to you.

Do you use this library?
Don't be shy to give it a star! โ˜…

Also if you are into NestJS you might be interested in one of my other NestJS libs.

create-nestjs-middleware-module's People

Contributors

actions-user avatar dependabot-preview[bot] avatar dependabot[bot] avatar github-actions[bot] avatar iamolegga avatar mergify[bot] avatar micalevisk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

create-nestjs-middleware-module's Issues

remove FacadeModule

FacadeModule seems to be redundant.
I was not patient enough and migrated this module to nest8 a long time ago.
As a part of the migration, I got rid of FacadeModule and it seems to work fine without it.
Maybe you consider removing it too

Add some description to `optionsToken` symbol

when using NEST_DEBUG=true on NestJS 8.2.0, the following line will crashes the app due to this bug: nestjs/nest#8560

const optionsToken = Symbol();

this isn't the problem, tho.


What do you think of changing that symbol to Symbol('create-nestjs-middleware-module:options') or something? I guess this will help people on debugging nestjs's resolutions

For now we'll get (after Nest 8.2.1) an entry like

... Resolving dependency FooToken in the Symbol() provider

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.