create-dp-koa 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/package.json +1 -1
  2. package/template/.cursor/commands/cheatsheet-backend-controller.md +2 -2
  3. package/template/.cursor/commands/implement-backend-api-controller.md +6 -4
  4. package/template/.cursor/rules/11-backend-controller-recipes.skill.md +89 -10
  5. package/template/.trae/skills/11-backend-controller-recipes.skill.md +91 -10
  6. package/template/src/controllers/example/ExampleController.ts +14 -0
  7. package/template/src/entity/index.ts +1 -15
  8. package/template/src/framework/decorator/processor/AnnotationProcessor.ts +5 -1
  9. package/template/src/routers/index.ts +0 -35
  10. package/template/src/utils/testDataInitializer.ts +2 -269
  11. package/template/test/controllers/example/ExampleController.test.ts +29 -31
  12. package/template/test/framework/annotation/AnnotationDecorators.test.ts +15 -15
  13. package/template/test/framework/annotation/AnnotationExecutor.test.ts +27 -32
  14. package/template/test/framework/annotation/AnnotationProcessor.test.ts +25 -24
  15. package/template/test/framework/annotation/CustomProcessors.test.ts +15 -25
  16. package/template/test/framework/annotation/NewRouter.test.ts +9 -7
  17. package/template/test/framework/annotation/ProcessorManager.test.ts +14 -27
  18. package/template/test/framework/databaseConfig.test.ts +2 -2
  19. package/template/test/integration/integration.test.ts +15 -72
  20. package/template/src/controllers/cacheManagement.controller.ts +0 -131
  21. package/template/src/controllers/captcha.controller.ts +0 -57
  22. package/template/src/controllers/example/NewAnnotationExampleController.ts +0 -159
  23. package/template/src/controllers/example/SwaggerExampleController.ts +0 -205
  24. package/template/src/controllers/example/TransactionExample.controller.ts +0 -336
  25. package/template/src/controllers/health.controller.ts +0 -235
  26. package/template/src/controllers/home/register.controller.ts +0 -58
  27. package/template/src/controllers/home/ytGoods.controller.ts +0 -92
  28. package/template/src/controllers/home/ytShop.controller.ts +0 -135
  29. package/template/src/controllers/home/ytUser.controller.ts +0 -89
  30. package/template/src/controllers/logManagement.controller.ts +0 -396
  31. package/template/src/controllers/public/emailSend.controller.ts +0 -65
  32. package/template/src/controllers/public/ytUserAuth.controller.ts +0 -174
  33. package/template/src/controllers/testData.controller.ts +0 -253
  34. package/template/src/dto/controller/example/NewAnnotationExampleController.dto.ts +0 -73
  35. package/template/src/dto/controller/home/emailSend.controller.dto.ts +0 -40
  36. package/template/src/dto/controller/home/register.controller.dto.ts +0 -45
  37. package/template/src/dto/controller/home/ytGoods.controller.dto.ts +0 -55
  38. package/template/src/dto/controller/home/ytShop.controller.dto.ts +0 -69
  39. package/template/src/dto/controller/home/ytUser.controller.dto.ts +0 -44
  40. package/template/src/dto/controller/public/ytUserAuth.controller.dto.ts +0 -63
  41. package/template/src/dto/goods.dto.ts +0 -212
  42. package/template/src/dto/service/ytService.dto.ts +0 -13
  43. package/template/src/dto/user.dto.ts +0 -177
  44. package/template/src/entity/columnTypes.ts +0 -13
  45. package/template/src/entity/goodsImagesUnlockKey.entity.ts +0 -33
  46. package/template/src/entity/goodsUnlocker.entity.ts +0 -34
  47. package/template/src/entity/shop.entity.ts +0 -52
  48. package/template/src/entity/shopUser.entity.ts +0 -41
  49. package/template/src/entity/ytGoods.entity.ts +0 -94
  50. package/template/src/entity/ytUser.entity.ts +0 -96
  51. package/template/src/examples/SwaggerProcessorExample.ts +0 -169
  52. package/template/src/examples/TransactionManagerDemo.ts +0 -377
  53. package/template/src/framework/utils/dynamicSwagger.ts +0 -410
  54. package/template/src/repository/UserRepository.ts +0 -122
  55. package/template/src/service/paramValidateTest.service.ts +0 -139
  56. package/template/src/service/ytGoods.service.ts +0 -42
  57. package/template/src/service/ytShop.service.ts +0 -90
  58. package/template/src/service/ytUser.service.ts +0 -451
  59. package/template/src/test/swaggerParameterTest.ts +0 -90
  60. package/template/test/controllers/controllers.test.ts +0 -173
  61. package/template/test/controllers/example/NewAnnotationExampleController.test.ts +0 -200
  62. package/template/test/framework/TransactionManagerDemo.test.ts +0 -363
  63. package/template/test/service/business.test.ts +0 -87
  64. package/template/test/service/paramValidateTest.service.test.ts +0 -184
  65. package/template/test/service/ytUser.service.test.ts +0 -566
