const defaults = require('./defaults') const { Op } = require('sequelize') 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) if (!fields) throw new Error('Table has no searchable fields') const or = fields.map(field => ({ [field.fieldName]: { [Op.like]: `%${req.query.q}%` } })) const where = { [Op.or]: or } const data = (await Type.findAll({ where })).map(d => d.sanitize ? d.sanitize() : d) res.status(200).send(data) } else if (res.query && res.query.ids) { const ids = res.query.ids.split(',') const data = (await Type.findAll({where: { id: { [Op.in]: ids }}})).map(d => d.sanitize ? d.sanitize() : d) res.status(200).send(data) } else { const data = (await Type.findAll()).map(d => d.sanitize ? d.sanitize() : d) res.status(200).send(data) } } const create = async (req, res) => { const data = (await Type.create(req.body)) res.status(200).send(data && data.sanitize ? data.sanitize() : data) } 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) } 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) } const $delete = async (req, res) => { const data = (await Type.destroy({ where: { id: req.params[opts.routeParam] } })) res.status(204).end() } const trash = async (req, res) => { const data = (await Type.findAll({ model: Type, paranoid: false, where: { deletedAt: { [Op.ne]: null } } })) res.status(200).send(data && data.sanitize ? data.sanitize() : data) } const undelete = async (req, res) => { const data = (await Type.update({ deletedAt: null }, { paranoid: false, 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