express
and knex
are beating me a little; I can't make this endpoint work using req.querys
(response from express
), even though I made one with req.params
and it was ok.
app.get(`/actor`, async (req: Request, res: Response) => {
try {
// const { gender } = req.query;
const count = await getActorsByGender(req.query.gender as string);
console.log({ count });
res.status(200).send({ quantity: count, });
} catch (error) {
res.status(200).send({ message: error.sqlMessage || error.message });
}
});
const getActorsByGender = async (gender: string): Promise<any> => {
try {
const result = await connection.raw(`
SELECT COUNT(*) as count FROM Actor
WHERE gender = "${gender}"
`);
// console.log(`Temos: ${result[0][0].count} ocorrências`);
return result;
} catch (error) {
console.log(error);
}
};
This might be because of the count()
, but I'm not sure. The knex
part is ok; I can console.log()
the result.
The express
part showed a empty object on insomnia
Using 'male' as parameter it was expected to return "2" as result.
Your sending male
as a route/path parameter since you use http://localhost:3000/actor/male
.
If you want to access it as a query-param, you can leave your code as it is, but you need to change your request-url to http://localhost:3000/actor?gender=male
Note that ff you wanted to define gender
as a route-parameter, you'd need to change your route-handler to app.get("/actor/:gender")
and access it using req.params.gender
.