0.5.0 • Published 2 years ago

request-sdk v0.5.0

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

request-sdk 服务端推送技术

此 SDK 用来提供 公共请求 的基础能力,集成了请求公共请求处理,超时时间,异常请求处理,取消请求等功能。

快速开始

安装 request-sdk

$ npm i -S request-sdk

// 注意点: 
由于request-sdk的异常报错alert,依赖于element-plus的message组件,所以安装时候 会检查安装依赖,否者会报warning。

在页面中引入。

// main.js/ts中
import bdAxios from 'request-sdk';

...
const app = createApp(App);
app.use(bdAxios, {
    // axios已有的配置都可以被配置
    baseURL: 'xxx.baidu.com',
    errCode: 1401, // 特殊code
    cb: () => {} // 特殊code的回调函数
})

组件内使用

import {bdRequest} from 'request-sdk'

export const getData = (req: Req) => {
    return bdRequest<Req, Res>({
        url: 'xxx/xx',
        method: 'get/post',
        data
    })
}

注:不论是get请求还是post请求,都可以传递data参数。

bdRequest 实例方法

方法名称说明类型
bdRequest请求() => void
cancelRequest取消请求(url: string) => void
cancelAllRequest取消全部请求() => void

请求类型说明

interface RequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
    interceptors?: RequestInterceptors<T>,
    'x-not-tip'?: Boolean | undefined
}

interface RequestInterceptors<T> {
    // 请求拦截
    requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig
    requestInterceptorsCatch?: (err: any) => any

    // 响应拦截
    responseInterceptors?: (config: T) => T
    responseInterceptorsCatch?: (err: any) => any
}

class Request {
    // 实例
    instance: AxiosInstance
    // 拦截器对象
    interceptorsObj?: RequestInterceptors<AxiosResponse>

    /**
     * 存放取消方法的集合
     */
    cancelRequestSourceList?: CancelRequestSource[]
    requestUrlList?: string[]

    constructor(config: RequestConfig) {
        this.requestUrlList = []
        this.cancelRequestSourceList = []
        this.instance = axios.create(config)
        this.interceptorsObj = config.interceptors
        // 拦截器执行顺序: 接口请求 -> 实例请求 -> 全局请求 -> 实例响应 -> 全局响应 -> 接口响应
        this.instance.interceptors.request.use(
            (res: AxiosRequestConfig) => res,
            (err: any) => err
        )
        // 实例拦截器
        this.instance.interceptors.request.use(
            this.interceptorsObj?.requestInterceptors,
            this.interceptorsObj?.requestInterceptorsCatch
        )
        // 响应拦截器
        this.instance.interceptors.response.use(
            this.interceptorsObj?.responseInterceptors,
            this.interceptorsObj?.responseInterceptorsCatch
        )
    }
}
0.5.0

2 years ago

0.4.3

2 years ago

0.4.2

2 years ago

0.4.1

2 years ago

0.4.0

2 years ago

0.3.1

2 years ago

0.3.0

2 years ago

0.2.5

2 years ago

0.2.4

2 years ago

0.2.3

2 years ago

0.2.2

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.7

2 years ago

0.1.6

2 years ago

0.1.5

2 years ago

0.1.4

2 years ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago

0.0.4

2 years ago