Skip to content

Commit 7e1cd77

Browse files
authored
docs: 补充基础注释内容 (#22)
Co-authored-by: cmtlyt <cmtlyt@163.com>
1 parent f7e8cfd commit 7e1cd77

File tree

24 files changed

+257
-3
lines changed

24 files changed

+257
-3
lines changed

src/cli.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { build as buildApp } from './cli/build';
77
import { generateRequestScriptCli } from './cli/generate-request-script';
88
import { runProd } from './cli/run-prod';
99

10+
/** dev 命令 */
1011
const dev = defineCommand({
1112
meta: {
1213
name: 'dev',
@@ -17,6 +18,7 @@ const dev = defineCommand({
1718
},
1819
});
1920

21+
/** build 命令 */
2022
const build = defineCommand({
2123
meta: {
2224
name: 'build',
@@ -27,6 +29,7 @@ const build = defineCommand({
2729
},
2830
});
2931

32+
/** run 命令 */
3033
const run = defineCommand({
3134
meta: {
3235
name: 'run',
@@ -37,6 +40,7 @@ const run = defineCommand({
3740
},
3841
});
3942

43+
/** 生成前端请求文件命令 */
4044
const requestScript = defineCommand({
4145
meta: {
4246
name: 'requestScript',
@@ -47,6 +51,7 @@ const requestScript = defineCommand({
4751
},
4852
});
4953

54+
/** generate 命令 */
5055
const generate = defineCommand({
5156
meta: {
5257
name: 'generate',
@@ -55,6 +60,7 @@ const generate = defineCommand({
5560
subCommands: { requestScript },
5661
});
5762

63+
/** tee 命令主入口 */
5864
const main = defineCommand({
5965
meta: {
6066
name: 'tee',

src/cli/bootstrap.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ import { resolve } from 'pathe';
66
import { getStorage, setStorage } from '../storage';
77
import { consola, getPkgInfo, loadModule, parseConfig, parseOptions, runSourceMain } from '../utils';
88

9+
/**
10+
* 初始化应用, 返回应用实例和路由
11+
*/
912
export async function bootstrap(_options?: GenerateTypeOptions) {
1013
const options = await parseOptions(_options);
1114

@@ -45,6 +48,9 @@ function errorHandler(e: Error) {
4548
consola.error(e);
4649
}
4750

51+
/**
52+
* 重启服务
53+
*/
4854
async function restart(options: DevOptions) {
4955
try {
5056
const oldServer = getStorage('server');
@@ -60,12 +66,20 @@ async function restart(options: DevOptions) {
6066
}
6167
}
6268

69+
/**
70+
* 监听文件变化的处理函数
71+
*
72+
* 打印日志和重启服务
73+
*/
6374
const watchHandler = debounce(async (options: DevOptions) => {
6475
consola.start('Watching for changes...');
6576
await restart(options);
6677
consola.success('Restarted');
6778
});
6879

80+
/**
81+
* 监听文件变化
82+
*/
6983
async function devHandler(options: DevOptions) {
7084
const { pkgPath, sourceDir } = options;
7185
fs.watchFile(resolve(pkgPath, 'main.ts'), () => watchHandler(options));
@@ -76,6 +90,9 @@ async function devHandler(options: DevOptions) {
7690
});
7791
}
7892

93+
/**
94+
* 命令行初始化应用的函数, 进行一些前后置处理
95+
*/
7996
export async function bootstrapCli() {
8097
const { port, sourceDir } = await parseConfig();
8198
const { pkgPath } = await getPkgInfo();

src/cli/build.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ interface BuildOptions extends BuildConfig {
99
sourceDir?: string;
1010
}
1111

12+
/**
13+
* 解析构建参数
14+
*/
1215
async function parseOptions(options?: BuildOptions) {
1316
const { sourceDir, build: { outDir, ...rest } } = await parseConfig();
1417

@@ -19,6 +22,9 @@ async function parseOptions(options?: BuildOptions) {
1922
});
2023
}
2124

25+
/**
26+
* 格式化入口文件信息
27+
*/
2228
function entryFormat(fileInfoMap: FileInfoMap): { in: string; out: string }[] {
2329
const entrys: { in: string; out: string }[] = [];
2430
for (const type in fileInfoMap) {
@@ -30,7 +36,12 @@ function entryFormat(fileInfoMap: FileInfoMap): { in: string; out: string }[] {
3036
return entrys;
3137
}
3238

33-
function getFilePoints(filePath: string) {
39+
/**
40+
* 获取单个文件的 point 信息
41+
*
42+
* 使用数组作为返回值, 是为了防止文件不存在返回 undefined 导致 esbuild 报错
43+
*/
44+
function getFilePoint(filePath: string) {
3445
const filePoints: { in: string; out: string }[] = [];
3546
if (existsSync(filePath)) {
3647
const out = basename(filePath, '.ts');
@@ -39,6 +50,9 @@ function getFilePoints(filePath: string) {
3950
return filePoints;
4051
}
4152

53+
/**
54+
* 打包代码
55+
*/
4256
export async function build(_options?: BuildOptions) {
4357
const options = await parseOptions(_options);
4458
const { outDir: outdir, clean } = options;
@@ -55,7 +69,7 @@ export async function build(_options?: BuildOptions) {
5569
await esbuild({
5670
entryPoints: [
5771
...entryPoints,
58-
...getFilePoints(mainFilePath),
72+
...getFilePoint(mainFilePath),
5973
],
6074
outdir,
6175
minify: true,

src/cli/generate-request-script/index.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ import { getStorage, setStorage } from '../../storage';
1212
import { getPkgInfo, loadModule, parseConfig, parseOptions } from '../../utils';
1313
import { API_METHOD_SYMBOL, API_TYPE_SYMBOL, template } from './template';
1414

15+
/**
16+
* 过滤无效的路由
17+
*
18+
* TODO: 暂时没有无效的定义, 留个口子
19+
*/
1520
function filterValidRouter(routerInfoMap: Record<string, RouterInfo>) {
1621
const validRouterInfoMap: Record<string, RouterInfo> = {};
1722

@@ -31,6 +36,9 @@ export type MethodTypeInfo = {
3136
params: string[];
3237
} & Partial<Record<RequestMethod, TypeInfo>>;
3338

39+
/**
40+
* 获取 dataKey 对应的字段的名称
41+
*/
3442
function getDataKeyName(key: string): DataKey {
3543
switch (key) {
3644
case 'params':
@@ -45,6 +53,9 @@ function getDataKeyName(key: string): DataKey {
4553
}
4654
}
4755

56+
/**
57+
* 通过字符串路径获取 params
58+
*/
4859
function getRouterParams(path: string) {
4960
const splitPath = path.split('/');
5061
const params: string[] = [];
@@ -56,13 +67,19 @@ function getRouterParams(path: string) {
5667
return params;
5768
}
5869

70+
/**
71+
* 获取 dataKey 对应的 schema
72+
*/
5973
function getRouterDataSchema(dataKey: string, schema: RouterDataSchema) {
6074
if (dataKey === 'response') {
6175
return schema.response?.['200'] || schema.response?.default || {};
6276
}
6377
return schema[dataKey];
6478
}
6579

80+
/**
81+
* 解析 methodSchema 中对应 dataKey 的类型
82+
*/
6683
function parseRouterDataSchema(methodSchema: RouterDataSchema) {
6784
const typeInfo: TypeInfo = {};
6885
for (const dataKey in methodSchema) {
@@ -73,6 +90,9 @@ function parseRouterDataSchema(methodSchema: RouterDataSchema) {
7390
return typeInfo;
7491
}
7592

93+
/**
94+
* 解析接口 methodSchema
95+
*/
7696
function parseMethodSchema(schemaMap: RouterSchema) {
7797
const methodTypeInfo: Partial<Record<RequestMethod, TypeInfo>> = {};
7898
for (const method in schemaMap) {
@@ -82,6 +102,9 @@ function parseMethodSchema(schemaMap: RouterSchema) {
82102
return methodTypeInfo;
83103
}
84104

105+
/**
106+
* 将 routerInfoMap 转换为 typeInfoList
107+
*/
85108
function parseTypeInfo(routerInfoMap: Record<string, RouterInfo>) {
86109
const typeInfoList: MethodTypeInfo[] = [];
87110
for (const stringPath in routerInfoMap) {
@@ -96,11 +119,17 @@ function parseTypeInfo(routerInfoMap: Record<string, RouterInfo>) {
96119
return typeInfoList;
97120
}
98121

122+
/**
123+
* 获取请求函数的函数名
124+
*/
99125
function getMethodName(method: string, path: string) {
100126
const splitPath = path.split('/').filter(item => item && !item.startsWith(':'));
101127
return camelCase(`${method}/${splitPath.join('/')}`);
102128
}
103129

130+
/**
131+
* 获取请求函数的入参类型
132+
*/
104133
function getMethodOptionsType(typeInfo: TypeInfo) {
105134
const optionsType: string[] = [];
106135
for (const dataKey in typeInfo) {
@@ -115,6 +144,11 @@ interface APIInfo {
115144
request: string;
116145
}
117146

147+
/**
148+
* 将 typeInfo 解析为 api 信息
149+
*
150+
* 包含类型和请求方法
151+
*/
118152
function parseAPIInfo(typeInfoList: MethodTypeInfo[]) {
119153
const apiInfoList: APIInfo[] = [];
120154
typeInfoList.forEach((item) => {
@@ -132,6 +166,9 @@ function parseAPIInfo(typeInfoList: MethodTypeInfo[]) {
132166
return apiInfoList;
133167
}
134168

169+
/**
170+
* 解析 api 信息为实际代码内容
171+
*/
135172
function parseAPIContentInfo(apiInfo: APIInfo[]) {
136173
const { type, method } = apiInfo.reduce<{ type: string[]; method: string[] }>((prev, cur) => {
137174
prev.type.push(cur.type);
@@ -144,14 +181,22 @@ function parseAPIContentInfo(apiInfo: APIInfo[]) {
144181
};
145182
}
146183

184+
/**
185+
* 生成前端请求接口的代码文件
186+
*/
147187
function generateAPIFile(contentInfo: { type: string; method: string }) {
148188
return template.replace(API_TYPE_SYMBOL, contentInfo.type).replace(API_METHOD_SYMBOL, contentInfo.method);
149189
}
150190

191+
/**
192+
* 根据 router-schema 生成前端请求接口的代码文件
193+
*/
151194
export async function generateRequestScriptCli() {
195+
// 禁用日志输出, 因为会载入代码收集依赖, 所以需要将 console 也进行代理, 屏蔽常用输出
152196
setStorage('disabledConsola', true);
153197
globalThis.console = new Proxy({}, { get: () => noop }) as Console;
154198

199+
// 初始化应用
155200
const { port, sourceDir } = await parseConfig();
156201
const { pkgPath } = await getPkgInfo();
157202
const devOptions = { pkgPath, sourceDir, port, isCli: true };
@@ -165,6 +210,7 @@ export async function generateRequestScriptCli() {
165210

166211
await loadModule(app, router, options);
167212

213+
// 处理文件依赖信息, 生成前端请求文件
168214
const routerInfoMap = getStorage('routerInfoMap');
169215
const validRouterInfoMap = filterValidRouter(routerInfoMap);
170216

src/cli/run-prod.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ import { setStorage } from '../storage';
22
import { consola, getPkgInfo, parseConfig } from '../utils';
33
import { bootstrap } from './bootstrap';
44

5+
/**
6+
* 运行打包后的应用
7+
*/
58
export async function runProd() {
69
setStorage('isProd', true);
710

src/constant/index.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,20 @@
11
import type { ModuleType } from '../types';
22

3+
/**
4+
* 需要读取原型的模块类型
5+
*
6+
* 例如 controller 和 service 返回的是 class, 所以想要拿到方法就需要读取他的原型
7+
*/
38
export const NEED_READ_PROTOTYPE_TYPES = ['controller', 'service'];
49

10+
/**
11+
* 需要返回模块返回值内容的模块类型
12+
*
13+
* 例如模块返回的是函数, 那想要获取详细类型就需要读取他的返回值类型
14+
*/
515
export const NEED_RETURN_TYPES = ['config', 'extend', 'routerSchema', 'service', 'middlewares', 'controller', 'router'];
616

17+
/**
18+
* 模块加载顺序
19+
*/
720
export const MODULE_LOAD_ORDER: ModuleType[] = ['config', 'extend', 'routerSchema', 'service', 'middlewares', 'controller', 'router'];

src/define.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,42 +10,73 @@ interface DefineMiddlewareNeedWrapOptions extends DefineMiddlewareOptions {
1010
needWrap: true;
1111
}
1212

13+
/**
14+
* 定义一个中间件
15+
*/
1316
export function defineMiddleware<C extends (options: TeeOptions<'middleware'>) => (...args: any[]) => TeeKoa.Middleware>(callback: C, options: DefineMiddlewareNeedWrapOptions): C;
1417
export function defineMiddleware<C extends (options: TeeOptions<'middleware'>) => TeeKoa.Middleware>(callback: C): C;
1518
export function defineMiddleware<C extends (options: TeeOptions<'middleware'>) => (...args: any[]) => any>(callback: C, _options?: DefineMiddlewareOptions): C {
1619
return callback;
1720
}
1821

22+
/**
23+
* 定义一个 config
24+
*/
1925
export function defineConfig<C extends (options: TeeOptions<'config'>) => Record<string, any>>(callback: C): C {
2026
return callback;
2127
}
2228

29+
/**
30+
* 定义一个 router
31+
*/
2332
export function defineRouter<C extends (options: Required<TeeOptions<'router'>>) => void>(callback: C): C {
2433
return callback;
2534
}
2635

2736
export interface TeeContext extends KoaRouter.RouterContext<Koa.DefaultState, TeeKoa.Context> {}
2837

38+
/**
39+
* 定义一个控制器
40+
*/
2941
export function defineController<C extends (options: TeeOptions<'controller'>) => new (...args: any) => any>(callback: C): C {
3042
return callback;
3143
}
3244

45+
/**
46+
* 定义一个 service
47+
*/
3348
export function defineService<C extends (options: TeeOptions<'service'>) => new (...args: any) => any>(callback: C): C {
3449
return callback;
3550
}
3651

52+
/**
53+
* 定义一个扩展
54+
*/
3755
export function defineExtend<C extends (options: TeeOptions<'extend'>) => any>(callback: C): C {
3856
return callback;
3957
}
4058

59+
/**
60+
* 定义一个 routerSchema
61+
*
62+
* 可用于自动生成前端接口请求文件
63+
*
64+
* TODO: 生成 OpenAPI 规范的请求文档
65+
*/
4166
export function defineRouterSchema<C extends (options: TeeOptions<'routerSchema'>) => Record<string, RouterSchema>>(callback: C): C {
4267
return callback;
4368
}
4469

70+
/**
71+
* 定义一个 tee 配置
72+
*/
4573
export function defineTeeConfig(config: ConfigFile): ConfigFile {
4674
return config;
4775
}
4876

77+
/**
78+
* 定义一个入口
79+
*/
4980
export function defineEntry<C extends (app: TeeKoa.Application, router: KoaRouter) => void>(callback: C): C {
5081
return callback;
5182
}

0 commit comments

Comments
 (0)