UNPKG

api-simplex-handler

Version:

一个api封装解析器

173 lines (153 loc) 4.89 kB
# api-simplex-handler > 一个轻量级的 API 请求封装库,支持 Axios 和 Fetch,提供更便捷的 API 调用方式。 ## 📦 安装 ```sh npm install api-simplex-handler ``` 或使用 Yarn: ```sh yarn add api-simplex-handler ``` ## 🚀 快速开始 ### **1. 导入库** ```js import { ApiFactory } from "api-simplex-handler"; ``` ### **2. 使用 ApiFactory 初始化内容** ```js const hanger = (api) => { console.log(api) /** * @type {Hanger<api>} */ return { before(args){ console.log('before:',args) return args }, after(res){ console.log("after",res) return res.then(({data,info})=>{ return {data,info} }) }, complete(res){ console.log("complete",res) return res; }, guard(args,info,next){ info['guard'] = 'loading' return next(args); } } } const apiFactory = new ApiFactory({ expectFunction: (res) => res.code === 200, successFunction: (res) => { ElMessage({ message: res.message, type: 'success', }) }, exceptionFunction: (res) => { if (res.code === 401) { ElMessage.error(`登录状态已过期,需要重新登录`) router.replace('/login'); return } if (res.code === 403) { ElMessage.error('您无此操作或访问的权限!') return } if (res.code === 500) { ElMessage.error('操作失败') ElMessage.error('内部服务器发生错误,请联系服务器管理员') return } ElMessage.error(`${res.message}`) }, failFunction: (res) => { ElMessage.error(`${res.message}`) } }, /** @type ApiConfig*/{ type: "axios", config: axiosInstance },hanger) ``` ### **3. 设置请求api** ```js /** * * @type {IApiCollection} */ export default { login: { method: "post", params: ['username', 'password'] }, register: { method: "post", params: ['username', 'password', 'email', 'code'], paramsDefault: "body", }, getById: { method: "get", params: ["id"], cachePolicy: "dynamic", limit: 1, }, } ``` ### **3. 使用ApiFactory构建API并发送请求和处理** ```js const userHandler = apiFactory.processApiCollection(user, baseApi + "users") userHandler.login.sendNotSuccessTips({ //发送无成功提示的请求 username:'123', password:'456' }).then(({data,info})=>{ //处理返回内容 }) ``` ## ⭐ 可用的API属性和构建后API方法 ### IAPI属性 ```ts interface IApi { //请求路径(默认使用key作为路径) path?: string, //方法(默认为get请求) method?: string, //请求参数定义 params?: IApiParamsCollection | string[], //为未指定请求参数类型设置默认请求类型(默认的默认是查询参数) paramsDefault?: "body" | "query" | "path", //并发请求限制数量,默认不限制或者小于1为不限制 limit?: number, //缓存策略 不缓存(默认)| 一直缓存|保存至本地持久化缓存|自动失效的缓存 cachePolicy?: "noCache" | "always" | "save" | "dynamic", //设置为自动失效缓存的时间,默认30分钟 expirationTime?: number, //缓存额外指定的key(一般没有用,主要用于解决防止持久化存储时的冲突) cacheKey?: string, //请求钩子,参考上述演示 hanger?: HangerIndex<this> | HangerIndex<this>[] } ``` ### API构造后的可用方法 ```ts interface IApiHandler<T extends IApiParamsCollection | undefined | string[]> { //发送不进行任何前后处理的请求,也不会执行自定以的hanger send(args: ResolveParams<T>): Promise<ISendResponse<any>>; //发送正常处理的请求,请求前后会执行自定义hanger以及响应解析responseHandlerFunction方法,可以重新设置本次请求的解析方法 sendHandler(args: ResolveParams<T>, responseHandlerFunction: ResponseHandlerFunction): Promise<SendHandlerResponse>; //同sendHandler,但是会禁止成功请求后触发responseHandlerFunction请求成功的解析方法 sendNotSuccessTips(args: ResolveParams<T>): Promise<SendHandlerResponse>; //获取请求路径 getURL(): string; //拼装query或者path参数的请求路径 composeURL(args: ResolveParams<T>): string; //清除缓存 clearCache(): void } ``` ## 📄 许可证 MIT License. 详情请查看 [LICENSE](./LICENSE) 文件。