@magicbe/api-generator
Version:
api 生成器
322 lines (321 loc) • 17.9 kB
JavaScript
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var axios_1 = __importDefault(require("axios"));
var Generator_1 = __importDefault(require("./Generator"));
var lodash_1 = require("lodash");
/**基本类型 */
var type_map = {
integer: "number",
undefined: "any",
};
var GeneratorSwaggerApi = /** @class */ (function (_super) {
__extends(GeneratorSwaggerApi, _super);
function GeneratorSwaggerApi(options) {
var _this = _super.call(this, options) || this;
_this._options_ = options;
_this.request = axios_1.default.create({ baseURL: options.service });
return _this;
}
GeneratorSwaggerApi.prototype.gen = function () {
var _this = this;
var resources = this._options_.resources;
this.request.get("/swagger-resources").then(function (_a) {
var data = _a.data;
var nexts = data.filter(function (_a) {
var name = _a.name;
return resources ? resources.includes(name) : true;
});
nexts.forEach(function (item) { return _this.genResource(item); });
});
};
GeneratorSwaggerApi.prototype.genResource = function (_a) {
return __awaiter(this, arguments, void 0, function (_b) {
var _c, target, function_path_code;
var _this = this;
var name = _b.name, url = _b.url;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_c = this._options_, target = _c.target, function_path_code = _c.function;
return [4 /*yield*/, this.mkDir()];
case 1:
_d.sent();
this.request.get(url).then(function (_a) {
var data = _a.data;
var basePath = data.basePath, definitions = data.definitions;
var target_map = {
"javascript": "js",
"typescript": "ts",
};
var file_name = (0, lodash_1.split)(basePath, /\//).filter(Boolean).join("_") || "default";
/**文件名 */
var next_file_name = file_name.concat(".").concat(target_map[target]);
/**生成头部注释 */
var exegesis = _this.genExegesis(data.info.title, data.info.contact.url);
/**生成 interface */
var interface_codes = _this.genDefinitions(file_name, data.definitions);
/**生成函数 */
var function_codes = (0, lodash_1.flattenDeep)(Object.keys(data.paths).map(function (path) {
return Object.keys(data.paths[path]).map(function (key) {
return _this.genApiDoc(basePath, name, path, key, definitions, data.paths[path][key]);
});
})).join("\n");
var import_code = "import request from \"".concat(function_path_code, "\";");
var content = "".concat(import_code, "\n").concat(exegesis, "\n").concat(interface_codes, "\n").concat(function_codes);
_this.write({ name: next_file_name, content: content });
});
return [2 /*return*/];
}
});
});
};
/**生成接口范型 */
GeneratorSwaggerApi.prototype.genDefinitions = function (file_name, definitions) {
var _this = this;
var name = (0, lodash_1.upperFirst)((0, lodash_1.camelCase)(file_name.concat("_definitions").replace(/\-/g, "_")));
var code = Object.keys(definitions).map(function (key) {
var definition = definitions[key];
var properties = definition.properties, title = definition.title;
var code = "";
if (definition.type === "object") {
if (!!properties) {
var properties_code = Object.keys(properties).map(function (key) {
var propertie = properties[key];
var nexts = _this.genDefinitionField(key, propertie, name);
return nexts;
}).join("\n");
code = "\t\"".concat(title, "\": {\n").concat(properties_code, "\n\t};");
}
}
return code;
}).join("\n");
return "export interface ".concat(name, " {\n").concat(code, "\n}");
};
/**生成范型字段类型 */
GeneratorSwaggerApi.prototype.genDefinitionField = function (key, propertie, name) {
var type = propertie.type, description = propertie.description, items = propertie.items, _enum_ = propertie.enum, $ref = propertie.$ref;
var description_code = description ? "\t\t/**".concat(description, " */") : undefined;
/**数组类型 */
if (type === "array") {
if (items === null || items === void 0 ? void 0 : items.$ref) {
var key_type = (0, lodash_1.last)((0, lodash_1.split)(items === null || items === void 0 ? void 0 : items.$ref, /\//));
var field_code_1 = "\t\t".concat(key, ": ").concat(name, "[\"").concat(key_type, "\"][];");
return [description_code, field_code_1].filter(Boolean).join("\n");
}
if ((items === null || items === void 0 ? void 0 : items.type) === "object") {
var field_code_2 = "\t\t".concat(key, ": any[];");
return [description_code, field_code_2].filter(Boolean).join("\n");
}
var field_code_3 = "\t\t".concat(key, ": ").concat((items === null || items === void 0 ? void 0 : items.type) || "Record<string, any>", "[];");
return [description_code, field_code_3].filter(Boolean).join("\n");
}
if (type === "object") {
var field_code_4 = "\t\t".concat(key, ": Record<string, any>;");
return [description_code, field_code_4].filter(Boolean).join("\n");
}
if ($ref) {
var key_type = (0, lodash_1.last)((0, lodash_1.split)($ref, /\//));
var field_code_5 = "\t\t".concat(key, ": ").concat(name, "[\"").concat(key_type, "\"];");
return [description_code, field_code_5].filter(Boolean).join("\n");
}
var _type_ = (_enum_ === null || _enum_ === void 0 ? void 0 : _enum_.length) ? _enum_.map(function (item) { return "\"".concat(item, "\""); }).join(" | ") : (type_map[type] || type);
var field_code = "\t\t".concat(key, ": ").concat(_type_, ";");
return [description_code, field_code].filter(Boolean).join("\n");
};
GeneratorSwaggerApi.prototype.genApiDoc = function (basePath, module, path, key, map, docPath) {
var _this = this;
var summary = docPath.summary, operationId = docPath.operationId, tags = docPath.tags;
var function_name = __spreadArray([key], (0, lodash_1.compact)((0, lodash_1.split)(path, /\/|{|}/)).map(lodash_1.upperFirst), true).join("");
var parameters = this.genApiDocPathParams(map, docPath.parameters, module);
var parameters_string = Object.keys(parameters).map(function (key) {
var parameter = (0, lodash_1.get)(parameters, key);
if (!parameter)
return undefined;
if (_this._options_.target !== "typescript") {
return "".concat(key);
}
return "".concat(key, ": ").concat(parameter);
}).filter(Boolean).join(", ");
var next_path = this.genApiDocNextPath(basePath, path, docPath.parameters);
var params;
var body;
if (parameters.body)
body = "body";
if (parameters.query)
params = "{ params: query }";
var parameters_input = [body, params].filter(Boolean).join(", ");
var url = (0, lodash_1.flattenDeep)([this._options_.service, "doc.html#", module, tags, operationId]).join("/");
var description_code = "\n/**".concat(summary, " ").concat(url, " */");
var next_input = ["`".concat(next_path, "`"), parameters_input].join(", ");
var responses_code = this.genApiDocResponseInterface(docPath.responses, map, module);
var function_code = "export const ".concat(function_name, " = (").concat(parameters_string, ") => request.").concat(key).concat(responses_code, "(").concat(next_input, ");");
return "".concat(description_code, "\n").concat(function_code);
};
GeneratorSwaggerApi.prototype.genApiDocPathParams = function (map, parameters, module) {
var ins = (0, lodash_1.groupBy)(parameters, "in");
var path;
{
var params = (0, lodash_1.get)(ins, "path");
if (params) {
var content = params.map(function (_a) {
var name = _a.name, type = _a.type, required = _a.required;
var _type_ = type_map[type] || type;
return "".concat([name]).concat(required ? "" : "?", ": ").concat(_type_);
}).join("; ");
path = "{ ".concat(content, " }");
}
}
var query;
{
var params = (0, lodash_1.get)(ins, "query");
if (params) {
var content = params.map(function (param) {
var name = param.name, type = param.type, required = param.required, items = param.items;
var _type_ = type_map[type] || type;
if (type === "array") {
_type_ = "".concat(((items === null || items === void 0 ? void 0 : items.type) || "any"), "[]");
}
return "".concat([name]).concat(required ? "" : "?", ": ").concat(_type_);
}).join("; ");
query = "{ ".concat(content, " }");
}
}
var body;
{
var params = (0, lodash_1.get)(ins, "body");
if (params === null || params === void 0 ? void 0 : params.length) {
var param = params[0];
var schema = param.schema;
body = "any";
if (schema === null || schema === void 0 ? void 0 : schema.$ref) {
var type = (0, lodash_1.last)((0, lodash_1.split)(schema === null || schema === void 0 ? void 0 : schema.$ref, /\//));
var name_1 = (0, lodash_1.upperFirst)((0, lodash_1.camelCase)(module.concat("_definitions").replace(/\-/g, "_")));
if (type)
body = "".concat(name_1, "[\"").concat(type, "\"]");
}
}
}
return ({ path: path, query: query, body: body });
};
GeneratorSwaggerApi.prototype.genApiDocNextPath = function (basePath, path, parameters) {
var ins = (0, lodash_1.groupBy)(parameters, "in");
if (ins.path) {
ins.path.forEach(function (_a) {
var name = _a.name;
path = path.replace(new RegExp("{".concat(name), "g"), "${path.".concat(name));
});
}
return basePath.concat(path);
};
GeneratorSwaggerApi.prototype.genApiDocResponseInterface = function (responses, map, module) {
var _a, _b, _c, _d, _e;
if (this._options_.target !== "typescript")
return "";
var response = (0, lodash_1.get)(responses, 200);
if (response.schema) {
if (response.schema.$ref) {
var type = (0, lodash_1.last)((0, lodash_1.split)(response.schema.$ref, /\//));
var name_2 = (0, lodash_1.upperFirst)((0, lodash_1.camelCase)(module.concat("_definitions").replace(/\-/g, "_")));
var next = "".concat(name_2, "[\"").concat(type, "\"]");
if (type)
return "<".concat(next, ">");
}
if (response.schema.type === "array") {
if (response.schema.items.$ref) {
var type = (0, lodash_1.last)((0, lodash_1.split)(response.schema.items.$ref, /\//));
var name_3 = (0, lodash_1.upperFirst)((0, lodash_1.camelCase)(module.concat("_definitions").replace(/\-/g, "_")));
var next = "".concat(name_3, "[\"").concat(type, "\"]");
if (type)
return "<".concat(next, "[]>");
}
if (response.schema.items.type === "object") {
if (((_a = response.schema.items.additionalProperties) === null || _a === void 0 ? void 0 : _a.type) === "object") {
return "<Record<string, any>[]>";
}
if (((_b = response.schema.items.additionalProperties) === null || _b === void 0 ? void 0 : _b.type) === "array") {
return "<Record<string, any[]>[]>";
}
if ((_c = response.schema.items.additionalProperties) === null || _c === void 0 ? void 0 : _c.type) {
return "<Record<string, ".concat(((_d = response.schema.items.additionalProperties) === null || _d === void 0 ? void 0 : _d.type) || "any", ">[]>");
}
}
return "<any[]>";
}
if (response.schema.type === "object") {
if ((_e = response.schema.additionalProperties) === null || _e === void 0 ? void 0 : _e.type) {
return "<Record<string, string>>";
}
return "";
}
if (type_map[response.schema.type]) {
return "<".concat(type_map[response.schema.type], ">");
}
}
return "";
};
return GeneratorSwaggerApi;
}(Generator_1.default));
exports.default = GeneratorSwaggerApi;
;