@@ -1,42 +0,0 @@
1
- import { BaseService } from "@src/service/base.service";
2
- import { CommonServiceResult, CommonServiceResultCode } from "@src/framework/types/ServiceResult";
3
- import { YtGoodsUnlockerEntity } from "@src/entity/goodsUnlocker.entity";
4
- import { GoodsImagesUnlockKeyEntity } from "@src/entity/goodsImagesUnlockKey.entity";
5
-
6
- export class YtGoodsService extends BaseService {
7
-
8
-
9
- async unlockGoodsImage(goodsId: number, userId: number, key: string): Promise<CommonServiceResult<boolean>> {
10
- // 验证解锁key
11
- const keyRepo = this.getDataRepository(GoodsImagesUnlockKeyEntity);
12
- const unlockKey = await keyRepo.findOneBy({ key });
13
-
14
- if (!unlockKey || unlockKey.isUse) {
15
- return new CommonServiceResult(CommonServiceResultCode.FAIL, false, "无效的解锁key");
16
- }
17
-
18
- // 标记key为已使用
19
- unlockKey.isUse = true;
20
- await keyRepo.save(unlockKey);
21
-
22
- // 创建解锁记录
23
- const unlockRepo = this.getDataRepository(YtGoodsUnlockerEntity);
24
- await unlockRepo.save({
25
- goodsId,
26
- ytUserId: userId
27
- });
28
-
29
- return new CommonServiceResult(CommonServiceResultCode.SUCCESS, true);
30
- }
31
-
32
- /**
33
- * 根据ID获取商品(兼容旧接口)
34
- */
35
- async getById(entityClass: any, id: number): Promise<any> {
36
- try {
37
- return await this.getDataRepository(entityClass).findOne({ where: { id } });
38
- } catch (error) {
39
- return null;
40
- }
41
- }
42
- }
@@ -1,90 +0,0 @@
1
- import { YtGoodsEntity, YtGoodsStatusEnum } from "@src/entity/ytGoods.entity";
2
- import { BaseService } from "@src/service/base.service";
3
- import { CommonServiceResult, CommonServiceResultCode } from "@src/framework/types/ServiceResult";
4
- import { YtUserEntity } from "@src/entity/ytUser.entity";
5
- import { ShopAndUserEntity } from "@src/entity/shopUser.entity";
6
-
7
- export class YtShopService extends BaseService {
8
-
9
-
10
- /**
11
- * 获取店铺的商品列表
12
- * @param shopId
13
- * @param page
14
- * @param pageSize
15
- * @returns
16
- */
17
- async getGoodsListByShopId(
18
- shopId: number,
19
- page: number,
20
- pageSize: number
21
- ): Promise<CommonServiceResult<[YtGoodsEntity[], number]>> {
22
- const ds = this.getDataRepository(YtGoodsEntity);
23
- try {
24
- const result = await ds.findAndCount({
25
- where: { shopId, status: YtGoodsStatusEnum.NORMAL },
26
- skip: (page - 1) * pageSize,
27
- take: pageSize,
28
- order: { id: "DESC" }
29
- });
30
- return new CommonServiceResult(CommonServiceResultCode.SUCCESS, result);
31
- } catch (error) {
32
- return new CommonServiceResult(CommonServiceResultCode.ERROR, [[], 0], "查询商品列表失败");
33
- }
34
- }
35
-
36
-
37
- /**
38
- * 读取店铺的用户基本信息
39
- * @param shopId
40
- */
41
- async getShopUserInfo(shopId: number): Promise<CommonServiceResult<YtUserEntity | null>> {
42
-
43
- const relation = await this.getDataRepository(ShopAndUserEntity).findOne({
44
- where: {
45
- shopId,
46
- }
47
- });
48
-
49
- if (!relation) {
50
- return new CommonServiceResult(CommonServiceResultCode.FAIL, null, "店铺未绑定用户")
51
- }
52
-
53
-
54
-
55
- const user = await this.getDataRepository(YtUserEntity).findOne({
56
- where: {
57
- id: relation.userId,
58
- }
59
- })
60
- if (!user) {
61
- return new CommonServiceResult(CommonServiceResultCode.FAIL, null, "用户不存在");
62
- }
63
- return new CommonServiceResult(CommonServiceResultCode.SUCCESS, user,);
64
- }
65
-
66
-
67
- /**
68
- * 检测用户是否有店铺 如果有,则返回shop id
69
- * @param userId
70
- */
71
- async checkHasShop(userId: number): Promise<CommonServiceResult<number | null>> {
72
- const result = await this.getDataRepository(ShopAndUserEntity).findOne({
73
- where: {
74
- userId,
75
- }
76
- })
77
- return new CommonServiceResult(CommonServiceResultCode.SUCCESS, result?.shopId || null);
78
- }
79
-
80
- /**
81
- * 根据ID获取店铺(兼容旧接口)
82
- */
83
- async getById(entityClass: any, id: number): Promise<any> {
84
- try {
85
- return await this.getDataRepository(entityClass).findOne({ where: { id } });
86
- } catch (error) {
87
- return null;
88
- }
89
- }
90
- }
@@ -1,451 +0,0 @@
1
- import { Injectable } from "dp-ioc2";
2
- import { transactionManager } from "@src/framework/utils/TransactionManager";
3
- import { UserRepository, IUserRepository } from "@src/repository/UserRepository";
4
- import { YtUserEntity, YtUserTypeEnum, YtUserStatusEnum } from "@src/entity/ytUser.entity";
5
- import { CreateUserDto, UpdateUserDto, QueryUserDto, LoginUserDto, ChangePasswordDto } from "@src/dto/user.dto";
6
- import { DtoValidator, ValidationResult } from "@src/framework/utils/DtoValidator";
7
- import { CommonServiceResultCode, CommonServiceResult } from "@src/framework/types/ServiceResult";
8
- import { logger } from "@src/framework/utils/logger";
9
- import { BaseService } from "@src/service/base.service";
10
- import * as bcrypt from 'bcryptjs';
11
- import { ServiceValidate } from "@src/libs/serviceValidate";
12
- import { isDebug } from "@src/framework/utils/function";
13
-
14
- /**
15
- * 企业级用户服务
16
- * 使用Repository模式和事务管理
17
- */
18
- @Injectable()
19
- export class YtUserService extends BaseService {
20
- private repositoryCache = new Map<string, any>();
21
-
22
- /**
23
- * 获取用户Repository(懒加载)
24
- * 使用基类的通用方法
25
- */
26
- private get userRepository(): IUserRepository {
27
- return this.createLazyRepository(
28
- YtUserEntity,
29
- UserRepository,
30
- this.repositoryCache
31
- );
32
- }
33
-
34
-
35
- // @Interceptor(ServiceValidate(TestValidateServiceDto))
36
- // async validateTest (param:TestValidateServiceDto){
37
- // }
38
-
39
- /**
40
- * 创建用户
41
- */
42
- async createUser(createUserDto: CreateUserDto): Promise<CommonServiceResult<YtUserEntity>> {
43
- try {
44
- // 验证DTO
45
- const validation = await DtoValidator.validateAndTransform(CreateUserDto, createUserDto);
46
- if (!validation.isValid) {
47
- return CommonServiceResult.validationError(validation.errors.join(', '));
48
- }
49
-
50
- // 验证密码强度
51
- if (!this.validatePasswordStrength(createUserDto.password)) {
52
- return CommonServiceResult.validationError(
53
- "密码强度不足。密码必须至少8位,包含数字、字母和特殊字符"
54
- );
55
- }
56
-
57
- // 检查邮箱是否已存在
58
- const existingUserByEmail = await this.userRepository.findByEmail(createUserDto.email);
59
- if (existingUserByEmail) {
60
- return CommonServiceResult.conflict("邮箱已被使用");
61
- }
62
-
63
- // 检查手机号是否已存在
64
- const existingUserByTel = await this.userRepository.findByTelNumber(createUserDto.telnumber);
65
- if (existingUserByTel) {
66
- return CommonServiceResult.conflict("手机号已被使用");
67
- }
68
-
69
- // 使用事务创建用户
70
- const user = await transactionManager.executeInTransaction(async (manager) => {
71
- // 加密密码
72
- const hashedPassword = await bcrypt.hash(createUserDto.password, 10);
73
-
74
- // 创建用户实体
75
- const userData = {
76
- ...validation.data,
77
- password: hashedPassword,
78
- userType: createUserDto.userType || YtUserTypeEnum.CUSTOMER,
79
- status: createUserDto.status || YtUserStatusEnum.NORMAL,
80
- };
81
-
82
- return await this.userRepository.save(userData);
83
- });
84
-
85
- logger.info(`用户创建成功: ${this.maskEmail(user.email)}`);
86
- return CommonServiceResult.success(user, "用户创建成功");
87
-
88
- } catch (error) {
89
- logger.error("创建用户失败:", error as Error);
90
- // 生产环境不返回详细错误,避免信息泄露
91
- const errorMessage = !isDebug()
92
- ? "创建用户时发生错误"
93
- : error instanceof Error ? error.message : "创建用户时发生错误";
94
- return CommonServiceResult.error(errorMessage);
95
- }
96
- }
97
-
98
- /**
99
- * 更新用户
100
- */
101
- async updateUser(id: number, updateUserDto: UpdateUserDto): Promise<CommonServiceResult<YtUserEntity | null>> {
102
- try {
103
- // 验证DTO
104
- const validation = await DtoValidator.validatePartial(UpdateUserDto, updateUserDto);
105
- if (!validation.isValid) {
106
- return CommonServiceResult.validationError(validation.errors.join(', '));
107
- }
108
-
109
- // 检查用户是否存在
110
- const existingUser = await this.userRepository.findById(id);
111
- if (!existingUser) {
112
- return CommonServiceResult.notFound("用户不存在");
113
- }
114
-
115
- // 使用事务更新用户
116
- const updatedUser = await transactionManager.executeInTransaction(async (manager) => {
117
- // 检查邮箱是否被其他用户使用
118
- if (updateUserDto.email && updateUserDto.email !== existingUser.email) {
119
- const userWithEmail = await this.userRepository.findByEmail(updateUserDto.email);
120
- if (userWithEmail && userWithEmail.id !== id) {
121
- throw new Error("邮箱已被其他用户使用");
122
- }
123
- }
124
-
125
- // 检查手机号是否被其他用户使用
126
- if (updateUserDto.telnumber && updateUserDto.telnumber !== existingUser.telnumber) {
127
- const userWithTel = await this.userRepository.findByTelNumber(updateUserDto.telnumber);
128
- if (userWithTel && userWithTel.id !== id) {
129
- throw new Error("手机号已被其他用户使用");
130
- }
131
- }
132
-
133
- await this.userRepository.update(id, validation.data);
134
- return await this.userRepository.findById(id);
135
- });
136
-
137
- logger.info(`用户更新成功: ${updatedUser?.email ? this.maskEmail(updatedUser.email) : ''}`);
138
- return CommonServiceResult.success(updatedUser, "用户更新成功");
139
-
140
- } catch (error) {
141
- logger.error("更新用户失败:", error as Error);
142
- // 生产环境不返回详细错误
143
- const errorMessage = !isDebug()
144
- ? "更新用户时发生错误"
145
- : error instanceof Error ? error.message : "更新用户时发生错误";
146
- return CommonServiceResult.error(errorMessage);
147
- }
148
- }
149
-
150
- /**
151
- * 根据ID获取用户
152
- */
153
- async getUserById(id: number): Promise<CommonServiceResult<YtUserEntity | null>> {
154
- try {
155
- const user = await this.userRepository.findById(id);
156
- if (!user) {
157
- return CommonServiceResult.notFound("用户不存在");
158
- }
159
-
160
- return CommonServiceResult.success(user);
161
-
162
- } catch (error) {
163
- logger.error("获取用户失败:", error as Error);
164
- return CommonServiceResult.error("获取用户时发生错误");
165
- }
166
- }
167
-
168
- /**
169
- * 用户登录
170
- */
171
- async login(loginDto: LoginUserDto): Promise<CommonServiceResult<YtUserEntity | null>> {
172
- try {
173
- // 验证DTO
174
- const validation = await DtoValidator.validateAndTransform(LoginUserDto, loginDto);
175
- if (!validation.isValid) {
176
- return CommonServiceResult.validationError(validation.errors.join(', '));
177
- }
178
-
179
- // 查找用户(通过邮箱或手机号)
180
- let user = await this.userRepository.findByEmail(loginDto.credential);
181
- if (!user) {
182
- user = await this.userRepository.findByTelNumber(loginDto.credential);
183
- }
184
-
185
- if (!user) {
186
- return CommonServiceResult.notFound("用户不存在");
187
- }
188
-
189
- // 检查用户状态
190
- if (user.status === YtUserStatusEnum.FORBIDDEN) {
191
- return CommonServiceResult.forbidden("用户已被禁用");
192
- }
193
-
194
- // 验证密码
195
- const isPasswordValid = await bcrypt.compare(loginDto.password, user.password);
196
- if (!isPasswordValid) {
197
- return CommonServiceResult.unauthorized("密码错误");
198
- }
199
-
200
- // 更新最后登录时间
201
- await this.userRepository.updateLastLoginTime(user.id);
202
-
203
- logger.info(`用户登录成功: ${this.maskEmail(user.email)}`);
204
- return CommonServiceResult.success(user, "登录成功");
205
-
206
- } catch (error) {
207
- logger.error("用户登录失败:", error as Error);
208
- return CommonServiceResult.error("登录时发生错误");
209
- }
210
- }
211
-
212
- /**
213
- * 修改密码
214
- */
215
- async changePassword(id: number, changePasswordDto: ChangePasswordDto): Promise<CommonServiceResult<boolean>> {
216
- try {
217
- // 验证DTO
218
- const validation = await DtoValidator.validateAndTransform(ChangePasswordDto, changePasswordDto);
219
- if (!validation.isValid) {
220
- return CommonServiceResult.validationError(validation.errors.join(', '), false);
221
- }
222
-
223
- // 检查新密码和确认密码是否一致
224
- if (changePasswordDto.newPassword !== changePasswordDto.confirmPassword) {
225
- return CommonServiceResult.validationError("新密码和确认密码不一致", false);
226
- }
227
-
228
- // 使用事务修改密码
229
- await transactionManager.executeInTransaction(async (manager) => {
230
- // 获取用户
231
- const user = await this.userRepository.findById(id);
232
- if (!user) {
233
- throw new Error("用户不存在");
234
- }
235
-
236
- // 验证当前密码
237
- const isCurrentPasswordValid = await bcrypt.compare(
238
- changePasswordDto.currentPassword,
239
- user.password
240
- );
241
- if (!isCurrentPasswordValid) {
242
- throw new Error("当前密码错误");
243
- }
244
-
245
- // 加密新密码
246
- const hashedNewPassword = await bcrypt.hash(changePasswordDto.newPassword, 10);
247
-
248
- // 更新密码
249
- await this.userRepository.updatePassword(id, hashedNewPassword);
250
- });
251
-
252
- logger.info(`用户密码修改成功: ${id}`);
253
- return CommonServiceResult.success(true, "密码修改成功");
254
-
255
- } catch (error) {
256
- logger.error("修改密码失败:", error as Error);
257
- return CommonServiceResult.error(error instanceof Error ? error.message : "修改密码时发生错误", false);
258
- }
259
- }
260
-
261
- /**
262
- * 查询用户列表
263
- */
264
- async getUsers(queryDto: QueryUserDto): Promise<CommonServiceResult<[YtUserEntity[], number]>> {
265
- try {
266
- // 验证DTO
267
- const validation = await DtoValidator.validatePartial(QueryUserDto, queryDto);
268
- if (!validation.isValid) {
269
- return new CommonServiceResult(
270
- CommonServiceResultCode.VALIDATION_ERROR,
271
- [[], 0],
272
- validation.errors.join(', ')
273
- );
274
- }
275
-
276
- const { page = 1, pageSize = 10, sortBy = 'id', sortOrder = 'DESC', ...filters } = validation.data;
277
-
278
- // 构建查询条件
279
- const whereConditions: any = {};
280
-
281
- if (filters.userType) {
282
- whereConditions.userType = filters.userType;
283
- }
284
-
285
- if (filters.status) {
286
- whereConditions.status = filters.status;
287
- }
288
-
289
- // 执行查询
290
- const [users, total] = await this.userRepository.findAndCount({
291
- where: whereConditions,
292
- skip: (page - 1) * pageSize,
293
- take: pageSize,
294
- order: { [sortBy]: sortOrder }
295
- });
296
-
297
- return new CommonServiceResult(CommonServiceResultCode.SUCCESS, [users, total]);
298
-
299
- } catch (error) {
300
- logger.error("查询用户列表失败:", error as Error);
301
- return new CommonServiceResult(
302
- CommonServiceResultCode.ERROR,
303
- [[], 0],
304
- "查询用户列表时发生错误"
305
- );
306
- }
307
- }
308
-
309
- /**
310
- * 删除用户
311
- */
312
- async deleteUser(id: number): Promise<CommonServiceResult<boolean>> {
313
- try {
314
- // 检查用户是否存在
315
- const user = await this.userRepository.findById(id);
316
- if (!user) {
317
- return new CommonServiceResult(
318
- CommonServiceResultCode.NOT_FOUND,
319
- false,
320
- "用户不存在"
321
- );
322
- }
323
-
324
- // 使用事务删除用户
325
- await transactionManager.executeInTransaction(async (manager) => {
326
- await this.userRepository.delete(id);
327
- });
328
-
329
- logger.info(`用户删除成功: ${id}`);
330
- return new CommonServiceResult(CommonServiceResultCode.SUCCESS, true, "用户删除成功");
331
-
332
- } catch (error) {
333
- logger.error("删除用户失败:", error as Error);
334
- return new CommonServiceResult(
335
- CommonServiceResultCode.ERROR,
336
- false,
337
- "删除用户时发生错误"
338
- );
339
- }
340
- }
341
-
342
- /**
343
- * 激活/禁用用户
344
- */
345
- async toggleUserStatus(id: number, activate: boolean): Promise<CommonServiceResult<boolean>> {
346
- try {
347
- // 检查用户是否存在
348
- const user = await this.userRepository.findById(id);
349
- if (!user) {
350
- return new CommonServiceResult(
351
- CommonServiceResultCode.NOT_FOUND,
352
- false,
353
- "用户不存在"
354
- );
355
- }
356
-
357
- // 更新用户状态
358
- if (activate) {
359
- await this.userRepository.activateUser(id);
360
- } else {
361
- await this.userRepository.deactivateUser(id);
362
- }
363
-
364
- const action = activate ? "激活" : "禁用";
365
- logger.info(`用户${action}成功: ${id}`);
366
- return new CommonServiceResult(CommonServiceResultCode.SUCCESS, true, `用户${action}成功`);
367
-
368
- } catch (error) {
369
- logger.error("切换用户状态失败:", error as Error);
370
- return new CommonServiceResult(
371
- CommonServiceResultCode.ERROR,
372
- false,
373
- "切换用户状态时发生错误"
374
- );
375
- }
376
- }
377
-
378
- /**
379
- * 根据邮箱查找用户(兼容旧接口)
380
- */
381
- async findByEmail(email: string): Promise<YtUserEntity | null> {
382
- try {
383
- return await this.userRepository.findByEmail(email);
384
- } catch (error) {
385
- logger.error("根据邮箱查找用户失败:", error as Error);
386
- return null;
387
- }
388
- }
389
-
390
- /**
391
- * 添加用户(兼容旧接口)
392
- * 注意:此方法用于兼容旧代码,新代码应使用 createUser
393
- */
394
- async addUser(user: YtUserEntity): Promise<YtUserEntity> {
395
- try {
396
- return await this.userRepository.save(user);
397
- } catch (error) {
398
- logger.error("添加用户失败:", error as Error);
399
- throw error;
400
- }
401
- }
402
-
403
- /**
404
- * 根据ID获取用户(兼容旧接口)
405
- * 注意:此方法用于兼容旧代码,新代码应使用 getUserById
406
- */
407
- async getUserByIdLegacy(entityClass: any, id: number): Promise<YtUserEntity | null> {
408
- try {
409
- return await this.userRepository.findById(id);
410
- } catch (error) {
411
- logger.error("根据ID获取用户失败:", error as Error);
412
- return null;
413
- }
414
- }
415
-
416
- /**
417
- * 邮箱脱敏处理
418
- * 用于日志记录,保护用户隐私
419
- */
420
- private maskEmail(email: string): string {
421
- if (!email || !email.includes('@')) return email;
422
- const [name, domain] = email.split('@');
423
- const maskedName = name.length > 2
424
- ? name.substring(0, 2) + '***'
425
- : '***';
426
- return `${maskedName}@${domain}`;
427
- }
428
-
429
- /**
430
- * 验证密码强度
431
- * 要求:至少8位,包含数字、字母和特殊字符
432
- */
433
- private validatePasswordStrength(password: string): boolean {
434
- if (password.length < 8) return false;
435
-
436
- const hasNumber = /\d/.test(password);
437
- const hasLetter = /[a-zA-Z]/.test(password);
438
- const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);
439
-
440
- return hasNumber && hasLetter && hasSpecial;
441
- }
442
-
443
- /**
444
- * 清理资源
445
- * 在应用关闭时调用
446
- */
447
- cleanup(): void {
448
- this.repositoryCache.clear();
449
- logger.info('YtUserService 资源已清理');
450
- }
451
- }
@@ -1,90 +0,0 @@
1
- /**
2
- * 测试Swagger处理器的参数推断功能
3
- */
4
-
5
- import { swaggerProcessor } from '@src/annotations/processors/SwaggerProcessor';
6
- import { SwaggerExampleController } from '@src/controllers/example/SwaggerExampleController';
7
- import { logger } from '@src/framework/utils/logger';
8
-
9
- /**
10
- * 测试参数推断功能
11
- */
12
- export function testSwaggerParameterInference() {
13
- try {
14
- logger.info('=== 测试Swagger处理器参数推断功能 ===');
15
-
16
- // 测试getUserById方法的参数推断
17
- const methodName = 'getUserById';
18
- const methodMetadata = swaggerProcessor.processMethod(SwaggerExampleController, methodName);
19
-
20
- logger.info(`方法 ${methodName} 的参数信息:`);
21
- logger.info(` - 参数数量: ${methodMetadata.parameters.length}`);
22
-
23
- methodMetadata.parameters.forEach((param, index) => {
24
- logger.info(` - 参数 ${index + 1}:`);
25
- logger.info(` * 名称: ${param.name}`);
26
- logger.info(` * 位置: ${param.in}`);
27
- logger.info(` * 描述: ${param.description}`);
28
- logger.info(` * 必需: ${param.required}`);
29
- logger.info(` * 类型: ${JSON.stringify(param.schema)}`);
30
- });
31
-
32
- // 测试updateUser方法的参数推断
33
- const updateMethodName = 'updateUser';
34
- const updateMethodMetadata = swaggerProcessor.processMethod(SwaggerExampleController, updateMethodName);
35
-
36
- logger.info(`\n方法 ${updateMethodName} 的参数信息:`);
37
- logger.info(` - 参数数量: ${updateMethodMetadata.parameters.length}`);
38
-
39
- updateMethodMetadata.parameters.forEach((param, index) => {
40
- logger.info(` - 参数 ${index + 1}:`);
41
- logger.info(` * 名称: ${param.name}`);
42
- logger.info(` * 位置: ${param.in}`);
43
- logger.info(` * 描述: ${param.description}`);
44
- logger.info(` * 必需: ${param.required}`);
45
- logger.info(` * 类型: ${JSON.stringify(param.schema)}`);
46
- });
47
-
48
- // 测试OpenAPI规范生成
49
- logger.info('\n=== 测试OpenAPI规范生成 ===');
50
- const openAPISpec = swaggerProcessor.generateOpenAPISpec([SwaggerExampleController]);
51
-
52
- // 检查特定路径的参数
53
- const userPath = '/swagger/c/user/{id}';
54
- if (openAPISpec.paths[userPath]) {
55
- const pathInfo = openAPISpec.paths[userPath];
56
-
57
- if (pathInfo.get) {
58
- logger.info(`GET ${userPath} 参数:`);
59
- if (pathInfo.get.parameters) {
60
- pathInfo.get.parameters.forEach((param: any, index: number) => {
61
- logger.info(` - 参数 ${index + 1}: ${param.name} (${param.in})`);
62
- });
63
- } else {
64
- logger.warn(`GET ${userPath} 没有参数定义`);
65
- }
66
- }
67
-
68
- if (pathInfo.put) {
69
- logger.info(`PUT ${userPath} 参数:`);
70
- if (pathInfo.put.parameters) {
71
- pathInfo.put.parameters.forEach((param: any, index: number) => {
72
- logger.info(` - 参数 ${index + 1}: ${param.name} (${param.in})`);
73
- });
74
- } else {
75
- logger.warn(`PUT ${userPath} 没有参数定义`);
76
- }
77
- }
78
- }
79
-
80
- logger.info('Swagger处理器参数推断功能测试完成!');
81
-
82
- } catch (error) {
83
- logger.error('测试Swagger处理器参数推断功能失败:', error as Error);
84
- }
85
- }
86
-
87
- // 如果直接运行此文件,执行测试
88
- if (require.main === module) {
89
- testSwaggerParameterInference();
90
- }