import Project from './model' import mongoose from 'mongoose' const routing = { /** GET handler (request one or more projects) */ get: (req, res, next) => { console.log(req.params) console.log(req.query) console.log(Project.schema.obj) const path = req.params['0'] let id = req.params['1'] /** If the path doesn't match, call the next router */ if (path !== '/project') { next() } /** check whether an id was specified. */ if (typeof id !== 'undefined') { try { id = mongoose.Types.ObjectId(req.params['1'].substring(1)) } catch (err) { res.status(422) res.send({error: err.message}) return } console.log(id) /** if yes, return the one project */ Project.findOne({ _id: id }, function (err, project) { if (err) { res.status(404) res.send(err) return } res.json(project) }) } else { /** if not, return all projects */ /** @todo: add some pagination here */ /** @todo: add some filtering here */ Project.find(function (err, projects) { if (err) { res.status(404) res.send(err) return } res.json(projects) }) } }, /** POST handler (insert new projects into database) */ post: (req, res, next) => { const path = req.params['0'] // const id = req.params['1'] /** If the path doesn't match, call the next router */ if (path !== '/project') { next() } const project = new Project(req.body) project.save(function (err) { if (err) { res.status(422) res.send(err) return } res.send({ success: 'Project added.' }) }) }, /** PUT handler (update existing project) */ put: (req, res, next) => { const path = req.params['0'] const id = mongoose.Types.ObjectId(req.params['1'].substring(1)) /** If the path doesn't match, call the next router */ if (path !== '/project') { next() } Project.findOne({ _id: id }, function (err, project) { if (err) { res.status(404) res.send(err) } for (let prop in req.body) { project[prop] = req.body[prop] } project.save(function (err) { if (err) { res.status(422) res.send(err) } res.json({ message: 'Movie updated.' }) }) }) }, /** DELETE handler (delete project) */ delete: (req, res, next) => { const path = req.params['0'] const id = mongoose.Types.ObjectId(req.params['1'].substring(1)) /** If the path doesn't match, call the next router */ if (path !== '/project') { next() } Project.remove({ _id: id }, function (err, project) { if (err) { res.send(err) } res.json({ message: 'Movie deleted.' }) }) } } export default routing