Blog

Blog

PHODAL

IoT CoAP 添加REST支持

在完成第一阶段的CoAP功能之后,顺手把RESTful的HTTP版也添加了进去。

CoAP REST 使用

创建一个简单的index.js

const iotcoap         = require('iot-coap');

iotcoap.run();
iotcoap.rest.run(); //运行REST

这样我们就可以在不破坏原来功能的基本上添加新的特性了。只是我们还需要修改数据的配置

{
    "db_name": "iot.db",
    "table_name": "basic",
    "key":[
        "id",
        "value",
        "sensors1",
        "sensors2"
    ],
    "db_table": "id integer primary key, value text, sensors1 float, sensors2 float",
    "init_table":[
        "insert or replace into basic (id,value,sensors1,sensors2) VALUES (1, 'is id 1', 19, 20);",
        "insert or replace into basic (id,value,sensors1,sensors2) VALUES (2, 'is id 2', 20, 21);"
    ],
    "query_table":"select * from basic;",
    "rest_url": "/id/:id",
    "rest_post_url": "/",
    "rest_port": 8848
}

添加了REST的端口配置,以及URL。

CoAP REST 创建

有一个大前提是这里共用的是同一个数据库,自然而然的我们也可以用同一个db_helper。修改index.js

添加rest

为了变成一个NodeJS的包提供给外部的函数使用,我们需要将其exports出去,于是修改index.js,添加下面的内容:

const rest         = require('./server/rest');
module.exports.rest = rest;

创建REST

代码如下所示,我们所做的便是创建一个RESTify 的基本资源管理

        restserver.use(restify.gzipResponse());
        restserver.use(restify.bodyParser());
        restserver  .use(restify.acceptParser(['json', 'application/json']));

        restserver.get(config["rest_url"],       rest_helper.get_respond);
        restserver.put(config["rest_post_url"],  rest_helper.post_respond);
        restserver.del(config["rest_url"],       rest_helper.del_respond);
        restserver.post(config["rest_post_url"], rest_helper.post_respond);
        restserver.head(config["rest_url"],      rest_helper.respond);

        restserver.listen(config["rest_port"], function() {
            console.log('%s listening at %s', restserver.name, restserver.url);
        });

详细代码可见

[https://github.com/gmszone/iot-coap](https://github.com/gmszone/iot-coap)

REST GET/DELETE

再exports出这个rest,而rest_helper所做的便是一个与数据库的兼容。

rest_helper.respond = function(req, res, next) {
    restdb_helper.urlQueryData(req.url, function(e){
        res.send(JSON.parse(e));
        next();
    })
};

看看在query_helper.js中写的

query_helper.syncJSON = function(req, res, block) {
    DBHelper.syncData(block, function (result) {
        returnResult.saveAndCode(block, res);
    });
};

两个看上去差不多,于是我们算是做了一个好的示例。而其他的大致也是类似的

rest_helper.get_respond = function (req, res, next) {
    restdb_helper.urlQueryData(req.url, function(e){
        res.send(JSON.parse(e));
        next();
    })
};

rest_helper.del_respond = function (req, res, next) {
    restdb_helper.urlQueryData(req.url, function(e){
        res.send(JSON.parse(e));
        next();
    })
};

REST POST

除了里面的post_respond,因为CoAP用的是Buffer来发送数据的,而REST则用的JSON,于是我们需要将数据格式转换为简单的格式传递进去。

rest_helper.post_respond = function (req, res, next) {
    var data=[];
    _.each((req.params), function(key,value){
        if(typeof key === "string"){
            key = "'" + key + "'";
        }
        data.push(key);
    });
    restdb_helper.syncData(data, function(e){
        res.send({});
        next();
    })
};

这里的做法与CoAP与数据之间的做法是一致的,POST和PUT用的是一样的写法。

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签