/** * @module RESTController * * RESTController for MongoDB. */ import * as debugStuff from 'debug' const debug = debugStuff.debug('dbApiRESTCtrl') import mongoose from 'mongoose' mongoose.Promise = Promise import { Router } from 'express' const MAX_RESULTS = 100 /** * REST controller for MongoDB backend. */ class RESTController { /** * Generates a controller for a model type. * * @param {mongoose.Model} mongoose model to use * @param {key} Key to use as index. Default is '_id' * @return {null} */ constructor (model, key = '_id') { this.model = model this.modelName = model.modelName.toLowerCase() this.key = key } /** * Creates a DB item. * * @param {object} data object * @return {null} */ create (data) { return this.model .create(data) .then(instance => { const response = {} response[this.modelName] = instance return response }) } read (id) { const filter = {} filter[this.key] = id return this.model .findOne(filter) .then(instance => { const response = {} response[this.modelName] = instance return response }) } list () { return this.model .find({}) .limit(MAX_RESULTS) .then(instance => { const response = {} response[this.modelName] = instance return response }) } update (id, data) { const filter = {} filter[this.key] = id return this.model .findOne(filter) .then(instance => { console.log(instance) for (let attribute in data) { if (data.hasOwnProperty(attribute) && attribute !== this.key && attribute !== '_id') { instance[attribute] = data[attribute] } } return instance.save() }) .then(instance => { const response = {} response[this.modelName] = instance return response }) } delete (id) { const filter = {} filter[this.key] = id return this.model .remove(filter) .then(() => { return {} }) } route () { const router = new Router() router.get('/', (req, res) => { this .list() .then(data => res.json(data)) .then(null, error => res.status(404).send(error)) }) router.post('/', (req, res) => { this .create(req.body) .then(data => res.json(data)) .then(null, error => res.status(404).send(error)) }) router.get('/:key', (req, res) => { this .read(req.params.key) .then(data => res.json(data)) .then(null, error => res.status(404).send(error)) }) router.put('/:key', (req, res) => { this .update(req.params.key, req.body) .then(data => res.json(data)) .then(null, error => res.status(404).send(error)) }) router.delete('/:key', (req, res) => { this .delete(req.params.key) .then(data => res.json(data)) .then(null, error => res.status(404).send(error)) }) return router } } debug('Defined RESTController') export default RESTController