I'm new in Nest JS. I want to serialize custom response

Viewed 161

I want to return this object on every response:

class Response<T> {
    success: boolean
    message: string
    data: T
}

but built in serializer can't process it because it waits for object which is under serialization. This is my solution. I created a custom response serializer and inherit built in one and map response. It works excellent for now! Offered me better way please.

export interface PlainLiteralObject {
    [key: string]: any;
}

@Injectable()
export class ResponseSerializerInterceptor extends ClassSerializerInterceptor {

    public intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
        const contextOptions = super.getContextOptions(context);
        const options = {
            ...super.defaultOptions,
            ...contextOptions,
        };

        return next.handle().pipe(map((res: Response<PlainLiteralObject> | Response<Array<PlainLiteralObject>>) => {// data property holds object which is under serialization
            const data = super.serialize(res.data, options);

            res.data = data;
            
            return res;
        }));
    }
}
0 Answers
Related