Created
November 29, 2017 17:14
-
-
Save ClementKerneur/8cf256e75df5e76b392016c5c9a4b5f7 to your computer and use it in GitHub Desktop.
provide crud router express via Model dynamoose
This file contains hidden or 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
const express = require('express') | |
const bodyParser = require('body-parser') | |
module.exports = (Model) => { | |
let controller = express.Router() | |
controller.use(bodyParser.json()) | |
controller.get('/', (req, res) => { | |
Model.scan().exec( (err, elements) => { | |
res.json(elements) | |
} ) | |
}) | |
controller.post('/', (req, res) => { | |
let entity = new Model(req.body) | |
entity.save( (err, entity) => { | |
if(err) { | |
//Gerer cas erreur | |
} | |
else { | |
res.status(201) | |
res.json(entity) | |
} | |
} ) | |
}) | |
controller.get('/:id', (req, res) => { | |
Model.query({ Id: req.params.id }).exec( (err, entity) => { | |
if(err) { res.json(err); return; } | |
if(!entity.length) { | |
res.status(404) | |
res.json({ | |
error: 'not found' | |
}) | |
return; | |
} | |
else { | |
entity = entity[0] | |
res.json(entity) | |
} | |
}) | |
}) | |
controller.patch('/:id', (req, res) => { | |
Model.query({ Id: req.params.id }).exec( (err, entity) => { | |
if(err) { res.json(err); return; } | |
if(!entity.length) { | |
res.status(404) | |
res.json({ | |
error: 'not found' | |
}) | |
return; | |
} | |
else { | |
entity = entity[0] | |
Object.keys(req.body).forEach( (key) => { | |
entity[key] = req.body[key] | |
} ) | |
entity.save( (err, entity) => { | |
res.json(entity) | |
}) | |
} | |
}) | |
}) | |
controller.delete('/:id', (req, res) => { | |
Model.query({ Id: req.params.id }).exec( (err, entity) => { | |
if(err) { res.json(err); return; } | |
if(!entity.length) { | |
res.status(404) | |
res.json({ | |
error: 'not found' | |
}) | |
return; | |
} | |
else { | |
entity = entity[0] | |
entity.delete( (err) => { | |
res.json(entity) | |
} ) | |
} | |
}) | |
}) | |
return controller | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment