i am learning backend, new to express framework and having difficult creating search bar api, i am using typescript, express.js with prisma & postgresql with db client Dbeaver, help me out how to create search bar api to get search user from database by email, name or phone number, with separate service, controller, schema and route. looking forward to your answers, thank you
i tried this but it return me the empty object data.
Service:
export async function search(query:string){
try{
const users = await prisma.user.findMany({
select: {
id: true,
name: true,
email: true,
number: true,
country: true,
city: true,
createdAt: true,
updatedAt: true,
active: true,
},
where:{OR:[{name:{contains:query, mode:"insensitive"}},
{number:{contains:query, mode:"insensitive"}},
{email:{contains:query, mode:"insensitive"}}
]},
})
return users;
}
catch(error:any){throw new Error(error.message)}
}
controller:
export async function searchBarHandler(req: Request, res: Response) {
try {
const currentUserId: number = (req as any).userId;
const user = await findUserById(currentUserId);
if (user.role != "Admin") throw new Error("Access denied");
const parsedQuery = searchBarSchema.parse(req.query.toString())
const querySearch = await search(parsedQuery);
console.log(querySearch)
res.status(200).json({
status: 200,
message: "Success",
data: querySearch,
success: true,
});
} catch (error: any) {
if (error instanceof ZodError) {`your text`
const messageJSON = JSON.parse(error.message);
const message = `${messageJSON[0].path[0]} is ${messageJSON[0].message}`;
console.error(message);
return res
.status(400)
.json({ status: 400, message: message, data: null, success: false });
}
console.error(error.message);
res.status(400).json({
status: 400,
message: error.message,
data: null,
success: false,
});
}
}
New contributor
Ashar Ul haq is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.