CherryRestRest接口調(diào)用方式
CherryRest
一種非常優(yōu)雅的Rest接口調(diào)用方式
Features
基于Restful風(fēng)格接口設(shè)計(jì)的模塊化接口url生成器
集中管理接口url
默認(rèn)使用 fetch 作為接口加載器
可以給模塊單獨(dú)設(shè)置 baseUrl
支持 response formatter 配置、支持單個(gè) module formatter
內(nèi)置默認(rèn) filter,當(dāng)前只有一個(gè) over,重載 response data filed
Install
npm install cherry-rest --save
Usage
import Cherry,{module as CherryModule,config as CherryConfig} from 'cherry-rest'
基于業(yè)務(wù)Rest接口定義模塊
//方式一
CherryModule('name');
//方式二、定義多個(gè)模塊、模塊設(shè)置別名
CherryModule('module2|home,moudle3|user');
//方式三、復(fù)合繼承模式
CherryModule([{
name:'module3',
alias:'about',
children:[{
name:'info',
},{
name:'concat'
}]
}]);
調(diào)用
Cherry.module3.info.query({query:{id:1}}).then(res=>res)
//fetch get /about/info?id=1;
Cherry.module3.info.create({body:{name:1}}).then(res=>res)
//fetch post /about/info {name:1};
Cherry.module3.info.update({query:{id:1}}).then(res=>res)
//fetch put /about/info?id=1;
Cherry.module3.info.remove({path:'1,2'}).then(res=>res)
//fetch delete /about/info/1/2;
Test
import Cherry,{module as CherryModule,config as CherryConfig} from '../dist/index.js'
//http://ip.taobao.com/service/getIpInfo.php?ip=114.114.114.114
jest.setTimeout(1200000);
CherryConfig({
credentials:'include'
},{
baseUrl:'http://ip.taobao.com',
formatter:function(res){
return res.json()
}
})
CherryModule('ip|service',{
formatter:[function(data){
return data.data;
}],
filters:[{
name:'over',
options:['city_id|id']
}]
});
it('async & filters test', () => {
expect.assertions(1);
return Cherry.ip.query({path:'getIpInfo.php',query:{ip:'114.114.114.114'}}).then(data => {
expect(JSON.stringify(data)).toEqual(JSON.stringify({"id":"320100"}))
});
});
Demo
Base
API Example:
get http://www.baidu.com/mock/v1/user
get http://www.baidu.com/mock/v1/user?id=${userId}
get http://www.baidu.com/mock/v1/user/${userId}/blogs
get http://www.baidu.com/mock/v1/books
post http://www.baidu.com/mock/v1/user {name:'hello'}
put http://www.baidu.com/mock/v1/user/{userId} {name:'world'}
//import
import Cherry,{module as CherryModule,config as CherryConfig} from 'cherry-rest'
//基于rest業(yè)務(wù)接口定義模塊
//配置baseUrl
CherryConfig({
//默認(rèn)使用fetch請(qǐng)求數(shù)據(jù)、這里可以配置fetch
fetch:{},
common:{
baseUrl:'http://www.baidu.com'
}
})
//定義模塊
CherryModule([{
name:'app',
alias:'mock',
children:[{
name:'version',
alias:'v1',
children:[{
name:'user'
},{
name:'books'
}]
}]
}])
let User=Cherry.app.version.user;
let Book=Cherry.app.version.app;
//GET http://www.baidu.com/mock/v1/user
User.query()
//GET http://www.baidu.com/mock/v1/user?id=123
User.query({query:{id:'123'}})
//POST http://www.baidu.com/mock/v1/user {name:'hello'}
User.create({body:{name:'hello'}})
//PUT http://www.baidu.com/mock/v1/user/123 {name:'world'}
User.update({path:'123',body:{name:'world'}})
//GET http://www.baidu.com/mock/v1/user/${userId}/blogs
User.query({path:['123','blogs'])
//DELETE http://www.baidu.com/mock/v1/user/123
User.remove({path:'123')
評(píng)論
圖片
表情
