@nest-omni/core 4.1.3-1 → 4.1.3-11

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 (249) hide show
  1. package/audit/audit.module.d.ts +10 -0
  2. package/audit/audit.module.js +39 -1
  3. package/audit/controllers/audit.controller.d.ts +24 -0
  4. package/audit/controllers/audit.controller.js +24 -0
  5. package/audit/decorators/audit-controller.decorator.d.ts +9 -1
  6. package/audit/decorators/audit-controller.decorator.js +11 -2
  7. package/audit/decorators/audit-operation.decorator.d.ts +45 -0
  8. package/audit/decorators/audit-operation.decorator.js +49 -0
  9. package/audit/decorators/entity-audit.decorator.d.ts +76 -1
  10. package/audit/decorators/entity-audit.decorator.js +135 -3
  11. package/audit/decorators/index.d.ts +1 -0
  12. package/audit/decorators/index.js +1 -0
  13. package/audit/dto/audit-log-query.dto.d.ts +3 -0
  14. package/audit/dto/audit-log-query.dto.js +3 -0
  15. package/audit/dto/begin-transaction.dto.d.ts +3 -0
  16. package/audit/dto/begin-transaction.dto.js +3 -0
  17. package/audit/dto/compare-entities.dto.d.ts +3 -0
  18. package/audit/dto/compare-entities.dto.js +3 -0
  19. package/audit/dto/pre-check-restore.dto.d.ts +3 -0
  20. package/audit/dto/pre-check-restore.dto.js +3 -0
  21. package/audit/dto/restore-entity.dto.d.ts +3 -0
  22. package/audit/dto/restore-entity.dto.js +3 -0
  23. package/audit/entities/entity-audit-log.entity.d.ts +8 -0
  24. package/audit/entities/entity-audit-log.entity.js +33 -1
  25. package/audit/entities/entity-transaction.entity.d.ts +10 -0
  26. package/audit/entities/entity-transaction.entity.js +33 -1
  27. package/audit/entities/index.d.ts +2 -0
  28. package/audit/entities/index.js +2 -0
  29. package/audit/entities/manual-operation-log.entity.d.ts +4 -0
  30. package/audit/entities/manual-operation-log.entity.js +4 -0
  31. package/audit/entities/operation-template.entity.d.ts +4 -0
  32. package/audit/entities/operation-template.entity.js +4 -0
  33. package/audit/enums/audit.enums.d.ts +45 -5
  34. package/audit/enums/audit.enums.js +47 -4
  35. package/audit/index.d.ts +3 -1
  36. package/audit/index.js +30 -1
  37. package/audit/interceptors/audit.interceptor.d.ts +15 -0
  38. package/audit/interceptors/audit.interceptor.js +23 -1
  39. package/audit/interfaces/audit.interfaces.d.ts +182 -2
  40. package/audit/services/audit-context.service.d.ts +15 -0
  41. package/audit/services/audit-context.service.js +15 -0
  42. package/audit/services/audit-strategy.service.d.ts +6 -0
  43. package/audit/services/audit-strategy.service.js +13 -0
  44. package/audit/services/entity-audit.service.d.ts +129 -3
  45. package/audit/services/entity-audit.service.js +301 -6
  46. package/audit/services/index.d.ts +2 -0
  47. package/audit/services/index.js +2 -0
  48. package/audit/services/manual-audit-log.service.d.ts +124 -0
  49. package/audit/services/manual-audit-log.service.js +138 -0
  50. package/audit/services/multi-database.service.d.ts +12 -0
  51. package/audit/services/multi-database.service.js +12 -0
  52. package/audit/services/operation-description.service.d.ts +59 -0
  53. package/audit/services/operation-description.service.js +76 -2
  54. package/audit/services/transaction-audit.service.d.ts +30 -0
  55. package/audit/services/transaction-audit.service.js +47 -0
  56. package/audit/subscribers/entity-audit.subscriber.d.ts +15 -0
  57. package/audit/subscribers/entity-audit.subscriber.js +29 -1
  58. package/cache/cache-metrics.service.d.ts +67 -0
  59. package/cache/cache-metrics.service.js +68 -4
  60. package/cache/cache-serialization.service.d.ts +31 -0
  61. package/cache/cache-serialization.service.js +25 -0
  62. package/cache/cache.constants.d.ts +9 -0
  63. package/cache/cache.constants.js +9 -0
  64. package/cache/cache.health.d.ts +26 -0
  65. package/cache/cache.health.js +30 -0
  66. package/cache/cache.module.d.ts +86 -0
  67. package/cache/cache.module.js +71 -0
  68. package/cache/cache.service.d.ts +140 -0
  69. package/cache/cache.service.js +157 -0
  70. package/cache/cache.warmup.service.d.ts +39 -0
  71. package/cache/cache.warmup.service.js +32 -0
  72. package/cache/decorators/cache-evict.decorator.d.ts +47 -0
  73. package/cache/decorators/cache-evict.decorator.js +56 -0
  74. package/cache/decorators/cache-put.decorator.d.ts +34 -0
  75. package/cache/decorators/cache-put.decorator.js +39 -0
  76. package/cache/decorators/cacheable.decorator.d.ts +40 -0
  77. package/cache/decorators/cacheable.decorator.js +55 -0
  78. package/cache/dependencies/callback.dependency.d.ts +33 -0
  79. package/cache/dependencies/callback.dependency.js +39 -1
  80. package/cache/dependencies/chain.dependency.d.ts +28 -0
  81. package/cache/dependencies/chain.dependency.js +34 -0
  82. package/cache/dependencies/db.dependency.d.ts +45 -0
  83. package/cache/dependencies/db.dependency.js +48 -1
  84. package/cache/dependencies/file.dependency.d.ts +32 -0
  85. package/cache/dependencies/file.dependency.js +34 -0
  86. package/cache/dependencies/tag.dependency.d.ts +36 -0
  87. package/cache/dependencies/tag.dependency.js +36 -0
  88. package/cache/dependencies/time.dependency.d.ts +43 -0
  89. package/cache/dependencies/time.dependency.js +43 -0
  90. package/cache/examples/basic-usage.d.ts +15 -0
  91. package/cache/examples/basic-usage.js +62 -8
  92. package/cache/index.js +9 -0
  93. package/cache/interfaces/cache-dependency.interface.d.ts +53 -0
  94. package/cache/interfaces/cache-options.interface.d.ts +81 -0
  95. package/cache/interfaces/cache-options.interface.js +6 -0
  96. package/cache/interfaces/cache-provider.interface.d.ts +78 -0
  97. package/cache/providers/base-cache.provider.d.ts +14 -0
  98. package/cache/providers/base-cache.provider.js +16 -0
  99. package/cache/providers/cls-cache.provider.d.ts +20 -0
  100. package/cache/providers/cls-cache.provider.js +28 -0
  101. package/cache/providers/memory-cache.provider.d.ts +23 -0
  102. package/cache/providers/memory-cache.provider.js +26 -0
  103. package/cache/providers/redis-cache.provider.d.ts +26 -0
  104. package/cache/providers/redis-cache.provider.js +29 -0
  105. package/cache/utils/dependency-manager.util.d.ts +52 -0
  106. package/cache/utils/dependency-manager.util.js +59 -0
  107. package/cache/utils/key-generator.util.d.ts +42 -0
  108. package/cache/utils/key-generator.util.js +53 -1
  109. package/common/abstract.entity.d.ts +14 -0
  110. package/common/abstract.entity.js +14 -0
  111. package/common/boilerplate.polyfill.d.ts +142 -4
  112. package/common/boilerplate.polyfill.js +24 -100
  113. package/common/dto/dto-container.d.ts +16 -0
  114. package/common/dto/dto-container.js +20 -0
  115. package/common/dto/dto-decorators.d.ts +18 -0
  116. package/common/dto/dto-decorators.js +14 -0
  117. package/common/dto/dto-extensions.d.ts +11 -0
  118. package/common/dto/dto-extensions.js +9 -0
  119. package/common/dto/dto-service-accessor.d.ts +17 -0
  120. package/common/dto/dto-service-accessor.js +18 -0
  121. package/common/dto/dto-transformer.d.ts +12 -0
  122. package/common/dto/dto-transformer.js +9 -0
  123. package/common/dto/index.js +2 -0
  124. package/common/examples/paginate-and-map.example.d.ts +6 -0
  125. package/common/examples/paginate-and-map.example.js +26 -0
  126. package/common/utils.d.ts +15 -0
  127. package/common/utils.js +15 -0
  128. package/constants/language-code.js +1 -0
  129. package/decorators/field.decorators.js +8 -1
  130. package/decorators/property.decorators.js +1 -0
  131. package/decorators/public-route.decorator.js +1 -0
  132. package/decorators/transform.decorators.d.ts +27 -0
  133. package/decorators/transform.decorators.js +29 -0
  134. package/decorators/translate.decorator.js +1 -0
  135. package/decorators/user.decorator.js +1 -0
  136. package/decorators/validator.decorators.d.ts +8 -18
  137. package/decorators/validator.decorators.js +22 -190
  138. package/filters/constraint-errors.js +1 -0
  139. package/helpers/common.helper.d.ts +13 -0
  140. package/helpers/common.helper.js +13 -0
  141. package/http-client/config/http-client.config.d.ts +15 -0
  142. package/http-client/config/http-client.config.js +25 -9
  143. package/http-client/decorators/http-client.decorators.d.ts +63 -0
  144. package/http-client/decorators/http-client.decorators.js +71 -3
  145. package/http-client/entities/http-log.entity.d.ts +229 -0
  146. package/http-client/entities/http-log.entity.js +6 -1
  147. package/http-client/errors/http-client.errors.d.ts +57 -0
  148. package/http-client/errors/http-client.errors.js +58 -0
  149. package/http-client/examples/advanced-usage.example.d.ts +41 -0
  150. package/http-client/examples/advanced-usage.example.js +68 -24
  151. package/http-client/examples/auth-with-waiting-lock.example.d.ts +31 -0
  152. package/http-client/examples/auth-with-waiting-lock.example.js +52 -5
  153. package/http-client/examples/basic-usage.example.d.ts +60 -0
  154. package/http-client/examples/basic-usage.example.js +60 -0
  155. package/http-client/examples/multi-api-configuration.example.d.ts +60 -0
  156. package/http-client/examples/multi-api-configuration.example.js +76 -5
  157. package/http-client/http-client.module.d.ts +13 -0
  158. package/http-client/http-client.module.js +20 -5
  159. package/http-client/index.js +8 -0
  160. package/http-client/interfaces/api-client-config.interface.d.ts +125 -0
  161. package/http-client/interfaces/api-client-config.interface.js +3 -0
  162. package/http-client/interfaces/http-client-config.interface.d.ts +60 -0
  163. package/http-client/services/api-client-registry.service.d.ts +57 -0
  164. package/http-client/services/api-client-registry.service.js +84 -1
  165. package/http-client/services/cache.service.d.ts +52 -0
  166. package/http-client/services/cache.service.js +72 -3
  167. package/http-client/services/circuit-breaker.service.d.ts +46 -0
  168. package/http-client/services/circuit-breaker.service.js +52 -0
  169. package/http-client/services/http-client.service.d.ts +67 -0
  170. package/http-client/services/http-client.service.js +105 -4
  171. package/http-client/services/http-log-query.service.d.ts +83 -0
  172. package/http-client/services/http-log-query.service.js +122 -1
  173. package/http-client/services/http-replay.service.d.ts +101 -0
  174. package/http-client/services/http-replay.service.js +86 -0
  175. package/http-client/services/log-cleanup.service.d.ts +63 -0
  176. package/http-client/services/log-cleanup.service.js +54 -2
  177. package/http-client/services/logging.service.d.ts +40 -0
  178. package/http-client/services/logging.service.js +53 -0
  179. package/http-client/utils/call-stack-extractor.util.d.ts +37 -0
  180. package/http-client/utils/call-stack-extractor.util.js +48 -0
  181. package/http-client/utils/context-extractor.util.d.ts +49 -0
  182. package/http-client/utils/context-extractor.util.js +52 -0
  183. package/http-client/utils/curl-generator.util.d.ts +21 -0
  184. package/http-client/utils/curl-generator.util.js +44 -3
  185. package/http-client/utils/request-id.util.d.ts +18 -0
  186. package/http-client/utils/request-id.util.js +20 -0
  187. package/http-client/utils/retry-recorder.util.d.ts +42 -0
  188. package/http-client/utils/retry-recorder.util.js +44 -0
  189. package/i18n/en_US/validation.json +2 -1
  190. package/i18n/zh_CN/validation.json +2 -1
  191. package/index.js +8 -0
  192. package/interceptors/translation-interceptor.service.js +5 -0
  193. package/package.json +1 -1
  194. package/providers/context.provider.js +2 -0
  195. package/providers/generator.provider.d.ts +4 -0
  196. package/providers/generator.provider.js +4 -0
  197. package/redis-lock/comprehensive-lock-cleanup.service.d.ts +94 -0
  198. package/redis-lock/comprehensive-lock-cleanup.service.js +253 -0
  199. package/redis-lock/examples/lock-strategy.examples.d.ts +89 -0
  200. package/redis-lock/examples/lock-strategy.examples.js +130 -15
  201. package/redis-lock/index.d.ts +2 -0
  202. package/redis-lock/index.js +8 -1
  203. package/redis-lock/lock-heartbeat.service.d.ts +78 -0
  204. package/redis-lock/lock-heartbeat.service.js +222 -0
  205. package/redis-lock/redis-lock.decorator.d.ts +101 -0
  206. package/redis-lock/redis-lock.decorator.js +120 -0
  207. package/redis-lock/redis-lock.module.d.ts +66 -0
  208. package/redis-lock/redis-lock.module.js +175 -70
  209. package/redis-lock/redis-lock.service.d.ts +278 -0
  210. package/redis-lock/redis-lock.service.js +282 -12
  211. package/setup/bootstrap.setup.js +20 -0
  212. package/setup/mode.setup.d.ts +44 -0
  213. package/setup/mode.setup.js +44 -0
  214. package/setup/schedule.decorator.d.ts +227 -0
  215. package/setup/schedule.decorator.js +235 -12
  216. package/setup/worker.decorator.d.ts +86 -0
  217. package/setup/worker.decorator.js +88 -0
  218. package/shared/serviceRegistryModule.js +27 -14
  219. package/shared/services/api-config.service.d.ts +3 -0
  220. package/shared/services/api-config.service.js +20 -9
  221. package/validator-json/decorators.d.ts +17 -0
  222. package/validator-json/decorators.js +17 -2
  223. package/validator-json/default.d.ts +6 -0
  224. package/validator-json/default.js +30 -2
  225. package/validator-json/defaultConverters.js +1 -0
  226. package/validator-json/options.d.ts +23 -0
  227. package/validators/common-validators.d.ts +143 -0
  228. package/validators/common-validators.js +249 -0
  229. package/validators/custom-validate.examples.d.ts +96 -0
  230. package/validators/custom-validate.examples.js +400 -0
  231. package/validators/custom-validate.validator.d.ts +134 -0
  232. package/validators/custom-validate.validator.js +214 -0
  233. package/validators/index.d.ts +2 -0
  234. package/validators/index.js +2 -0
  235. package/validators/is-exists.validator.d.ts +18 -4
  236. package/validators/is-exists.validator.js +67 -6
  237. package/validators/is-unique.validator.d.ts +32 -5
  238. package/validators/is-unique.validator.js +99 -17
  239. package/validators/skip-empty.validator.d.ts +5 -0
  240. package/validators/skip-empty.validator.js +5 -0
  241. package/vault/interfaces/vault-options.interface.d.ts +9 -0
  242. package/vault/vault-config.loader.d.ts +30 -0
  243. package/vault/vault-config.loader.js +48 -1
  244. package/vault/vault-config.service.d.ts +53 -0
  245. package/vault/vault-config.service.js +57 -0
  246. package/vault/vault.module.d.ts +4 -0
  247. package/vault/vault.module.js +4 -0
  248. package/decorators/examples/validation-decorators.example.d.ts +0 -69
  249. package/decorators/examples/validation-decorators.example.js +0 -331
