I have an application in NestJS using Fastify. I want to set a the Content-Type to application/hal+json
in my responses. I have the following code in a NestJS interceptor:
@Injectable()
export class SampleInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
context.switchToHttp().getResponse()
.header('Content-Type', 'application/hal+json; charset=utf-8');
return next.handle().pipe(
map((data) => {
const serializer = MyCustomSerializer();
return serializer.serialize(data);
})
);
}
}
However, I have the following error because I defined the Content-Type:
FastifyError [FST_ERR_REP_INVALID_PAYLOAD_TYPE]: FST_ERR_REP_INVALID_PAYLOAD_TYPE: Attempted to send payload of invalid type 'object'. Expected a string or Buffer.
at onSendEnd (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:363:11)
at onSendHook (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:325:5)
at _Reply.Reply.send (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:151:3)
at FastifyAdapter.reply (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/platform-fastify/adapters/fastify-adapter.js:37:25)
at RouterResponseController.apply (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-response-controller.js:10:36)
at /home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-execution-context.js:163:48
at processTicksAndRejections (internal/process/task_queues.js:85:5)
at async /home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-execution-context.js:46:13
at async Object.<anonymous> (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-proxy.js:8:17)
After some investigation, I noticed that if I do not define the Content-Type, the payload is a string representation of my JSON response. If not, the payload is an object. This happens because this code in fastify never runs and never serializes the payload as string.
Here is a repository for you to easily replicate the issue.
Is there a way to solve this issue?