UNPKG

@alova/wormhole

Version:

More modern openAPI generating solution for alova.js

98 lines (97 loc) 3.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.templateHelper = exports.TemplateHelper = void 0; const lodash_1 = require("lodash"); const config_1 = require("../../config"); const alovaJson_1 = require("../../functions/alovaJson"); const utils_1 = require("../../utils"); const DEFAULT_CONFIG = (0, config_1.getGlobalConfig)(); const DEFAULT_OPTIONS = { root: false, hasVersion: true, }; class TemplateHelper { static getInstance() { if (!TemplateHelper.instance) { TemplateHelper.instance = new TemplateHelper(); } return TemplateHelper.instance; } constructor(config) { if (config) { this.config = config; } } load(config) { this.config = config; return this; } static load(config) { return new TemplateHelper(config); } getVersion() { switch (this.config.version) { case 'v3': return 'v3-'; default: return ''; } } // Get the suffix name of the generated file getExt() { return TemplateHelper.getExt(this.config.type); } // Get module type getModuleType() { return TemplateHelper.getModuleType(this.config.type); } static async readData(projectPath, output) { const alovaJsonPath = (0, alovaJson_1.getAlovaJsonPath)(projectPath, output); try { const alovaJson = await (0, alovaJson_1.readAlovaJson)(alovaJsonPath); DEFAULT_CONFIG.templateData.set(alovaJsonPath, alovaJson); return alovaJson; } catch { DEFAULT_CONFIG.templateData.delete(alovaJsonPath); return {}; } } static getData(projectPath, output) { return DEFAULT_CONFIG.templateData.get((0, alovaJson_1.getAlovaJsonPath)(projectPath, output)); } static setData(templateData, projectPath, output) { return (0, alovaJson_1.writeAlovaJson)(templateData, (0, alovaJson_1.getAlovaJsonPath)(projectPath, output)); } static getExt(type) { switch (type) { case 'typescript': return '.ts'; default: return '.js'; } } static getModuleType(type) { switch (type) { case 'typescript': case 'module': return 'ESModule'; default: return 'commonJs'; } } async outputFile(options) { return (0, utils_1.generateFile)(options.output, `${options?.outFileName ?? options.fileName}${options?.ext ?? this.getExt()}`, await this.readAndRenderTemplate(options.fileName, options.data, options)); } readAndRenderTemplate(fileName, data, userConfig) { const config = (0, lodash_1.merge)((0, lodash_1.cloneDeep)(DEFAULT_OPTIONS), userConfig); const fileVersion = config.hasVersion ? this.getVersion() : ''; const filePath = config?.root ? fileVersion + fileName : `${this.config.type}/${fileVersion}${fileName}`; return (0, utils_1.readAndRenderTemplate)(filePath, data); } async outputFiles(optionsArray) { return Promise.all(optionsArray.filter(item => !!item).map(options => this.outputFile(options))); } } exports.TemplateHelper = TemplateHelper; exports.templateHelper = TemplateHelper.getInstance();