@@ -1,4 +1,33 @@
1
1
  import type { CacheDependency } from '../interfaces/cache-dependency.interface';
2
+ /**
3
+ * File-based cache dependency
4
+ *
5
+ * This dependency monitors file modification time. When the file is modified,
6
+ * the cache becomes invalid.
7
+ *
8
+ * Useful for configuration files, templates, or other file-based resources.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * // Cache template, invalidate when template file changes
13
+ * @Cacheable({
14
+ * key: (name) => `template:${name}`,
15
+ * dependencies: [
16
+ * new FileDependency((name) => `./templates/${name}.html`)
17
+ * ]
18
+ * })
19
+ * async getTemplate(name: string) { }
20
+ *
21
+ * // Cache config, invalidate when config file changes
22
+ * @Cacheable({
23
+ * key: 'app:config',
24
+ * dependencies: [
25
+ * new FileDependency('./config/app.json')
26
+ * ]
27
+ * })
28
+ * async getConfig() { }
29
+ * ```
30
+ */
2
31
  export declare class FileDependency implements CacheDependency {
3
32
  private readonly filePath;
4
33
  constructor(filePath: string | ((...args: any[]) => string));
@@ -13,5 +42,8 @@ export declare class FileDependency implements CacheDependency {
13
42
  mtime: number;
14
43
  size: number;
15
44
  } | null): Promise<boolean>;
