@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.
- package/config/naming-strategy.d.ts +6 -0
- package/config/naming-strategy.js +17 -0
- package/config/redis.constants.d.ts +1 -0
- package/config/redis.constants.js +4 -0
- package/context-logger.service.d.ts +4 -0
- package/context-logger.service.js +23 -0
- package/decorators/date-range.d.ts +4 -0
- package/decorators/date-range.js +17 -0
- package/decorators/encrypted.d.ts +10 -0
- package/decorators/encrypted.js +15 -0
- package/decorators/file-column.d.ts +17 -0
- package/decorators/file-column.js +20 -0
- package/decorators/get-user.decorator.d.ts +6 -0
- package/decorators/get-user.decorator.js +12 -0
- package/decorators/luxon.d.ts +6 -0
- package/decorators/luxon.js +20 -0
- package/decorators/multipart.decorator.d.ts +4 -0
- package/decorators/multipart.decorator.js +51 -0
- package/decorators/post-get.decorator.d.ts +10 -0
- package/decorators/post-get.decorator.js +25 -0
- package/decorators/query-or-body.decorator.d.ts +8 -0
- package/decorators/query-or-body.decorator.js +15 -0
- package/decorators/when.decorator.d.ts +8 -0
- package/decorators/when.decorator.js +16 -0
- package/html/components/badge.d.ts +13 -0
- package/html/components/badge.js +29 -0
- package/html/components/colors.d.ts +11 -0
- package/html/components/colors.js +15 -0
- package/html/components/component.d.ts +11 -0
- package/html/components/component.js +35 -0
- package/html/components/default/default-footer.d.ts +6 -0
- package/html/components/default/default-footer.js +18 -0
- package/html/components/default/default-header.d.ts +13 -0
- package/html/components/default/default-header.js +30 -0
- package/html/components/env-badge.d.ts +7 -0
- package/html/components/env-badge.js +29 -0
- package/html/components/grid.d.ts +17 -0
- package/html/components/grid.js +44 -0
- package/html/components/shell.d.ts +18 -0
- package/html/components/shell.js +423 -0
- package/html/components/table.d.ts +16 -0
- package/html/components/table.js +55 -0
- package/html/components/unordered-list.d.ts +6 -0
- package/html/components/unordered-list.js +21 -0
- package/index.d.ts +49 -0
- package/index.js +65 -0
- package/interfaces/paginated-result.d.ts +21 -0
- package/interfaces/paginated-result.js +12 -0
- package/modules/auth/access-token.d.ts +27 -0
- package/modules/auth/access-token.js +14 -0
- package/modules/auth/known-module.d.ts +45 -0
- package/modules/auth/known-module.js +46 -0
- package/modules/auth/refresh-token.d.ts +18 -0
- package/modules/auth/refresh-token.js +2 -0
- package/modules/auth/token-type.d.ts +4 -0
- package/modules/auth/token-type.js +8 -0
- package/modules/encrypted-column/encrypted-column.module.d.ts +16 -0
- package/modules/encrypted-column/encrypted-column.module.js +35 -0
- package/modules/pubsub/pubsub-dynamic-topic.service.d.ts +77 -0
- package/modules/pubsub/pubsub-dynamic-topic.service.js +324 -0
- package/modules/pubsub/pubsub-redeliver-subscriber.service.d.ts +14 -0
- package/modules/pubsub/pubsub-redeliver-subscriber.service.js +77 -0
- package/modules/pubsub/pubsub-redeliver.service.d.ts +22 -0
- package/modules/pubsub/pubsub-redeliver.service.js +48 -0
- package/modules/pubsub/pubsub.constants.d.ts +2 -0
- package/modules/pubsub/pubsub.constants.js +5 -0
- package/modules/pubsub/pubsub.methods.d.ts +18 -0
- package/modules/pubsub/pubsub.methods.js +18 -0
- package/modules/pubsub/pubsub.methods.redelivery.d.ts +3 -0
- package/modules/pubsub/pubsub.methods.redelivery.js +2 -0
- package/modules/redis/redis.module.d.ts +10 -0
- package/modules/redis/redis.module.js +59 -0
- package/modules/redis/redis.options.d.ts +7 -0
- package/modules/redis/redis.options.js +4 -0
- package/modules/storage/storage.service.d.ts +16 -0
- package/modules/storage/storage.service.js +61 -0
- package/monitoramento/http-request-log/http-request-log.controller.d.ts +184 -0
- package/monitoramento/http-request-log/http-request-log.controller.js +32 -0
- package/monitoramento/http-request-log/http-request-log.dto.d.ts +220 -0
- package/monitoramento/http-request-log/http-request-log.dto.js +42 -0
- package/monitoramento/http-request-log/http-request-log.entity.d.ts +17 -0
- package/monitoramento/http-request-log/http-request-log.entity.js +87 -0
- package/monitoramento/http-request-log/http-request-log.module.d.ts +2 -0
- package/monitoramento/http-request-log/http-request-log.module.js +26 -0
- package/monitoramento/http-request-log/http-request-log.service.d.ts +8 -0
- package/monitoramento/http-request-log/http-request-log.service.js +35 -0
- package/monitoramento/index.d.ts +17 -0
- package/monitoramento/index.js +33 -0
- package/monitoramento/migrations/1792689106394-create_http_request_logs_table.d.ts +5 -0
- package/monitoramento/migrations/1792689106394-create_http_request_logs_table.js +96 -0
- package/monitoramento/migrations/1792689106395-create_pubsub_message_logs_table.d.ts +5 -0
- package/monitoramento/migrations/1792689106395-create_pubsub_message_logs_table.js +157 -0
- package/monitoramento/monitoramento.constants.d.ts +2 -0
- package/monitoramento/monitoramento.constants.js +5 -0
- package/monitoramento/monitoramento.entities.d.ts +1 -0
- package/monitoramento/monitoramento.entities.js +7 -0
- package/monitoramento/monitoramento.module.d.ts +6 -0
- package/monitoramento/monitoramento.module.js +61 -0
- package/monitoramento/monitoramento.options.d.ts +15 -0
- package/monitoramento/monitoramento.options.js +2 -0
- package/monitoramento/outbound-request.interceptor.d.ts +14 -0
- package/monitoramento/outbound-request.interceptor.js +113 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.controller.d.ts +257 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.controller.js +34 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.dto.d.ts +320 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.dto.js +57 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.entity.d.ts +44 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.entity.js +152 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.module.d.ts +2 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.module.js +26 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.service.d.ts +20 -0
- package/monitoramento/pubsub-message-log/pubsub-message-log.service.js +99 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.controller.d.ts +9 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.controller.js +45 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.module.d.ts +11 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.module.js +41 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.options.d.ts +10 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.options.js +4 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.service.d.ts +68 -0
- package/monitoramento/pubsub-self-check/pubsub-self-check.service.js +213 -0
- package/package.json +1 -1
- package/schema/abstract.entity.d.ts +28 -0
- package/schema/abstract.entity.js +68 -0
- package/schema/schema-builder.d.ts +131 -0
- package/schema/schema-builder.js +162 -0
- package/schema/schema.controller.d.ts +51 -0
- package/schema/schema.controller.js +121 -0
- package/schema/schema.service.d.ts +81 -0
- package/schema/schema.service.js +305 -0
- package/schema/typeorm-extensions.d.ts +6 -0
- package/schema/typeorm-extensions.js +6 -0
- package/schema/zod-extensions/cnpj.validator.d.ts +28 -0
- package/schema/zod-extensions/cnpj.validator.js +133 -0
- package/schema/zod-extensions/cpf-cnpj.validator.d.ts +2 -0
- package/schema/zod-extensions/cpf-cnpj.validator.js +8 -0
- package/schema/zod-extensions/cpf.validator.d.ts +18 -0
- package/schema/zod-extensions/cpf.validator.js +166 -0
- package/schema/zod-extensions.d.ts +50 -0
- package/schema/zod-extensions.js +144 -0
- package/schema-kit.module.d.ts +2 -0
- package/schema-kit.module.js +23 -0
- package/transformers/date-range.transformer.d.ts +6 -0
- package/transformers/date-range.transformer.js +44 -0
- package/transformers/encrypted.transformer.d.ts +11 -0
- package/transformers/encrypted.transformer.js +35 -0
- package/transformers/luxon.transformer.d.ts +3 -0
- package/transformers/luxon.transformer.js +12 -0
- package/utils/utils.d.ts +49 -0
- package/utils/utils.js +79 -0
- package/validators/ip-validator.d.ts +3 -0
- package/validators/ip-validator.js +8 -0
- package/validators/pubsub-delete.validator.d.ts +6 -0
- package/validators/pubsub-delete.validator.js +11 -0
- package/validators/url-validator.d.ts +3 -0
- package/validators/url-validator.js +8 -0
- package/validators/uuid-validator.d.ts +3 -0
- package/validators/uuid-validator.js +8 -0
|
@@ -0,0 +1,121 @@
|
|
|
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 __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.SchemaController = SchemaController;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const when_decorator_1 = require("../decorators/when.decorator");
|
|
18
|
+
const post_get_decorator_1 = require("../decorators/post-get.decorator");
|
|
19
|
+
const query_or_body_decorator_1 = require("../decorators/query-or-body.decorator");
|
|
20
|
+
const multipart_decorator_1 = require("../decorators/multipart.decorator");
|
|
21
|
+
function SchemaController(options) {
|
|
22
|
+
const has = (r) => options.routes?.includes(r) ?? true;
|
|
23
|
+
const { createSchema, patchSchema, indexParamsSchema } = options;
|
|
24
|
+
class SchemaController {
|
|
25
|
+
_service;
|
|
26
|
+
constructor(_service) {
|
|
27
|
+
this._service = _service;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Roda antes de cada rota base. Faça o override para validar (ex: permissões); lance exceção para bloquear a rota.
|
|
31
|
+
*/
|
|
32
|
+
// oxlint-disable-next-line no-unused-vars
|
|
33
|
+
beforeRoute(route, args) { }
|
|
34
|
+
/**
|
|
35
|
+
* Roda depois de cada rota base. Faça o override para adicionar comportamento; por padrão retorna o resultado inalterado.
|
|
36
|
+
*/
|
|
37
|
+
// oxlint-disable-next-line no-unused-vars
|
|
38
|
+
afterRoute(route, result) {
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Rota de indexação.
|
|
43
|
+
*/
|
|
44
|
+
async index(query, req) {
|
|
45
|
+
await this.beforeRoute('index', { req, query });
|
|
46
|
+
const result = await this._service.index(query);
|
|
47
|
+
result.data = await Promise.all(result.data.map((model) => this._service.signFiles(model)));
|
|
48
|
+
return this.afterRoute('index', result);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Rota de criação.
|
|
52
|
+
*/
|
|
53
|
+
async findOne(uuid, req) {
|
|
54
|
+
await this.beforeRoute('find', { req, uuid });
|
|
55
|
+
return this.afterRoute('find', await this._service.signFiles(await this._service.find(uuid)));
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Rota de criação.
|
|
59
|
+
*/
|
|
60
|
+
async create(dto, req) {
|
|
61
|
+
await this.beforeRoute('create', { req, dto });
|
|
62
|
+
return this.afterRoute('create', await this._service.signFiles(await this._service.create(dto)));
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Rota de atualização.
|
|
66
|
+
*/
|
|
67
|
+
async patch(uuid, dto, req) {
|
|
68
|
+
await this.beforeRoute('patch', { req, uuid, dto });
|
|
69
|
+
return this.afterRoute('patch', await this._service.signFiles(await this._service.patch(uuid, dto)));
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Rota de remoção.
|
|
73
|
+
*/
|
|
74
|
+
async remove(uuid, req) {
|
|
75
|
+
await this.beforeRoute('delete', { req, uuid });
|
|
76
|
+
return this.afterRoute('delete', await this._service.remove(uuid));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
__decorate([
|
|
80
|
+
(0, when_decorator_1.When)(has('index'), (0, post_get_decorator_1.PostGet)('index')),
|
|
81
|
+
__param(0, (0, query_or_body_decorator_1.QueryOrBody)({ schema: indexParamsSchema })),
|
|
82
|
+
__param(1, (0, common_1.Req)()),
|
|
83
|
+
__metadata("design:type", Function),
|
|
84
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
85
|
+
__metadata("design:returntype", Promise)
|
|
86
|
+
], SchemaController.prototype, "index", null);
|
|
87
|
+
__decorate([
|
|
88
|
+
(0, when_decorator_1.When)(has('find'), (0, common_1.Get)(':uuid')),
|
|
89
|
+
__param(0, (0, common_1.Param)('uuid')),
|
|
90
|
+
__param(1, (0, common_1.Req)()),
|
|
91
|
+
__metadata("design:type", Function),
|
|
92
|
+
__metadata("design:paramtypes", [String, Object]),
|
|
93
|
+
__metadata("design:returntype", Promise)
|
|
94
|
+
], SchemaController.prototype, "findOne", null);
|
|
95
|
+
__decorate([
|
|
96
|
+
(0, when_decorator_1.When)(has('create'), (0, common_1.Post)(), (0, multipart_decorator_1.Multipart)()),
|
|
97
|
+
__param(0, (0, common_1.Body)({ schema: createSchema })),
|
|
98
|
+
__param(1, (0, common_1.Req)()),
|
|
99
|
+
__metadata("design:type", Function),
|
|
100
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
101
|
+
__metadata("design:returntype", Promise)
|
|
102
|
+
], SchemaController.prototype, "create", null);
|
|
103
|
+
__decorate([
|
|
104
|
+
(0, when_decorator_1.When)(has('patch'), (0, common_1.Patch)(':uuid'), (0, multipart_decorator_1.Multipart)()),
|
|
105
|
+
__param(0, (0, common_1.Param)('uuid')),
|
|
106
|
+
__param(1, (0, common_1.Body)({ schema: patchSchema })),
|
|
107
|
+
__param(2, (0, common_1.Req)()),
|
|
108
|
+
__metadata("design:type", Function),
|
|
109
|
+
__metadata("design:paramtypes", [String, Object, Object]),
|
|
110
|
+
__metadata("design:returntype", Promise)
|
|
111
|
+
], SchemaController.prototype, "patch", null);
|
|
112
|
+
__decorate([
|
|
113
|
+
(0, when_decorator_1.When)(has('delete'), (0, common_1.Delete)(':uuid')),
|
|
114
|
+
__param(0, (0, common_1.Param)('uuid')),
|
|
115
|
+
__param(1, (0, common_1.Req)()),
|
|
116
|
+
__metadata("design:type", Function),
|
|
117
|
+
__metadata("design:paramtypes", [String, Object]),
|
|
118
|
+
__metadata("design:returntype", Promise)
|
|
119
|
+
], SchemaController.prototype, "remove", null);
|
|
120
|
+
return SchemaController;
|
|
121
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { DeepPartial, EntityManager, Repository, SelectQueryBuilder } from 'typeorm';
|
|
2
|
+
import { StorageService } from '../modules/storage/storage.service';
|
|
3
|
+
import { WithFileInput } from '../decorators/file-column';
|
|
4
|
+
import { ContextLogger } from '../context-logger.service';
|
|
5
|
+
import { IPageIndex, IPaginatedResult } from '../interfaces/paginated-result';
|
|
6
|
+
import { IIndexSchema } from './schema-builder';
|
|
7
|
+
import { UuidEntity } from './abstract.entity';
|
|
8
|
+
export declare abstract class SchemaService<T extends UuidEntity, CreateDto extends DeepPartial<WithFileInput<T>>, PatchDto extends DeepPartial<WithFileInput<T>>, IndexParamsDto extends IPageIndex<T>> {
|
|
9
|
+
private repository;
|
|
10
|
+
private indexSchema;
|
|
11
|
+
constructor(repository: Repository<T>, indexSchema: IIndexSchema);
|
|
12
|
+
protected logger: ContextLogger;
|
|
13
|
+
protected storage?: StorageService;
|
|
14
|
+
/** Propriedades da entidade decoradas com `@FileColumn()` */
|
|
15
|
+
private get fileColumns();
|
|
16
|
+
/** Storage das colunas de arquivo; falha só quando há arquivo para tratar e o SchemaKitModule não foi importado */
|
|
17
|
+
private get fileStorage();
|
|
18
|
+
/**
|
|
19
|
+
* Cria um novo registro da entidade, usando o DTO informado. Override para customizar a criação (ex: adicionar lógica de negócio).
|
|
20
|
+
* @param createDto DTO com os dados para criar o registro.
|
|
21
|
+
* @param manager EntityManager opcional para usar na transação.
|
|
22
|
+
* @returns Promise<T> com o registro criado.
|
|
23
|
+
*/
|
|
24
|
+
create(createDto: CreateDto, manager?: EntityManager): Promise<T>;
|
|
25
|
+
/**
|
|
26
|
+
* Envia para o bucket os `File` das colunas de arquivo do DTO, trocando-os pelos caminhos.
|
|
27
|
+
* `null` limpa o arquivo; qualquer outro valor (a URL que o front devolve, ou `undefined`) é removido do DTO, mantendo o arquivo atual.
|
|
28
|
+
* @param current Registro atual, cujos arquivos substituídos ou limpos são retornados em `replaced`.
|
|
29
|
+
*/
|
|
30
|
+
private uploadFiles;
|
|
31
|
+
/** Remove arquivos do bucket; falhas só são registradas, para não desfazer o que já foi salvo */
|
|
32
|
+
private deleteFiles;
|
|
33
|
+
private filePaths;
|
|
34
|
+
/**
|
|
35
|
+
* Cópia do registro com os caminhos das colunas de arquivo trocados por URLs assinadas, para a resposta HTTP.
|
|
36
|
+
* Não altera o registro, para que a URL temporária nunca seja salva no lugar do caminho.
|
|
37
|
+
*/
|
|
38
|
+
signFiles(model: T): Promise<T>;
|
|
39
|
+
/**
|
|
40
|
+
* Cria um query builder para a entidade, usando o manager informado (ou o padrão).
|
|
41
|
+
* Override para customizar o query builder (ex: adicionar joins).
|
|
42
|
+
* @param manager EntityManager opcional para usar no query builder.
|
|
43
|
+
* @returns SelectQueryBuilder<T>
|
|
44
|
+
*/
|
|
45
|
+
protected createIndexQueryBuilder(manager?: EntityManager): SelectQueryBuilder<T>;
|
|
46
|
+
/**
|
|
47
|
+
* Executa a query de indexação, aplicando filtros, paginação e ordenação.
|
|
48
|
+
* Override para customizar a query (ex: adicionar joins).
|
|
49
|
+
* @param query DTO com os parâmetros de indexação.
|
|
50
|
+
* @returns Promise<IPaginatedResult<T>> com os resultados paginados.
|
|
51
|
+
*/
|
|
52
|
+
index(query: IndexParamsDto): Promise<IPaginatedResult<T>>;
|
|
53
|
+
/**
|
|
54
|
+
* Aplica filtros de `lstFilter` e `query` no query builder. Override para adicionar filtros customizados.
|
|
55
|
+
* `lstFilter` é um array de filtros específicos, enquanto `query` é uma string de busca genérica.
|
|
56
|
+
*/
|
|
57
|
+
protected applyFilters(qb: SelectQueryBuilder<T>, index: IndexParamsDto): void;
|
|
58
|
+
/**
|
|
59
|
+
* Executado antes de executar a query de indexação, permitindo customizar o query builder (ex: adicionar joins, filtros complexos).
|
|
60
|
+
* Override para adicionar lógica customizada.
|
|
61
|
+
* @param qb Query builder da entidade.
|
|
62
|
+
* @param params DTO com os parâmetros de indexação.
|
|
63
|
+
*/
|
|
64
|
+
beforeIndex(_query: SelectQueryBuilder<T>, _params: IndexParamsDto): Promise<void>;
|
|
65
|
+
/**
|
|
66
|
+
* Busca um registro pelo UUID. Override para customizar a busca (ex: adicionar joins).
|
|
67
|
+
* @param uuid UUID do registro.
|
|
68
|
+
* @param manager EntityManager opcional para usar na transação.
|
|
69
|
+
* @returns Promise<T> com o registro encontrado.
|
|
70
|
+
*/
|
|
71
|
+
find(uuid: string, manager?: EntityManager): Promise<T>;
|
|
72
|
+
/**
|
|
73
|
+
* Atualiza um registro pelo UUID, aplicando os dados do DTO informado. Override para customizar a atualização (ex: adicionar lógica de negócio).
|
|
74
|
+
* @param uuid UUID do registro.
|
|
75
|
+
* @param patchDto DTO com os dados para atualizar o registro.
|
|
76
|
+
* @param manager EntityManager opcional para usar na transação.
|
|
77
|
+
* @returns Promise<T> com o registro atualizado.
|
|
78
|
+
*/
|
|
79
|
+
patch(uuid: string, patchDto: PatchDto, manager?: EntityManager): Promise<T>;
|
|
80
|
+
remove(uuid: string, manager?: EntityManager): Promise<void>;
|
|
81
|
+
}
|
|
@@ -0,0 +1,305 @@
|
|
|
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.SchemaService = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const storage_service_1 = require("../modules/storage/storage.service");
|
|
15
|
+
const file_column_1 = require("../decorators/file-column");
|
|
16
|
+
const context_logger_service_1 = require("../context-logger.service");
|
|
17
|
+
const paginated_result_1 = require("../interfaces/paginated-result");
|
|
18
|
+
const schema_builder_1 = require("./schema-builder");
|
|
19
|
+
class SchemaService {
|
|
20
|
+
repository;
|
|
21
|
+
indexSchema;
|
|
22
|
+
constructor(repository, indexSchema) {
|
|
23
|
+
this.repository = repository;
|
|
24
|
+
this.indexSchema = indexSchema;
|
|
25
|
+
this.logger = new context_logger_service_1.ContextLogger();
|
|
26
|
+
this.logger.setContext(this.constructor.name);
|
|
27
|
+
}
|
|
28
|
+
logger;
|
|
29
|
+
// Injeção por propriedade para não mudar o construtor das subclasses.
|
|
30
|
+
// Opcional: contextos sem o SchemaKitModule (ex.: seeder) usam o service normalmente, só sem arquivos
|
|
31
|
+
storage;
|
|
32
|
+
/** Propriedades da entidade decoradas com `@FileColumn()` */
|
|
33
|
+
get fileColumns() {
|
|
34
|
+
return (0, file_column_1.getFileColumns)(this.repository.target);
|
|
35
|
+
}
|
|
36
|
+
/** Storage das colunas de arquivo; falha só quando há arquivo para tratar e o SchemaKitModule não foi importado */
|
|
37
|
+
get fileStorage() {
|
|
38
|
+
if (!this.storage) {
|
|
39
|
+
throw new Error(`${this.constructor.name}: StorageService indisponível. Importe o SchemaKitModule para usar colunas de arquivo.`);
|
|
40
|
+
}
|
|
41
|
+
return this.storage;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Cria um novo registro da entidade, usando o DTO informado. Override para customizar a criação (ex: adicionar lógica de negócio).
|
|
45
|
+
* @param createDto DTO com os dados para criar o registro.
|
|
46
|
+
* @param manager EntityManager opcional para usar na transação.
|
|
47
|
+
* @returns Promise<T> com o registro criado.
|
|
48
|
+
*/
|
|
49
|
+
async create(createDto, manager) {
|
|
50
|
+
const repo = this.repository.use(manager);
|
|
51
|
+
const { uploaded } = await this.uploadFiles(createDto);
|
|
52
|
+
try {
|
|
53
|
+
// uploadFiles já trocou os `File` pelos caminhos
|
|
54
|
+
return await repo.save(repo.create(createDto));
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
await this.deleteFiles(uploaded);
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Envia para o bucket os `File` das colunas de arquivo do DTO, trocando-os pelos caminhos.
|
|
63
|
+
* `null` limpa o arquivo; qualquer outro valor (a URL que o front devolve, ou `undefined`) é removido do DTO, mantendo o arquivo atual.
|
|
64
|
+
* @param current Registro atual, cujos arquivos substituídos ou limpos são retornados em `replaced`.
|
|
65
|
+
*/
|
|
66
|
+
async uploadFiles(dto, current) {
|
|
67
|
+
const values = dto;
|
|
68
|
+
const uploaded = [];
|
|
69
|
+
const replaced = [];
|
|
70
|
+
const prefix = this.repository.metadata.tableName;
|
|
71
|
+
for (const key of this.fileColumns) {
|
|
72
|
+
const value = values[key];
|
|
73
|
+
const files = [value].flat().filter((item) => item instanceof File);
|
|
74
|
+
if (value !== null && !files.length) {
|
|
75
|
+
delete values[key];
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const paths = await Promise.all(files.map((file) => this.fileStorage.upload(file, prefix)));
|
|
79
|
+
uploaded.push(...paths);
|
|
80
|
+
replaced.push(...this.filePaths(current?.[key]));
|
|
81
|
+
values[key] = value === null ? null : Array.isArray(value) ? paths : paths[0];
|
|
82
|
+
}
|
|
83
|
+
return { uploaded, replaced };
|
|
84
|
+
}
|
|
85
|
+
/** Remove arquivos do bucket; falhas só são registradas, para não desfazer o que já foi salvo */
|
|
86
|
+
async deleteFiles(paths) {
|
|
87
|
+
// async no map: a falta do storage também vira só log, sem desfazer o que já foi salvo
|
|
88
|
+
await Promise.all(paths.map(async (path) => {
|
|
89
|
+
try {
|
|
90
|
+
await this.fileStorage.delete(path);
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
this.logger.error(`Falha ao remover o arquivo "${path}" do bucket`, error);
|
|
94
|
+
}
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
filePaths(value) {
|
|
98
|
+
return [value].flat().filter((item) => typeof item === 'string');
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Cópia do registro com os caminhos das colunas de arquivo trocados por URLs assinadas, para a resposta HTTP.
|
|
102
|
+
* Não altera o registro, para que a URL temporária nunca seja salva no lugar do caminho.
|
|
103
|
+
*/
|
|
104
|
+
async signFiles(model) {
|
|
105
|
+
const columns = this.fileColumns;
|
|
106
|
+
if (!columns.length) {
|
|
107
|
+
return model;
|
|
108
|
+
}
|
|
109
|
+
const signed = Object.assign(Object.create(Object.getPrototypeOf(model)), model);
|
|
110
|
+
const values = signed;
|
|
111
|
+
for (const key of columns) {
|
|
112
|
+
const paths = this.filePaths(values[key]);
|
|
113
|
+
const urls = await Promise.all(paths.map((path) => this.fileStorage.signedUrl(path)));
|
|
114
|
+
values[key] = Array.isArray(values[key]) ? urls : (urls[0] ?? values[key]);
|
|
115
|
+
}
|
|
116
|
+
return signed;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Cria um query builder para a entidade, usando o manager informado (ou o padrão).
|
|
120
|
+
* Override para customizar o query builder (ex: adicionar joins).
|
|
121
|
+
* @param manager EntityManager opcional para usar no query builder.
|
|
122
|
+
* @returns SelectQueryBuilder<T>
|
|
123
|
+
*/
|
|
124
|
+
createIndexQueryBuilder(manager) {
|
|
125
|
+
return this.repository.use(manager).createQueryBuilder('e');
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Executa a query de indexação, aplicando filtros, paginação e ordenação.
|
|
129
|
+
* Override para customizar a query (ex: adicionar joins).
|
|
130
|
+
* @param query DTO com os parâmetros de indexação.
|
|
131
|
+
* @returns Promise<IPaginatedResult<T>> com os resultados paginados.
|
|
132
|
+
*/
|
|
133
|
+
async index(query) {
|
|
134
|
+
const qb = this.createIndexQueryBuilder();
|
|
135
|
+
const filterableFields = Object.entries(query).filter(([key, value]) => {
|
|
136
|
+
return !schema_builder_1.defaultIndexParamsKeys.includes(key) && value != undefined;
|
|
137
|
+
});
|
|
138
|
+
if (query.lstUuids?.length) {
|
|
139
|
+
qb.andWhere('e.uuid IN (:...uuids)', { uuids: query.lstUuids });
|
|
140
|
+
}
|
|
141
|
+
for (const element of filterableFields) {
|
|
142
|
+
const [key, value] = element;
|
|
143
|
+
if (Array.isArray(value)) {
|
|
144
|
+
if (value.length)
|
|
145
|
+
qb.andWhere(`e.${key} IN (:...${key})`, { [key]: value });
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (typeof value === 'string' && value.includes('%')) {
|
|
149
|
+
qb.andWhere(`e.${key} ILIKE :${key}`, { [key]: value });
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
qb.skip((query.page - 1) * query.size).take(query.size);
|
|
154
|
+
for (const element of query.sort || []) {
|
|
155
|
+
const { index: field, order } = element;
|
|
156
|
+
qb.addOrderBy(`e.${String(field)}`, order);
|
|
157
|
+
}
|
|
158
|
+
this.applyFilters(qb, query);
|
|
159
|
+
await this.beforeIndex(qb, query);
|
|
160
|
+
return (0, paginated_result_1.createPaginatedResult)(await qb.getManyAndCount(), query);
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Aplica filtros de `lstFilter` e `query` no query builder. Override para adicionar filtros customizados.
|
|
164
|
+
* `lstFilter` é um array de filtros específicos, enquanto `query` é uma string de busca genérica.
|
|
165
|
+
*/
|
|
166
|
+
applyFilters(qb, index) {
|
|
167
|
+
const { lstFilter, query } = index;
|
|
168
|
+
for (const element of lstFilter || []) {
|
|
169
|
+
const { index, value } = element;
|
|
170
|
+
const { type } = this.indexSchema[index];
|
|
171
|
+
//check if table contains the column
|
|
172
|
+
if (!this.repository.metadata.columns.find((c) => c.propertyName === index)) {
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
switch (type) {
|
|
176
|
+
case schema_builder_1.FieldType.String:
|
|
177
|
+
case schema_builder_1.FieldType.TextArea:
|
|
178
|
+
case schema_builder_1.FieldType.Cpf:
|
|
179
|
+
case schema_builder_1.FieldType.Cnpj:
|
|
180
|
+
case schema_builder_1.FieldType.CpfCnpj:
|
|
181
|
+
case schema_builder_1.FieldType.Phone:
|
|
182
|
+
qb.andWhere(`e.${index} ILIKE :${index}`, { [index]: `%${value}%` });
|
|
183
|
+
break;
|
|
184
|
+
case schema_builder_1.FieldType.Bool:
|
|
185
|
+
case schema_builder_1.FieldType.Icon:
|
|
186
|
+
qb.andWhere(`e.${index} = :${index}`, { [index]: value });
|
|
187
|
+
break;
|
|
188
|
+
case schema_builder_1.FieldType.UUID:
|
|
189
|
+
qb.andWhere(`e.${index} = :${index}`, { [index]: value });
|
|
190
|
+
break;
|
|
191
|
+
case schema_builder_1.FieldType.Select:
|
|
192
|
+
qb.andWhere(`e.${index} = :${index}`, { [index]: value });
|
|
193
|
+
break;
|
|
194
|
+
case schema_builder_1.FieldType.Currency:
|
|
195
|
+
case schema_builder_1.FieldType.Decimal:
|
|
196
|
+
case schema_builder_1.FieldType.Number:
|
|
197
|
+
case schema_builder_1.FieldType.Time:
|
|
198
|
+
if (!Array.isArray(value) || value.length !== 2) {
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
let min = value[0] ?? null;
|
|
202
|
+
let max = value[1] ?? null;
|
|
203
|
+
if (min != null) {
|
|
204
|
+
qb.andWhere(`e.${index} >= :${index}_min`, { [`${index}_min`]: min });
|
|
205
|
+
}
|
|
206
|
+
if (max != null) {
|
|
207
|
+
qb.andWhere(`e.${index} <= :${index}_max`, { [`${index}_max`]: max });
|
|
208
|
+
}
|
|
209
|
+
break;
|
|
210
|
+
case schema_builder_1.FieldType.Date:
|
|
211
|
+
case schema_builder_1.FieldType.DateTime: {
|
|
212
|
+
if (!Array.isArray(value) || value.length !== 2) {
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
let min = value[0] ?? null;
|
|
216
|
+
let max = value[1] ?? null;
|
|
217
|
+
if (min != null) {
|
|
218
|
+
qb.andWhere(`e.${index} >= :${index}_min`, { [`${index}_min`]: min });
|
|
219
|
+
}
|
|
220
|
+
if (max != null) {
|
|
221
|
+
qb.andWhere(`e.${index} <= :${index}_max`, { [`${index}_max`]: max });
|
|
222
|
+
}
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (query?.trim()) {
|
|
228
|
+
const searchableFields = Object.entries(this.indexSchema)
|
|
229
|
+
.filter(([key, { type }]) => {
|
|
230
|
+
return ([
|
|
231
|
+
schema_builder_1.FieldType.String,
|
|
232
|
+
schema_builder_1.FieldType.TextArea,
|
|
233
|
+
schema_builder_1.FieldType.Cpf,
|
|
234
|
+
schema_builder_1.FieldType.Cnpj,
|
|
235
|
+
schema_builder_1.FieldType.CpfCnpj,
|
|
236
|
+
schema_builder_1.FieldType.Phone,
|
|
237
|
+
].includes(type) && this.repository.metadata.columns.some((c) => c.propertyName === key));
|
|
238
|
+
})
|
|
239
|
+
.map(([key]) => key);
|
|
240
|
+
if (searchableFields.length) {
|
|
241
|
+
qb.andWhere(`(${searchableFields.map((key) => `e.${key} ILIKE :query`).join(' OR ')})`, {
|
|
242
|
+
query: `%${query.trim()}%`,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Executado antes de executar a query de indexação, permitindo customizar o query builder (ex: adicionar joins, filtros complexos).
|
|
249
|
+
* Override para adicionar lógica customizada.
|
|
250
|
+
* @param qb Query builder da entidade.
|
|
251
|
+
* @param params DTO com os parâmetros de indexação.
|
|
252
|
+
*/
|
|
253
|
+
async beforeIndex(_query, _params) { }
|
|
254
|
+
/**
|
|
255
|
+
* Busca um registro pelo UUID. Override para customizar a busca (ex: adicionar joins).
|
|
256
|
+
* @param uuid UUID do registro.
|
|
257
|
+
* @param manager EntityManager opcional para usar na transação.
|
|
258
|
+
* @returns Promise<T> com o registro encontrado.
|
|
259
|
+
*/
|
|
260
|
+
async find(uuid, manager) {
|
|
261
|
+
return this.repository.use(manager).findOneOrFail({
|
|
262
|
+
where: { uuid },
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Atualiza um registro pelo UUID, aplicando os dados do DTO informado. Override para customizar a atualização (ex: adicionar lógica de negócio).
|
|
267
|
+
* @param uuid UUID do registro.
|
|
268
|
+
* @param patchDto DTO com os dados para atualizar o registro.
|
|
269
|
+
* @param manager EntityManager opcional para usar na transação.
|
|
270
|
+
* @returns Promise<T> com o registro atualizado.
|
|
271
|
+
*/
|
|
272
|
+
async patch(uuid, patchDto, manager) {
|
|
273
|
+
const model = await this.repository.use(manager).findOneOrFail({
|
|
274
|
+
where: { uuid },
|
|
275
|
+
});
|
|
276
|
+
const { uploaded, replaced } = await this.uploadFiles(patchDto, model);
|
|
277
|
+
Object.assign(model, patchDto);
|
|
278
|
+
let saved;
|
|
279
|
+
try {
|
|
280
|
+
saved = await this.repository.use(manager).save(model);
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
await this.deleteFiles(uploaded);
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
await this.deleteFiles(replaced);
|
|
287
|
+
return saved;
|
|
288
|
+
}
|
|
289
|
+
// Remove pela entidade, e não por softDelete/delete do uuid: só assim os subscribers recebem a entidade e o entityId
|
|
290
|
+
async remove(uuid, manager) {
|
|
291
|
+
const repo = this.repository.use(manager);
|
|
292
|
+
const model = await repo.findOneOrFail({ where: { uuid } });
|
|
293
|
+
if (this.repository.metadata.deleteDateColumn) {
|
|
294
|
+
await repo.softRemove(model);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
await repo.remove(model);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
exports.SchemaService = SchemaService;
|
|
301
|
+
__decorate([
|
|
302
|
+
(0, common_1.Optional)(),
|
|
303
|
+
(0, common_1.Inject)(storage_service_1.StorageService),
|
|
304
|
+
__metadata("design:type", storage_service_1.StorageService)
|
|
305
|
+
], SchemaService.prototype, "storage", void 0);
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Opções para `cnpj.generate()`. */
|
|
2
|
+
export interface GenerateOptions {
|
|
3
|
+
/** Retorna o CNPJ com máscara `XX.XXX.XXX/XXXX-YY` quando `true`. */
|
|
4
|
+
formatted?: boolean;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Valida um CNPJ verificando tamanho, lista negra, shape dos DVs e os
|
|
8
|
+
* dois dígitos verificadores via Módulo 11.
|
|
9
|
+
*
|
|
10
|
+
* Aceita tanto CNPJs puramente numéricos (formato legado) quanto
|
|
11
|
+
* alfanuméricos (novo formato da Nota Técnica RFB 49/2024 — vigência
|
|
12
|
+
* obrigatória em julho/2026).
|
|
13
|
+
*
|
|
14
|
+
* @param value - CNPJ (cru, formatado ou com lixo, conforme `strict`).
|
|
15
|
+
* @param strict - Se `true`, só aceita máscara canônica ou 14 caracteres
|
|
16
|
+
* `[0-9A-Z]` sem normalização de case.
|
|
17
|
+
* @returns `true` se o CNPJ é válido; `false` caso contrário.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* cnpj.isValid('54.550.752/0001-55') // true
|
|
22
|
+
* cnpj.isValid('54550752000155') // true
|
|
23
|
+
* cnpj.isValid('12ABC34501DE35') // true (novo formato RFB)
|
|
24
|
+
* cnpj.isValid('12.ABC.345/01DE-35') // true
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
declare function isValid(value: string, strict?: boolean): boolean;
|
|
28
|
+
export { isValid as isCnpjValid };
|