Skip to content

Commit

Permalink
working prototype
Browse files Browse the repository at this point in the history
  • Loading branch information
Kam1ni committed Feb 16, 2018
1 parent a05ccfe commit 83ade97
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
package-lock.json
66 changes: 66 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const express = require("express");

function onError(err,req,res,next){
return module.exports.onError(err,req,res,next);
}

module.exports = function(model){
let router = express.Router();
router.get("/", async function(req,res,next){
try{
res.json(await model.find());
}catch(err){
onError(err,req,res,next);
}
});

router.get("/:id", async function(req,res,next){
try{
res.json(await model.findById(req.params.id));
}catch(err){
onError(err,req,res,next);
}
});

router.post("/", async function(req,res,next){
try{
let item = new model(req.body);
await item.save();
res.json(item);
}catch(err){
onError(err,req,res,next);
}
});

router.put("/:id", async function(req,res,next){
try{
let item = await model.findById(req.params.id);
if (!item){
throw new Error("Item does not exist", {status: 401});
}
item.set(req.body);
await item.save();
res.json(item);
}catch(err){
onError(err,req,res,next);
}
});

router.delete("/:id", async function(req,res,next){
try{
let item = await model.findById(req.params.id);
await item.remove();
res.json(item);
}catch(err){
onError(err,req,res,next);
}
});

return router;
}

module.exports.onError = function(err, req, res, next){
console.error(err.message);
console.error(err.stack);
res.status(err.status || 500).json({message:err.message});
}
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,9 @@
"bugs": {
"url": "https://github.com/Kam1ni/restify-express-mongoose/issues"
},
"homepage": "https://github.com/Kam1ni/restify-express-mongoose#readme"
"homepage": "https://github.com/Kam1ni/restify-express-mongoose#readme",
"dependencies": {
"express": "^4.16.2",
"mongoose": "^5.0.6"
}
}

0 comments on commit 83ade97

Please sign in to comment.