Skip to content

Instantly share code, notes, and snippets.

@watert
Created July 30, 2014 09:41
Show Gist options
  • Save watert/5822c1498c9757454623 to your computer and use it in GitHub Desktop.
Save watert/5822c1498c9757454623 to your computer and use it in GitHub Desktop.
RestfulAPI router with expressjs and mongoose
# usage: app.use "/[collectionName]", require("./routes/[collectionName]")
express = require('express')
class ModelRestfulRouter
findOne:(req,res)->
@model.findById req.params.id,(err,data)->
unless err then res.json(data)
find:(req,res)->
query = req?.query or {}
@model.find query,(err,data)->
if not err then res.json(data)
else throw "Query Error"
insert:(req,res)->
body = req.body
@model.findOne body,(err,data)=>
if data
throw new Error err = "Inserting Duplicate Entry"
res.json err
return
model = new @model(body)
model.save (err,data)->
unless err then res.json(data)
update:(req,res)->
data = req.body
@model.findById req.params._id,(err,model)->
model.set(data).save (err,data)->
res.json(data)
remove:(req,res)->
@model.findByIdAndRemove req.params._id,(err,data)->
res.json yes
bindAll:()->
@router.get "/",@find
@router.get "/id",@findOne
@router.put "/",@insert
@router.post "/",@insert
@router.post "/:id",@update
@router.delete "/:id",@remove
return this
constructor:(options)->
@options = options
@model = options.model
@router = express.Router()
@bindAll()
# User = require "../models/user.coffee" # Mongoose Model
mongoose = require "mongoose"
mongoose.connect("localhost/test")
Model = mongoose.model "ModelName",{name:"String"}
routerModel = new ModelRestfulRouter({model:Model})
module.exports = routerModel.router
# Mocha test case
if require.main.filename.indexOf("_mocha") isnt -1
assert = require("assert")
describe "Restful API", ->
testingId = null
it "Query:return json is obj",(done)->
routerModel.find req=null,res=json:(data)->
assert typeof(data) is "object","isobj"
done()
it "Insert:", (done)->
req = body:
name:"testing2"
routerModel.insert req,res=json:(data)->
assert data.name is req.body.name and data._id
testingId = data._id
done()
it "Find One:", (done)->
assert testingId
req= params: id: testingId
routerModel.findOne req,res=json:(data)->
assert typeof(data) is "object"
done()
it "Update Item:", (done)->
assert testingId
# if not testingId then throw new Error "No ID"
req =
params: _id: testingId
body: name: "testcase2"
routerModel.update req,json:(data)->
assert data.email is req.body.email and data._id
done()
it "Remove Item",(done)->
assert testingId
req = params: _id: testingId
routerModel.remove req,res=json:(data)->
done()
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment