@cristian-israel/giganet_lib_conecta 1.0.1
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/LICENSE +21 -0
- package/README.md +318 -0
- package/dist/index.d.mts +34259 -0
- package/dist/index.d.ts +34259 -0
- package/dist/index.js +90459 -0
- package/dist/index.mjs +90420 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cristian Israel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
Perfeito! Aqui está a documentação atualizada, removendo completamente qualquer referência a `relations.ts` e refletindo que as relações agora são aplicadas automaticamente no `initModels` gerado pelo `sequelize-auto` ou no Service:
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# 📚 Documentação Atualizada — Lib de Conexões (MySQL + Mongo + IXC)
|
|
6
|
+
|
|
7
|
+
## 🎯 Objetivo
|
|
8
|
+
|
|
9
|
+
Criar uma biblioteca desacoplada, escalável e tipada para:
|
|
10
|
+
|
|
11
|
+
- Conexões com bancos MySQL e MongoDB
|
|
12
|
+
- Reuso entre projetos
|
|
13
|
+
- Padronização com logger
|
|
14
|
+
- Estrutura modular e evolutiva
|
|
15
|
+
- Singleton + Service pattern para acesso a dados
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
# 🧱 Estrutura Geral
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
/core
|
|
23
|
+
├── mysql.connection.ts
|
|
24
|
+
├── mongo.connection.ts
|
|
25
|
+
├── database.factory.ts
|
|
26
|
+
├── logger.ts
|
|
27
|
+
├── retry.ts
|
|
28
|
+
├── types.ts
|
|
29
|
+
|
|
30
|
+
/databases
|
|
31
|
+
└── ixc-soft
|
|
32
|
+
├── ixc-soft.service.ts
|
|
33
|
+
├── ixc-soft.connection.ts
|
|
34
|
+
├── ixc-soft.types.ts
|
|
35
|
+
└── models/
|
|
36
|
+
└── init-models.ts (gerado via sequelize-auto)
|
|
37
|
+
|
|
38
|
+
/index.ts
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
# ✅ 1. Conexões Base
|
|
44
|
+
|
|
45
|
+
## 1.1 MySQL Connection
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
createMysqlConnection(config: MysqlConfig): Promise<Sequelize>
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- Validação de dados
|
|
52
|
+
- Logger padronizado
|
|
53
|
+
- Tratamento de erro
|
|
54
|
+
- Timeout / timezone
|
|
55
|
+
- Retorna instância Sequelize
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## 1.2 Mongo Connection
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
createMongoConnection(config: MongoConfig): Promise<Connection>
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- URI dinâmica
|
|
66
|
+
- Suporte a authSource
|
|
67
|
+
- Logger
|
|
68
|
+
- Tratamento de erro
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
# ✅ 2. Retry Pattern (Resiliência)
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
retry(fn, { retries: number, delay: number, onRetry?: (error, attempt) => void })
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
- Evita falha por instabilidade temporária
|
|
79
|
+
- Reutilizável
|
|
80
|
+
- Centralizado
|
|
81
|
+
|
|
82
|
+
Exemplo com Mongo:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
const conn = await retry(async () => {
|
|
86
|
+
const connection = createConnection(uri);
|
|
87
|
+
return await new Promise((resolve, reject) => {
|
|
88
|
+
connection.once("connected", () => resolve(connection));
|
|
89
|
+
connection.once("error", reject);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
# ✅ 3. Factory de Conexões
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
createConnectionFactory(factoryFn);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
- Singleton automático
|
|
103
|
+
- Evita múltiplas instâncias
|
|
104
|
+
- Centraliza criação de conexões
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
# ✅ 4. Logger
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
logger({
|
|
112
|
+
level?: "INFO" | "WARN" | "ERROR",
|
|
113
|
+
database: "MYSQL" | "MONGO",
|
|
114
|
+
context: string,
|
|
115
|
+
message: string
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
- Padronização
|
|
120
|
+
- Observabilidade
|
|
121
|
+
- Fácil debug
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
# ✅ 5. Tipos Base
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
type MysqlConfig
|
|
129
|
+
type MongoConfig
|
|
130
|
+
type ConfigCreationConnection
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
- Tipagem das entradas
|
|
134
|
+
- Segurança
|
|
135
|
+
- Reuso
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
# ✅ 6. Implementação IXC (MySQL)
|
|
140
|
+
|
|
141
|
+
## 6.1 Estrutura da conexão IXC
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
async function createIXCConnection(): Promise<IXCSoftConnection>;
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Fluxo:
|
|
148
|
+
|
|
149
|
+
1. Cria conexão MySQL via `createMysqlConnection`
|
|
150
|
+
2. Inicializa models gerados via `sequelize-auto` (`initModels`)
|
|
151
|
+
3. Retorna conexão tipada (`IXCSoftConnection`)
|
|
152
|
+
|
|
153
|
+
> Relações são aplicadas dentro de `initModels` automaticamente; **não há mais arquivo separado de relations**.
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## 6.2 Tipagem dos Models (forte)
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
export class IXCSoftCliente extends Model<
|
|
161
|
+
InferAttributes<IXCSoftCliente>,
|
|
162
|
+
InferCreationAttributes<IXCSoftCliente>
|
|
163
|
+
> {
|
|
164
|
+
declare id: CreationOptional<number>;
|
|
165
|
+
declare razao: string;
|
|
166
|
+
declare fantasia: string | null;
|
|
167
|
+
declare ativo: string;
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
- Autocomplete real
|
|
172
|
+
- Segurança no `create`/`update`
|
|
173
|
+
- Menos bugs
|
|
174
|
+
- Tipagem apenas dos campos relevantes
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## 6.3 Geração automática de Models
|
|
179
|
+
|
|
180
|
+
### Ferramenta:
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
sequelize-auto
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### Comando Exemplo:
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
npx sequelize-auto \
|
|
190
|
+
-h HOST \
|
|
191
|
+
-d DATABASE \
|
|
192
|
+
-u USER \
|
|
193
|
+
-p PORT \
|
|
194
|
+
-x PASSWORD \
|
|
195
|
+
-e mysql \
|
|
196
|
+
-o "./src/databases/ixc-soft/models" \
|
|
197
|
+
--lang ts
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
- Não editar arquivos gerados
|
|
201
|
+
- Sempre regenerar quando schema mudar
|
|
202
|
+
- Estrutura final acessível via `initModels(sequelize)`
|
|
203
|
+
|
|
204
|
+
---
|
|
205
|
+
|
|
206
|
+
# ✅ 7. Service Pattern (Singleton + acesso aos models)
|
|
207
|
+
|
|
208
|
+
## 7.1 IXCSoftService
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
const ixcs = IXCSoftService.getInstance();
|
|
212
|
+
await ixcs.init();
|
|
213
|
+
const { Cliente, ClienteContrato } = ixcs.models;
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### Principais decisões:
|
|
217
|
+
|
|
218
|
+
1. **Singleton**: garante uma única instância por app
|
|
219
|
+
2. **Init obrigatório**: chama `ixcs.init()` antes de usar os models
|
|
220
|
+
3. **Models tipados**: `ixcs.models` retorna apenas os models do IXC
|
|
221
|
+
4. **Static vs Getter**:
|
|
222
|
+
- `ixcs.models` (getter) → uso normal por instância
|
|
223
|
+
- `IXCSoftService.getModels()` → conveniência estática (chama o singleton internamente)
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
### 7.2 Vantagens do Service
|
|
228
|
+
|
|
229
|
+
- Protege acesso direto à connection
|
|
230
|
+
- Abstrai inicialização e relações
|
|
231
|
+
- Permite apenas usar models e fazer queries
|
|
232
|
+
- Facilita testes e refatorações futuras
|
|
233
|
+
|
|
234
|
+
---
|
|
235
|
+
|
|
236
|
+
# ✅ 8. Uso da lib no projeto
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
import { IXCSoftService } from "giganet_conecta";
|
|
240
|
+
|
|
241
|
+
async function main() {
|
|
242
|
+
const ixcs = IXCSoftService.getInstance();
|
|
243
|
+
await ixcs.init();
|
|
244
|
+
|
|
245
|
+
const { Cliente, ClienteContrato } = ixcs.models;
|
|
246
|
+
|
|
247
|
+
const clientesAtivos = await Cliente.findAll({ where: { ativo: "S" } });
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
- Não é necessário instanciar `connection` manualmente
|
|
252
|
+
- O Service controla inicialização e singleton
|
|
253
|
+
- Queries podem ser feitas diretamente nos models
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
# ✅ 9. Exportação da lib
|
|
258
|
+
|
|
259
|
+
**Index da lib (`src/index.ts`)**:
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
export { IXCSoftService } from "./databases/ixc-soft/ixc-soft.service";
|
|
263
|
+
export { OPAService } from "./databases/opa-suite/opa.service";
|
|
264
|
+
// outros services que quiser expor
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
- Expor apenas Services
|
|
268
|
+
- Conexões internas (`connection`, `initModels`) ficam encapsuladas
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
272
|
+
# 🧠 Arquitetura Atualizada (até 3.4)
|
|
273
|
+
|
|
274
|
+
```
|
|
275
|
+
core/
|
|
276
|
+
conexão + retry + logger
|
|
277
|
+
|
|
278
|
+
databases/
|
|
279
|
+
ixc-soft/
|
|
280
|
+
service.ts (singleton + init + models)
|
|
281
|
+
connection.ts (interna)
|
|
282
|
+
types.ts
|
|
283
|
+
models/ (gerados via sequelize-auto, com relations aplicadas)
|
|
284
|
+
|
|
285
|
+
index.ts
|
|
286
|
+
└── exporta apenas services
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
---
|
|
290
|
+
|
|
291
|
+
# 📍 Status Atual
|
|
292
|
+
|
|
293
|
+
| Etapa | Status |
|
|
294
|
+
| ------------------------ | ------------------------------------------- |
|
|
295
|
+
| 1 — Conexões base | ✅ Concluído |
|
|
296
|
+
| 2 — Retry pattern | ✅ Concluído |
|
|
297
|
+
| 3.1 — Estrutura IXC | ✅ Concluído |
|
|
298
|
+
| 3.2 — Relations | ❌ Removido (agora integrado no initModels) |
|
|
299
|
+
| 3.3 — Tipagem Models | ✅ Concluído |
|
|
300
|
+
| 3.3.2 — Auto geração | ✅ Definido |
|
|
301
|
+
| 3.4 — Service + Includes | ✅ Definido |
|
|
302
|
+
|
|
303
|
+
---
|
|
304
|
+
|
|
305
|
+
# ⚡ Conclusão
|
|
306
|
+
|
|
307
|
+
- Lib modular, escalável e tipada
|
|
308
|
+
- Singleton + Service pattern protege inicialização
|
|
309
|
+
- Geração automática de models via `sequelize-auto`
|
|
310
|
+
- Queries podem ser feitas diretamente nos Services
|
|
311
|
+
- Relações aplicadas automaticamente nos models
|
|
312
|
+
- Base pronta para produção e fácil manutenção
|
|
313
|
+
|
|
314
|
+
---
|
|
315
|
+
|
|
316
|
+
Se quiser, posso complementar a documentação com **exemplos práticos de queries tipadas com includes**, mostrando como usar `cliente.contratos` com autocomplete seguro e filtros avançados.
|
|
317
|
+
|
|
318
|
+
Quer que eu faça isso agora?
|