Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/soft-goats-shake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-ts-request": Minor
---

feat: 以 cli 方式使用时添加交互行为 & 新增 defineConfig 定义配置
42 changes: 33 additions & 9 deletions README-en_US.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,28 @@ create `openapi-ts-request.config.ts` file in the project root directory
> the config file also supports **_.openapi-ts-request.ts_**, **_openapi-ts-request.config.cjs_** format, reference [cosmiconfig](https://github.com/cosmiconfig/cosmiconfig?tab=readme-ov-file#cosmiconfig)

```ts
import type { GenerateServiceProps } from 'openapi-ts-request';
import { defineConfig } from 'openapi-ts-request';

export default {
// schemaPath: './openapi.json', // local openapi file
// serversPath: './src/apis', // interface storage path
export default defineConfig({
schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
} as GenerateServiceProps;
serversPath: './src/apis',
});

// 或

// import type { GenerateServiceProps } from 'openapi-ts-request';

// export default {
// schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
// } as GenerateServiceProps;
```

support passing in array config for generate

```ts
import type { GenerateServiceProps } from 'openapi-ts-request';
import { defineConfig } from 'openapi-ts-request';

export default [
export default defineConfig([
{
schemaPath: 'http://app.swagger.io/v2/swagger.json',
serversPath: './src/apis/app',
Expand All @@ -68,7 +75,22 @@ export default [
schemaPath: 'http://auth.swagger.io/v2/swagger.json',
serversPath: './src/apis/auth',
},
] as GenerateServiceProps[];
]);

// or

// import type { GenerateServiceProps } from 'openapi-ts-request';

// export default [
// {
// schemaPath: 'http://app.swagger.io/v2/swagger.json',
// serversPath: './src/apis/app',
// },
// {
// schemaPath: 'http://auth.swagger.io/v2/swagger.json',
// serversPath: './src/apis/auth',
// },
// ] as GenerateServiceProps[];
```

add the command in `script` of `package.json`: `"openapi": "openapi-ts",`
Expand Down Expand Up @@ -229,6 +251,7 @@ openapi -i ./spec.json -o ./apis
| serversPath | no | string | './src/apis' | the folder path for the run results |
| requestLibPath | no | string | 'axios' | custom request lib path, for example: '@/request', 'node-fetch' |
| full | no | boolean | true | full replacement |
| describe | no | string | - | description information, which will be used when using cli interactive operation mode |
| enableLogging | no | boolean | false | open the log |
| priorityRule | no | string | 'include' | priority rule, include/exclude/both |
| filterCaseInsensitive | no | boolean | false | whether to perform a case-insensitive match with includeTags, includePaths, excludeTags, excludePaths filters |
Expand Down Expand Up @@ -345,7 +368,8 @@ export default {
4. make sure your code passes all test cases (new functional test cases need to be added for new features):`pnpm test:unit`
5. create a changeset file using the command:`pnpm changeset`
6. submit your changes using commit (must follow commitlint specification)
7. submit Pull Request
7. If documents are involved, please update README.md, READMD-en_US.md, and agents.md simultaneousl
8. submit Pull Request

## Thanks

Expand Down
42 changes: 35 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,28 @@ pnpm i openapi-ts-request -D
> 配置文件还支持 **_.openapi-ts-request.ts_**, **_openapi-ts-request.config.cjs_** 等格式,参考 [cosmiconfig](https://github.com/cosmiconfig/cosmiconfig?tab=readme-ov-file#cosmiconfig)

```ts
import type { GenerateServiceProps } from 'openapi-ts-request';
import { defineConfig } from 'openapi-ts-request';

export default {
export default defineConfig({
schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
} as GenerateServiceProps;
serversPath: './src/apis',
});

// 或

// import type { GenerateServiceProps } from 'openapi-ts-request';

// export default {
// schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
// } as GenerateServiceProps;
```

支持传入数组配置进行生成

```ts
import type { GenerateServiceProps } from 'openapi-ts-request';
import { defineConfig } from 'openapi-ts-request';

export default [
export default defineConfig([
{
schemaPath: 'http://app.swagger.io/v2/swagger.json',
serversPath: './src/apis/app',
Expand All @@ -66,7 +75,22 @@ export default [
schemaPath: 'http://auth.swagger.io/v2/swagger.json',
serversPath: './src/apis/auth',
},
] as GenerateServiceProps[];
]);

// 或

// import type { GenerateServiceProps } from 'openapi-ts-request';

// export default [
// {
// schemaPath: 'http://app.swagger.io/v2/swagger.json',
// serversPath: './src/apis/app',
// },
// {
// schemaPath: 'http://auth.swagger.io/v2/swagger.json',
// serversPath: './src/apis/auth',
// },
// ] as GenerateServiceProps[];
```

在 `package.json` 的 `script` 中添加命令: `"openapi": "openapi-ts",`
Expand Down Expand Up @@ -227,6 +251,7 @@ openapi --i ./spec.json --o ./apis
| serversPath | 否 | string | './src/apis' | 运行结果文件夹路径 |
| requestLibPath | 否 | string | 'axios' | 自定义请求方法路径,例如:'@/request'、'node-fetch' |
| full | 否 | boolean | true | 是否全量替换 |
| describe | 否 | string | - | 描述信息,在用 cli 可交互运行方式时会用到 |
| enableLogging | 否 | boolean | false | 是否开启日志 |
| priorityRule | 否 | string | 'include' | 模式规则,可选include/exclude/both |
| filterCaseInsensitive | 否 | boolean | false | 执行 includeTags、includePaths、excludeTags、excludePaths 过滤时是否忽略大小写 |
Expand Down Expand Up @@ -266,6 +291,8 @@ openapi --i ./spec.json --o ./apis
| customTemplates | {<br>[TypescriptFileType.serviceController]?: <T, U>(item: T, context: U) => string;<br>} | 自定义模板,详情请看源码 |
| customRenderTemplateData | {<br>[TypescriptFileType]?: (list: any[], context: {fileName: string, params: Record<string, unknown>}) => any[]<br>} | 自定义文件生成时的 list 参数处理,支持对不同文件类型进行精细化控制 |

[hooks 示例](https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md#-advanced-customization-hooks)

## Apifox-Config

| 属性 | 类型 | 说明 | 必填 |
Expand Down Expand Up @@ -343,7 +370,8 @@ export default {
4. 确保你的代码可以通过所有测试用例(新增功能需要添加新的功能测试用例):`pnpm test:unit`
5. 创建 changeset 文件通过命令:`pnpm changeset`
6. 使用 commit 提交你的修改(需遵循 commitlint 规范)
7. 发起 Pull Request
7. 如果涉及文档,请同步更新 README.md、READMD-en_US.md、agents.md
8. 发起 Pull Request

## 感谢

Expand Down
1 change: 1 addition & 0 deletions agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ else if (isNodeProject) {
| `namespace` | string | `"API"` | TypeScript namespace | Custom namespace |
| `templatesFolder` | string | - | Custom template directory | Custom templates |
| `apifoxConfig` | object | - | Apifox-specific configuration | Apifox integration |
| `describe` | string | - | description information | Using cli interactive operation mode |

### 3. Feature Requirements Mapping

Expand Down
12 changes: 9 additions & 3 deletions openapi-ts-request.config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { type GenerateServiceProps } from './src/index';
import { defineConfig } from './src/index';

export default [
export default defineConfig([
{
schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
serversPath: './apis/app',
describe: 'Petstore API-1',
},
] as GenerateServiceProps[];
{
schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
serversPath: './apis/app2',
describe: 'Petstore API-2',
},
]);
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"openapi-ts-request": "openapi-ts"
},
"dependencies": {
"@clack/prompts": "^0.11.0",
"@prettier/sync": "^0.6.1",
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
"axios": "^1.7.2",
Expand Down
25 changes: 25 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions src/bin/cli.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env node
import { cancel, intro, isCancel, multiselect, outro } from '@clack/prompts';
import chalk from 'chalk';
import { program } from 'commander';

Expand Down Expand Up @@ -30,10 +31,33 @@ async function run() {
? config
: [config];

/** 是否交互式 */
let isInteractive = false;

if (options.uniqueKey) {
configs = configs.filter(
(config) => config.uniqueKey === options.uniqueKey
);
} else if (configs.length > 1) {
// 如果没有指定 uniqueKey,并且有多个配置,则交互式选择
isInteractive = true;

console.log(''); // 添加一个空行
intro('🎉 欢迎使用 openapi-ts-request 生成器');
const selected = await multiselect({
message: '请选择要生成的 service',
options: configs.map((config) => ({
value: config,
label: config.describe || config.schemaPath,
})),
});

if (isCancel(selected)) {
cancel('👋 Has cancelled');
process.exit(0);
}

configs = selected;
}

for (const config of configs) {
Expand All @@ -55,6 +79,10 @@ async function run() {
if (errorMsg) {
throw new Error(errorMsg);
}

if (isInteractive && !errors.length) {
outro('🎉 All done!');
}
} else {
throw new Error('config is not found');
}
Expand Down
2 changes: 1 addition & 1 deletion src/generator/serviceGenarator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ export default class ServiceGenerator {
);

// 打印日志
log('✅ 成功生成 api 文件目录-> ', this.config.serversPath);
log('✅ 成功生成 api 文件目录-> ', ` ${this.config.serversPath}`);
}

private getInterfaceTPConfigs() {
Expand Down
13 changes: 13 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ export type GenerateServiceProps = {
* Swagger2/OpenAPI3 地址
*/
schemaPath: string;
/**
* 描述信息,在用 cli 可交互运行方式时会用到
*/
describe?: string;
/**
* 生成的文件夹的路径
*/
Expand Down Expand Up @@ -448,3 +452,12 @@ export async function generateService({
});
}
}

/**
* Defines the configuration for openapi-ts-request.
*/
export function defineConfig(
config: GenerateServiceProps | GenerateServiceProps[]
) {
return config;
}
4 changes: 2 additions & 2 deletions src/log.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import chalk from 'chalk';

const log = (...rest) =>
console.log(`${chalk.blue('[openAPI]')}: ${rest.join('\n')}`);
console.log(` ${chalk.blue('[openAPI]')}: ${rest.join('\n')}`);

export const logError = (...rest) =>
console.error(`${chalk.red('❌ [openAPI]')}: ${rest.join('\n')}`);
console.error(` ${chalk.red('❌ [openAPI]')}: ${rest.join('\n')}`);

export default log;