@redhare/interceptors
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

@infra-node-kit/interceptors

NestJS provide a Interceptor concept. Interceptors have a set of useful capabilities which are inspired by the Aspect Oriented Programming (AOP) technique. This package function is to collect commonly used interceptor.

Installation

yarn add '@infra-node-kit/interceptors'

StandardResponseInterceptor

Introduce

This interceptor wrap normal return value to data field of standard response. The standard response as follow:

{
  data,
  code: 0,
  message: 'OK',
  status: 200
}
  • Hint: if you has the demand of custom the special response format, you can use @Res() response to skip the StandardResponseInterceptor.

Usage

Import and call app.use

import { StandardResponseInterceptor } from '@infra-node-kit/interceptors';

const app = await NestFactory(AppModule);
...
app.use(new StandardResponseInterceptor());

await app.listen(3000);
  • Response example
@Controller('')
export class TestController {
  @Get()
  async test() {
    return {
      name: 'infra-node-kit'
    }
  }
}

the response will be:

{
  data: {
    name: 'infra-node-kit'
  },
  code: 0,
  message: 'OK',
  status: 200
}
  • Not work example
@Controller('')
export class TestController {
  @Get()
  async ResPassthrough(@Res() res: Response) {
    res.send({
      name: 'infra-node-kit'
    })
  }
}

the response will be:

{
  name: 'infra-node-kit'
}

Custom Option

GetStandardResponseInterceptor( options: IStandardResponseOptions )

interface IStandardResponseOptions {
  skipPaths?: string[] // the path in the skipPaths will ignore wrapper
  code?: number // the uniform code
  message?: string // the uniform message
}
import { GetStandardResponseInterceptor } from '@infra-node-kit/interceptors';

const app = await NestFactory(AppModule);
...
const StandardResponseInterceptor = GetStandardResponseInterceptor({
  skipPaths: ['/metrics'],
  code: 1,
  message: 'is success'
})
app.use(new StandardResponseInterceptor());

await app.listen(3000);

Readme

Keywords

none

Package Sidebar

Install

npm i @redhare/interceptors

Weekly Downloads

2

Version

0.0.2

License

ISC

Unpacked Size

104 kB

Total Files

11

Last publish

Collaborators

  • tobywan
  • yann001
  • jiushu
  • keyunlei
  • zsynuting