初始化
改案例对应的是 vben 项目的请求改的
安装依赖
// 全局依赖
pnpm add -g pont-engine
// 项目依赖
pnpm add pont-engine
配置
根目录下创建pont-config.json
文件
{
"origins": [
{
"originUrl": "", // 接口平台提供数据源的
"name": "trace", // 数据源名称
"usingMultipleOrigins": true // 是否使用多个数据源
}
],
"templatePath": "./pont/pontTemplate", // 模板地址
"outDir": "./src/api", // api 生成代码地址
"mocks": {
"enable": false // 是否生成mock
},
// 生成代码 prettier 格式化配置
"prettierConfig": {
"printWidth": 100,
"semi": true,
"vueIndentScriptAndStyle": true,
"singleQuote": true,
"trailingComma": "all",
"proseWrap": "never",
"htmlWhitespaceSensitivity": "strict",
"endOfLine": "auto"
}
}
templatePath
import { Interface, CodeGenerator, Mod } from 'pont-engine';
export default class MyGenerator extends CodeGenerator {
/** 获取接口内容的类型定义代码 */
getInterfaceContentInDeclaration(inter: Interface) {
let requestParams = inter.getRequestParams();
const paramsCode = inter.getParamsCode('Params');
requestParams = requestParams.replace('body', 'data');
return `
export ${paramsCode}
export type Response = ${inter.responseType}
export const init: Response;
export function ${inter.name}(${requestParams}): Promise<Response>;
`;
}
/** 获取接口实现内容的代码 */
getInterfaceContent(inter: Interface) {
// 请求类型
const method = inter.method.toLowerCase();
// 接口传参
const Interface = inter.getParamsCode().replace(/class/, 'interface');
// 请求参数
let requestParams = inter.getRequestParams(this.surrounding);
// 描述
const index = inter.description.indexOf('\n');
const description = inter.description.substring(0, index);
const body = requestParams.includes('body') ? 'data' : '';
requestParams = requestParams.replace('body', 'data');
return `
import { defHttp } from '/@/utils/http/axios';
// eslint-disable-next-line @typescript-eslint/no-empty-interface
${Interface}
/**
* @desc ${description}
*/
export function ${inter.name}(${requestParams}) {
return defHttp.${method}<${inter.responseType}>(
{
url: "${inter.path}",
params,
${body}
},
{
...options
}
)
}
`;
}
/** 获取单个模块的 index 入口文件 */
getModIndex(mod: Mod): string {
return `
/**
* @description ${mod.description}
*/
${mod.interfaces
.map((inter) => {
return `export { ${inter.name} } from './${inter.name}';`;
})
.join('\n')}
`;
}
}
使用
操作过程都存在 ts
语法提示
<template>
<div> </div>
</template>
<script lang="tsx" setup>
import { onMounted } from 'vue';
// 引入 api 地址
import { trace } from '/@/api/trace';
onMounted(async () => {
// 请求 api
const { data } = await trace.ngReasonInfo.NgReasonInfo_page({}, { isReturnOneResponse: true });
data?.records?.map((i) => {
console.log(i);
});
});
</script>