0.3.1 • Published 8 months ago

create-nestjs-middleware-module v0.3.1

Weekly downloads
2,826
License
MIT
Repository
github
Last release
8 months ago

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.
0.2.2-alpha.9d66e6

9 months ago

0.2.2-alpha.11bb6a

9 months ago

0.2.2-alpha.0b0f99

9 months ago

0.2.2-alpha.1242bd

9 months ago

0.2.2-alpha.62a949

8 months ago

0.2.2-alpha.bd0ea6

9 months ago

0.2.2-alpha.dee776

9 months ago

0.2.2-alpha.4831b5

9 months ago

0.2.2-alpha.2ade47

9 months ago

0.2.2-alpha.20021c

9 months ago

0.3.0-alpha.3dd795

8 months ago

0.2.2-alpha.b7c782

9 months ago

0.2.2-alpha.dba834

10 months ago

0.2.2-alpha.f5acfa

9 months ago

0.2.2-alpha.46624

9 months ago

0.2.2-alpha.3c3861

10 months ago

0.3.0

8 months ago

0.3.1

8 months ago

0.2.2-alpha.7b00fb

9 months ago

0.2.2-alpha.2b27d5

8 months ago

0.2.2-alpha.a3f95d

9 months ago

0.2.2-alpha.a4f032

10 months ago

0.2.2-alpha.8cc5f3

10 months ago

0.2.2-alpha.7f86f1

10 months ago

0.2.2-alpha.6b79ec

10 months ago

0.2.2-alpha.8606e6

10 months ago

0.2.2-alpha.2c70f9

10 months ago

0.2.2-alpha.17464

11 months ago

0.2.2-alpha.056ef6

11 months ago

0.2.2-alpha.04d59c

11 months ago

0.2.2-alpha.40ce92

11 months ago

0.2.2-alpha.0cf3fb

11 months ago

0.2.2-alpha.99136c

11 months ago

0.2.2-alpha.20615c

11 months ago

0.2.2-alpha.35a63e

11 months ago

0.2.2-alpha.ecb542

11 months ago

0.2.2-alpha.30a105

12 months ago

0.2.2-alpha.a60522

12 months ago

0.2.2-alpha.fe15ee

12 months ago

0.2.2-alpha.bd692d

12 months ago

0.2.2-alpha.964e62

12 months ago

0.2.2-alpha.01c6a0

11 months ago

0.2.2-alpha.8c09c6

12 months ago

0.2.2-alpha.21d653

12 months ago

0.2.2-alpha.26005b

12 months ago

0.2.2-alpha.40f385

12 months ago

0.2.2

2 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.1.0

4 years ago