As a newcomer to JavaScript and React, I am currently working on a TypeScript project that involves using React, Sequelize, and Postgres for the database.
In my post route with Fastify, I am struggling to access the quantity
member of request.body
. Although I can see the correct quantity when logging the entire body, the individual extraction of the quantity yields undefined
.
interface IMyInterfaceCreateBody {
quantity: number;
}
interface IMyInterfacePostReply {
200: { items: MyObject[] };
201: { items: MyObject[] };
302: { url: string };
'4xx': { error: string };
}
const myRoute: FastifyPluginAsync = (fastify): Promise<void> => {
fastify.post<{
Body: IMyInterfaceCreateBody;
Reply: IMyInterfacePostReply;
}>('/myRoute', async function (request, reply) {
const newItems: MyObject[] = [];
const body: IMyInterfaceCreateBody = request.body;
console.log(body);
const quantity: number = body.quantity;
console.log(quantity);
for (let i = 0; i < quantity; i++) {
const newMyObject = await MyObject.create({
id: uuid(),
});
console.log(newMyObject);
newItems.push(newMyObject);
}
await reply.code(201).send({ items: newItems });
});
return Promise.resolve();
};
Upon looking at the console output:
[App] {"quantity":1}
[App] undefined
I suspect that the issue lies in how I am handling raw data with Fastify hooks.
Despite attempting different approaches such as directly extracting the quantity value or using an interface instance to handle the body, I still encounter the issue of getting an undefined value for quantity.
The goal is to successfully retrieve the passed quantity value using the post route.