After carefully following the documentation, I successfully implemented an interceptor for response mapping.
I am aiming to establish a uniform JSON format for all responses.
Is there a more effective way to achieve this rather than using an interceptor?
{
"statusCode": 201,
"message": "Custom Dynamic Message"
"data": {
// properties
meta: {}
}
}
transform.interceptor.ts
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface Response<T> {
statusCode: number;
data: T;
}
@Injectable()
export class TransformInterceptor<T>
implements NestInterceptor<T, Response<T>> {
intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<Response<T>> {
return next
.handle()
.pipe(
map((data) => ({
statusCode: context.switchToHttp().getResponse().statusCode,
data,
})),
);
}
}
app.controller.ts
export class AppController {
@Post('login')
@UseGuards(AuthGuard('local'))
@ApiOperation({ summary: 'Login user' })
@ApiBody({ type: LoginDto })
@ApiOkResponse({ content: { 'application/json': {} } })
@UseInterceptors(TransformInterceptor)
async login(@Request() req) {
const result = await this.authService.login(req.user);
return { message: 'Thank you!', result };
}
}