Nodejs Restful Api几点讨论

2015年8月24日 262点热度 0人点赞 0条评论

关于 rest api 版本控制

很多事情,标准和最佳实践是一种平衡

看那本rest api会被玩死,并不实用

rest本身是好东西,其实我只要取其精华就好了

没必要完全按照它做,理解状态变化就好了

标准rest api

自己去实现一下,https://developer.github.com/v3/

写起来还是挺那啥的,举个例子

Current Version

By default, all requests receive the v3 version of the API. We encourage you to explicitly request this version via the Accept header.

Accept: application/vnd.github.v3+json

核心是We encourage you to explicitly request this version via the Accept header.,这是非常标准的rest api写法

可是有多人理解Content-Type(Mime-Type)是啥呢?尤其还要自定义,如果你不理解怎么能用好呢?

再举个例子:link-header

https://developer.github.com/v3/#link-header

The pagination info is included in the Link header. It is important to follow these Link header values instead of constructing your own URLs. In some instances, such as in the Commits API, pagination is based on SHA1 and not on page number.

Link: <https://api.github.com/user/repos?page=3&per_page=100>; rel="next",
  <https://api.github.com/user/repos?page=50&per_page=100>; rel="last"

分页信息里包含link-header,是非常好的表达了状态,从上面的例子,我们可以很轻松的理解下一页和最后一页的

但问题是

  • 很多人不一定理解这种状态是如何用的,对开发的要求还是比较高的

  • 请求的response里增加了这些描述信息,是否真的必要呢?

土,也未必一定不好

标准和最佳实践是一种平衡,一种取舍,有些事情是做了锦上添花,有的是必须的,那么我们能做的就是,做好必须得,如果能锦上添花更好

现实中的开发还是按照自己项目情况来取舍的。

举个土,但实用的例子:微博的接口

它是比较适合国人思维的

http://open.weibo.com/wiki/2/statuses/public_timeline

约定也许更好

比如我写的res.api就是一个约定

res.api is an express middleware for render json api , it convention over api format like this :

{  data: {  },  status: {    code : x,
    msg  : 'some message'
  }
}

如果api都这样约定,开发速度会非常快,而且简单

  • 客户端 API 开发总结 https://cnodejs.org/topic/552b3b9382388cec50cf6d95

  • res.api https://cnodejs.org/topic/55818a0c395a0c1812f18273

moa-api里如何做法?

mount-routes里使用 https://github.com/moajs/mount-routes。

mount-routes里的做法是自动加载某个目录,比如app/routes下的所有目录,子目录作为路由

api的设计可以这样玩

app/routes/api/v3/users

它可以自动映射到url里,对于版本控制还是比较友好的

给mysql和mongodb提供restful接口,有啥现成的包可提供吗?

先给几个简单的

  • restify

  • hapi

  • sails

  • loopback

其实还有一个我的解决方案,使用我的moajs

首先创建moajs插件

nmm init

使用脚手架,创建模型和基本的rest接口

moag location name:string order_num:string is_full:string  is_available:string warehouse_id:string shelf_id:string

这里会自动创建api目录和对应的文件的

测试这些接口,执行moas即可

moas

这样就可以测试接口了。

目前moajs的状态实现了足够的features,但稳定性和文档等不足,各位可以先拿moa-api玩玩,其他高级特性待稳定后放出

全文完

欢迎关注我的公众号【node全栈】

图片

49290Nodejs Restful Api几点讨论

这个人很懒,什么都没留下

文章评论