1

I'm new to fastify and all the back-end js stuff. I'm currently working on a TypeScript/Fastify backend which I should maybe have started only with JS lol. My issue is the same as this one, which is kinda old now: Fastify Typescript request query Here's my code:

type ParamsType = { id: string }

const getOpts = {
    schema: {
        response: {
            200: {
                type: 'object',
                properties: {
                    id: { type: 'number' },
                    title: { type: 'string' },
                    author: { type: 'string' },
                    imagePath: { type: 'string' },
                },
            },
        },
    },
    handler: (req: FastifyRequest<{ Params: ParamsType }>, reply: FastifyReply) => {
        const { id } = req.params
        reply.send(repository.read(id));
    }
};
fastify.get('/articles/:id', getOpts);
next();

Nothing fancy here I guess, but still when reaching the endpoint i get the error:

{"statusCode":500,"error":"Internal Server Error","message":"Cannot read properties of null (reading 'id')"}

Here's the result of console.log(req.params):

{ id: '1' }

Futhermore, the getOpts is underlined in my IDE in the fastify.get but does not trigger any warning or alert when building

Any help is appreciated !

Symtox
  • 77
  • 5
  • 1
    What does return repository.read? – Manuel Spigolon Feb 27 '23 at 12:13
  • okay, my mistake, i was wrongly assuming that the params where the problem, but it seems like it's not. repository.read was returning a null object. I feel dumb ahah. Thanks for your help, feel free to leave an answer, i'll mark it as valid ! – Symtox Feb 27 '23 at 17:00

1 Answers1

2

Starting from the code reply.send(repository.read(id)) I assume the repository returns a Promise or something else.

This is not handled by Fastify - you need to await the result or use an async function:

    handler: async (req: FastifyRequest<{ Params: ParamsType }>, reply: FastifyReply) => {
        const { id } = req.params
        return repository.read(id);
    }

Then the output will be processed by the response schema set.

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73