45
+ /**
46
+ * Resolve the file path (handle dynamic paths)
47
+ */
16
48
  private resolveFilePath;
17
49
  }
@@ -11,6 +11,35 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.FileDependency = void 0;
13
13
  const node_fs_1 = require("node:fs");
14
+ /**
15
+ * File-based cache dependency
16
+ *
17
+ * This dependency monitors file modification time. When the file is modified,
18
+ * the cache becomes invalid.
19
+ *
20
+ * Useful for configuration files, templates, or other file-based resources.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * // Cache template, invalidate when template file changes
25
+ * @Cacheable({
26
+ * key: (name) => `template:${name}`,
27
+ * dependencies: [
28
+ * new FileDependency((name) => `./templates/${name}.html`)
29
+ * ]
30
+ * })
31
+ * async getTemplate(name: string) { }
32
+ *
33
+ * // Cache config, invalidate when config file changes
34
+ * @Cacheable({
35
+ * key: 'app:config',
36
+ * dependencies: [
37
+ * new FileDependency('./config/app.json')
38
+ * ]
39
+ * })
40
+ * async getConfig() { }
41
+ * ```
42
+ */
14
43
  class FileDependency {
15
44
  constructor(filePath) {
16
45
  if (!filePath) {
@@ -42,15 +71,20 @@ class FileDependency {
42
71
  return __awaiter(this, void 0, void 0, function* () {
43
72
  try {
44
73
  const currentData = yield this.getData();
74
+ // File path changed or mtime changed or size changed
45
75
  return (currentData.path !== oldData.path ||
46
76
  currentData.mtime !== oldData.mtime ||
47
77
  currentData.size !== oldData.size);
48
78
  }
49
79
  catch (_a) {
80
+ // If we can't access file, consider it changed
50
81
  return true;
51
82
  }
52
83
  });
53
84
  }
85
+ /**
86
+ * Resolve the file path (handle dynamic paths)
87
+ */
54
88
  resolveFilePath() {
55
89
  return __awaiter(this, void 0, void 0, function* () {
56
90
  if (typeof this.filePath === 'function') {
@@ -1,13 +1,49 @@
1
1
  import type { CacheDependency } from '../interfaces/cache-dependency.interface';
2
+ /**
3
+ * Tag-based cache dependency
4
+ *
5
+ * This dependency allows you to invalidate multiple cache entries by tags.
6
+ * When a tag is invalidated, all cache entries depending on that tag become invalid.
7
+ *
8
+ * This is the most commonly used dependency type for managing related cache entries.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * // Cache user list with tag dependency
13
+ * @Cacheable({
14
+ * key: (tenantId) => `users:list:${tenantId}`,
15
+ * dependencies: [new TagDependency(['user-list', `tenant:${tenantId}`])]
16
+ * })
17
+ * async getUserList(tenantId: string) { }
18
+ *
19
+ * // When creating a new user, invalidate the tag
20
+ * await cacheService.invalidateTags(['user-list']);
21
+ * ```
22
+ */
2
23
  export declare class TagDependency implements CacheDependency {
3
24
  private readonly tags;
4
25
  private static readonly PREFIX;
5
26
  private static tagVersions;
6
27
  constructor(tags: string[]);
28
+ /**
29
+ * Get current version of a tag
30
+ */
7
31
  static getTagVersion(tag: string): number;
32
+ /**
33
+ * Invalidate a tag (increment its version)
34
+ */
8
35
  static invalidateTag(tag: string): void;
36
+ /**
37
+ * Invalidate multiple tags
38
+ */
9
39
  static invalidateTags(tags: string[]): void;
40
+ /**
41
+ * Reset all tag versions (useful for testing)
42
+ */
10
43
  static resetAllTags(): void;
44
+ /**
45
+ * Get all tags and their versions
46
+ */
11
47
  static getAllTags(): Map<string, number>;
12
48
  getKey(): string;
13
49
  getData(): Promise<Record<string, number>>;
@@ -10,6 +10,27 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.TagDependency = void 0;
13
+ /**
14
+ * Tag-based cache dependency
15
+ *
16
+ * This dependency allows you to invalidate multiple cache entries by tags.
17
+ * When a tag is invalidated, all cache entries depending on that tag become invalid.
18
+ *
19
+ * This is the most commonly used dependency type for managing related cache entries.
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * // Cache user list with tag dependency
24
+ * @Cacheable({
25
+ * key: (tenantId) => `users:list:${tenantId}`,
26
+ * dependencies: [new TagDependency(['user-list', `tenant:${tenantId}`])]
27
+ * })
28
+ * async getUserList(tenantId: string) { }
29
+ *
30
+ * // When creating a new user, invalidate the tag
31
+ * await cacheService.invalidateTags(['user-list']);
32
+ * ```
33
+ */
13
34
  class TagDependency {
14
35
  constructor(tags) {
15
36
  this.tags = tags;
@@ -17,21 +38,36 @@ class TagDependency {
17
38
  throw new Error('TagDependency requires at least one tag');
18
39
  }
19
40
  }
41
+ /**
42
+ * Get current version of a tag
43
+ */
20
44
  static getTagVersion(tag) {
21
45
  return this.tagVersions.get(tag) || 0;
22
46
  }
47
+ /**
48
+ * Invalidate a tag (increment its version)
49
+ */
23
50
  static invalidateTag(tag) {
24
51
  const currentVersion = this.tagVersions.get(tag) || 0;
25
52
  this.tagVersions.set(tag, currentVersion + 1);
26
53
  }
54
+ /**
55
+ * Invalidate multiple tags
56
+ */
27
57
  static invalidateTags(tags) {
28
58
  for (const tag of tags) {
29
59
  this.invalidateTag(tag);
30
60
  }
31
61
  }
62
+ /**
63
+ * Reset all tag versions (useful for testing)
64
+ */
32
65
  static resetAllTags() {
33
66
  this.tagVersions.clear();
34
67
  }
68
+ /**
69
+ * Get all tags and their versions
70
+ */
35
71
  static getAllTags() {
36
72
  return new Map(this.tagVersions);
37
73
  }
@@ -1,4 +1,38 @@
1
1
  import type { CacheDependency } from '../interfaces/cache-dependency.interface';
2
+ /**
3
+ * Time-based cache dependency
4
+ *
5
+ * This dependency invalidates cache after a specific duration.
6
+ * Unlike TTL which is checked on read, this is checked as a dependency.
7
+ *
8
+ * Useful for implementing complex time-based invalidation logic.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * // Cache for 5 minutes
13
+ * @Cacheable({
14
+ * key: 'daily:report',
15
+ * dependencies: [
16
+ * new TimeDependency(5 * 60 * 1000) // 5 minutes
17
+ * ]
18
+ * })
19
+ * async getDailyReport() { }
20
+ *
21
+ * // Cache until midnight
22
+ * @Cacheable({
23
+ * key: 'today:stats',
24
+ * dependencies: [
25
+ * new TimeDependency(() => {
26
+ * const now = new Date();
27
+ * const midnight = new Date(now);
28
+ * midnight.setHours(24, 0, 0, 0);
29
+ * return midnight.getTime() - now.getTime();
30
+ * })
31
+ * ]
32
+ * })
33
+ * async getTodayStats() { }
34
+ * ```
35
+ */
2
36
  export declare class TimeDependency implements CacheDependency {
3
37
  private readonly duration;
4
38
  private createdAt;
@@ -13,7 +47,16 @@ export declare class TimeDependency implements CacheDependency {
13
47
  duration: number;
14
48
  }): Promise<boolean>;
15
49
  reset(): Promise<void>;
50
+ /**
51
+ * Get remaining time in milliseconds
52
+ */
16
53
  getRemainingTime(): number;
54
+ /**
55
+ * Check if dependency has expired
56
+ */
17
57
  isExpired(): boolean;
58
+ /**
59
+ * Resolve duration value (handle dynamic duration)
60
+ */
18
61
  private resolveDuration;
19
62
  }
@@ -10,6 +10,40 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.TimeDependency = void 0;
13
+ /**
14
+ * Time-based cache dependency
15
+ *
16
+ * This dependency invalidates cache after a specific duration.
17
+ * Unlike TTL which is checked on read, this is checked as a dependency.
18
+ *
19
+ * Useful for implementing complex time-based invalidation logic.
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * // Cache for 5 minutes
24
+ * @Cacheable({
25
+ * key: 'daily:report',
26
+ * dependencies: [
27
+ * new TimeDependency(5 * 60 * 1000) // 5 minutes
28
+ * ]
29
+ * })
30
+ * async getDailyReport() { }
31
+ *
32
+ * // Cache until midnight
33
+ * @Cacheable({
34
+ * key: 'today:stats',
35
+ * dependencies: [
36
+ * new TimeDependency(() => {
37
+ * const now = new Date();
38
+ * const midnight = new Date(now);
39
+ * midnight.setHours(24, 0, 0, 0);
40
+ * return midnight.getTime() - now.getTime();
41
+ * })
42
+ * ]
43
+ * })
44
+ * async getTodayStats() { }
45
+ * ```
46
+ */
13
47
  class TimeDependency {
14
48
  constructor(duration) {
15
49
  if (typeof duration !== 'number' && typeof duration !== 'function') {
@@ -48,15 +82,24 @@ class TimeDependency {
48
82
  this.createdAt = Date.now();
49
83
  });
50
84
  }
85
+ /**
86
+ * Get remaining time in milliseconds
87
+ */
51
88
  getRemainingTime() {
52
89
  const duration = this.resolveDuration();
53
90
  const elapsed = Date.now() - this.createdAt;
54
91
  const remaining = duration - elapsed;
55
92
  return Math.max(0, remaining);
56
93
  }
94
+ /**
95
+ * Check if dependency has expired
96
+ */
57
97
  isExpired() {
58
98
  return this.getRemainingTime() === 0;
59
99
  }
100
+ /**
101
+ * Resolve duration value (handle dynamic duration)
102
+ */
60
103
  resolveDuration() {
61
104
  if (typeof this.duration === 'function') {
62
105
  const value = this.duration();
@@ -1,3 +1,6 @@
1
+ /**
2
+ * 基础缓存使用示例
3
+ */
1
4
  import { CacheService } from '../index';
2
5
  interface User {
3
6
  id: string;
@@ -25,6 +28,9 @@ declare class UserRepository {
25
28
  declare class PostRepository {
26
29
  findByAuthor(authorId: string): Promise<Post[]>;
27
30
  }
31
+ /**
32
+ * 用户服务示例
33
+ */
28
34
  export declare class UserService {
29
35
  private cacheService;
30
36
  private userRepository;
@@ -39,6 +45,9 @@ export declare class UserService {
39
45
  cacheLargeData(id: string): Promise<void>;
40
46
  getLargeData(id: string): Promise<any>;
41
47
  }
48
+ /**
49
+ * 文章服务示例 - 展示依赖使用
50
+ */
42
51
  export declare class PostService {
43
52
  private cacheService;
44
53
  private postRepository;
@@ -47,6 +56,9 @@ export declare class PostService {
47
56
  getFeaturedPosts(): Promise<Post[]>;
48
57
  private getConfigVersion;
49
58
  }
59
+ /**
60
+ * 缓存统计和监控示例
61
+ */
50
62
  export declare class CacheMonitoringService {
51
63
  private cacheService;
52
64
  constructor(cacheService: CacheService);
@@ -54,5 +66,8 @@ export declare class CacheMonitoringService {
54
66
  resetStats(): void;
55
67
  startMonitoring(intervalMs?: number): void;
56
68
  }
69
+ /**
70
+ * 使用示例
71
+ */
57
72
  declare function demonstrateCacheUsage(): Promise<void>;
58
73
  export { demonstrateCacheUsage };
@@ -1,4 +1,7 @@
1
1
  "use strict";
2
+ /**
3
+ * 基础缓存使用示例
4
+ */
2
5
  var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
6
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
7
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -22,16 +25,18 @@ exports.CacheMonitoringService = exports.PostService = exports.UserService = voi
22
25
  exports.demonstrateCacheUsage = demonstrateCacheUsage;
23
26
  const common_1 = require("@nestjs/common");
24
27
  const index_1 = require("../index");
28
+ // 模拟的仓库类
25
29
  class UserRepository {
26
30
  findOne(id) {
27
31
  return __awaiter(this, void 0, void 0, function* () {
32
+ // 模拟数据库查询
28
33
  console.log(`[DB] 查询用户 ${id}`);
29
34
  return {
30
35
  id,
31
36
  name: `User ${id}`,
32
37
  email: `user${id}@example.com`,
33
38
  profile: {
34
- bio: `这是用户 ${id} 的个人简介`.repeat(10),
39
+ bio: `这是用户 ${id} 的个人简介`.repeat(10), // 长文本,用于测试压缩
35
40
  avatar: `avatar_${id}.jpg`,
36
41
  },
37
42
  };
@@ -80,37 +85,45 @@ class PostRepository {
80
85
  .map((_, i) => ({
81
86
  id: `post_${authorId}_${i}`,
82
87
  title: `文章 ${i}`,
83
- content: `这是文章 ${i} 的内容`.repeat(15),
88
+ content: `这是文章 ${i} 的内容`.repeat(15), // 长内容,用于测试压缩
84
89
  authorId,
85
90
  createdAt: new Date(),
86
91
  }));
87
92
  });
88
93
  }
89
94
  }
95
+ /**
96
+ * 用户服务示例
97
+ */
90
98
  let UserService = class UserService {
91
99
  constructor(cacheService, userRepository) {
92
100
  this.cacheService = cacheService;
93
101
  this.userRepository = userRepository;
94
102
  }
103
+ // 基础缓存使用
95
104
  getUser(id) {
96
105
  return __awaiter(this, void 0, void 0, function* () {
97
106
  return yield this.cacheService.getOrSet(`user:${id}`, () => this.userRepository.findOne(id), { ttl: 300000 });
98
107
  });
99
108
  }
109
+ // 使用装饰器缓存
100
110
  getUserProfile(id) {
101
111
  return __awaiter(this, void 0, void 0, function* () {
102
112
  return yield this.userRepository.findOne(id);
103
113
  });
104
114
  }
115
+ // 条件缓存 - 不缓存管理员用户
105
116
  getUserData(id) {
106
117
  return __awaiter(this, void 0, void 0, function* () {
107
118
  return yield this.userRepository.findOne(id);
108
119
  });
109
120
  }
121
+ // 批量获取用户
110
122
  getUsersBatch(ids) {
111
123
  return __awaiter(this, void 0, void 0, function* () {
112
124
  const keys = ids.map((id) => `user:${id}`);
113
125
  const cachedUsers = yield this.cacheService.mget(keys);
126
+ // 找出缓存中没有的用户
114
127
  const uncachedIds = [];
115
128
  const result = [];
116
129
  cachedUsers.forEach((user, index) => {
@@ -121,8 +134,10 @@ let UserService = class UserService {
121
134
  uncachedIds.push(ids[index]);
122
135
  }
123
136
  });
137
+ // 批量查询未缓存的用户
124
138
  if (uncachedIds.length > 0) {
125
139
  const newUsers = yield this.userRepository.findMany(uncachedIds);
140
+ // 批量设置缓存
126
141
  const cacheItems = newUsers.map((user) => ({
127
142
  key: `user:${user.id}`,
128
143
  value: user,
@@ -133,22 +148,26 @@ let UserService = class UserService {
133
148
  return result;
134
149
  });
135
150
  }
151
+ // 更新用户并缓存
136
152
  updateUser(id, data) {
137
153
  return __awaiter(this, void 0, void 0, function* () {
138
154
  const updatedUser = yield this.userRepository.save(Object.assign({ id }, data));
139
155
  return updatedUser;
140
156
  });
141
157
  }
158
+ // 删除用户并清除缓存
142
159
  deleteUser(id) {
143
160
  return __awaiter(this, void 0, void 0, function* () {
144
161
  yield this.userRepository.delete(id);
145
162
  });
146
163
  }
164
+ // 使用标签失效
147
165
  invalidateAllProfiles() {
148
166
  return __awaiter(this, void 0, void 0, function* () {
149
167
  console.log('清除所有用户资料缓存');
150
168
  });
151
169
  }
170
+ // 缓存大数据(测试压缩)
152
171
  cacheLargeData(id) {
153
172
  return __awaiter(this, void 0, void 0, function* () {
154
173
  const largeData = {
@@ -173,11 +192,13 @@ let UserService = class UserService {
173
192
  averageRating: (Math.random() * 5).toFixed(2),
174
193
  },
175
194
  };
195
+ // 这个数据会被自动压缩,因为大于 1KB
176
196
  yield this.cacheService.set(`user:${id}:large-data`, largeData, {
177
- ttl: 3600000,
197
+ ttl: 3600000, // 1小时
178
198
  });
179
199
  });
180
200
  }
201
+ // 获取大数据
181
202
  getLargeData(id) {
182
203
  return __awaiter(this, void 0, void 0, function* () {
183
204
  return yield this.cacheService.get(`user:${id}:large-data`);
@@ -188,7 +209,7 @@ exports.UserService = UserService;
188
209
  __decorate([
189
210
  (0, index_1.Cacheable)({
190
211
  key: (id) => `user:${id}:profile`,
191
- ttl: 600000,
212
+ ttl: 600000, // 10分钟
192
213
  dependencies: [new index_1.TagDependency(['user-profile'])],
193
214
  }),
194
215
  __metadata("design:type", Function),
@@ -235,18 +256,24 @@ exports.UserService = UserService = __decorate([
235
256
  __metadata("design:paramtypes", [index_1.CacheService,
236
257
  UserRepository])
237
258
  ], UserService);
259
+ /**
260
+ * 文章服务示例 - 展示依赖使用
261
+ */
238
262
  let PostService = class PostService {
239
263
  constructor(cacheService, postRepository) {
240
264
  this.cacheService = cacheService;
241
265
  this.postRepository = postRepository;
242
266
  }
267
+ // 使用数据库依赖 - 当用户表更新时,相关文章缓存会自动失效
243
268
  getPostsByAuthor(authorId) {
244
269
  return __awaiter(this, void 0, void 0, function* () {
245
270
  return yield this.postRepository.findByAuthor(authorId);
246
271
  });
247
272
  }
273
+ // 使用回调依赖 - 基于配置版本
248
274
  getFeaturedPosts() {
249
275
  return __awaiter(this, void 0, void 0, function* () {
276
+ // 模拟获取推荐文章
250
277
  console.log('[DB] 获取推荐文章');
251
278
  return Array(10)
252
279
  .fill(null)
@@ -261,6 +288,7 @@ let PostService = class PostService {
261
288
  }
262
289
  getConfigVersion() {
263
290
  return __awaiter(this, void 0, void 0, function* () {
291
+ // 模拟获取配置版本
264
292
  return '1.0.0';
265
293
  });
266
294
  }
@@ -269,7 +297,7 @@ exports.PostService = PostService;
269
297
  __decorate([
270
298
  (0, index_1.Cacheable)({
271
299
  key: (authorId) => `posts:by-author:${authorId}`,
272
- ttl: 600000,
300
+ ttl: 600000, // 10分钟
273
301
  dependencies: [
274
302
  new index_1.DbDependency('SELECT updated_at FROM users WHERE id = ?', (authorId) => [authorId]),
275
303
  ],
@@ -281,10 +309,11 @@ __decorate([
281
309
  __decorate([
282
310
  (0, index_1.Cacheable)({
283
311
  key: 'posts:featured',
284
- ttl: 1800000,
312
+ ttl: 1800000, // 30分钟
285
313
  dependencies: [
286
314
  new index_1.CallbackDependency(() => __awaiter(void 0, void 0, void 0, function* () {
287
- return yield 'v1.0.0';
315
+ // 检查配置版本,如果配置改变则失效缓存
316
+ return yield 'v1.0.0'; // 简化为固定值
288
317
  })),
289
318
  ],
290
319
  }),
@@ -297,10 +326,14 @@ exports.PostService = PostService = __decorate([
297
326
  __metadata("design:paramtypes", [index_1.CacheService,
298
327
  PostRepository])
299
328
  ], PostService);
329
+ /**
330
+ * 缓存统计和监控示例
331
+ */
300
332
  let CacheMonitoringService = class CacheMonitoringService {
301
333
  constructor(cacheService) {
302
334
  this.cacheService = cacheService;
303
335
  }
336
+ // 获取缓存统计信息
304
337
  getCacheStats() {
305
338
  const stats = this.cacheService.getStats();
306
339
  console.log('=== 缓存统计信息 ===');
@@ -317,13 +350,16 @@ let CacheMonitoringService = class CacheMonitoringService {
317
350
  }
318
351
  return stats;
319
352
  }
353
+ // 重置统计
320
354
  resetStats() {
321
355
  this.cacheService.resetStats();
322
356
  console.log('缓存统计已重置');
323
357
  }
358
+ // 定期监控
324
359
  startMonitoring(intervalMs = 60000) {
325
360
  setInterval(() => {
326
361
  const stats = this.getCacheStats();
362
+ // 如果命中率过低,发出警告
327
363
  if (stats.hitRate < 0.7) {
328
364
  console.warn(`⚠️ 缓存命中率过低: ${(stats.hitRate * 100).toFixed(2)}%`);
329
365
  }
@@ -336,38 +372,56 @@ exports.CacheMonitoringService = CacheMonitoringService = __decorate([
336
372
  (0, common_1.Injectable)(),
337
373
  __metadata("design:paramtypes", [index_1.CacheService])
338
374
  ], CacheMonitoringService);
375
+ /**
376
+ * 使用示例
377
+ */
339
378
  function demonstrateCacheUsage() {
340
379
  return __awaiter(this, void 0, void 0, function* () {
341
- const userService = new UserService(new index_1.CacheService({}, {}, {}, true, 1024), new UserRepository());
380
+ // 注意:在实际应用中,这些服务会通过依赖注入获得
381
+ const userService = new UserService(new index_1.CacheService(
382
+ // 这些参数在实际应用中会通过模块配置自动注入
383
+ {}, // CLS Provider
384
+ {}, // Memory Provider
385
+ {}, // Redis Provider
386
+ true, // 启用压缩
387
+ 1024), new UserRepository());
342
388
  const postService = new PostService(new index_1.CacheService({}, {}, {}, true, 1024), new PostRepository());
343
389
  const monitoringService = new CacheMonitoringService(new index_1.CacheService({}, {}, {}, true, 1024));
344
390
  console.log('🚀 开始缓存演示...\n');
345
391
  try {
392
+ // 1. 基础缓存演示
346
393
  console.log('1. 基础缓存使用:');
347
394
  const user1 = yield userService.getUser('1');
348
395
  console.log(`获取用户: ${user1.name}`);
396
+ // 第二次获取应该从缓存获取
349
397
  const user1Cached = yield userService.getUser('1');
350
398
  console.log(`从缓存获取用户: ${user1Cached.name}\n`);
399
+ // 2. 装饰器缓存演示
351
400
  console.log('2. 装饰器缓存:');
352
401
  const profile = yield userService.getUserProfile('2');
353
402
  console.log(`获取用户资料: ${profile.name}`);
354
403
  const profileCached = yield userService.getUserProfile('2');
355
404
  console.log(`从缓存获取用户资料: ${profileCached.name}\n`);
405
+ // 3. 批量操作演示
356
406
  console.log('3. 批量操作:');
357
407
  const users = yield userService.getUsersBatch(['1', '2', '3', '4', '5']);
358
408
  console.log(`批量获取 ${users.length} 个用户\n`);
409
+ // 4. 大数据压缩演示
359
410
  console.log('4. 大数据压缩:');
360
411
  yield userService.cacheLargeData('1');
361
412
  console.log('缓存大数据完成(应该自动压缩)');
362
413
  const largeData = yield userService.getLargeData('1');
363
414
  console.log(`获取大数据: 用户 ${largeData.user.name}, 文章数 ${largeData.posts.length}\n`);
415
+ // 5. 依赖系统演示
364
416
  console.log('5. 依赖系统:');
365
417
  const posts = yield postService.getPostsByAuthor('1');
366
418
  console.log(`获取作者文章: ${posts.length} 篇`);
367
419
  const featuredPosts = yield postService.getFeaturedPosts();
368
420
  console.log(`获取推荐文章: ${featuredPosts.length} 篇\n`);
421
+ // 6. 缓存统计
369
422
  console.log('6. 缓存统计:');
370
423
  monitoringService.getCacheStats();
424
+ // 7. 缓存失效演示
371
425
  console.log('\n7. 缓存失效:');
372
426
  yield userService.invalidateAllProfiles();
373
427
  console.log('已清除所有用户资料缓存');