在项目里面,我网站用的是2层结构:UI + WebService(REST API),这样的好处是UI和后端可以完全分离。UI我用的是expressJs,后端Service层用的也是expressJs。今天看到一个轻量级的、专为REST API定制的框架,restify(详细文档:http://mcavage.github.io/node-restify)。restify应该是基于connect的,和expressJs用法也差不多,只不过,有少许区别,好处是,他支持server、client两种!server可以是一个http server、json server、string server(区别是返回的body类型是application/plain, application/json, ...)。而且他还支持带version支持的RESTFUL API(使用header: accept-version: ~1控制)。下面就是使用代码:
var restify = require('restify') , routes = require('./routes'); var server = restify.createServer({ name: 'CER Web Service', versions: ['1.0.0'] }); server.use(restify.pre.userAgentConnection()); // work around for curl server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser()); // static files: /, /index.html, /images... server.get(/^\/((.*)(\.)(.+))*$/, restify.serveStatic({ directory: 'public', default: "index.html" })); // testing the service server.get('/test', function (req, res, next) { res.send("testing..."); next(); }); server.get('/products', routes.product_list); server.get('/sendEmail', routes.sendEmail); server.get('/:productId/top_crash/week/:weekId', routes.top_crash); server.get('/:productId/weekly_crash/week/:weekId', routes.weekly_crash); server.get('/:productId/weekly_crash_per_user/week/:weekId', routes.weekly_crash_per_user); server.get('/:productId/related_products', routes.related_product_list); server.get('/:productId/weeks', routes.week_list); server.get('/:productId/fix_rate/week/:weekId', routes.fix_rate); server.get('/:productId/os_breakdown/week/:weekId', routes.os_breakdown); server.get('/:productId/bucket/week/:weekId', routes.bucket); server.listen(8080, function () { console.log('%s listening at %s', server.name, server.url); });
1. pre.userAgentConnection():这个是为处理keep-alive的curl命令的。
2. acceptParser():返回支持信息,比如json, plain等。
接下来就是路由功能了:
1. serveStatic:这个需要讲一下,和expressJs不同,对于静态文件的获取,expressJs是调用use(),并传入一个static()中间件的,但是restify要求,一定要映射到一个路径上去,所以只能使用get。
2. 最后一个参数next()不能省略。
3. 之后的一些get,都和expressJs一模一样了,完全相同。
从expressJs移植到restify很方便,对于我来说,只是修改了app.js,然后删除了一些无用的目录即可。
接下来看看client端,以前我是使用http.get()来访问页面的,现在可以使用restify提供的client类:
var http = require('http') , util = require('util') , assert = require('assert') , restify = require('restify'); var jsonClient = restify.createJsonClient({ url: "http://localhost:8080", version: "1.0.0" }); module.exports = { host: "http://localhost:8080", products: "/products", relatedProducts: "/{productId}/related_products", weeks: "/{productId}/weeks", weeklyCrashCount: "/{productId}/weekly_crash/week/{weekId}", weeklyCrashCountPerUser: "/{productId}/weekly_crash_per_user/week/{weekId}", topCrashCommands: "/{productId}/top_crash/week/0", fixRate: "/{productId}/fix_rate/week/{weekId}", osBreakdown: "/{productId}/os_breakdown/week/{weekId}", bucket: "/{productId}/bucket/week/{weekId}", getRequestUrl: function (url, keyValues) { for (var key in keyValues) { url = url.replace("{" + key + "}", keyValues[key]); } return url; }, getCall: function (url, callback) { jsonClient.get(url, function (err, req, res, obj) { if (err) { console.log(err); callback(err, res.statusCode); } else { callback(undefined, obj); } }); } };
其实,你看看restify的实现,也超简单的,就是从服务器端拿到数据,然后用JSON.parse()将他转换成js的对象而已。