您的位置:首页 > 运维架构 > 网站架构

网站重构——轻量化的网站架构设计二,使用restify生成RESTful接口

2014-03-16 14:43 288 查看
有趣的是在有了数据之后,我们可以用很快的速度构建出一个app,构建出一个接口。我们要做的就是将系统一部分一部分解耦出来,成为一个又一个的独立部分

node restify

简单地来说,这是一个用于构建REST服务的工具。

restify is a node.js module built specifically to enable you to build correct REST web services. It intentionally borrows heavily from express as that is more or less the de facto API for writing web applications on top of node.js.

安装restify

还是一句命令
npm install restify

用restify创建rest接口

引自官网的示例
var restify = require('restify');

function respond(req, res, next) {
res.send('hello ' + req.params.name);
}

var server = restify.createServer();
server.get('/hello/:name', respond);
server.head('/hello/:name', respond);

server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});


运行
node app.js
我们可以直接打开浏览器查看http://0.0.0.0:8080/hello/z

整合sqlite3

我们需要取出其中的数据,因为暂时找不到合理的办法,每次查询都需要打开数据库。(转载保留:网站重构)
var restify = require('restify');

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('sqlite3.db');

var server = restify.createServer();
var content = new Array();

db.all("SELECT id,content,title,description,slug,created,updated<Plug>PeepOpenublish_date,keywords_string FROM blog_blogpost", function(err, rows) {
rows.forEach(function (row) {
content.push({
id:row.id,
slug:row.slug,
description:row.description,
title:row.title,
content:row.content,
keywords:row.keywords_string,
created:row.created,
updated:row.updated,
publish_date:row.publish_date
});
});
function respond(req,res,next){
var data = content[req.params.name-1];
res.json(data, {'content-type': 'application/json; charset=utf-8'});
}
server.get ('/blog/:name',respond);
server.head ('/blog/:name',respond);
db.close();
});

server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});


需要注意的是代码中的
var data = content[req.params.name-1];
是因为数组的关系
res.json(data, {'content-type': 'application/json; charset=utf-8'});
这部分则是对中文的支持,也就是UTF-8

结果

打开指定ID的时候就是下面的格式。
{"id":221,"slug":"restify-sqlite3-nodejs-to-refactory-website","description":"","keywords":"restify RESTful nodejs refactory","created":"2014-03-15 09:30:44.145964","updated":"2014-03-16 01:40:34.374479","publish_date":"2014-03-15 09:22:33"}

format一下

{ "content" : "",
"created" : "2014-03-15 09:30:44.145964",
"description" : "有趣的是在有了数据之后,我们可以用很快的速度构建出一个app,构建出一个接口。我们要做的就是将系统一部分一部分解耦出来,成为一个又一个的独立部分",
"id" : 221,
"keywords" : "restify RESTful nodejs refactory",
"publish_date" : "2014-03-15 09:22:33",
"slug" : "restify-sqlite3-nodejs-to-refactory-website",
"title" : "nodejs restify sqlite3网站重构二,生成RESTful接口",
"updated" : "2014-03-16 01:40:34.374479"
}
运行
forever start app.js

最后效果可见:Phodal's
New Homepage
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