api-simplex-handler
Version:
一个api封装解析器
52 lines (51 loc) • 1.93 kB
JavaScript
import { ApiHandlerAxios } from "./ApiHandlerAxios";
import { ApiHandlerFetch } from "./ApiHandlerFetch";
class ApiFactory {
responseHandlerDefineFunction;
apiConfig;
hanger;
constructor(responseHandlerDefineFunction, apiConfig, hanger) {
this.responseHandlerDefineFunction = responseHandlerDefineFunction;
this.apiConfig = apiConfig;
this.hanger = hanger;
}
processApiCollection(apiCollection, basePath, hanger) {
const apiHandlers = {};
for (const apiCollectionKey in apiCollection) {
apiHandlers[apiCollectionKey] = this.factory(apiCollectionKey, apiCollection[apiCollectionKey], basePath, hanger);
}
return apiHandlers;
}
factory(apiCollectionKey, api, basePath, hanger) {
const newApi = { ...api };
if (typeof api.path === "undefined")
api.path = apiCollectionKey;
newApi.path = basePath + "/" + api.path;
if (typeof api.hanger === 'undefined')
newApi.hanger = [];
else {
if (!Array.isArray(api.hanger))
newApi.hanger = [api.hanger];
}
if (hanger) {
if (Array.isArray(hanger))
newApi.hanger.push(...hanger);
else
newApi.hanger.push(hanger);
}
if (this.hanger) {
if (Array.isArray(this.hanger))
newApi.hanger.push(...this.hanger);
else
newApi.hanger.push(this.hanger);
}
switch (this.apiConfig.type) {
case "fetch":
return new ApiHandlerFetch(newApi, this.responseHandlerDefineFunction, this.apiConfig.config);
case "axios":
this.apiConfig.config.defaults.baseURL = "";
return new ApiHandlerAxios(newApi, this.responseHandlerDefineFunction, this.apiConfig.config);
}
}
}
export { ApiFactory };