I'm working in this API where I can access data for many queries, but I'm having problems to retrieve data for a query by name containing (like:%data%), with dynamic data. I think it might just be a problem configuring the route so I can have access to this data in the URL api/data/dynamicdata.
Here's what I have - the controller:
const { Op } = require('sequelize');
const Artisan = require ('../models/artisan');
exports.getByName = async (req, res, next) => {
try {
const { nom } = req.params;
const artisan = await Artisan.findAll({
attributes: { exclude: ['createdAt', 'updatedAt'] },
where: {nom: {[Op.like]: `%${nom}%}`},
}});
if (artisan) {
return res.status(200).json(artisan);
}
return res.status(404).json('user_not_found');
} catch (error) {
console.error('Erreur dans /artisan :', error);
res.status(500).json({ error: 'Failed to fetch artisan' });
}
};
The route
var express = require('express');
var router = express.Router();
const service = require ('../services/artisans');
router.get ('/', service.getAll);
router.get ('/nom', service.getByName);
module.exports = router;
The app
const artisanNom = require('./routes/artisans');
app.use('/artisans/',artisanNom);
If I try to access the data from the URL localhost:3000/artisans/nom?=data, it returns me an empty array. If I put a static data in my controller localhost:3000/artisans/nom, it returns the data I expected, so this route is working for static data so it seems either I don't know how to retrieve the result from the URL using dynamic data, or I might configure the route differently.
I'd be grateful for any help.