|
|
@@ -1,9 +1,10 @@
|
|
|
+const defaults = require('./defaults')
|
|
|
const { Op } = require('sequelize')
|
|
|
|
|
|
-const crudController = ({
|
|
|
- Type
|
|
|
-}) => ({
|
|
|
- list: async (req, res) => {
|
|
|
+const crudController = (opts) => {
|
|
|
+ opts = defaults(opts)
|
|
|
+ const { Type } = opts
|
|
|
+ const list = async (req, res) => {
|
|
|
// TODO Pagination (http://docs.sequelizejs.com/manual/tutorial/querying.html#pagination-limiting)
|
|
|
if (req.query && req.query.q) {
|
|
|
const fields = [Type.tableAttributes.name, Type.tableAttributes.tag].filter(x => x)
|
|
|
@@ -18,24 +19,24 @@ const crudController = ({
|
|
|
const data = (await Type.findAll()).map(d => d.sanitize ? d.sanitize() : d)
|
|
|
res.status(200).send(data && data.sanitize ? data.sanitize() : data)
|
|
|
}
|
|
|
- },
|
|
|
- create: async (req, res) => {
|
|
|
+ }
|
|
|
+ const create = async (req, res) => {
|
|
|
const data = (await Type.create(req.body))
|
|
|
res.status(200).send(data && data.sanitize ? data.sanitize() : data)
|
|
|
- },
|
|
|
- read: async (req, res) => {
|
|
|
- const data = (await Type.findOne({where: {id: req.params.id}}))
|
|
|
+ }
|
|
|
+ const read = async (req, res) => {
|
|
|
+ const data = (await Type.findOne({where: {id: req.params[opts.routeParam]}}))
|
|
|
res.status(200).send(data && data.sanitize ? data.sanitize() : data)
|
|
|
- },
|
|
|
- update: async (req, res) => {
|
|
|
- const data = (await Type.update(req.body, { where: { id: req.params.id } }))
|
|
|
+ }
|
|
|
+ const update = async (req, res) => {
|
|
|
+ const data = (await Type.update(req.body, { where: { id: req.params[opts.routeParam] } }))
|
|
|
res.status(200).send(data && data.sanitize ? data.sanitize() : data)
|
|
|
- },
|
|
|
- delete: async (req, res) => {
|
|
|
- const data = (await Type.destroy({ where: { id: req.params.id } }))
|
|
|
+ }
|
|
|
+ const $delete = async (req, res) => {
|
|
|
+ const data = (await Type.destroy({ where: { id: req.params[opts.routeParam] } }))
|
|
|
res.status(204).end()
|
|
|
- },
|
|
|
- trash: async (req, res) => {
|
|
|
+ }
|
|
|
+ const trash = async (req, res) => {
|
|
|
const data = (await Type.findAll({
|
|
|
model: Type,
|
|
|
paranoid: false,
|
|
|
@@ -44,15 +45,25 @@ const crudController = ({
|
|
|
}
|
|
|
}))
|
|
|
res.status(200).send(data && data.sanitize ? data.sanitize() : data)
|
|
|
- },
|
|
|
- undelete: async (req, res) => {
|
|
|
+ }
|
|
|
+ const undelete = async (req, res) => {
|
|
|
const data = (await Type.update({ deletedAt: null }, {
|
|
|
paranoid: false,
|
|
|
- where: { id: req.params.id }
|
|
|
+ where: { id: req.params[opts.routeParam] }
|
|
|
}))
|
|
|
res.status(200).send(data && data.sanitize ? data.sanitize() : data)
|
|
|
}
|
|
|
// TODO: Create, Read, Update, Delete
|
|
|
-})
|
|
|
+
|
|
|
+ return {
|
|
|
+ list,
|
|
|
+ create,
|
|
|
+ read,
|
|
|
+ update,
|
|
|
+ delete: $delete,
|
|
|
+ trash,
|
|
|
+ undelete
|
|
|
+ }
|
|
|
+}
|
|
|
|
|
|
module.exports = crudController
|