/resource

api resource manager for frontend by JavaScript

Primary LanguageTypeScript

Build Status npm version

目的

  1. 为接口提供统一管理能力
  2. 统一接口相关api

特性

  1. url参数解析
  2. 返回值容错
  3. 返回结果为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) // {...}

实例方法

  1. resource.get(param:any, data:any, option = {}): Resource
  2. resource.post(param:any, data:any, option = {}): Resource
  3. resource.put(param:any, data:any, option = {}): Resource
  4. resource.del(param:any, data:any, option = {}): Resource
  5. resource.send(param:any, method:string, data:any, option = {}): Resource
  6. resource.arrayBuffer(): Promise
  7. resource.blob(): Promise
  8. resource.json(): Promise
  9. resource.text(): Promise
  10. resource.formData(): Promise

静态方法

  1. Resource.create(uri:string): Resource
  2. Resource.get(uri:string, params:any, data:any, options:any): Resource
  3. Resource.post(uri:string, params:any, data:any, options:any): Resource
  4. Resource.put(uri:string, params:any, data:any, options:any): Resource
  5. 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>
  1. 接收两个参数
  1. 返回值为一个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)
})