import { CodeGenerator, Interface, FileStructures as PontFileStructures, BaseClass, Mod } from 'pont-engine' export class FileStructures extends PontFileStructures { public getMultipleOriginsFileStructures() { const files = {} // @ts-ignore this.generators.forEach(generator => { const dsName = generator.dataSource.name if (dsName) { const dsFiles = this.getOriginFileStructures(generator, true) files[dsName] = dsFiles } }) return { ...files, 'index.ts': this.getDataSourcesTs.bind(this), 'api.d.ts': this.getDataSourcesDeclarationTs.bind(this), 'api-lock.json': this.getLockContent.bind(this) } } public getDataSourcesTs() { // @ts-ignore const dsNames = this.generators .map(ge => ge.dataSource.name) .filter(v => v) return ` ${dsNames .map(name => { return `import ${name} from './${name}'; ` }) .join('\n')} export default { defs: { ${dsNames.map(name => `${name}: ${name}.defs,`).join('\n')} }, modules: { ${dsNames.map(name => `${name}: ${name}.modules,`).join('\n')} } } ` } public getOriginFileStructures( generator: CodeGenerator, usingMultipleOrigins = false ) { let mods = {} const dataSource = generator.dataSource dataSource.mods.forEach(mod => { const currMod = {} mod.interfaces.forEach(inter => { currMod[ getName(inter.name) + '.ts' ] = generator.getInterfaceContent.bind(generator, inter) currMod['index.ts'] = generator.getModIndex.bind(generator, mod) }) mods[mod.name] = currMod mods['index.ts'] = generator.getModsIndex.bind(generator) }) generator.getBaseClassesInDeclaration = this.getBaseClassesInDeclaration.bind( this, generator.getBaseClassesInDeclaration(), usingMultipleOrigins ) generator.getModsDeclaration = this.getModsDeclaration.bind( this, generator.getModsDeclaration(), usingMultipleOrigins ) const result = { 'baseClass.ts': generator.getBaseClassesIndex.bind(generator), mods: mods, 'index.ts': generator.getIndex.bind(generator), 'api.d.ts': generator.getDeclaration.bind(generator) } if (!usingMultipleOrigins) { result['api-lock.json'] = this.getLockContent.bind(this) } return result } } export default class MyGenerator extends CodeGenerator { public getIndex() { let conclusion = ` import * as defs from './baseClass' import modules from './mods/' export default { defs, modules, } ` // dataSource name means multiple dataSource if (this.dataSource.name) { conclusion = ` import { ${this.dataSource.name} as defs } from './baseClass' import { ${this.dataSource.name} as modules } from './mods/' export default { defs, modules } ` } return conclusion } /** 获取所有基类的类型定义代码,一个 namespace */ public getBaseClassesInDeclaration() { function getParamsCode(inter: Interface, className = 'Params') { return ` interface ${className} { ${inter.parameters .filter(param => param.in !== 'body') .map(param => { let code = param.toPropertyCode(true) // .replace('class ', 'interface ') // .replace('*/\n', '*/\n public') // console.log(code) return code }) .join('')} } ` } let reqClsCodes: string[] = [] this.dataSource.mods.forEach(mod => { return mod.interfaces.forEach(inter => { let clsName = this.firstUpperCase(mod.name) + this.firstUpperCase(inter.name) const bodyParmas = getBodyParamsCode(inter) if (bodyParmas) { return '' } return reqClsCodes.push(getParamsCode(inter, `${clsName}Req`)) }) }) const content = `namespace ${this.dataSource.name || 'defs'} { ${this.dataSource.baseClasses .map(base => ` export ${this.getBaseClassInDeclaration(base)} `.replace('export class ', 'export interface ') ) .join('\n')} ${reqClsCodes .map( code => `export ${code} ` ) .join('\n')} } ` return content } /** 获取某个基类的类型定义代码 */ public getBaseClassInDeclaration(base: BaseClass) { if (base.templateArgs && base.templateArgs.length) { return `class ${base.name}<${base.templateArgs .map((ignored, index) => `T${index} = any`) .join(', ')}> { ${base.properties.map(prop => prop.toPropertyCode(true)).join('\n')} } ` } return `class ${base.name} { ${base.properties.map(prop => prop.toPropertyCode(true)).join('\n')} } ` } /** 获取总的类型定义代码 */ public getDeclaration() { return ` type ObjectMap = { [key in Key]: Value; } ${this.getCommonDeclaration()} ${this.getBaseClassesInDeclaration()} ` } /** 获取所有模块的 index 入口文件 */ public getModsIndex() { let conclusion = ` export default { ${this.dataSource.mods.map(mod => getName(mod.name)).join(', \n')} } ` // dataSource name means multiple dataSource if (this.dataSource.name) { conclusion = ` export const ${this.dataSource.name} = { ${this.dataSource.mods.map(mod => getName(mod.name)).join(', \n')} } ` } return ` ${this.dataSource.mods .map(mod => { return `import ${getName(mod.name)} from './${mod.name}'` }) .join('\n')} ${conclusion} ` } /** 获取接口实现内容的代码 */ public getInterfaceContent(inter: Interface) { // const bodyParmas = getBodyParamsCode(inter) const getParamNames = ( type: 'path' | 'query' | 'body' | 'formData' ) => { return ( inter.parameters .filter(item => { return item.in === type }) .map(item => { return item.name }) || [] ) } let isRequiredParame = ( inter.parameters .filter(item => { return ['path', 'query', 'body', 'formData'].includes( item.in ) }) .map(item => { return item.name }) || [] ).length ? true : false let formDataKeys = getParamNames('formData') let bodyKeys = getParamNames('body') let paramOnlyBody = getParamNames('path').length + getParamNames('query').length + getParamNames('formData').length === 0 && bodyKeys.length let useFormData = formDataKeys.length ? true : false let param = ` interface Params { ${inter.parameters // .filter(param => param.in !== 'body') .map(param => param.toPropertyCode(true)) .join('')} }` if (paramOnlyBody) { const bodyParam = inter.parameters.find( param => param.in === 'body' ) const type = bodyParam && bodyParam.dataType.generateCode(inter.getDsName()) param = ` interface Params extends ${type} {}` } let method = inter.method.toLocaleLowerCase() let axArgs = 'params, options' if (['get', 'delete', 'head', 'options'].includes(method)) { axArgs = `{ ...options, params }` } // 返回的 response interface let resType = inter.response.typeArgs .map(arg => arg.generateCode(inter.getDsName())) .join(', ') if (!resType) { resType = 'any' } let payloadCode = '' if (useFormData) { payloadCode = ` let form = new FormData() let keys = ${JSON.stringify(formDataKeys)} keys.forEach(key => { // @ts-ignore form.append(key, params[key]) }) // @ts-ignore params = form ` } let pathKeys = getParamNames('path') let pathCode = '' if (pathKeys.length) { pathCode = ` ${pathKeys .map(key => { return ` url = url.replace(/\\{${key}\\}/g, String(params.${key}) || '') // @ts-ignore delete params.${key} ` }) .join('\n')} ` } let clonParams = '' if (pathCode) { // 只删一层,不用深度 clone clonParams = 'params = {...params}' } let changeBody = '' if (bodyKeys.length === 1 && !paramOnlyBody) { changeBody = ` // @ts-ignore params = params['${bodyKeys[0]}'] ` } switch (resType) { case 'int': resType = 'number' break } let httpLibPath = '../../../http' if (this.dataSource.name) { httpLibPath = '../../../../http' } return ` /** * -------------------------------------- * !注意,这是生成的代码,不要修改,会被覆盖! * --------------------------------------- **/ import { ax, AxOptions, handleError } from '${httpLibPath}' ${param.replace('class ', 'interface ')} /** * ${inter.description .split('\n') .map((v, ix) => (ix ? ' * ' : '') + v) .join('\n')} **/ export default function (params: Params${ isRequiredParame ? '' : ' = {}' }, options: AxOptions = {}) { let url = '${inter.path}' ${ isRequiredParame ? ` ${clonParams} ${pathCode} ${payloadCode} ` : '' } ${changeBody} return ax.${method}<${resType}>(url, ${axArgs}) // @ts-ignore // .then(res => res ? res.data : void 0) .catch(err => handleError(err, options.hideError)) } ` } /** 获取单个模块的 index 入口文件 */ public getModIndex(mod: Mod) { return ` /** * ${mod.description} */ ${mod.interfaces .map(inter => { return `import ${getName(inter.name)} from './${inter.name}';` }) .join('\n')} export default { ${mod.interfaces.map(inter => getName(inter.name)).join(', \n')} } ` } public firstUpperCase(str) { return str.toLowerCase().replace(/( |^)[a-z]/g, L => L.toUpperCase()) } /** 获取所有基类文件代码 */ public getBaseClassesIndex() { function getParamsCode(inter: Interface, className = 'Params') { return ` class ${className} { ${inter.parameters // .filter(param => param.in !== 'body') .map(param => { let code = param .toPropertyCodeWithInitValue(param.name) // .toPropertyCode(true) .replace('*/\n', '*/\n public') // console.log(code) return code }) .join('')} } ` } let reqClsCodes: string[] = [] this.dataSource.mods.forEach(mod => { return mod.interfaces.forEach(inter => { let clsName = this.firstUpperCase(mod.name) + this.firstUpperCase(inter.name) + 'Req' const bodyParmas = getBodyParamsCode(inter) if (bodyParmas) { return '' } return reqClsCodes.push(getParamsCode(inter, clsName)) }) }) const clsCodes = this.dataSource.baseClasses.map( base => ` class ${base.name} { ${base.properties .map(prop => { return prop .toPropertyCodeWithInitValue(base.name) .replace('*/\n', '*/\n public') }) .filter(id => id) .join('\n')} } ` ) if (this.dataSource.name) { return ` ${reqClsCodes.join('\n')} ${clsCodes.join('\n')} export const ${this.dataSource.name} = { ${this.dataSource.baseClasses.map(bs => bs.name).join(',\n')} } ` } return ( reqClsCodes.map(cls => `export ${cls}`).join('\n') + '\n' + clsCodes.map(cls => `export ${cls}`).join('\n') ) } /** 获取接口内容的类型定义代码 */ public getInterfaceContentInDeclaration(inter: Interface) { const bodyParmas = getBodyParamsCode(inter) const param = (() => { let o = inter.getParamsCode() if (!bodyParmas) { return o } return o.replace('Params ', `Params extends BodyParams `) })() return ` ${bodyParmas} export ${param} export type Response = ${inter.responseType}; export const init: Response; export function request(param: Params): Promise<${ inter.responseType }>; ` } } function getName(name: string) { switch (name) { case 'public': return 'publicApi' case 'index': return 'indexApi' case 'export': return 'exportApi' default: return name } } function getBodyParamsCode(inter: Interface) { const bodyParam = inter.parameters.find(param => param.in === 'body') const type = bodyParam && bodyParam.dataType.generateCode(inter.getDsName()) if (type && bodyParam) { return ` export class BodyParams { ${bodyParam.name}: ${type} } ` } return '' }