#What's the best way to return a response in nestjs?

2 messages · Page 1 of 1 (latest)

naive escarp
#

I followed the docs on this, but whenever I print the response status and if it's ok after the request is returned I get undefined:
Response Status: undefined multi-select.tsx:58 Response OK: undefined

` async retrieveConversationCollections(
id: string,
): Promise<conversationCollectionsDTO> {
const collections = await this.prisma.collection.findMany({
where: { id: uid },
});

console.log('[RetrievedConversationCollections]', collections);

const response: conversationCollectionsDTO = {
  collections: collections.map((c) => ({
    id: c.id,
    label: c.label,
    color: c.color,
    id: creatorId,
  })),
};

return response;

}
`

This returns as 200 in my console, but it's not ok, nor status prints. Any idea why?

`async retrieveConversationCollections(
@Res() response: Response,
@Query('id') id: string,
) {
const data = await this.messagesService.retrieveConversationCollections(id);
return response.status(HttpStatus.OK).send(data);

}`

bronze perch
#

It seems strange that the Status is returned as undefined.

https://docs.nestjs.com/controllers#status-code
As mentioned, the response status code is always 200 by default, except for POST requests which are 201. We can easily change this behavior by adding the @HttpCode(...) decorator at a handler level.