Skip to content

Commit

Permalink
refactor: 优化使用体验,支持新调用格式
Browse files Browse the repository at this point in the history
  • Loading branch information
yangqianjun committed May 6, 2021
1 parent 5e61140 commit f67af6e
Show file tree
Hide file tree
Showing 16 changed files with 289 additions and 31 deletions.
24 changes: 23 additions & 1 deletion GettingStarted.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ $ npx autos --help

```
-V, --version output the version number
-c, --config [path] config file (default: "json2service.json")
-c, --config [path] config file (default: "json2service.json" or "json2service.js")
--clear rm typescript service before gen
--quiet auto merge without popup
--apis [boolean] 是否生成 apis,如果未指定 models 且未指定 typeScriptDataFile 则会生成 apis
Expand Down Expand Up @@ -284,6 +284,28 @@ export declare class Ajax {
): Promise<any>;
/** 接口传参校验 */
check<V>(value: V, name: string): void;
/** 新 fetch 接口,>= 3.5.4 */
public autosFetch<S extends keyof AutosAPIS>(
source: S,
...args: AutosAPIS[S][0]
): Promise<AutosAPIS[S][1]> {
const { isFile, opt, ...config } = (args[0] || {}) as AutosParams;
let { headers = {} } = opt || {};
if (isFile) {
headers = {
...headers,
'Content-Type': 'multipart/form-data'
};
}
const [method, url] = source.split(' ') as [WrappedFetchParams['method'], string];
return this.ajax({
...config,
...opt,
method,
url,
headers
});
}
}
declare const _default: Ajax;
export default _default;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "auto-service",
"version": "3.5.2",
"version": "3.5.3",
"description": "auto generate swagger or yapi mock to typescript services and models",
"repository": "[email protected]:gogoyqj/auto-service.git",
"author": "杨乾军 <yang@yang>",
Expand Down
63 changes: 63 additions & 0 deletions plugins/typescript-tkit-autos/api.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{{>licenseInfo}}
import { ExtraFetchParams } from '@ajax';
{{^models.isEmpty}}
import * as models from '../model/models';
{{/models.isEmpty}}

/* tslint:disable:no-unused-variable member-ordering object-literal-shorthand */

{{#operations}}
{{#description}}
/** @description {{&description}} */
{{/description}}

declare global {
interface AutosAPIS {
{{#operation}}
{{#description}}/** {{&description}} */{{/description}}
'{{httpMethod}} {{{contextPath}}}{{{path}}}': [[
{
opt?: {{^headerParams.0}}ExtraFetchParams{{/headerParams.0}}{{#headerParams.0}}{ headers: ParamsHeader{{nickname}} } & Omit<ExtraFetchParams, 'headers'> {{/headerParams.0}}
{{#queryParams.0}}
query: {
{{#queryParams}}
'{{paramName}}'{{^required}}?{{/required}}: {{&dataType}};
{{/queryParams}}
};
{{/queryParams.0}}
{{#pathParams.0}}
path: {
{{#pathParams}}
'{{paramName}}'{{^required}}?{{/required}}: {{&dataType}};
{{/pathParams}}
};
{{/pathParams.0}}
{{#formParams.0}}
{{#isFile}}
form: {
{{#formParams}}
'{{baseName}}'{{^required}}?{{/required}}: {{&dataType}};
{{/formParams}}
};
isFile: true;
{{/isFile}}
{{^isFile}}
form: {
{{#formParams}}
'{{paramName}}'{{^required}}?{{/required}}: {{&dataType}};
{{/formParams}}
};
{{/isFile}}
{{/formParams.0}}
{{#bodyParam.0}}
data: {
{{#bodyParam}}
'{{paramName}}'{{^required}}?{{/required}}: {{&dataType}};
{{/bodyParam}}
};
{{/bodyParam.0}}
}], {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}];
{{/operation}}
}
}
{{/operations}}
Empty file.
Empty file.
3 changes: 3 additions & 0 deletions plugins/typescript-tkit-autos/gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
wwwroot/*.js
node_modules
typings
2 changes: 2 additions & 0 deletions plugins/typescript-tkit-autos/index.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './api/api';
export * from './model/models';
11 changes: 11 additions & 0 deletions plugins/typescript-tkit-autos/licenseInfo.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
46 changes: 46 additions & 0 deletions plugins/typescript-tkit-autos/model.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{{>licenseInfo}}
import * as models from './models';

{{#models}}
{{#model}}
/**
{{#description}}
* @description {{&description}}
{{/description}}
{{#vars}}
* @property `{{^required}}[{{/required}}{{name}}{{^required}}]{{/required}}` {{&description}}
{{/vars}}
*/
export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{
{{#vars}}
{{#description}}
/**
* {{&description}}
*/
{{/description}}
"{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}}
}

{{#hasEnums}}
export namespace {{classname}} {
{{#vars}}
{{#isEnum}}
export enum {{enumName}} {
{{#allowableValues}}
{{#enumVars}}
{{#description}}
/**
* `{{name}}` {{&description}}
*/
{{/description}}
{{{name}}} = {{{value}}} as any{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}
{{/isEnum}}
{{/vars}}
}
{{/hasEnums}}
{{/model}}
{{/models}}
8 changes: 8 additions & 0 deletions plugins/typescript-tkit-autos/models.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{{#models}}
{{#model}}
export * from './{{{ classFilename }}}';
{{/model}}
{{/models}}
export type ModelInteger = number;
export type ModelFloat = number;
export type LocalDate = Date;
85 changes: 85 additions & 0 deletions plugins/typescript-tkit-autos/params.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
{{#operations}}
{{#operation}}
{{#allParams.0}}
{{^hasOnlyBodyParams}}
{{#headerParams.0}}
/**{{#headerParams}}
* @description {{nickname}} headers 参数
* @property `{{^required}}[{{/required}}{{baseName}}{{^required}}]{{/required}}` {{&description}}
{{/headerParams}}*/
export interface ParamsHeader{{nickname}} {
{{#headerParams}}
{{#description}}
/** {{&description}} */
{{/description}}
'{{baseName}}'{{^required}}?{{/required}}: {{&dataType}};
{{/headerParams}}
}
{{/headerParams.0}}
/**
{{#description}}
* @description {{nickname}}参数
{{/description}}
{{#pathParams.0}}
{{#pathParams}}
* @property `{{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}}` {{&description}}
{{/pathParams}}
{{/pathParams.0}}
{{#queryParams.0}}
{{#queryParams}}
* @property `{{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}}` {{&description}}
{{/queryParams}}
{{/queryParams.0}}
{{#formParams.0}}
{{#formParams}}
* @property `{{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}}` {{&description}}
{{/formParams}}
{{/formParams.0}}
*/
export interface Params{{nickname}} {
{{#pathParams.0}}
// pathParams
{{#pathParams}}
{{#description}}
/**
* {{&description}}
*/
{{/description}}
{{paramName}}{{^required}}?{{/required}}: {{&dataType}};
{{/pathParams}}
{{/pathParams.0}}
{{#queryParams.0}}
// queryParams
{{#queryParams}}
{{#description}}
/**
* {{&description}}
*/
{{/description}}
{{paramName}}{{^required}}?{{/required}}: {{{dataType}}};
{{/queryParams}}
{{/queryParams.0}}
{{#formParams.0}}
// formParams
{{#formParams}}
{{#description}}
/**
* {{&description}}
*/
{{/description}}
{{paramName}}{{^required}}?{{/required}}: {{&dataType}};
{{/formParams}}
{{/formParams.0}}
}
{{/hasOnlyBodyParams}}
{{#bodyParam}}
/**
{{#description}}
* {{&description}}
{{/description}}
*/
export type ParamsBody{{nickname}} = {{&dataType}};
{{/bodyParam}}
{{/allParams.0}}
{{/operation}}
{{/operations}}
18 changes: 12 additions & 6 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import * as fs from 'fs';
import * as path from 'path';
import commander from 'commander'; // @fix no import * https://github.com/microsoft/tslib/issues/58
import chalk from 'chalk';
import { Json2Service } from './consts';
import { Json2Service, ProjectDir } from './consts';
import gen from './index';

const CD = process.cwd();
const defaultConfig = 'json2service.json';

commander
.version(require('../package.json').version)
.option('-c, --config [path]', 'config file', 'json2service.json')
.option('-c, --config [path]', 'config file', defaultConfig)
.option('--clear', 'rm typescript service before gen', false)
.option('--quiet', 'auto merge without popup', false)
.option(
Expand All @@ -31,10 +31,16 @@ commander
.parse(process.argv);

const Config = commander.config as string;
const ConfigFile = path.join(CD, Config);

let ConfigFile = path.join(ProjectDir, Config);
if (!fs.existsSync(ConfigFile)) {
ConfigFile = ConfigFile.replace(/\.json/g, '.js');
}
if (!fs.existsSync(ConfigFile)) {
console.log(chalk.red(`[ERROR]: ${Config} not found in ${CD}`));
console.log(
chalk.red(
`[ERROR]: ${Config} or ${Config.replace(/\.json/g, '.js')} not found in ${ProjectDir}`
)
);
} else {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const config: Json2Service = require(ConfigFile);
Expand Down
6 changes: 4 additions & 2 deletions src/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ export interface Json2Service {
export interface SwaggerParser {
/** 输出 typescript 代码目录,默认是当前 src/services */
'-o'?: string;
/** 模板目录,默认是 plugins/typescript-tkit,避免修改;配置成 plugins/types-only 仅输出类型 */
/** 模板目录,默认是 plugins/typescript-tkit,避免修改;配置成 plugins/types-only 仅输出类型;配置成 plugins/typescript-tkit-autos 输出新调用方式格式接口 */
'-t'?: string;
/** language,默认是 typescript-angularjs,避免修改 */
'-l'?: string;
Expand All @@ -191,5 +191,7 @@ export interface SwaggerParser {
/** 项目目录 */
export const ProjectDir = process.cwd();
export const RemoteUrlReg = /^http/;
/** 模块目录 */
export const ModuleDir = path.join(__dirname, '..');
/** 放置依赖 web 静态文件目录 */
export const StaticDir = path.join(__dirname, '..', 'static');
export const StaticDir = path.join(ModuleDir, 'static');
18 changes: 12 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,19 +78,25 @@ export default async function gen(
});
};
const swagger2tsConfig = { ...defaultParseConfig, ...swaggerParser };
if (
swagger2tsConfig['-t'] === 'plugins/types-only' ||
swagger2tsConfig['-t'] === 'plugins/typescript-tkit-autos'
) {
swagger2tsConfig['-t'] = path.join(pluginsPath, '..', swagger2tsConfig['-t']);
}
const servicesPath = swagger2tsConfig['-o'] || '';
// IMP: 加载新版
const code: number = await new Promise(rs => {
const loader = (cb: (err: any, res: { body?: SwaggerJson }) => any) => {
remoteSwaggerUrl
? remoteSwaggerUrl.match(RemoteUrlReg)
? request.get(
{
...requestConfig,
url: remoteSwaggerUrl
},
(err, res) => cb(err, { body: JSON.parse(res.body) })
)
{
...requestConfig,
url: remoteSwaggerUrl
},
(err, res) => cb(err, { body: JSON.parse(res.body) })
)
: cb(undefined, { body: require(remoteSwaggerUrl) as SwaggerJson })
: cb(undefined, {});
};
Expand Down
4 changes: 4 additions & 0 deletions static/service.css
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
.select-count {
float: left;
padding: 0 5px;
position: fixed;
right: 0;
top: 0;
background: lightgreen;
}

.select-change {
Expand Down

0 comments on commit f67af6e

Please sign in to comment.