foca-openapi
Version:
根据openapi文档生成请求客户端
77 lines (74 loc) • 2.01 kB
JavaScript
// src/lib/adapter.ts
var methods = ["get", "post", "put", "patch", "delete"];
// src/utils.ts
import qs from "query-string";
import objectToFormData from "object-to-formdata";
var utils = {
/**
* 路由拼接查询字符串
*/
uriConcatQuery(uri, query) {
if (!query) return uri;
const querystring = qs.stringify(query, { arrayFormat: "bracket" });
if (!querystring) return uri;
if (uri.includes("?")) {
if (!uri.endsWith("?")) {
uri += "&";
}
} else {
uri += "?";
}
return uri += querystring;
},
formatBody(contentType, body, formData) {
if (!body) return;
return contentType === "multipart/form-data" ? objectToFormData.serialize(body, {}, formData) : body;
}
};
// src/base-openapi-client.ts
var BaseOpenapiClient = class {
constructor(adapter) {
this.adapter = adapter;
}
replaceURI(uri, params) {
if (!params) return uri;
Object.entries(params).forEach(([key, value]) => {
uri = uri.replace(new RegExp(`{${key}}`), value);
});
return uri;
}
request(uri, method, opts = {}) {
const contentTypes = this.pickContentTypes(uri, method);
const requestBodyType = opts.requestBodyType || contentTypes[0] || "application/json";
const responseType = opts.responseType || contentTypes[1] || "json";
const headers = opts.headers || {};
if (!Object.hasOwn(headers, "Content-Type") && !Object.hasOwn(headers, "content-type")) {
headers["Content-Type"] = requestBodyType;
}
const formattedUri = this.replaceURI(uri, opts.params);
return this.adapter.request(
{
uri: formattedUri,
method,
...opts,
requestBodyType,
responseType,
headers
},
utils
);
}
pickContentTypes(_uri, _method) {
return [void 0, void 0];
}
};
// src/define-config.ts
var defineConfig = (options) => {
return options;
};
export {
BaseOpenapiClient,
defineConfig,
methods
};
//# sourceMappingURL=index.js.map