restify是用于编写RESTful API的Node.js的模块。
下面介绍如何使用restify和mongodb编写一个面向geek的招聘平台,使用RESTful API发布和查看用工需求。
restify = require 'restify'
mongojs = require mongojs
ip_addr = '127.0.0.1'
port = '3000'
server = restify.createServer(name : "geekjob")
server.listen(port ,ip_addr, ->
console.log('%s listening at %s ', server.name , server.url))
运行:
coffee geek-job.coffee
很好,虽然什么也没干,但是已经能跑了!
restify模块有很多内置插件,不用白不用。
server.use restify.queryParser()
server.use restify.bodyParser()
server.use restify.CORS()
restify.queryParser()
插件用于解析HTTP请求结果存在req.query
。restify.bodyParser()
将请求数据转化成CoffeeScript对象。restify.CORS()
添加CORS支持。
连接MongoDB数据库
connection_string = '127.0.0.1:27017/geekjob';
db = mongojs(connection_string, ['geekjob']);
jobs = db.collection("jobs")
准备工作完成了。开始干正事,定义CRUD。
PATH = '/jobs'
server.get({path : PATH, version : '0.0.1'} , list_all_jobs)
server.get({path : PATH +'/:jobId', version : '0.0.1'} , show_job)
server.post({path : PATH , version: '0.0.1'}, add_new_job)
server.del({path : PATH +'/:jobId', version: '0.0.1'} , remove_job)
框架已经有了,往里填回调函数:
list_all_jobs = (req, res , next) ->
res.setHeader('Access-Control-Allow-Origin','*')
jobs.find().limit(20).sort({postedOn : -1} , (err , success) ->
console.log('Response success '+success)
console.log('Response error '+err)
res.send(200 , success)
next()
else
next(err)
)
show_job = (req, res , next) ->
res.setHeader('Access-Control-Allow-Origin','*')
jobs.findOne({_id:mongojs.ObjectId(req.params.jobId)} , (err , success) ->
console.log('Response success '+success)
console.log('Response error '+err)
if success
res.send(200 , success)
next()
else
next(err)
)
add_new_job (req , res , next) ->
job = {}
job.title = req.params.title
job.description = req.params.description
job.location = req.params.location
job.postedOn = new Date()
res.setHeader('Access-Control-Allow-Origin','*')
jobs.save(job , (err , success) ->
console.log('Response success '+success)
console.log('Response error '+err)
if success
res.send(201 , job)
next()
else
next(err)
)
remove_job = (req , res , next) ->
res.setHeader('Access-Control-Allow-Origin','*')
jobs.remove({_id:mongojs.ObjectId(req.params.jobId)} , (err , success) ->
console.log('Response success '+success)
console.log('Response error '+err)
if success
res.send(204)
next()
else
next(err)
)
O.K. 搞定了。快吧?
用curl
测试下:
curl -i -X POST -H 'Content-Type: application/json' -d '{"title":"CoffeeScript Developer Required" , "description":"NodeJS Developer Required" , "location":"A.T. Field"}' http://127.0.0.1:3000/jobs
curl -is http://127.0.0.1:3000/jobs