Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

框架支持RESTFUL风格的接口 #102

Open
iyuxy opened this issue Mar 23, 2016 · 6 comments
Open

框架支持RESTFUL风格的接口 #102

iyuxy opened this issue Mar 23, 2016 · 6 comments

Comments

@iyuxy
Copy link

iyuxy commented Mar 23, 2016

现在框架里面的API都需要通过提前定义而且只支持get和post的方法,如何支持put和delete以及动态路由呢?

@Justineo
Copy link
Member

现在的框架不是为 RESTful 后端设计的,是针对我们自己部门的后端框架的。

@iyuxy
Copy link
Author

iyuxy commented Mar 23, 2016

哦,我们现在想用这个框架,但是同时想支持后端同学的RESTful接口,有没有办法通过hook的方法或者其他来支持呢?

@yibuyisheng
Copy link
Member

改一改 serverIO ?

@iyuxy
Copy link
Author

iyuxy commented Mar 23, 2016

@yibuyisheng 主要吧,restful接口地址是动态的,所以common下面那个apiconfig就有些问题了

@Justineo
Copy link
Member

serverIO 可以不动。可以尝试自己覆盖一下 util.genRequesters。这个方法会把 API 配置转成请求发送函数,返回一个 Promise。自带的实现只会转换字符串类型的配置(/data/user/list 这样的,如果是数组或对象,会遍历找字符串去替换。)。你覆盖的时候可以把 url 配置成 GET /data/user/:id 这样的路径,然后自己解析替换一下,在返回的请求函数里转成这样调用:

io.request(realURL, data, {method: method});

// 代入运行时参数可能是:
io.request('/data/user/10086', {}, {method: 'GET'});

// 或者
io.request('/data/user/create', {name: 'Steve'}, {method: 'PUT'});

这样在业务代码里可以还按现有的逻辑来写:

model.requestUser({id: '10086'}).then(function (data) {
    // handle data
});

@iyuxy
Copy link
Author

iyuxy commented Mar 26, 2016

感谢 @Justineo 大神的指导
我在util.genRequesters这个方法中新增了get,post,put,delete四种方法,类似下面这样👇

request.post = function (path, data, options) {
    options = options ? options : {};
            u.extend(options, {method:'POST'});
            var realUrl = handlerUrl(url, path);
            return io.request(realUrl, data, options);
      };
      request.put = function (path, data, options) {
           options = options ? options : {};
           u.extend(options, {method:'PUT'});
                var realUrl = handlerUrl(url, path);
                return io.request(realUrl, data, options);
            };

在config里面URL定义是这样
appList: '/api/{app}/list'
然后现在已经可以支持了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants