@grupo-argenta/schema-kit-nest 0.0.20 → 0.0.21

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 (157) hide show
  1. package/config/naming-strategy.d.ts +6 -0
  2. package/config/naming-strategy.js +17 -0
  3. package/config/redis.constants.d.ts +1 -0
  4. package/config/redis.constants.js +4 -0
  5. package/context-logger.service.d.ts +4 -0
  6. package/context-logger.service.js +23 -0
  7. package/decorators/date-range.d.ts +4 -0
  8. package/decorators/date-range.js +17 -0
  9. package/decorators/encrypted.d.ts +10 -0
  10. package/decorators/encrypted.js +15 -0
  11. package/decorators/file-column.d.ts +17 -0
  12. package/decorators/file-column.js +20 -0
  13. package/decorators/get-user.decorator.d.ts +6 -0
  14. package/decorators/get-user.decorator.js +12 -0
  15. package/decorators/luxon.d.ts +6 -0
  16. package/decorators/luxon.js +20 -0
  17. package/decorators/multipart.decorator.d.ts +4 -0
  18. package/decorators/multipart.decorator.js +51 -0
  19. package/decorators/post-get.decorator.d.ts +10 -0
  20. package/decorators/post-get.decorator.js +25 -0
  21. package/decorators/query-or-body.decorator.d.ts +8 -0
  22. package/decorators/query-or-body.decorator.js +15 -0
  23. package/decorators/when.decorator.d.ts +8 -0
  24. package/decorators/when.decorator.js +16 -0
  25. package/html/components/badge.d.ts +13 -0
  26. package/html/components/badge.js +29 -0
  27. package/html/components/colors.d.ts +11 -0
  28. package/html/components/colors.js +15 -0
  29. package/html/components/component.d.ts +11 -0
  30. package/html/components/component.js +35 -0
  31. package/html/components/default/default-footer.d.ts +6 -0
  32. package/html/components/default/default-footer.js +18 -0
  33. package/html/components/default/default-header.d.ts +13 -0
  34. package/html/components/default/default-header.js +30 -0
  35. package/html/components/env-badge.d.ts +7 -0
  36. package/html/components/env-badge.js +29 -0
  37. package/html/components/grid.d.ts +17 -0
  38. package/html/components/grid.js +44 -0
  39. package/html/components/shell.d.ts +18 -0
  40. package/html/components/shell.js +423 -0
  41. package/html/components/table.d.ts +16 -0
  42. package/html/components/table.js +55 -0
  43. package/html/components/unordered-list.d.ts +6 -0
  44. package/html/components/unordered-list.js +21 -0
  45. package/index.d.ts +49 -0
  46. package/index.js +65 -0
  47. package/interfaces/paginated-result.d.ts +21 -0
  48. package/interfaces/paginated-result.js +12 -0
  49. package/modules/auth/access-token.d.ts +27 -0
  50. package/modules/auth/access-token.js +14 -0
  51. package/modules/auth/known-module.d.ts +45 -0
  52. package/modules/auth/known-module.js +46 -0
  53. package/modules/auth/refresh-token.d.ts +18 -0
  54. package/modules/auth/refresh-token.js +2 -0
  55. package/modules/auth/token-type.d.ts +4 -0
  56. package/modules/auth/token-type.js +8 -0
  57. package/modules/encrypted-column/encrypted-column.module.d.ts +16 -0
  58. package/modules/encrypted-column/encrypted-column.module.js +35 -0
  59. package/modules/pubsub/pubsub-dynamic-topic.service.d.ts +77 -0
  60. package/modules/pubsub/pubsub-dynamic-topic.service.js +324 -0
  61. package/modules/pubsub/pubsub-redeliver-subscriber.service.d.ts +14 -0
  62. package/modules/pubsub/pubsub-redeliver-subscriber.service.js +77 -0
  63. package/modules/pubsub/pubsub-redeliver.service.d.ts +22 -0
  64. package/modules/pubsub/pubsub-redeliver.service.js +48 -0
  65. package/modules/pubsub/pubsub.constants.d.ts +2 -0
  66. package/modules/pubsub/pubsub.constants.js +5 -0
  67. package/modules/pubsub/pubsub.methods.d.ts +18 -0
  68. package/modules/pubsub/pubsub.methods.js +18 -0
  69. package/modules/pubsub/pubsub.methods.redelivery.d.ts +3 -0
  70. package/modules/pubsub/pubsub.methods.redelivery.js +2 -0
  71. package/modules/redis/redis.module.d.ts +10 -0
  72. package/modules/redis/redis.module.js +59 -0
  73. package/modules/redis/redis.options.d.ts +7 -0
  74. package/modules/redis/redis.options.js +4 -0
  75. package/modules/storage/storage.service.d.ts +16 -0
  76. package/modules/storage/storage.service.js +61 -0
  77. package/monitoramento/http-request-log/http-request-log.controller.d.ts +184 -0
  78. package/monitoramento/http-request-log/http-request-log.controller.js +32 -0
  79. package/monitoramento/http-request-log/http-request-log.dto.d.ts +220 -0
  80. package/monitoramento/http-request-log/http-request-log.dto.js +42 -0
  81. package/monitoramento/http-request-log/http-request-log.entity.d.ts +17 -0
  82. package/monitoramento/http-request-log/http-request-log.entity.js +87 -0
  83. package/monitoramento/http-request-log/http-request-log.module.d.ts +2 -0
  84. package/monitoramento/http-request-log/http-request-log.module.js +26 -0
  85. package/monitoramento/http-request-log/http-request-log.service.d.ts +8 -0
  86. package/monitoramento/http-request-log/http-request-log.service.js +35 -0
  87. package/monitoramento/index.d.ts +17 -0
  88. package/monitoramento/index.js +33 -0
  89. package/monitoramento/migrations/1792689106394-create_http_request_logs_table.d.ts +5 -0
  90. package/monitoramento/migrations/1792689106394-create_http_request_logs_table.js +96 -0
  91. package/monitoramento/migrations/1792689106395-create_pubsub_message_logs_table.d.ts +5 -0
  92. package/monitoramento/migrations/1792689106395-create_pubsub_message_logs_table.js +157 -0
  93. package/monitoramento/monitoramento.constants.d.ts +2 -0
  94. package/monitoramento/monitoramento.constants.js +5 -0
  95. package/monitoramento/monitoramento.entities.d.ts +1 -0
  96. package/monitoramento/monitoramento.entities.js +7 -0
  97. package/monitoramento/monitoramento.module.d.ts +6 -0
  98. package/monitoramento/monitoramento.module.js +61 -0
  99. package/monitoramento/monitoramento.options.d.ts +15 -0
  100. package/monitoramento/monitoramento.options.js +2 -0
  101. package/monitoramento/outbound-request.interceptor.d.ts +14 -0
  102. package/monitoramento/outbound-request.interceptor.js +113 -0
  103. package/monitoramento/pubsub-message-log/pubsub-message-log.controller.d.ts +257 -0
  104. package/monitoramento/pubsub-message-log/pubsub-message-log.controller.js +34 -0
  105. package/monitoramento/pubsub-message-log/pubsub-message-log.dto.d.ts +320 -0
  106. package/monitoramento/pubsub-message-log/pubsub-message-log.dto.js +57 -0
  107. package/monitoramento/pubsub-message-log/pubsub-message-log.entity.d.ts +44 -0
  108. package/monitoramento/pubsub-message-log/pubsub-message-log.entity.js +152 -0
  109. package/monitoramento/pubsub-message-log/pubsub-message-log.module.d.ts +2 -0
  110. package/monitoramento/pubsub-message-log/pubsub-message-log.module.js +26 -0
  111. package/monitoramento/pubsub-message-log/pubsub-message-log.service.d.ts +20 -0
  112. package/monitoramento/pubsub-message-log/pubsub-message-log.service.js +99 -0
  113. package/monitoramento/pubsub-self-check/pubsub-self-check.controller.d.ts +9 -0
  114. package/monitoramento/pubsub-self-check/pubsub-self-check.controller.js +45 -0
  115. package/monitoramento/pubsub-self-check/pubsub-self-check.module.d.ts +11 -0
  116. package/monitoramento/pubsub-self-check/pubsub-self-check.module.js +41 -0
  117. package/monitoramento/pubsub-self-check/pubsub-self-check.options.d.ts +10 -0
  118. package/monitoramento/pubsub-self-check/pubsub-self-check.options.js +4 -0
  119. package/monitoramento/pubsub-self-check/pubsub-self-check.service.d.ts +68 -0
  120. package/monitoramento/pubsub-self-check/pubsub-self-check.service.js +213 -0
  121. package/package.json +1 -1
  122. package/schema/abstract.entity.d.ts +28 -0
  123. package/schema/abstract.entity.js +68 -0
  124. package/schema/schema-builder.d.ts +131 -0
  125. package/schema/schema-builder.js +162 -0
  126. package/schema/schema.controller.d.ts +51 -0
  127. package/schema/schema.controller.js +121 -0
  128. package/schema/schema.service.d.ts +81 -0
  129. package/schema/schema.service.js +305 -0
  130. package/schema/typeorm-extensions.d.ts +6 -0
  131. package/schema/typeorm-extensions.js +6 -0
  132. package/schema/zod-extensions/cnpj.validator.d.ts +28 -0
  133. package/schema/zod-extensions/cnpj.validator.js +133 -0
  134. package/schema/zod-extensions/cpf-cnpj.validator.d.ts +2 -0
  135. package/schema/zod-extensions/cpf-cnpj.validator.js +8 -0
  136. package/schema/zod-extensions/cpf.validator.d.ts +18 -0
  137. package/schema/zod-extensions/cpf.validator.js +166 -0
  138. package/schema/zod-extensions.d.ts +50 -0
  139. package/schema/zod-extensions.js +144 -0
  140. package/schema-kit.module.d.ts +2 -0
  141. package/schema-kit.module.js +23 -0
  142. package/transformers/date-range.transformer.d.ts +6 -0
  143. package/transformers/date-range.transformer.js +44 -0
  144. package/transformers/encrypted.transformer.d.ts +11 -0
  145. package/transformers/encrypted.transformer.js +35 -0
  146. package/transformers/luxon.transformer.d.ts +3 -0
  147. package/transformers/luxon.transformer.js +12 -0
  148. package/utils/utils.d.ts +49 -0
  149. package/utils/utils.js +79 -0
  150. package/validators/ip-validator.d.ts +3 -0
  151. package/validators/ip-validator.js +8 -0
  152. package/validators/pubsub-delete.validator.d.ts +6 -0
  153. package/validators/pubsub-delete.validator.js +11 -0
  154. package/validators/url-validator.d.ts +3 -0
  155. package/validators/url-validator.js +8 -0
  156. package/validators/uuid-validator.d.ts +3 -0
  157. package/validators/uuid-validator.js +8 -0
