- 为接口提供统一管理能力
- 统一接口相关api
- url参数解析
- 返回值容错
- 返回结果为Promise
import { Resource } from 'resource'
// create instance
const $resources = {
create: Resource.create('/user/create'),
findOne: Resource.create('/user/find/:email')
}
// use
// post
const create_res = await $resources.create({}, {email: 'xxx@xx.xx', password:'xxx'}).json()
console.log(create_res) // {...}
// get
const find_res = await $resources.findOne({email: 'xxx@xx.xx'}, {}).json()
console.log(find_res) // {...}
// static
// send post request
const sign_res = await Resouce.post('/user/sign', {}, {email: 'xxx@xx.xx', password:'xxx'}).json()
console.log(sign_res) // {...}
- resource.get(param:any, data:any, option = {}): Resource
- resource.post(param:any, data:any, option = {}): Resource
- resource.put(param:any, data:any, option = {}): Resource
- resource.del(param:any, data:any, option = {}): Resource
- resource.send(param:any, method:string, data:any, option = {}): Resource
- resource.arrayBuffer(): Promise
- resource.blob(): Promise
- resource.json(): Promise
- resource.text(): Promise
- resource.formData(): Promise
- Resource.create(uri:string): Resource
- Resource.get(uri:string, params:any, data:any, options:any): Resource
- Resource.post(uri:string, params:any, data:any, options:any): Resource
- Resource.put(uri:string, params:any, data:any, options:any): Resource
- Resource.del(uri:string, params:any, data:any, options:any): Resource
Resource 默认使用window.fetch
提供发送请求能力,如果用户需要其他发送请求工具,
可以通过Resource.setServer
来变发送请求功能,server
函数必需满足如下定义。
function server(input: RequestInfo, init?: RequestInit): Promise<Response>
- 接收两个参数
- input可以是一个
uri:string
,也可能是一个新的Request对象 - init为请求配置,详细见 https://developer.mozilla.org/zh-CN/docs/Web/API/Request/Request
- 返回值为一个Promise,Promise结果必须为Response
import {Resource} from 'resource'
Resource.setServer(function(input, opt){
const {method, body} = opt
if (method === 'get') {
return window.fetch(input)
}
if (method === 'post') {
return window.fetch(input, {
headers: {
'Content-type':'application/json'
},
credentials: 'include',
body: typeof body === 'object' ? JSON.stringfy(body) : body
})
}
return window.fetch(input, opt)
})
在服务端可以使用node-fetch
来代替
import fetch from 'node-fetch'
import {Resource} from 'resource'
Resource.setServer(function(input, init){
return fetch(input, init)
})