UNPKG

api-simplex-handler

Version:

一个api封装解析器

39 lines (38 loc) 1.39 kB
import { ApiHandler } from "./ApiHandler"; class ApiHandlerFetch extends ApiHandler { config; constructor(api, responseHandlerDefineFunction, config) { super(api, responseHandlerDefineFunction); this.config = config; } send(args) { if (!this.api.path) return Promise.reject(`request path is undefined`); const init = { ...this.config }; let path = this.api.path; init.method = this.api.method; if (Array.isArray(this.api.params)) { const params = ApiHandler.assemblyParameters(this.api.params, args, this.api); if (typeof params === 'string') path += params; else init.body = JSON.stringify(params); } else if (typeof this.api.params !== 'undefined') { const params = ApiHandler.assemblyParametersToUnion(this.api.params, args, this.api); path += params.path + params.query; init.body = JSON.stringify(params.body); } return fetch(path, init) .then(r => r.json()) .then(res => { const response = { code: res.code ?? res.status ?? 200, message: res.message ?? res.msg ?? "成功", data: res.data }; return response; }); } } export { ApiHandlerFetch };