Last active
June 5, 2020 14:14
-
-
Save Raduuu/66d22d1a821ec6e77c6ac203e2eda359 to your computer and use it in GitHub Desktop.
This file contains 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 getOne = model => async (req, res) => { | |
try { | |
const doc = await model | |
.findOne({ createdBy: req.user._id, _id: req.params.id }) | |
.lean() | |
.exec() | |
if (!doc) { | |
return res.status(400).end() | |
} | |
res.status(200).json({ data: doc }) | |
} catch (e) { | |
console.error(e) | |
res.status(400).end() | |
} | |
} | |
export const getMany = model => async (req, res) => { | |
try { | |
let query = {} | |
const count = await model.count() | |
const docs = await model | |
.find(query) | |
.lean() | |
.exec() | |
res.status(200).json({ | |
data: docs, | |
count, | |
}) | |
} catch (e) { | |
console.error(e) | |
res.status(400).end() | |
} | |
} | |
export const createOne = model => async (req, res) => { | |
const createdBy = req.user._id | |
try { | |
const doc = await model.create({ ...req.body, createdBy }) | |
res.status(201).json({ data: doc }) | |
} catch (e) { | |
console.error(e) | |
res.status(400).end() | |
} | |
} | |
export const updateOne = model => async (req, res) => { | |
try { | |
const updatedDoc = await model | |
.findOneAndUpdate( | |
{ | |
_id: req.params.id | |
}, | |
req.body, | |
{ new: true } | |
) | |
.lean() | |
.exec() | |
if (!updatedDoc) { | |
return res.status(400).end() | |
} | |
res.status(200).json({ data: updatedDoc }) | |
} catch (e) { | |
console.error(e) | |
res.status(400).end() | |
} | |
} | |
export const removeOne = model => async (req, res) => { | |
try { | |
const removed = await model.findOneAndRemove({ | |
_id: req.params.id | |
}) | |
if (!removed) { | |
return res.status(400).end() | |
} | |
return res.status(200).json({ data: removed }) | |
} catch (e) { | |
console.error(e) | |
res.status(400).end() | |
} | |
} | |
export const crudControllers = model => ({ | |
removeOne: removeOne(model), | |
updateOne: updateOne(model), | |
getMany: getMany(model), | |
getOne: getOne(model), | |
createOne: createOne(model) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment