@redhare/interceptors
v0.0.2
Published
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.
Downloads
2
Keywords
Readme
@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 theStandardResponseInterceptor
.
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);