erest
Version:
Easy to build api server depend on @leizm/web and express.
95 lines (92 loc) • 2.84 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = generateAsiox;
const path = require("node:path");
const debug_1 = require("../../debug");
const utils = require("../../utils");
function generateAsiox(data, dir, options, writter) {
(0, debug_1.plugin)("generateAsiox: %s - %o", dir, options);
function slashToCamel(name) {
return name.replace(/\/[a-z]/g, (match) => {
return match.slice(1).toUpperCase();
});
}
function rmPathParam(path) {
return path.replace(/:([a-z]+)/gi, "$1");
}
function getReqFuncName(req) {
return `${req.method}${slashToCamel(rmPathParam(req.realPath))}`;
}
function getFuncParams(req) {
const parseData = req.method === "get" ? req.query : req.body;
const dataKeys = Object.keys(parseData);
if (!dataKeys.length) {
return "";
}
return `{ ${dataKeys.join(", ")} }`;
}
function hasUrlParam(path) {
return /:[a-z]+/i.test(path);
}
function getReqSendPath(path) {
if (hasUrlParam(path)) {
return `\`${path.replace(/:([a-z]+)/gi, "\\$\\{$1\\}")}\``;
}
return `'${path}'`;
}
function getPathParams(req) {
if (req.params) {
const params = Object.keys(req.params)
.map((key) => `${key},`)
.join("");
return params;
}
return "";
}
function getReqSendData(req) {
const isGetReq = req.method === "get";
const parseData = isGetReq ? req.query : req.body;
const dataKeys = Object.keys(parseData);
if (!dataKeys.length) {
return "";
}
if (isGetReq) {
return `{
params: { ${dataKeys.join(", ")} }
}`;
}
return `{ ${dataKeys.join(", ")} }`;
}
const baseURL = `${data.info.host || ""}${data.info.basePath}`;
const { apis } = data;
const request = Object.keys(apis).map((key) => {
const req = apis[key];
let reqSendData = getReqSendData(req);
if (reqSendData) {
reqSendData = `, ${reqSendData}`;
}
return `
// ${req.title}
${getReqFuncName(req)}(
${getPathParams(req)}
${getFuncParams(req)}) {
return this.instance.${req.method}(
${getReqSendPath(req.realPath)}
${reqSendData})
}`;
});
const template = `
// ${data.info.title} ${data.genTime}
import axios from 'axios';
const BASE = "${baseURL}";
const api = {
instance: axios.create({
baseURL: BASE,
}),
${request.join(",\n")}
};
export default api;
`;
const filename = utils.getPath("jssdk.js", options.axios);
writter(path.resolve(dir, filename), template);
}
;