Home > Back-end >  How to transform Prisma result into custom model before returning to client with NestJS?
How to transform Prisma result into custom model before returning to client with NestJS?

Time:10-04

I'm pretty new to NestJS and Prisma. I need help understanding how to transform Prisma result into custom model before returning to client.

Result from Prisma:

{
  "id": 1,
  "name": "Ajitesh",
  "age": 24
}

If I return directly to client, I get the same response as above.

What I want:

{
  "status": 200,
  "message": "User data retrieved",
  "data": {
    "user": {
      "id": 1,
      "name": "Ajitesh",
      "age": 24
    }
  }
}

I want the response to be in the above structure. The data should be added to this custom model before returning to client.

In fact, all the response should be in this format. Is there anyway to add it globally in NestJS?

Thanks.

CodePudding user response:

Sounds like the exact use case mentioned in the docs for response mapping using an interceptor. You'd probably need to modify a few things, like adding a decorator to set the message and top level data key, but then something like this could work

@Injectable()
export class ResponseMappingInterceptor implements NestInterceptor {
  constructor(private readonly reflector: Reflector) {}

  intercept(context: ExecutionContext, next: CallHandler) {
    const message = this.reflector.get('RESPONSE_MESSAGE', context.getHandler());
    const topLevelKey = this.reflector.get('RESPONSE_DATA_KEY', context.getHandler());
    return next.handle().pipe(
      map((data) => ({
        status: context.switchToHttp().getResponse().statusCode,
        message,
        data: {
          [key]: data
        }
      })
    }
  }
}
  • Related