@@ -0,0 +1,213 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.PubsubSelfCheckService = void 0;
16
+ const pubsub_1 = require("@google-cloud/pubsub");
17
+ const common_1 = require("@nestjs/common");
18
+ const schedule_1 = require("@nestjs/schedule");
19
+ const ioredis_1 = __importDefault(require("ioredis"));
20
+ const luxon_1 = require("luxon");
21
+ const zod_1 = __importDefault(require("zod"));
22
+ const redis_constants_1 = require("../../config/redis.constants");
23
+ const pubsub_dynamic_topic_service_1 = require("../../modules/pubsub/pubsub-dynamic-topic.service");
24
+ const pubsub_constants_1 = require("../../modules/pubsub/pubsub.constants");
25
+ const zod_extensions_1 = require("../../schema/zod-extensions");
26
+ const pubsub_self_check_options_1 = require("./pubsub-self-check.options");
27
+ /** Tempo sem resposta a partir do qual a API é considerada sem saúde */
28
+ const UNHEALTHY_AFTER_MINUTES = 5;
29
+ /** Menor que o intervalo do cron, para que só uma réplica envie os pings em cada minuto */
30
+ const LOCK_TTL_SECONDS = 50;
31
+ /** Atraso de entrega acima do qual a mensagem é logada como atrasada (fila acumulando) */
32
+ const DELAYED_AFTER_SECONDS = 30;
33
+ let PubsubSelfCheckService = class PubsubSelfCheckService extends pubsub_dynamic_topic_service_1.PubSubDynamicTopicService {
34
+ constructor() {
35
+ super({
36
+ modelName: 'PubSubSelfCheck',
37
+ validators: {
38
+ [pubsub_dynamic_topic_service_1.PubSubAction.SAVE]: PubSubSelfCheckValidator,
39
+ },
40
+ monitor: false,
41
+ });
42
+ }
43
+ selfCheckOptions;
44
+ pubsubApiName;
45
+ // O `pubSubInstance` da classe base é privado
46
+ pubSubClient;
47
+ redis;
48
+ /** Só envia pings depois que o tópico e a subscription existem */
49
+ ready = false;
50
+ /** Hash com os pings sem resposta (campo: API alvo; valor: ISO do primeiro ping sem resposta), comum às réplicas */
51
+ get pendingKey() {
52
+ return `pubsub-self-check:${this.pubsubApiName}:pending`;
53
+ }
54
+ /** Hash com o último PONG de cada API (campo: API alvo; valor: JSON com os horários), comum às réplicas */
55
+ get lastPongKey() {
56
+ return `pubsub-self-check:${this.pubsubApiName}:last-pong`;
57
+ }
58
+ get lockKey() {
59
+ return `pubsub-self-check:${this.pubsubApiName}:lock`;
60
+ }
61
+ /** Registra o próprio tópico e subscription, sem depender da lista de services de Pub/Sub da app */
62
+ async onApplicationBootstrap() {
63
+ try {
64
+ const [lstTopics] = await this.pubSubClient.getTopics();
65
+ const [lstSubscriptions] = await this.pubSubClient.getSubscriptions();
66
+ await this.ensureTopicRegistered(lstTopics);
67
+ await this.ensureSubscriptionRegistered(lstSubscriptions);
68
+ this.ready = true;
69
+ }
70
+ catch (error) {
71
+ this.logger.error(`Falha ao registrar o self-check do Pub/Sub: ${error}`);
72
+ }
73
+ }
74
+ /** Envia um ping para todas as APIs que estão na lista de monitoramento */
75
+ async check() {
76
+ if (!this.ready) {
77
+ return;
78
+ }
79
+ // Todas as réplicas rodam o cron; só a que pegar o lock envia os pings
80
+ const lock = await this.redis.set(this.lockKey, '1', 'EX', LOCK_TTL_SECONDS, 'NX');
81
+ if (!lock) {
82
+ return;
83
+ }
84
+ const lstApis = this.selfCheckOptions.lstApiPubSubCheck;
85
+ // API removida da configuração não deve continuar pendente
86
+ for (const key of [this.pendingKey, this.lastPongKey]) {
87
+ const lstRemovidas = (await this.redis.hkeys(key)).filter((api) => !lstApis.includes(api));
88
+ if (lstRemovidas.length) {
89
+ await this.redis.hdel(key, ...lstRemovidas);
90
+ }
91
+ }
92
+ for (const api of lstApis) {
93
+ try {
94
+ // HSETNX mantém o horário do primeiro ping sem resposta; o ping é reenviado mesmo pendente
95
+ const sentAt = luxon_1.DateTime.now();
96
+ await this.redis.hsetnx(this.pendingKey, api, sentAt.toISO());
97
+ await this.send({ type: PubSubSelfCheckType.PING, apiName: api, sentAt }, pubsub_dynamic_topic_service_1.PubSubAction.SAVE);
98
+ }
99
+ catch (error) {
100
+ this.logger.error(`Falha ao enviar o ping para ${api}: ${error}`);
101
+ }
102
+ }
103
+ }
104
+ /** Trata a mensagem de self-check */
105
+ async onSave(message) {
106
+ const receivedAt = luxon_1.DateTime.now();
107
+ // Atraso entre o envio e o recebimento: alto indica a subscription com mensagens acumuladas
108
+ const delayMs = receivedAt.diff(message.sentAt).toMillis();
109
+ if (delayMs >= DELAYED_AFTER_SECONDS * 1000) {
110
+ this.logger.warn(`${message.type} de ${message.apiName} recebido com ${Math.round(delayMs / 1000)} s de atraso (enviado em ${message.sentAt.toISO()})`);
111
+ }
112
+ if (message.type === PubSubSelfCheckType.PONG) {
113
+ const lastPong = {
114
+ pingSentAt: message.pingSentAt.toISO(),
115
+ pongSentAt: message.sentAt.toISO(),
116
+ receivedAt: receivedAt.toISO(),
117
+ roundTripMs: receivedAt.diff(message.pingSentAt).toMillis(),
118
+ };
119
+ // O estado é comum às réplicas: qualquer uma que receber o PONG limpa o pendente
120
+ await this.redis.hdel(this.pendingKey, message.apiName);
121
+ await this.redis.hset(this.lastPongKey, message.apiName, JSON.stringify(lastPong));
122
+ }
123
+ else {
124
+ // PING de outra API: o PONG leva o envio do PING para medir o tempo total
125
+ await this.send({
126
+ type: PubSubSelfCheckType.PONG,
127
+ apiName: this.pubsubApiName,
128
+ sentAt: luxon_1.DateTime.now(),
129
+ pingSentAt: message.sentAt,
130
+ }, pubsub_dynamic_topic_service_1.PubSubAction.SAVE);
131
+ }
132
+ }
133
+ /** Retorna as APIs da lista que estão sem resposta há 5 minutos ou mais */
134
+ async getUnhealthyApis() {
135
+ const pending = await this.redis.hgetall(this.pendingKey);
136
+ const lstApis = this.selfCheckOptions.lstApiPubSubCheck;
137
+ return Object.entries(pending)
138
+ .filter(([api]) => lstApis.includes(api))
139
+ .map(([apiName, iso]) => ({ apiName, pendingSince: luxon_1.DateTime.fromISO(iso) }))
140
+ .filter(({ pendingSince }) => luxon_1.DateTime.now().diff(pendingSince, 'minutes').minutes >= UNHEALTHY_AFTER_MINUTES);
141
+ }
142
+ /** Retorna o estado de todas as APIs da lista, com o último PONG de cada uma */
143
+ async getAll() {
144
+ const pending = await this.redis.hgetall(this.pendingKey);
145
+ const lastPongs = await this.redis.hgetall(this.lastPongKey);
146
+ const lstApis = this.selfCheckOptions.lstApiPubSubCheck;
147
+ return lstApis.map((apiName) => {
148
+ const iso = pending[apiName];
149
+ return {
150
+ apiName,
151
+ pendingSince: iso ? luxon_1.DateTime.fromISO(iso) : null,
152
+ lastPong: lastPongs[apiName] ? this.parseLastPong(lastPongs[apiName]) : null,
153
+ };
154
+ });
155
+ }
156
+ parseLastPong(json) {
157
+ const lastPong = JSON.parse(json);
158
+ return {
159
+ pingSentAt: luxon_1.DateTime.fromISO(lastPong.pingSentAt),
160
+ pongSentAt: luxon_1.DateTime.fromISO(lastPong.pongSentAt),
161
+ receivedAt: luxon_1.DateTime.fromISO(lastPong.receivedAt),
162
+ roundTripMs: lastPong.roundTripMs,
163
+ };
164
+ }
165
+ };
166
+ exports.PubsubSelfCheckService = PubsubSelfCheckService;
167
+ __decorate([
168
+ (0, common_1.Inject)(pubsub_self_check_options_1.PUBSUB_SELF_CHECK_OPTIONS),
169
+ __metadata("design:type", Object)
170
+ ], PubsubSelfCheckService.prototype, "selfCheckOptions", void 0);
171
+ __decorate([
172
+ (0, common_1.Inject)(pubsub_constants_1.PUBSUB_API_NAME),
173
+ __metadata("design:type", String)
174
+ ], PubsubSelfCheckService.prototype, "pubsubApiName", void 0);
175
+ __decorate([
176
+ (0, common_1.Inject)(pubsub_1.PubSub),
177
+ __metadata("design:type", pubsub_1.PubSub)
178
+ ], PubsubSelfCheckService.prototype, "pubSubClient", void 0);
179
+ __decorate([
180
+ (0, common_1.Inject)(redis_constants_1.REDIS_CLIENT),
181
+ __metadata("design:type", ioredis_1.default)
182
+ ], PubsubSelfCheckService.prototype, "redis", void 0);
183
+ __decorate([
184
+ (0, schedule_1.Cron)(schedule_1.CronExpression.EVERY_MINUTE),
185
+ __metadata("design:type", Function),
186
+ __metadata("design:paramtypes", []),
187
+ __metadata("design:returntype", Promise)
188
+ ], PubsubSelfCheckService.prototype, "check", null);
189
+ exports.PubsubSelfCheckService = PubsubSelfCheckService = __decorate([
190
+ (0, common_1.Injectable)(),
191
+ __metadata("design:paramtypes", [])
192
+ ], PubsubSelfCheckService);
193
+ var PubSubSelfCheckType;
194
+ (function (PubSubSelfCheckType) {
195
+ PubSubSelfCheckType["PING"] = "PING";
196
+ PubSubSelfCheckType["PONG"] = "PONG";
197
+ })(PubSubSelfCheckType || (PubSubSelfCheckType = {}));
198
+ const PubSubSelfCheckValidator = zod_1.default.discriminatedUnion('type', [
199
+ zod_1.default.object({
200
+ type: zod_1.default.literal(PubSubSelfCheckType.PING),
201
+ /** API alvo do ping */
202
+ apiName: zod_1.default.string(),
203
+ sentAt: zod_extensions_1.zExt.dateTime(),
204
+ }),
205
+ zod_1.default.object({
206
+ type: zod_1.default.literal(PubSubSelfCheckType.PONG),
207
+ /** API que respondeu */
208
+ apiName: zod_1.default.string(),
209
+ sentAt: zod_extensions_1.zExt.dateTime(),
210
+ /** Envio do PING respondido */
211
+ pingSentAt: zod_extensions_1.zExt.dateTime(),
212
+ }),
213
+ ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grupo-argenta/schema-kit-nest",
3
- "version": "0.0.20",
3
+ "version": "0.0.21",
4
4
  "description": "Base NestJS do schema-kit: SchemaService/SchemaController de CRUD, decorators, validators, Pub/Sub, storage e monitoramento",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -0,0 +1,28 @@
1
+ import { DateTime } from 'luxon';
2
+ import { BaseEntity } from 'typeorm';
3
+ /** uuid only */
4
+ export declare abstract class UuidEntity extends BaseEntity {
5
+ uuid: string;
6
+ }
7
+ /** uuid + createdAt/updatedAt, no soft delete */
8
+ export declare abstract class TimestampedEntity extends UuidEntity {
9
+ createdAt: DateTime;
10
+ updatedAt: DateTime;
11
+ }
12
+ type Ctor<T = {}> = abstract new (...args: any[]) => T;
13
+ export declare function Timestamped<B extends Ctor>(Base: B): (abstract new (...args: any[]) => {
14
+ createdAt: DateTime;
15
+ updatedAt: DateTime;
16
+ }) & B;
17
+ export declare function SoftDeletable<B extends Ctor>(Base: B): (abstract new (...args: any[]) => {
18
+ deletedAt: DateTime | null;
19
+ }) & B;
20
+ declare const AbstractEntity_base: (abstract new (...args: any[]) => {
21
+ deletedAt: DateTime | null;
22
+ }) & (abstract new (...args: any[]) => {
23
+ createdAt: DateTime;
24
+ updatedAt: DateTime;
25
+ }) & typeof UuidEntity;
26
+ export declare abstract class AbstractEntity extends AbstractEntity_base {
27
+ }
28
+ export {};
@@ -0,0 +1,68 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.AbstractEntity = exports.TimestampedEntity = exports.UuidEntity = void 0;
13
+ exports.Timestamped = Timestamped;
14
+ exports.SoftDeletable = SoftDeletable;
15
+ const luxon_1 = require("../decorators/luxon");
16
+ const luxon_2 = require("luxon");
17
+ const typeorm_1 = require("typeorm");
18
+ /** uuid only */
19
+ class UuidEntity extends typeorm_1.BaseEntity {
20
+ uuid;
21
+ }
22
+ exports.UuidEntity = UuidEntity;
23
+ __decorate([
24
+ (0, typeorm_1.PrimaryColumn)({ type: 'uuid', default: () => 'uuidv7()' }),
25
+ __metadata("design:type", String)
26
+ ], UuidEntity.prototype, "uuid", void 0);
27
+ /** uuid + createdAt/updatedAt, no soft delete */
28
+ class TimestampedEntity extends UuidEntity {
29
+ createdAt;
30
+ updatedAt;
31
+ }
32
+ exports.TimestampedEntity = TimestampedEntity;
33
+ __decorate([
34
+ (0, luxon_1.CreateDateTimeColumn)(),
35
+ __metadata("design:type", luxon_2.DateTime)
36
+ ], TimestampedEntity.prototype, "createdAt", void 0);
37
+ __decorate([
38
+ (0, luxon_1.UpdateDateTimeColumn)(),
39
+ __metadata("design:type", luxon_2.DateTime)
40
+ ], TimestampedEntity.prototype, "updatedAt", void 0);
41
+ function Timestamped(Base) {
42
+ class M extends Base {
43
+ createdAt;
44
+ updatedAt;
45
+ }
46
+ __decorate([
47
+ (0, luxon_1.CreateDateTimeColumn)(),
48
+ __metadata("design:type", luxon_2.DateTime)
49
+ ], M.prototype, "createdAt", void 0);
50
+ __decorate([
51
+ (0, luxon_1.UpdateDateTimeColumn)(),
52
+ __metadata("design:type", luxon_2.DateTime)
53
+ ], M.prototype, "updatedAt", void 0);
54
+ return M;
55
+ }
56
+ function SoftDeletable(Base) {
57
+ class M extends Base {
58
+ deletedAt;
59
+ }
60
+ __decorate([
61
+ (0, luxon_1.DeleteDateTimeColumn)({ nullable: true }),
62
+ __metadata("design:type", Object)
63
+ ], M.prototype, "deletedAt", void 0);
64
+ return M;
65
+ }
66
+ class AbstractEntity extends SoftDeletable(Timestamped(UuidEntity)) {
67
+ }
68
+ exports.AbstractEntity = AbstractEntity;
@@ -0,0 +1,131 @@
1
+ import z from 'zod';
2
+ export interface IIndexSchema {
3
+ [key: string]: {
4
+ type: FieldType;
5
+ validator?: z.ZodType;
6
+ };
7
+ }
8
+ export declare class SchemaBuilder {
9
+ static build<T extends z.core.$ZodShape>(options: {
10
+ modelSchema: z.ZodObject<T & {
11
+ uuid: z.ZodType;
12
+ }>;
13
+ indexSchema: IIndexSchema;
14
+ }): {
15
+ createValidator: z.ZodPipe<z.ZodObject<((Exclude<"uuid", "uuid" | Extract<keyof T, "uuid">> | Exclude<keyof T, "uuid" | Extract<keyof T, "uuid">>) & "uuid" extends never ? (Omit<T & {
16
+ uuid: z.ZodType;
17
+ }, "uuid" | Extract<keyof T, "uuid">> extends infer T_2 ? { [k_1 in keyof T_2]: T_2[k_1]; } : never) & {
18
+ uuid: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
19
+ } : ((Omit<T & {
20
+ uuid: z.ZodType;
21
+ }, "uuid" | Extract<keyof T, "uuid">> extends infer T_4 ? { [k_1 in keyof T_4]: T_4[k_1]; } : never) extends infer T_3 extends z.core.util.SomeObject ? { [K in keyof T_3 as K extends "uuid" ? never : K]: T_3[K]; } : never) & {
22
+ uuid: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
23
+ }) extends infer T_1 ? { [k in keyof T_1]: T_1[k]; } : never, z.core.$strip>, z.ZodTransform<Awaited<Omit<z.core.$InferObjectOutput<((Exclude<"uuid", "uuid" | Extract<keyof T, "uuid">> | Exclude<keyof T, "uuid" | Extract<keyof T, "uuid">>) & "uuid" extends never ? (Omit<T & {
24
+ uuid: z.ZodType;
25
+ }, "uuid" | Extract<keyof T, "uuid">> extends infer T_6 ? { [k_1 in keyof T_6]: T_6[k_1]; } : never) & {
26
+ uuid: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
27
+ } : ((Omit<T & {
28
+ uuid: z.ZodType;
29
+ }, "uuid" | Extract<keyof T, "uuid">> extends infer T_8 ? { [k_1 in keyof T_8]: T_8[k_1]; } : never) extends infer T_7 extends z.core.util.SomeObject ? { [K in keyof T_7 as K extends "uuid" ? never : K]: T_7[K]; } : never) & {
30
+ uuid: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
31
+ }) extends infer T_5 ? { [k in keyof T_5]: T_5[k]; } : never, {}>, "uuid"> & {
32
+ uuid?: string;
33
+ }>, z.core.$InferObjectOutput<((Exclude<"uuid", "uuid" | Extract<keyof T, "uuid">> | Exclude<keyof T, "uuid" | Extract<keyof T, "uuid">>) & "uuid" extends never ? (Omit<T & {
34
+ uuid: z.ZodType;
35
+ }, "uuid" | Extract<keyof T, "uuid">> extends infer T_10 ? { [k_1 in keyof T_10]: T_10[k_1]; } : never) & {
36
+ uuid: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
37
+ } : ((Omit<T & {
38
+ uuid: z.ZodType;
39
+ }, "uuid" | Extract<keyof T, "uuid">> extends infer T_12 ? { [k_1 in keyof T_12]: T_12[k_1]; } : never) extends infer T_11 extends z.core.util.SomeObject ? { [K in keyof T_11 as K extends "uuid" ? never : K]: T_11[K]; } : never) & {
40
+ uuid: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
41
+ }) extends infer T_9 ? { [k in keyof T_9]: T_9[k]; } : never, {}>>>;
42
+ patchValidator: z.ZodObject<Omit<T & {
43
+ uuid: z.ZodType;
44
+ } extends infer T_14 extends Readonly<{
45
+ [k: string]: z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
46
+ }> ? { -readonly [k_3 in keyof T_14]: z.ZodOptional<T_14[k_3]>; } : never, "uuid" | Extract<keyof T, "uuid">> extends infer T_13 ? { [k_2 in keyof T_13]: T_13[k_2]; } : never, z.core.$strip>;
47
+ indexValidator: z.ZodObject<{
48
+ page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
49
+ size: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
50
+ sort: z.ZodDefault<z.ZodOptional<z.ZodPreprocess<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
51
+ index: z.ZodString;
52
+ order: z.ZodEnum<{
53
+ ASC: "ASC";
54
+ DESC: "DESC";
55
+ }>;
56
+ }, z.core.$strip>, z.ZodPreprocess<z.ZodObject<{
57
+ index: z.ZodString;
58
+ order: z.ZodEnum<{
59
+ ASC: "ASC";
60
+ DESC: "DESC";
61
+ }>;
62
+ }, z.core.$strip>, unknown>]>>, unknown>>>;
63
+ query: z.ZodOptional<z.ZodString>;
64
+ lstUuids: z.ZodOptional<z.ZodPreprocess<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodPreprocess<z.ZodString, unknown>]>>, unknown>>;
65
+ lstFilter: z.ZodOptional<z.ZodPreprocess<z.ZodArray<z.ZodUnion<readonly [z.ZodUnion<z.ZodObject<{
66
+ value: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
67
+ index: z.ZodLiteral<string>;
68
+ }, z.core.$strip>[]>, z.ZodPreprocess<z.ZodUnion<z.ZodObject<{
69
+ value: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
70
+ index: z.ZodLiteral<string>;
71
+ }, z.core.$strip>[]>, unknown>]>>, unknown>>;
72
+ }, z.core.$strip>;
73
+ saveValidator: z.ZodObject<("uuid" | (keyof T & "uuid") extends never ? T & {
74
+ uuid: z.ZodType;
75
+ } & {
76
+ uuid: z.ZodUUID;
77
+ } : (T & {
78
+ uuid: z.ZodType;
79
+ } extends infer T_16 extends z.core.util.SomeObject ? { [K_1 in keyof T_16 as K_1 extends "uuid" ? never : K_1]: T_16[K_1]; } : never) & {
80
+ uuid: z.ZodUUID;
81
+ }) extends infer T_15 ? { [k_4 in keyof T_15]: T_15[k_4]; } : never, z.core.$strip>;
82
+ };
83
+ }
84
+ export declare enum FieldType {
85
+ UUID = "UUID",
86
+ Bool = "Bool",
87
+ Currency = "Currency",
88
+ Date = "Date",
89
+ DateTime = "DateTime",
90
+ Time = "Time",
91
+ Decimal = "Decimal",
92
+ Number = "Number",
93
+ File = "File",
94
+ String = "String",
95
+ Phone = "Phone",
96
+ TextArea = "TextArea",
97
+ Select = "Select",
98
+ Cpf = "Cpf",
99
+ Cnpj = "Cnpj",
100
+ CpfCnpj = "CpfCnpj",
101
+ Icon = "Icon"
102
+ }
103
+ declare function filterSchema(index: string, options: {
104
+ type: FieldType;
105
+ validator?: z.ZodType;
106
+ }): z.ZodObject<{
107
+ value: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
108
+ index: z.ZodLiteral<string>;
109
+ }, z.core.$strip>;
110
+ export type FilterSchema = z.infer<ReturnType<typeof filterSchema>>;
111
+ export declare const defaultIndexParams: z.ZodObject<{
112
+ page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
113
+ size: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
114
+ sort: z.ZodDefault<z.ZodOptional<z.ZodPreprocess<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
115
+ index: z.ZodString;
116
+ order: z.ZodEnum<{
117
+ ASC: "ASC";
118
+ DESC: "DESC";
119
+ }>;
120
+ }, z.core.$strip>, z.ZodPreprocess<z.ZodObject<{
121
+ index: z.ZodString;
122
+ order: z.ZodEnum<{
123
+ ASC: "ASC";
124
+ DESC: "DESC";
125
+ }>;
126
+ }, z.core.$strip>, unknown>]>>, unknown>>>;
127
+ query: z.ZodOptional<z.ZodString>;
128
+ lstUuids: z.ZodOptional<z.ZodPreprocess<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodPreprocess<z.ZodString, unknown>]>>, unknown>>;
129
+ }, z.core.$strip>;
130
+ export declare const defaultIndexParamsKeys: string[];
131
+ export {};
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.defaultIndexParamsKeys = exports.defaultIndexParams = exports.FieldType = exports.SchemaBuilder = void 0;
7
+ const zod_extensions_1 = require("./zod-extensions");
8
+ const zod_1 = __importDefault(require("zod"));
9
+ class SchemaBuilder {
10
+ static build(options) {
11
+ const { modelSchema, indexSchema } = options;
12
+ const createValidator = modelSchema
13
+ .omit({
14
+ uuid: true,
15
+ })
16
+ .extend({
17
+ uuid: zod_1.default.uuid().nullish(),
18
+ })
19
+ .transform((data) => {
20
+ const record = data;
21
+ if (record.uuid == null)
22
+ delete record.uuid;
23
+ return data;
24
+ });
25
+ const patchValidator = modelSchema.partial().omit({
26
+ uuid: true,
27
+ });
28
+ const saveValidator = modelSchema.extend({
29
+ uuid: zod_1.default.uuid(),
30
+ });
31
+ const lstFilter = Object.entries(indexSchema).map(([k, v]) => filterSchema(k, v));
32
+ const indexValidator = exports.defaultIndexParams.extend({
33
+ lstFilter: zod_extensions_1.zExt.jsonStringArray(zod_1.default.union(lstFilter)).optional(),
34
+ });
35
+ return {
36
+ createValidator,
37
+ patchValidator,
38
+ indexValidator,
39
+ saveValidator,
40
+ };
41
+ }
42
+ }
43
+ exports.SchemaBuilder = SchemaBuilder;
44
+ var FieldType;
45
+ (function (FieldType) {
46
+ FieldType["UUID"] = "UUID";
47
+ FieldType["Bool"] = "Bool";
48
+ FieldType["Currency"] = "Currency";
49
+ FieldType["Date"] = "Date";
50
+ FieldType["DateTime"] = "DateTime";
51
+ FieldType["Time"] = "Time";
52
+ FieldType["Decimal"] = "Decimal";
53
+ FieldType["Number"] = "Number";
54
+ FieldType["File"] = "File";
55
+ FieldType["String"] = "String";
56
+ FieldType["Phone"] = "Phone";
57
+ FieldType["TextArea"] = "TextArea";
58
+ FieldType["Select"] = "Select";
59
+ FieldType["Cpf"] = "Cpf";
60
+ FieldType["Cnpj"] = "Cnpj";
61
+ FieldType["CpfCnpj"] = "CpfCnpj";
62
+ FieldType["Icon"] = "Icon";
63
+ })(FieldType || (exports.FieldType = FieldType = {}));
64
+ function filterSchema(index, options) {
65
+ const base = { index: zod_1.default.literal(index) };
66
+ if (options.validator) {
67
+ return zod_1.default.object({
68
+ ...base,
69
+ value: options.validator,
70
+ });
71
+ }
72
+ switch (options.type) {
73
+ case FieldType.String:
74
+ case FieldType.Icon:
75
+ return zod_1.default.object({
76
+ ...base,
77
+ value: zod_1.default.string().max(255),
78
+ });
79
+ case FieldType.TextArea:
80
+ return zod_1.default.object({
81
+ ...base,
82
+ value: zod_1.default.string().max(2048),
83
+ });
84
+ case FieldType.UUID:
85
+ return zod_1.default.object({
86
+ ...base,
87
+ value: zod_1.default.uuidv7(),
88
+ });
89
+ case FieldType.Cpf:
90
+ return zod_1.default.object({
91
+ ...base,
92
+ value: zod_1.default.string().max(11, { message: 'Apenas 11 números são permitidos' }),
93
+ });
94
+ case FieldType.Cnpj:
95
+ return zod_1.default.object({
96
+ ...base,
97
+ value: zod_1.default.string().max(14, { message: 'Apenas 14 caracteres são permitidos' }),
98
+ });
99
+ case FieldType.CpfCnpj:
100
+ return zod_1.default.object({
101
+ ...base,
102
+ value: zod_1.default.string().max(14, { message: 'Apenas 14 caracteres são permitidos' }),
103
+ });
104
+ case FieldType.Phone:
105
+ return zod_1.default.object({
106
+ ...base,
107
+ value: zod_1.default.string().max(16, { message: 'Apenas 16 caracteres são permitidos' }),
108
+ });
109
+ case FieldType.Currency:
110
+ case FieldType.Decimal:
111
+ case FieldType.Number:
112
+ return zod_1.default.object({
113
+ ...base,
114
+ value:
115
+ // zExt.span(z.coerce.number().nullish())
116
+ zod_1.default.array(zod_1.default.coerce.number().nullish()).max(2, { message: 'Apenas 2 números são permitidos (min & max)' }),
117
+ });
118
+ case FieldType.Bool:
119
+ return zod_1.default.object({
120
+ ...base,
121
+ value: zod_1.default.coerce.boolean(),
122
+ });
123
+ // Intervalos [min, max] no formato do `Span` dos inputs *-span do front
124
+ case FieldType.Date: {
125
+ return zod_1.default.object({
126
+ ...base,
127
+ value: zod_extensions_1.zExt.dateTimeSpan({ dayEdges: true, nullish: true }).nullable(),
128
+ });
129
+ }
130
+ case FieldType.DateTime:
131
+ return zod_1.default.object({
132
+ ...base,
133
+ value: zod_extensions_1.zExt.dateTimeSpan({ dayEdges: true, nullish: true }).nullable(),
134
+ });
135
+ case FieldType.Time:
136
+ return zod_1.default.object({
137
+ ...base,
138
+ value: zod_1.default.tuple([zod_1.default.iso.time().nullish(), zod_1.default.iso.time().nullish()]),
139
+ });
140
+ default:
141
+ throw new Error(`Unsupported field type: ${options.type}`);
142
+ }
143
+ }
144
+ exports.defaultIndexParams = zod_1.default.object({
145
+ page: zod_1.default.coerce.number().default(1),
146
+ size: zod_1.default.coerce.number().default(10),
147
+ sort: zod_extensions_1.zExt
148
+ .jsonStringArray(zod_1.default.object({
149
+ index: zod_1.default.string(),
150
+ order: zod_1.default.enum(['ASC', 'DESC']),
151
+ }))
152
+ .optional()
153
+ .default([
154
+ {
155
+ index: 'uuid',
156
+ order: 'DESC',
157
+ },
158
+ ]),
159
+ query: zod_1.default.string().optional(),
160
+ lstUuids: zod_extensions_1.zExt.jsonStringArray(zod_1.default.string()).optional(),
161
+ });
162
+ exports.defaultIndexParamsKeys = [...Object.keys(exports.defaultIndexParams.shape), 'lstFilter'];
@@ -0,0 +1,51 @@
1
+ import { DeepPartial } from 'typeorm';
2
+ import z from 'zod';
3
+ import { IPageIndex } from '../interfaces/paginated-result';
4
+ import { UuidEntity } from './abstract.entity';
5
+ import { SchemaService } from './schema.service';
6
+ import type { Request } from 'express';
7
+ import { WithFileInput } from '../decorators/file-column';
8
+ export type BaseRoute = 'create' | 'index' | 'find' | 'patch' | 'delete';
9
+ /** What each base route received: `uuid` on find/patch/delete, `dto` on create/patch, `query` on index */
10
+ export interface BeforeRouteArgs<CreateDto, PatchDto, IndexParamsDto> {
11
+ req?: Request;
12
+ uuid?: string;
13
+ dto?: CreateDto | PatchDto;
14
+ query?: IndexParamsDto;
15
+ }
16
+ export declare function SchemaController<T extends UuidEntity, CreateDto extends DeepPartial<WithFileInput<T>>, PatchDto extends DeepPartial<WithFileInput<T>>, IndexParamsDto extends IPageIndex<T>>(options: {
17
+ createSchema: z.ZodType<CreateDto>;
18
+ patchSchema: z.ZodType<PatchDto>;
19
+ indexParamsSchema: z.ZodType<IndexParamsDto>;
20
+ routes?: BaseRoute[];
21
+ }): abstract new (_service: SchemaService<T, CreateDto, PatchDto, IndexParamsDto>) => {
22
+ readonly _service: SchemaService<T, CreateDto, PatchDto, IndexParamsDto>;
23
+ /**
24
+ * Roda antes de cada rota base. Faça o override para validar (ex: permissões); lance exceção para bloquear a rota.
25
+ */
26
+ beforeRoute(route: BaseRoute, args: BeforeRouteArgs<CreateDto, PatchDto, IndexParamsDto>): void | Promise<void>;
27
+ /**
28
+ * Roda depois de cada rota base. Faça o override para adicionar comportamento; por padrão retorna o resultado inalterado.
29
+ */
30
+ afterRoute<R>(route: BaseRoute, result: R): R | Promise<R>;
31
+ /**
32
+ * Rota de indexação.
33
+ */
34
+ index(query: IndexParamsDto, req?: Request): Promise<import("../interfaces/paginated-result").IPaginatedResult<T>>;
35
+ /**
36
+ * Rota de criação.
37
+ */
38
+ findOne(uuid: string, req?: Request): Promise<T>;
39
+ /**
40
+ * Rota de criação.
41
+ */
42
+ create(dto: CreateDto, req?: Request): Promise<T>;
43
+ /**
44
+ * Rota de atualização.
45
+ */
46
+ patch(uuid: string, dto: PatchDto, req?: Request): Promise<T>;
47
+ /**
48
+ * Rota de remoção.
49
+ */
50
+ remove(uuid: string, req?: Request): Promise<void>;
51
+ };