36 lines
1.1 KiB
TypeScript
36 lines
1.1 KiB
TypeScript
import {
|
|
Injectable,
|
|
NestInterceptor,
|
|
ExecutionContext,
|
|
CallHandler,
|
|
} from '@nestjs/common';
|
|
import { Observable } from 'rxjs';
|
|
import { map } from 'rxjs/operators';
|
|
import { Request } from 'express';
|
|
import { Reflector } from '@nestjs/core';
|
|
import { PAGINATION_RESPONSE } from '../constants';
|
|
import { createPaginationResponse } from './utils/pagination-meta.helper';
|
|
|
|
@Injectable()
|
|
export class TransformInterceptor implements NestInterceptor {
|
|
constructor(protected readonly reflector: Reflector) {}
|
|
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
|
const isPagination = this.reflector.getAllAndOverride<boolean>(
|
|
PAGINATION_RESPONSE,
|
|
[context.getHandler(), context.getClass()],
|
|
);
|
|
|
|
const request = context.switchToHttp().getRequest<Request>();
|
|
const start = request.query.page ?? 1;
|
|
const limit = request.query.limit ?? 10;
|
|
|
|
return next.handle().pipe(
|
|
map((data) => {
|
|
return isPagination
|
|
? createPaginationResponse(data, +start, +limit)
|
|
: { data };
|
|
}),
|
|
);
|
|
}
|
|
}
|