@innv/nest-initializer 0.1.0

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 (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +257 -0
  3. package/dist/cjs/core/app-initializer.js +431 -0
  4. package/dist/cjs/core/auto-discovery.helper.js +46 -0
  5. package/dist/cjs/core/config-validator.helper.js +28 -0
  6. package/dist/cjs/core/index.js +17 -0
  7. package/dist/cjs/features/health.controller.js +92 -0
  8. package/dist/cjs/features/index.js +18 -0
  9. package/dist/cjs/features/metrics/metrics.controller.js +41 -0
  10. package/dist/cjs/features/metrics/metrics.interceptor.js +45 -0
  11. package/dist/cjs/features/metrics/metrics.module.js +38 -0
  12. package/dist/cjs/features/metrics/metrics.provider.js +29 -0
  13. package/dist/cjs/features/metrics/metrics.tokens.js +5 -0
  14. package/dist/cjs/features/terminus-health-check.module.js +39 -0
  15. package/dist/cjs/index.js +18 -0
  16. package/dist/cjs/plugins/index.js +19 -0
  17. package/dist/cjs/plugins/rate-limiter.plugin.js +26 -0
  18. package/dist/cjs/plugins/request-logger.plugin.js +13 -0
  19. package/dist/cjs/plugins/typeorm-migration.plugin.js +30 -0
  20. package/dist/cjs/starters/caching.starter.js +27 -0
  21. package/dist/cjs/starters/index.js +19 -0
  22. package/dist/cjs/starters/mongoose.starter.js +24 -0
  23. package/dist/cjs/starters/typeorm.starter.js +31 -0
  24. package/dist/esm/core/app-initializer.js +431 -0
  25. package/dist/esm/core/auto-discovery.helper.js +46 -0
  26. package/dist/esm/core/config-validator.helper.js +28 -0
  27. package/dist/esm/core/index.js +17 -0
  28. package/dist/esm/features/health.controller.js +92 -0
  29. package/dist/esm/features/index.js +18 -0
  30. package/dist/esm/features/metrics/metrics.controller.js +41 -0
  31. package/dist/esm/features/metrics/metrics.interceptor.js +45 -0
  32. package/dist/esm/features/metrics/metrics.module.js +38 -0
  33. package/dist/esm/features/metrics/metrics.provider.js +29 -0
  34. package/dist/esm/features/metrics/metrics.tokens.js +5 -0
  35. package/dist/esm/features/terminus-health-check.module.js +39 -0
  36. package/dist/esm/index.js +18 -0
  37. package/dist/esm/plugins/index.js +19 -0
  38. package/dist/esm/plugins/rate-limiter.plugin.js +26 -0
  39. package/dist/esm/plugins/request-logger.plugin.js +13 -0
  40. package/dist/esm/plugins/typeorm-migration.plugin.js +30 -0
  41. package/dist/esm/starters/caching.starter.js +27 -0
  42. package/dist/esm/starters/index.js +19 -0
  43. package/dist/esm/starters/mongoose.starter.js +24 -0
  44. package/dist/esm/starters/typeorm.starter.js +31 -0
  45. package/dist/types/core/app-initializer.d.ts +206 -0
  46. package/dist/types/core/auto-discovery.helper.d.ts +15 -0
  47. package/dist/types/core/config-validator.helper.d.ts +9 -0
  48. package/dist/types/core/index.d.ts +1 -0
  49. package/dist/types/features/health.controller.d.ts +11 -0
  50. package/dist/types/features/index.d.ts +2 -0
  51. package/dist/types/features/metrics/metrics.controller.d.ts +6 -0
  52. package/dist/types/features/metrics/metrics.interceptor.d.ts +8 -0
  53. package/dist/types/features/metrics/metrics.module.d.ts +4 -0
  54. package/dist/types/features/metrics/metrics.provider.d.ts +2 -0
  55. package/dist/types/features/metrics/metrics.tokens.d.ts +2 -0
  56. package/dist/types/features/terminus-health-check.module.d.ts +11 -0
  57. package/dist/types/index.d.ts +6 -0
  58. package/dist/types/plugins/index.d.ts +3 -0
  59. package/dist/types/plugins/rate-limiter.plugin.d.ts +8 -0
  60. package/dist/types/plugins/request-logger.plugin.d.ts +5 -0
  61. package/dist/types/plugins/typeorm-migration.plugin.d.ts +15 -0
  62. package/dist/types/starters/caching.starter.d.ts +20 -0
  63. package/dist/types/starters/index.d.ts +3 -0
  64. package/dist/types/starters/mongoose.starter.d.ts +24 -0
  65. package/dist/types/starters/typeorm.starter.d.ts +19 -0
  66. package/package.json +159 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Innovare
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,257 @@
1
+ # @innv/nest-initializer 🚀
2
+
3
+ [![NPM Version](https://img.shields.io/npm/v/@innv/nest-initializer?style=flat-square)](https://www.npmjs.com/package/@innv/nest-initializer)
4
+ [![CI Status](https://img.shields.io/github/actions/workflow/status/innovare-tech/nest-initializer/ci.yml?branch=main)](https://github.com/innovare-tech/nest-initializer/actions/workflows/ci.yml)
5
+ [![Test Coverage](https://codecov.io/gh/innovare-tech/nest-initializer/graph/badge.svg?token=AO4URNQ042)](https://codecov.io/gh/innovare-tech/nest-initializer)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)
7
+
8
+ > **Uma plataforma fluente, opinativa e "estilo Spring Boot" para inicializar e configurar suas aplicações NestJS com as melhores práticas.**
9
+
10
+ Diga adeus ao boilerplate repetitivo no `main.ts` e `AppModule`!
11
+ `@innv/nest-initializer` oferece uma **API Builder elegante** para configurar tudo — desde validação de variáveis de ambiente até auto-discovery de componentes e observabilidade pronta para produção.
12
+
13
+ ---
14
+
15
+ ## ✨ Por que usar `@innv/nest-initializer`?
16
+
17
+ - **API Fluente e Declarativa:** Configure sua aplicação de forma encadeada e legível no `main.ts`.
18
+ - **Convenção sobre Configuração:** Starters inteligentes para TypeORM, Mongoose e Cache que se auto-configuram.
19
+ - **Configuração Segura (Fail-Fast):** Valide variáveis de ambiente com `class-validator`. Sem mais erros em runtime!
20
+ - **Auto-Discovery ("Component Scanning"):** Detecta e registra automaticamente `@Injectable()` e `@Controller()`.
21
+ - **Produção Pronta por Padrão:**
22
+ - Presets para desenvolvimento e produção (`useDevelopmentDefaults`, `useProductionDefaults`);
23
+ - Helmet, Compressão, Graceful Shutdown e Métricas Prometheus (`.withMetrics`);
24
+ - Health Checks (`.withHealthCheck`).
25
+ - **Extensível:** Sistema de Plugins (`.withPlugin`) para lógicas customizadas.
26
+ - **Flexível:** Suporte nativo a Express e Fastify.
27
+
28
+ ---
29
+
30
+ ## 📦 Instalação
31
+
32
+ ```bash
33
+ # Com pnpm (recomendado)
34
+ pnpm add @innv/nest-initializer @nestjs/config class-validator class-transformer reflect-metadata
35
+ pnpm add -D @types/compression @types/helmet
36
+
37
+ # Com npm
38
+ npm install @innv/nest-initializer @nestjs/config class-validator class-transformer reflect-metadata
39
+ npm install --save-dev @types/compression @types/helmet
40
+
41
+ # Com yarn
42
+ yarn add @innv/nest-initializer @nestjs/config class-validator class-transformer reflect-metadata
43
+ yarn add --dev @types/compression @types/helmet
44
+ ```
45
+
46
+ > ⚠️ **Importante:**
47
+ > Esta biblioteca utiliza `peerDependencies`.
48
+ > Certifique-se de que seu projeto já possui as dependências principais do NestJS (`@nestjs/common`, `@nestjs/core`, `rxjs`) e as específicas das features que ativar (ex: `@nestjs/typeorm`, `typeorm` se usar `.withTypeOrm()`).
49
+ > Veja o `package.json` para a lista completa.
50
+
51
+ ---
52
+
53
+ ## 🚀 Quick Start (Exemplo Completo)
54
+
55
+ ### 1️⃣ Defina seu Schema de Configuração
56
+ `src/config/env.schema.ts`:
57
+
58
+ ```ts
59
+ import { IsString, IsInt, IsNotEmpty, Min, Max } from 'class-validator';
60
+
61
+ export class EnvironmentVariables {
62
+ @IsInt()
63
+ @Min(1)
64
+ @Max(65535)
65
+ PORT: number = 3000;
66
+
67
+ @IsString()
68
+ @IsNotEmpty()
69
+ DATABASE_URL: string; // Ex: postgresql://user:pass@host:5432/db
70
+
71
+ @IsString()
72
+ @IsNotEmpty()
73
+ REDIS_URL: string; // Ex: redis://localhost:6379
74
+ }
75
+ ```
76
+
77
+ ---
78
+
79
+ ### 2️⃣ Configure seu `main.ts`
80
+
81
+ ```ts
82
+ // src/main.ts
83
+ import 'reflect-metadata';
84
+ import { AppModule } from './app/app.module';
85
+ import { AppInitializer } from '@innv/nest-initializer';
86
+ import { EnvironmentVariables } from './config/env.schema';
87
+ import { VersioningType } from '@nestjs/common';
88
+
89
+ async function bootstrap() {
90
+ const isDevelopment = process.env.NODE_ENV !== 'production';
91
+
92
+ await AppInitializer.bootstrap(AppModule, async (app) => {
93
+ app
94
+ .withValidatedConfig(EnvironmentVariables)
95
+ .withTypeOrm({
96
+ autoLoadEntities: true,
97
+ runMigrationsOnStartup: isDevelopment,
98
+ })
99
+ .withCaching({ defaultTtlInSeconds: 600 })
100
+ .withAutoDiscovery({ basePath: __dirname })
101
+ .withValidationPipe()
102
+ .withClassSerializer()
103
+ .withHealthCheck({ database: true, memory: true })
104
+ .withMetrics()
105
+ .onPort(parseInt(process.env.PORT || '3000', 10))
106
+ .withGlobalPrefix('/api')
107
+ .withVersioning({ type: VersioningType.URI, prefix: 'v' })
108
+ .withCors({ origin: '*' })
109
+
110
+ .when(isDevelopment, (builder) => {
111
+ builder.useDevelopmentDefaults({
112
+ title: 'API (Dev)',
113
+ description: 'Documentação da API',
114
+ version: '1.0.0',
115
+ });
116
+ })
117
+ .when(!isDevelopment, (builder) => {
118
+ builder.useProductionDefaults();
119
+ });
120
+
121
+ // Exemplos extras:
122
+ // .useGlobalGuard(JwtAuthGuard)
123
+ // .withPlugin(new MyCustomPlugin())
124
+ });
125
+ }
126
+
127
+ void bootstrap();
128
+ ```
129
+
130
+ Pronto! Sua aplicação NestJS está configurada com **validação, banco, cache, observabilidade, métricas e auto-discovery** — tudo de forma fluente.
131
+
132
+ ---
133
+
134
+ ## ⚙️ Uso Detalhado
135
+
136
+ ### 🔧 Configuração Core
137
+
138
+ | Método | Descrição |
139
+ |--------|------------|
140
+ | `AppInitializer.bootstrap(AppModule, configurator)` | Ponto de entrada principal. |
141
+ | `onPort(port)` | Define a porta. |
142
+ | `withGlobalPrefix(prefix)` | Prefixo global para rotas. |
143
+ | `withVersioning(options)` | Configura versionamento de API. |
144
+ | `withCors(options)` | Habilita CORS. |
145
+
146
+ ---
147
+
148
+ ### 🧩 Configuração e Validação
149
+
150
+ `withValidatedConfig<T>(schema: Type<T>)`
151
+ Valida `.env` e injeta `ConfigModule` globalmente.
152
+ A aplicação **falha na inicialização** se a validação falhar.
153
+
154
+ ---
155
+
156
+ ### ⚡ Starters (Auto-Configuração)
157
+
158
+ - `withTypeOrm(options)`
159
+ - `withMongoose(options)`
160
+ - `withCaching(options)`
161
+
162
+ Todos configuram seus módulos respectivos (`TypeOrmModule`, `MongooseModule`, `CacheModule`) automaticamente com `ConfigService`.
163
+
164
+ ---
165
+
166
+ ### 🔍 Descoberta de Componentes
167
+
168
+ `withAutoDiscovery({ basePath })`
169
+ Varre o diretório e registra automaticamente:
170
+ - `@Injectable()` como providers
171
+ - `@Controller()` como controllers
172
+
173
+ Ignora `*.module.*`, `*.spec.*`, `node_modules`, `features`, `plugins`.
174
+
175
+ ---
176
+
177
+ ### 🧱 Pipeline Global
178
+
179
+ | Método | Função |
180
+ |--------|--------|
181
+ | `withValidationPipe()` | Registra `ValidationPipe` global. |
182
+ | `useGlobalPipe(pipe)` | Pipe customizado global. |
183
+ | `useGlobalFilter(filter)` | Filtro de exceção global. |
184
+ | `useGlobalGuard(guard)` | Guard global. |
185
+ | `useGlobalInterceptor(interceptor)` | Interceptor global. |
186
+ | `withClassSerializer()` | Ativa `ClassSerializerInterceptor`. |
187
+
188
+ ---
189
+
190
+ ### 🩺 Observabilidade ("Actuator")
191
+
192
+ | Método | Descrição |
193
+ |--------|------------|
194
+ | `withHealthCheck(options)` | Cria endpoint `/health` usando `@nestjs/terminus`. |
195
+ | `withMetrics()` | Cria endpoint `/metrics` no formato Prometheus. |
196
+
197
+ Suporte nativo a métricas HTTP (latência, contadores, etc).
198
+
199
+ ---
200
+
201
+ ### 🧰 Middlewares e Hooks
202
+
203
+ | Método | Ação |
204
+ |--------|------|
205
+ | `withGracefulShutdown()` | Habilita `enableShutdownHooks()`. |
206
+ | `useHelmet()` | Adiciona `helmet()` para segurança. |
207
+ | `enableCompression()` | Adiciona `compression()` para gzip. |
208
+
209
+ ---
210
+
211
+ ### 📘 Swagger (OpenAPI)
212
+
213
+ | Método | Descrição |
214
+ |--------|------------|
215
+ | `withSwagger(options)` | Configura documentação Swagger. |
216
+ | `withAdvancedSwaggerUI()` | Tema escuro e UI aprimorada. |
217
+
218
+ ---
219
+
220
+ ### 🧩 Extensibilidade
221
+
222
+ | Método | Descrição |
223
+ |--------|------------|
224
+ | `withPlugin(plugin)` | Adiciona plugins customizados. |
225
+ | `when(condition, fn)` | Executa blocos condicionais. |
226
+
227
+ ---
228
+
229
+ ### 🪄 Presets
230
+
231
+ | Método | Descrição |
232
+ |--------|------------|
233
+ | `useDevelopmentDefaults(swaggerOptions)` | Atalho para Swagger + Logger. |
234
+ | `useProductionDefaults()` | Atalho para Helmet, Compression, Shutdown e RateLimiter. |
235
+
236
+ ---
237
+
238
+ ## 💡 Filosofia
239
+
240
+ `@innv/nest-initializer` traz a **produtividade e convenções inteligentes do Spring Boot** para o NestJS, mantendo a flexibilidade e o poder da plataforma.
241
+ O foco é **reduzir boilerplate e aumentar a consistência** entre projetos NestJS, permitindo que times foquem no que realmente importa: **a lógica de negócio.**
242
+
243
+ ---
244
+
245
+ ## 🤝 Contribuição
246
+
247
+ Contribuições são bem-vindas!
248
+ Abra uma **Issue** ou **Pull Request** no repositório:
249
+
250
+ 👉 [https://github.com/innovare-tech/nest-initializer](https://github.com/innovare-tech/nest-initializer)
251
+
252
+ ---
253
+
254
+ ## 📜 Licença
255
+
256
+ Distribuído sob a licença **MIT**.
257
+ Veja o arquivo [LICENSE](./LICENSE) para mais informações.