Created
February 8, 2023 14:57
-
-
Save jotredev/ec170ccc77aee526f8b985999ae8e6ac to your computer and use it in GitHub Desktop.
Buscador de usuarios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const searchUsers = async (req, res) => { | |
const { user } = req; | |
const { q, active } = req.query; | |
// Verify profiles | |
if (!user.profiles.includes("admin")) { | |
return res.status(401).json({ | |
response: "error", | |
msg: "No permissions", | |
type: "no-permissions", | |
}); | |
} | |
if (!ObjectId.isValid(user._id)) { | |
return res.status(404).json({ | |
response: "error", | |
type: "id-is-not-valid", | |
msg: "Id is not valid", | |
}); | |
} | |
if (q === "" || q === undefined) { | |
return res.status(404).json({ | |
response: "error", | |
type: "query-is-not-valid", | |
msg: "Query is not valid", | |
}); | |
} | |
let query = {}; | |
if (!isNaN(q)) { | |
query = { | |
cellphone: q, | |
}; | |
} else { | |
query = { | |
$or: [ | |
{ name: { $regex: q, $options: "i" } }, | |
{ firstLastname: { $regex: q, $options: "i" } }, | |
{ secondLastname: { $regex: q, $options: "i" } }, | |
{ email: { $regex: q, $options: "i" } }, | |
{ profiles: { $elemMatch: { $regex: q, $options: "i" } } }, | |
], | |
}; | |
} | |
if (active) { | |
query = { | |
...query, | |
active: true, | |
}; | |
} | |
const users = await User.find(query).select( | |
"-password -__v -logs -active -createdAt -updatedAt -lastLogin" | |
); | |
try { | |
return res.status(201).json(users); | |
} catch (error) { | |
console.log(error); | |
return res | |
.status(500) | |
.json({ response: "error", type: "server-error", msg: "Server error" }); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment