@nest-omni/core 3.1.1-18 → 3.1.1-19

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 (37) hide show
  1. package/cache/cache-serialization.service.d.ts +4 -11
  2. package/cache/cache-serialization.service.js +29 -124
  3. package/cache/cache.constants.d.ts +2 -0
  4. package/cache/cache.constants.js +5 -0
  5. package/cache/cache.module.d.ts +2 -0
  6. package/cache/cache.module.js +49 -3
  7. package/cache/cache.service.d.ts +3 -1
  8. package/cache/cache.service.js +32 -4
  9. package/cache/examples/basic-usage.d.ts +58 -0
  10. package/cache/examples/basic-usage.js +379 -0
  11. package/cache/index.d.ts +2 -1
  12. package/cache/index.js +4 -1
  13. package/common/boilerplate.polyfill.d.ts +0 -6
  14. package/common/dto/page-options.dto.d.ts +0 -3
  15. package/common/dto/page-options.dto.js +0 -12
  16. package/common/examples/paginate-and-map.example.d.ts +14 -0
  17. package/common/examples/paginate-and-map.example.js +158 -0
  18. package/decorators/examples/validation-decorators.example.d.ts +69 -0
  19. package/decorators/examples/validation-decorators.example.js +331 -0
  20. package/decorators/validator.decorators.d.ts +8 -1
  21. package/decorators/validator.decorators.js +115 -0
  22. package/i18n/en_US/validation.json +4 -1
  23. package/i18n/zh_CN/validation.json +4 -1
  24. package/index.d.ts +1 -0
  25. package/index.js +1 -0
  26. package/package.json +1 -1
  27. package/redis-lock/examples/lock-strategy.examples.d.ts +73 -0
  28. package/redis-lock/examples/lock-strategy.examples.js +387 -0
  29. package/redis-lock/index.d.ts +2 -2
  30. package/redis-lock/index.js +4 -1
  31. package/redis-lock/redis-lock.decorator.d.ts +4 -0
  32. package/redis-lock/redis-lock.decorator.js +43 -7
  33. package/redis-lock/redis-lock.service.d.ts +19 -0
  34. package/redis-lock/redis-lock.service.js +131 -6
  35. package/setup/index.d.ts +0 -1
  36. package/setup/index.js +0 -1
  37. package/shared/serviceRegistryModule.js +2 -0
@@ -0,0 +1,379 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13
+ return new (P || (P = Promise))(function (resolve, reject) {
14
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
16
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
17
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
18
+ });
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.CacheMonitoringService = exports.PostService = exports.UserService = void 0;
22
+ exports.demonstrateCacheUsage = demonstrateCacheUsage;
23
+ const common_1 = require("@nestjs/common");
24
+ const index_1 = require("../index");
25
+ class UserRepository {
26
+ findOne(id) {
27
+ return __awaiter(this, void 0, void 0, function* () {
28
+ console.log(`[DB] 查询用户 ${id}`);
29
+ return {
30
+ id,
31
+ name: `User ${id}`,
32
+ email: `user${id}@example.com`,
33
+ profile: {
34
+ bio: `这是用户 ${id} 的个人简介`.repeat(10),
35
+ avatar: `avatar_${id}.jpg`,
36
+ },
37
+ };
38
+ });
39
+ }
40
+ findMany(ids) {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ console.log(`[DB] 批量查询用户 ${ids.join(', ')}`);
43
+ return Promise.all(ids.map((id) => this.findOne(id)));
44
+ });
45
+ }
46
+ findAll() {
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ console.log('[DB] 查询所有用户');
49
+ return Array(100)
50
+ .fill(null)
51
+ .map((_, i) => ({
52
+ id: `user_${i}`,
53
+ name: `User ${i}`,
54
+ email: `user${i}@example.com`,
55
+ profile: {
56
+ bio: `这是用户 ${i} 的个人简介`.repeat(5),
57
+ avatar: `avatar_${i}.jpg`,
58
+ },
59
+ }));
60
+ });
61
+ }
62
+ save(user) {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ console.log(`[DB] 保存用户 ${user.id}`);
65
+ return Object.assign({}, user);
66
+ });
67
+ }
68
+ delete(id) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ console.log(`[DB] 删除用户 ${id}`);
71
+ });
72
+ }
73
+ }
74
+ class PostRepository {
75
+ findByAuthor(authorId) {
76
+ return __awaiter(this, void 0, void 0, function* () {
77
+ console.log(`[DB] 查询作者 ${authorId} 的文章`);
78
+ return Array(20)
79
+ .fill(null)
80
+ .map((_, i) => ({
81
+ id: `post_${authorId}_${i}`,
82
+ title: `文章 ${i}`,
83
+ content: `这是文章 ${i} 的内容`.repeat(15),
84
+ authorId,
85
+ createdAt: new Date(),
86
+ }));
87
+ });
88
+ }
89
+ }
90
+ let UserService = class UserService {
91
+ constructor(cacheService, userRepository) {
92
+ this.cacheService = cacheService;
93
+ this.userRepository = userRepository;
94
+ }
95
+ getUser(id) {
96
+ return __awaiter(this, void 0, void 0, function* () {
97
+ return yield this.cacheService.getOrSet(`user:${id}`, () => this.userRepository.findOne(id), { ttl: 300000 });
98
+ });
99
+ }
100
+ getUserProfile(id) {
101
+ return __awaiter(this, void 0, void 0, function* () {
102
+ return yield this.userRepository.findOne(id);
103
+ });
104
+ }
105
+ getUserData(id) {
106
+ return __awaiter(this, void 0, void 0, function* () {
107
+ return yield this.userRepository.findOne(id);
108
+ });
109
+ }
110
+ getUsersBatch(ids) {
111
+ return __awaiter(this, void 0, void 0, function* () {
112
+ const keys = ids.map((id) => `user:${id}`);
113
+ const cachedUsers = yield this.cacheService.mget(keys);
114
+ const uncachedIds = [];
115
+ const result = [];
116
+ cachedUsers.forEach((user, index) => {
117
+ if (user) {
118
+ result.push(user);
119
+ }
120
+ else {
121
+ uncachedIds.push(ids[index]);
122
+ }
123
+ });
124
+ if (uncachedIds.length > 0) {
125
+ const newUsers = yield this.userRepository.findMany(uncachedIds);
126
+ const cacheItems = newUsers.map((user) => ({
127
+ key: `user:${user.id}`,
128
+ value: user,
129
+ }));
130
+ yield this.cacheService.mset(cacheItems, { ttl: 300000 });
131
+ result.push(...newUsers);
132
+ }
133
+ return result;
134
+ });
135
+ }
136
+ updateUser(id, data) {
137
+ return __awaiter(this, void 0, void 0, function* () {
138
+ const updatedUser = yield this.userRepository.save(Object.assign({ id }, data));
139
+ return updatedUser;
140
+ });
141
+ }
142
+ deleteUser(id) {
143
+ return __awaiter(this, void 0, void 0, function* () {
144
+ yield this.userRepository.delete(id);
145
+ });
146
+ }
147
+ invalidateAllProfiles() {
148
+ return __awaiter(this, void 0, void 0, function* () {
149
+ console.log('清除所有用户资料缓存');
150
+ });
151
+ }
152
+ cacheLargeData(id) {
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ const largeData = {
155
+ user: yield this.userRepository.findOne(id),
156
+ posts: Array(50)
157
+ .fill(null)
158
+ .map((_, i) => ({
159
+ id: `post_${i}`,
160
+ title: `文章标题 ${i}`,
161
+ content: `这是很长的文章内容 ${i}`.repeat(20),
162
+ metadata: {
163
+ tags: ['tag1', 'tag2', 'tag3'],
164
+ category: 'test',
165
+ views: Math.floor(Math.random() * 10000),
166
+ likes: Math.floor(Math.random() * 1000),
167
+ },
168
+ })),
169
+ statistics: {
170
+ totalPosts: 50,
171
+ totalViews: Math.floor(Math.random() * 100000),
172
+ totalLikes: Math.floor(Math.random() * 10000),
173
+ averageRating: (Math.random() * 5).toFixed(2),
174
+ },
175
+ };
176
+ yield this.cacheService.set(`user:${id}:large-data`, largeData, {
177
+ ttl: 3600000,
178
+ });
179
+ });
180
+ }
181
+ getLargeData(id) {
182
+ return __awaiter(this, void 0, void 0, function* () {
183
+ return yield this.cacheService.get(`user:${id}:large-data`);
184
+ });
185
+ }
186
+ };
187
+ exports.UserService = UserService;
188
+ __decorate([
189
+ (0, index_1.Cacheable)({
190
+ key: (id) => `user:${id}:profile`,
191
+ ttl: 600000,
192
+ dependencies: [new index_1.TagDependency(['user-profile'])],
193
+ }),
194
+ __metadata("design:type", Function),
195
+ __metadata("design:paramtypes", [String]),
196
+ __metadata("design:returntype", Promise)
197
+ ], UserService.prototype, "getUserProfile", null);
198
+ __decorate([
199
+ (0, index_1.Cacheable)({
200
+ key: (id) => `user:${id}:data`,
201
+ ttl: 300000,
202
+ condition: (id) => id !== 'admin',
203
+ }),
204
+ __metadata("design:type", Function),
205
+ __metadata("design:paramtypes", [String]),
206
+ __metadata("design:returntype", Promise)
207
+ ], UserService.prototype, "getUserData", null);
208
+ __decorate([
209
+ (0, index_1.CachePut)({
210
+ key: (id) => `user:${id}`,
211
+ ttl: 300000,
212
+ }),
213
+ __metadata("design:type", Function),
214
+ __metadata("design:paramtypes", [String, Object]),
215
+ __metadata("design:returntype", Promise)
216
+ ], UserService.prototype, "updateUser", null);
217
+ __decorate([
218
+ (0, index_1.CacheEvict)({
219
+ keys: [(id) => `user:${id}`, (id) => `user:${id}:profile`],
220
+ }),
221
+ __metadata("design:type", Function),
222
+ __metadata("design:paramtypes", [String]),
223
+ __metadata("design:returntype", Promise)
224
+ ], UserService.prototype, "deleteUser", null);
225
+ __decorate([
226
+ (0, index_1.CacheEvict)({
227
+ tags: ['user-profile'],
228
+ }),
229
+ __metadata("design:type", Function),
230
+ __metadata("design:paramtypes", []),
231
+ __metadata("design:returntype", Promise)
232
+ ], UserService.prototype, "invalidateAllProfiles", null);
233
+ exports.UserService = UserService = __decorate([
234
+ (0, common_1.Injectable)(),
235
+ __metadata("design:paramtypes", [index_1.CacheService,
236
+ UserRepository])
237
+ ], UserService);
238
+ let PostService = class PostService {
239
+ constructor(cacheService, postRepository) {
240
+ this.cacheService = cacheService;
241
+ this.postRepository = postRepository;
242
+ }
243
+ getPostsByAuthor(authorId) {
244
+ return __awaiter(this, void 0, void 0, function* () {
245
+ return yield this.postRepository.findByAuthor(authorId);
246
+ });
247
+ }
248
+ getFeaturedPosts() {
249
+ return __awaiter(this, void 0, void 0, function* () {
250
+ console.log('[DB] 获取推荐文章');
251
+ return Array(10)
252
+ .fill(null)
253
+ .map((_, i) => ({
254
+ id: `featured_${i}`,
255
+ title: `推荐文章 ${i}`,
256
+ content: `推荐文章内容 ${i}`.repeat(10),
257
+ authorId: `author_${i}`,
258
+ createdAt: new Date(),
259
+ }));
260
+ });
261
+ }
262
+ getConfigVersion() {
263
+ return __awaiter(this, void 0, void 0, function* () {
264
+ return '1.0.0';
265
+ });
266
+ }
267
+ };
268
+ exports.PostService = PostService;
269
+ __decorate([
270
+ (0, index_1.Cacheable)({
271
+ key: (authorId) => `posts:by-author:${authorId}`,
272
+ ttl: 600000,
273
+ dependencies: [
274
+ new index_1.DbDependency('SELECT updated_at FROM users WHERE id = ?', (authorId) => [authorId]),
275
+ ],
276
+ }),
277
+ __metadata("design:type", Function),
278
+ __metadata("design:paramtypes", [String]),
279
+ __metadata("design:returntype", Promise)
280
+ ], PostService.prototype, "getPostsByAuthor", null);
281
+ __decorate([
282
+ (0, index_1.Cacheable)({
283
+ key: 'posts:featured',
284
+ ttl: 1800000,
285
+ dependencies: [
286
+ new index_1.CallbackDependency(() => __awaiter(void 0, void 0, void 0, function* () {
287
+ return yield 'v1.0.0';
288
+ })),
289
+ ],
290
+ }),
291
+ __metadata("design:type", Function),
292
+ __metadata("design:paramtypes", []),
293
+ __metadata("design:returntype", Promise)
294
+ ], PostService.prototype, "getFeaturedPosts", null);
295
+ exports.PostService = PostService = __decorate([
296
+ (0, common_1.Injectable)(),
297
+ __metadata("design:paramtypes", [index_1.CacheService,
298
+ PostRepository])
299
+ ], PostService);
300
+ let CacheMonitoringService = class CacheMonitoringService {
301
+ constructor(cacheService) {
302
+ this.cacheService = cacheService;
303
+ }
304
+ getCacheStats() {
305
+ const stats = this.cacheService.getStats();
306
+ console.log('=== 缓存统计信息 ===');
307
+ console.log(`总请求数: ${stats.totalGets}`);
308
+ console.log(`命中数: ${stats.hits}`);
309
+ console.log `未命中数: ${stats.misses}`;
310
+ console.log(`命中率: ${(stats.hitRate * 100).toFixed(2)}%`);
311
+ if (stats.byLayer) {
312
+ console.log('\n各层级统计:');
313
+ Object.entries(stats.byLayer).forEach(([layer, layerStats]) => {
314
+ const stats = layerStats;
315
+ console.log(`${layer}: 命中 ${stats.hits}, 未命中 ${stats.misses}`);
316
+ });
317
+ }
318
+ return stats;
319
+ }
320
+ resetStats() {
321
+ this.cacheService.resetStats();
322
+ console.log('缓存统计已重置');
323
+ }
324
+ startMonitoring(intervalMs = 60000) {
325
+ setInterval(() => {
326
+ const stats = this.getCacheStats();
327
+ if (stats.hitRate < 0.7) {
328
+ console.warn(`⚠️ 缓存命中率过低: ${(stats.hitRate * 100).toFixed(2)}%`);
329
+ }
330
+ console.log(`✅ 缓存状态良好,命中率: ${(stats.hitRate * 100).toFixed(2)}%`);
331
+ }, intervalMs);
332
+ }
333
+ };
334
+ exports.CacheMonitoringService = CacheMonitoringService;
335
+ exports.CacheMonitoringService = CacheMonitoringService = __decorate([
336
+ (0, common_1.Injectable)(),
337
+ __metadata("design:paramtypes", [index_1.CacheService])
338
+ ], CacheMonitoringService);
339
+ function demonstrateCacheUsage() {
340
+ return __awaiter(this, void 0, void 0, function* () {
341
+ const userService = new UserService(new index_1.CacheService({}, {}, {}, true, 1024), new UserRepository());
342
+ const postService = new PostService(new index_1.CacheService({}, {}, {}, true, 1024), new PostRepository());
343
+ const monitoringService = new CacheMonitoringService(new index_1.CacheService({}, {}, {}, true, 1024));
344
+ console.log('🚀 开始缓存演示...\n');
345
+ try {
346
+ console.log('1. 基础缓存使用:');
347
+ const user1 = yield userService.getUser('1');
348
+ console.log(`获取用户: ${user1.name}`);
349
+ const user1Cached = yield userService.getUser('1');
350
+ console.log(`从缓存获取用户: ${user1Cached.name}\n`);
351
+ console.log('2. 装饰器缓存:');
352
+ const profile = yield userService.getUserProfile('2');
353
+ console.log(`获取用户资料: ${profile.name}`);
354
+ const profileCached = yield userService.getUserProfile('2');
355
+ console.log(`从缓存获取用户资料: ${profileCached.name}\n`);
356
+ console.log('3. 批量操作:');
357
+ const users = yield userService.getUsersBatch(['1', '2', '3', '4', '5']);
358
+ console.log(`批量获取 ${users.length} 个用户\n`);
359
+ console.log('4. 大数据压缩:');
360
+ yield userService.cacheLargeData('1');
361
+ console.log('缓存大数据完成(应该自动压缩)');
362
+ const largeData = yield userService.getLargeData('1');
363
+ console.log(`获取大数据: 用户 ${largeData.user.name}, 文章数 ${largeData.posts.length}\n`);
364
+ console.log('5. 依赖系统:');
365
+ const posts = yield postService.getPostsByAuthor('1');
366
+ console.log(`获取作者文章: ${posts.length} 篇`);
367
+ const featuredPosts = yield postService.getFeaturedPosts();
368
+ console.log(`获取推荐文章: ${featuredPosts.length} 篇\n`);
369
+ console.log('6. 缓存统计:');
370
+ monitoringService.getCacheStats();
371
+ console.log('\n7. 缓存失效:');
372
+ yield userService.invalidateAllProfiles();
373
+ console.log('已清除所有用户资料缓存');
374
+ }
375
+ catch (error) {
376
+ console.error('演示过程中出现错误:', error);
377
+ }
378
+ });
379
+ }
package/cache/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  export { CacheModule, type CacheModuleOptions, CACHE_SERVICE, } from './cache.module';
2
+ export { CACHE_COMPRESSION_ENABLED, CACHE_COMPRESSION_THRESHOLD, } from './cache.constants';
2
3
  export { CacheService } from './cache.service';
3
4
  export { CacheHealthChecker, type CacheHealthResult } from './cache.health';
4
5
  export { CacheWarmupService, type CacheWarmupConfig, type CacheWarmupResult, } from './cache.warmup.service';
5
6
  export { CacheMetricsService, type CacheMetrics, type CacheOperationRecord, } from './cache-metrics.service';
6
- export { CacheSerializationService, type CacheSerializationOptions, } from './cache-serialization.service';
7
+ export { CacheSerializationService, type CacheSerializationOptions, type SerializationResult, type DeserializationResult, } from './cache-serialization.service';
7
8
  export { Cacheable, CacheEvict, CachePut, getCacheService, setCacheService, } from './decorators';
8
9
  export { ClsCacheProvider, MemoryCacheProvider, RedisCacheProvider, BaseCacheProvider, } from './providers';
9
10
  export { REDIS_CLIENT } from './providers/redis-cache.provider';
package/cache/index.js CHANGED
@@ -1,9 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KeyGenerator = exports.DependencyManager = exports.CacheLayer = exports.TimeDependency = exports.TagDependency = exports.FileDependency = exports.DbDependency = exports.ChainDependency = exports.CallbackDependency = exports.REDIS_CLIENT = exports.BaseCacheProvider = exports.RedisCacheProvider = exports.MemoryCacheProvider = exports.ClsCacheProvider = exports.setCacheService = exports.getCacheService = exports.CachePut = exports.CacheEvict = exports.Cacheable = exports.CacheSerializationService = exports.CacheMetricsService = exports.CacheWarmupService = exports.CacheHealthChecker = exports.CacheService = exports.CACHE_SERVICE = exports.CacheModule = void 0;
3
+ exports.KeyGenerator = exports.DependencyManager = exports.CacheLayer = exports.TimeDependency = exports.TagDependency = exports.FileDependency = exports.DbDependency = exports.ChainDependency = exports.CallbackDependency = exports.REDIS_CLIENT = exports.BaseCacheProvider = exports.RedisCacheProvider = exports.MemoryCacheProvider = exports.ClsCacheProvider = exports.setCacheService = exports.getCacheService = exports.CachePut = exports.CacheEvict = exports.Cacheable = exports.CacheSerializationService = exports.CacheMetricsService = exports.CacheWarmupService = exports.CacheHealthChecker = exports.CacheService = exports.CACHE_COMPRESSION_THRESHOLD = exports.CACHE_COMPRESSION_ENABLED = exports.CACHE_SERVICE = exports.CacheModule = void 0;
4
4
  var cache_module_1 = require("./cache.module");
5
5
  Object.defineProperty(exports, "CacheModule", { enumerable: true, get: function () { return cache_module_1.CacheModule; } });
6
6
  Object.defineProperty(exports, "CACHE_SERVICE", { enumerable: true, get: function () { return cache_module_1.CACHE_SERVICE; } });
7
+ var cache_constants_1 = require("./cache.constants");
8
+ Object.defineProperty(exports, "CACHE_COMPRESSION_ENABLED", { enumerable: true, get: function () { return cache_constants_1.CACHE_COMPRESSION_ENABLED; } });
9
+ Object.defineProperty(exports, "CACHE_COMPRESSION_THRESHOLD", { enumerable: true, get: function () { return cache_constants_1.CACHE_COMPRESSION_THRESHOLD; } });
7
10
  var cache_service_1 = require("./cache.service");
8
11
  Object.defineProperty(exports, "CacheService", { enumerable: true, get: function () { return cache_service_1.CacheService; } });
9
12
  var cache_health_1 = require("./cache.health");
@@ -9,12 +9,6 @@ import type { PageOptionsDto } from './dto/page-options.dto';
9
9
  import type { LanguageCode } from '../constants/language-code';
10
10
  import type { KeyOfType } from './types';
11
11
  declare global {
12
- type Uuid = string & {
13
- _uuidBrand: undefined;
14
- };
15
- type Todo = any & {
16
- _todoBrand: undefined;
17
- };
18
12
  interface Array<T> {
19
13
  toDtos<Dto extends AbstractDto>(this: T[], options?: unknown): Dto[];
20
14
  getByLanguage(this: CreateTranslationDto[], languageCode: LanguageCode): string;
@@ -1,8 +1,5 @@
1
- import { Order } from '../../constants';
2
1
  export declare class PageOptionsDto {
3
- readonly order: Order;
4
2
  readonly page: number;
5
3
  readonly pageSize: number;
6
- readonly q?: string;
7
4
  get skip(): number;
8
5
  }
@@ -10,11 +10,9 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.PageOptionsDto = void 0;
13
- const constants_1 = require("../../constants");
14
13
  const decorators_1 = require("../../decorators");
15
14
  class PageOptionsDto {
16
15
  constructor() {
17
- this.order = constants_1.Order.ASC;
18
16
  this.page = 1;
19
17
  this.pageSize = 10;
20
18
  }
@@ -23,12 +21,6 @@ class PageOptionsDto {
23
21
  }
24
22
  }
25
23
  exports.PageOptionsDto = PageOptionsDto;
26
- __decorate([
27
- (0, decorators_1.EnumFieldOptional)(() => constants_1.Order, {
28
- default: constants_1.Order.ASC,
29
- }),
30
- __metadata("design:type", String)
31
- ], PageOptionsDto.prototype, "order", void 0);
32
24
  __decorate([
33
25
  (0, decorators_1.NumberFieldOptional)({
34
26
  minimum: 1,
@@ -46,7 +38,3 @@ __decorate([
46
38
  }),
47
39
  __metadata("design:type", Number)
48
40
  ], PageOptionsDto.prototype, "pageSize", void 0);
49
- __decorate([
50
- (0, decorators_1.StringFieldOptional)(),
51
- __metadata("design:type", String)
52
- ], PageOptionsDto.prototype, "q", void 0);
@@ -0,0 +1,14 @@
1
+ import { Repository } from 'typeorm';
2
+ import { PageOptionsDto } from '../dto/page-options.dto';
3
+ export declare function basicPaginationExample(repository: Repository<any>, pageOptions: PageOptionsDto): Promise<import("..").PageDto<import("..").AbstractDto>>;
4
+ export declare function syncTransformExample(repository: Repository<any>, pageOptions: PageOptionsDto): Promise<import("..").PageDto<import("..").AbstractDto>>;
5
+ export declare function asyncTransformExample(repository: Repository<any>, pageOptions: PageOptionsDto, externalService: any): Promise<import("..").PageDto<import("..").AbstractDto>>;
6
+ export declare function asyncBatchTransformExample(repository: Repository<any>, pageOptions: PageOptionsDto, batchProcessor: any): Promise<import("..").PageDto<import("..").AbstractDto>>;
7
+ export declare function complexAsyncTransformExample(repository: Repository<any>, pageOptions: PageOptionsDto, services: {
8
+ validation: any;
9
+ enrichment: any;
10
+ calculation: any;
11
+ }): Promise<import("..").PageDto<import("..").AbstractDto>>;
12
+ export declare function iterateExample(repository: Repository<any>, processor: any): Promise<void>;
13
+ export declare function eachBatchSingleExample(repository: Repository<any>, processor: any): Promise<void>;
14
+ export declare function eachBatchGroupExample(repository: Repository<any>, processor: any): Promise<void>;
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.basicPaginationExample = basicPaginationExample;
20
+ exports.syncTransformExample = syncTransformExample;
21
+ exports.asyncTransformExample = asyncTransformExample;
22
+ exports.asyncBatchTransformExample = asyncBatchTransformExample;
23
+ exports.complexAsyncTransformExample = complexAsyncTransformExample;
24
+ exports.iterateExample = iterateExample;
25
+ exports.eachBatchSingleExample = eachBatchSingleExample;
26
+ exports.eachBatchGroupExample = eachBatchGroupExample;
27
+ function basicPaginationExample(repository, pageOptions) {
28
+ return __awaiter(this, void 0, void 0, function* () {
29
+ const result = yield repository
30
+ .createQueryBuilder('entity')
31
+ .paginateAndMap(pageOptions);
32
+ return result;
33
+ });
34
+ }
35
+ function syncTransformExample(repository, pageOptions) {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ const result = yield repository
38
+ .createQueryBuilder('entity')
39
+ .where('entity.isActive = :isActive', { isActive: true })
40
+ .paginateAndMap(pageOptions, {
41
+ transform: (items) => {
42
+ return items.filter(item => item.status === 'approved');
43
+ },
44
+ });
45
+ return result;
46
+ });
47
+ }
48
+ function asyncTransformExample(repository, pageOptions, externalService) {
49
+ return __awaiter(this, void 0, void 0, function* () {
50
+ const result = yield repository
51
+ .createQueryBuilder('entity')
52
+ .where('entity.isActive = :isActive', { isActive: true })
53
+ .paginateAndMap(pageOptions, {
54
+ transform: (items) => __awaiter(this, void 0, void 0, function* () {
55
+ const enrichedItems = yield Promise.all(items.map((item) => __awaiter(this, void 0, void 0, function* () {
56
+ const additionalData = yield externalService.fetchData(item.id);
57
+ return Object.assign(Object.assign({}, item), { additionalData });
58
+ })));
59
+ return enrichedItems.filter(item => { var _a; return (_a = item.additionalData) === null || _a === void 0 ? void 0 : _a.isValid; });
60
+ }),
61
+ });
62
+ return result;
63
+ });
64
+ }
65
+ function asyncBatchTransformExample(repository, pageOptions, batchProcessor) {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ const result = yield repository
68
+ .createQueryBuilder('entity')
69
+ .leftJoinAndSelect('entity.relations', 'relations')
70
+ .paginateAndMap(pageOptions, {
71
+ dtoOptions: { includeRelations: true },
72
+ transform: (items) => __awaiter(this, void 0, void 0, function* () {
73
+ const processedItems = yield batchProcessor.processBatch(items);
74
+ return processedItems.map(item => (Object.assign(Object.assign({}, item), { processed: true, processedAt: new Date() })));
75
+ }),
76
+ });
77
+ return result;
78
+ });
79
+ }
80
+ function complexAsyncTransformExample(repository, pageOptions, services) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ const result = yield repository
83
+ .createQueryBuilder('entity')
84
+ .where('entity.createdAt > :date', { date: new Date('2024-01-01') })
85
+ .paginateAndMap(pageOptions, {
86
+ skipCount: false,
87
+ transform: (items) => __awaiter(this, void 0, void 0, function* () {
88
+ const validatedItems = yield Promise.all(items.map((item) => __awaiter(this, void 0, void 0, function* () {
89
+ try {
90
+ const isValid = yield services.validation.validate(item);
91
+ return isValid ? item : null;
92
+ }
93
+ catch (error) {
94
+ console.error(`Validation failed for item ${item.id}:`, error);
95
+ return null;
96
+ }
97
+ })));
98
+ const validItems = validatedItems.filter(item => item !== null);
99
+ const enrichedItems = yield Promise.all(validItems.map((item) => __awaiter(this, void 0, void 0, function* () {
100
+ const enrichmentData = yield services.enrichment.enrich(item.id);
101
+ return Object.assign(Object.assign({}, item), enrichmentData);
102
+ })));
103
+ const finalItems = yield Promise.all(enrichedItems.map((item) => __awaiter(this, void 0, void 0, function* () {
104
+ const calculatedFields = yield services.calculation.calculate(item);
105
+ return Object.assign(Object.assign({}, item), calculatedFields);
106
+ })));
107
+ return finalItems;
108
+ }),
109
+ });
110
+ return result;
111
+ });
112
+ }
113
+ function iterateExample(repository, processor) {
114
+ return __awaiter(this, void 0, void 0, function* () {
115
+ var _a, e_1, _b, _c;
116
+ const queryBuilder = repository
117
+ .createQueryBuilder('entity')
118
+ .where('entity.needsProcessing = :needsProcessing', { needsProcessing: true });
119
+ try {
120
+ for (var _d = true, _e = __asyncValues(queryBuilder.iterate({ batchSize: 500 })), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
121
+ _c = _f.value;
122
+ _d = false;
123
+ const batch = _c;
124
+ console.log(`Processing batch of ${batch.length} entities`);
125
+ yield processor.processBatch(batch);
126
+ }
127
+ }
128
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
129
+ finally {
130
+ try {
131
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
132
+ }
133
+ finally { if (e_1) throw e_1.error; }
134
+ }
135
+ });
136
+ }
137
+ function eachBatchSingleExample(repository, processor) {
138
+ return __awaiter(this, void 0, void 0, function* () {
139
+ yield repository
140
+ .createQueryBuilder('entity')
141
+ .where('entity.status = :status', { status: 'pending' })
142
+ .eachBatch((entity) => __awaiter(this, void 0, void 0, function* () {
143
+ console.log(`Processing entity ${entity.id}`);
144
+ yield processor.processOne(entity);
145
+ }), { batchSize: 100, mode: 'single' });
146
+ });
147
+ }
148
+ function eachBatchGroupExample(repository, processor) {
149
+ return __awaiter(this, void 0, void 0, function* () {
150
+ yield repository
151
+ .createQueryBuilder('entity')
152
+ .where('entity.status = :status', { status: 'pending' })
153
+ .eachBatch((batch) => __awaiter(this, void 0, void 0, function* () {
154
+ console.log(`Processing batch of ${batch.length} entities`);
155
+ yield processor.processBatch(batch);
156
+ }), { batchSize: 500, mode: 'batch' });
157
+ });
158
+ }