prisma-entity-gen 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.
- package/README.md +368 -0
- package/dist/cli/index.cjs +711 -0
- package/dist/cli/index.cjs.map +1 -0
- package/dist/cli/index.d.cts +1 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +709 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/index.cjs +691 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +209 -0
- package/dist/index.d.ts +209 -0
- package/dist/index.js +680 -0
- package/dist/index.js.map +1 -0
- package/package.json +67 -0
package/README.md
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
# prisma-entity-gen
|
|
2
|
+
|
|
3
|
+
Gerador de entities TypeScript a partir do `schema.prisma` via AST.
|
|
4
|
+
|
|
5
|
+
Resolve o problema de lentidão do TypeScript em projetos com muitos modelos Prisma — cada model é gerado em um arquivo isolado com tipos explícitos, eliminando a inferência pesada do `@prisma/client`.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Instalação
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install -D prisma-entity-gen
|
|
13
|
+
# ou
|
|
14
|
+
pnpm add -D prisma-entity-gen
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Uso rápido
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npx prisma-entity-gen
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Por padrão lê `prisma/schema.prisma` e gera em `src/entities`.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Configuração
|
|
30
|
+
|
|
31
|
+
Crie um `.entitygenrc.json` na raiz do projeto:
|
|
32
|
+
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"schemaPath": "prisma/schema.prisma",
|
|
36
|
+
"outputDir": "src/entities",
|
|
37
|
+
"mode": "type",
|
|
38
|
+
"relations": "optional",
|
|
39
|
+
"enumOutput": "enum",
|
|
40
|
+
"barrel": true,
|
|
41
|
+
"suffix": "entity",
|
|
42
|
+
"exclude": [],
|
|
43
|
+
"include": [],
|
|
44
|
+
"classValidator": false,
|
|
45
|
+
"classTransformer": false,
|
|
46
|
+
"dryRun": false,
|
|
47
|
+
"logLevel": "info"
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## Opções de configuração
|
|
54
|
+
|
|
55
|
+
### `schemaPath`
|
|
56
|
+
**Tipo:** `string` — **Padrão:** `"prisma/schema.prisma"`
|
|
57
|
+
|
|
58
|
+
Caminho para o arquivo `schema.prisma`. Aceita caminhos relativos e absolutos.
|
|
59
|
+
|
|
60
|
+
Se seu projeto usa Prisma multi-file schema, aponte para o schema consolidado:
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"schemaPath": "node_modules/.prisma/client/schema.prisma"
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
### `outputDir`
|
|
71
|
+
**Tipo:** `string` — **Padrão:** `"src/entities"`
|
|
72
|
+
|
|
73
|
+
Diretório onde os arquivos de entity serão gerados. Criado automaticamente se não existir.
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
### `mode`
|
|
78
|
+
**Tipo:** `"type" | "class" | "both"` — **Padrão:** `"type"`
|
|
79
|
+
|
|
80
|
+
Define o formato de saída das entities.
|
|
81
|
+
|
|
82
|
+
| Valor | Saída | Uso indicado |
|
|
83
|
+
|---|---|---|
|
|
84
|
+
| `"type"` | `export interface UserEntity` | Projetos TypeScript puros, melhor performance de compilação |
|
|
85
|
+
| `"class"` | `export class UserEntity` | NestJS com `class-validator` / `class-transformer` |
|
|
86
|
+
| `"both"` | Ambos em subpastas `/types` e `/classes` | Projetos que precisam dos dois formatos |
|
|
87
|
+
|
|
88
|
+
```json
|
|
89
|
+
{ "mode": "class" }
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
### `relations`
|
|
95
|
+
**Tipo:** `"optional" | "required"` — **Padrão:** `"optional"`
|
|
96
|
+
|
|
97
|
+
Controla se campos de relação são opcionais ou obrigatórios na entity gerada.
|
|
98
|
+
|
|
99
|
+
| Valor | Comportamento | Quando usar |
|
|
100
|
+
|---|---|---|
|
|
101
|
+
| `"optional"` | `Company?: CompanyEntity` | Queries sem `include` — o campo pode não existir |
|
|
102
|
+
| `"required"` | `Company: CompanyEntity` | Sempre usa `include` nas queries que retornam o tipo |
|
|
103
|
+
|
|
104
|
+
**`"optional"` (padrão):**
|
|
105
|
+
```ts
|
|
106
|
+
export interface UserEntity {
|
|
107
|
+
id: bigint;
|
|
108
|
+
Company?: CompanyEntity; // só existe se vier com include
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// funciona sem include
|
|
112
|
+
const user = await prisma.user.findUnique({ where: { id } });
|
|
113
|
+
// user.Company → undefined (sem erro de tipo)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
**`"required"`:**
|
|
117
|
+
```ts
|
|
118
|
+
export interface UserEntity {
|
|
119
|
+
id: bigint;
|
|
120
|
+
Company: CompanyEntity; // sempre obrigatório
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// requer include em toda query que retornar UserEntity
|
|
124
|
+
const user = await prisma.user.findUnique({
|
|
125
|
+
where: { id },
|
|
126
|
+
include: { Company: true },
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
```json
|
|
131
|
+
{ "relations": "required" }
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
### `enumOutput`
|
|
137
|
+
**Tipo:** `"enum" | "union"` — **Padrão:** `"enum"`
|
|
138
|
+
|
|
139
|
+
Define o formato de saída dos enums.
|
|
140
|
+
|
|
141
|
+
| Valor | Saída |
|
|
142
|
+
|---|---|
|
|
143
|
+
| `"enum"` | `export enum Role { ADMIN = "ADMIN" }` |
|
|
144
|
+
| `"union"` | `export type Role = "ADMIN" \| "USER"` |
|
|
145
|
+
|
|
146
|
+
Use `"union"` para evitar conflitos de tipo nominal com enums gerados pelo `@prisma/client`.
|
|
147
|
+
Enums são nominais no TypeScript — dois enums com o mesmo nome e valores são tipos incompatíveis.
|
|
148
|
+
`union` usa tipagem estrutural, aceitando qualquer string que corresponda ao valor.
|
|
149
|
+
|
|
150
|
+
```json
|
|
151
|
+
{ "enumOutput": "union" }
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
---
|
|
155
|
+
|
|
156
|
+
### `barrel`
|
|
157
|
+
**Tipo:** `boolean` — **Padrão:** `true`
|
|
158
|
+
|
|
159
|
+
Gera um arquivo `index.ts` na raiz do `outputDir` que re-exporta todas as entities.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
// src/entities/index.ts — gerado automaticamente
|
|
163
|
+
export * from "./user.entity.js";
|
|
164
|
+
export * from "./post.entity.js";
|
|
165
|
+
export * from "./role.enum.js";
|
|
166
|
+
// ...
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Permite imports limpos no projeto:
|
|
170
|
+
```ts
|
|
171
|
+
import { UserEntity, PostEntity } from '@/entities';
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
### `suffix`
|
|
177
|
+
**Tipo:** `string` — **Padrão:** `"entity"`
|
|
178
|
+
|
|
179
|
+
Sufixo dos arquivos gerados. O nome do model é convertido para kebab-case.
|
|
180
|
+
|
|
181
|
+
```json
|
|
182
|
+
{ "suffix": "entity" }
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Resulta em: `user.entity.ts`, `post.entity.ts`, etc.
|
|
186
|
+
|
|
187
|
+
---
|
|
188
|
+
|
|
189
|
+
### `exclude`
|
|
190
|
+
**Tipo:** `string[]` — **Padrão:** `[]`
|
|
191
|
+
|
|
192
|
+
Lista de models a ignorar na geração. Útil para models internos ou de auditoria.
|
|
193
|
+
|
|
194
|
+
```json
|
|
195
|
+
{ "exclude": ["AuditLog", "Session", "MigrationHistory"] }
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
---
|
|
199
|
+
|
|
200
|
+
### `include`
|
|
201
|
+
**Tipo:** `string[]` — **Padrão:** `[]` (todos)
|
|
202
|
+
|
|
203
|
+
Quando preenchido, gera apenas os models listados. Ignora todos os outros.
|
|
204
|
+
|
|
205
|
+
```json
|
|
206
|
+
{ "include": ["User", "Post", "Company"] }
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
### `classValidator`
|
|
212
|
+
**Tipo:** `boolean` — **Padrão:** `false`
|
|
213
|
+
|
|
214
|
+
Quando `mode` é `"class"` ou `"both"`, adiciona decorators do `class-validator`.
|
|
215
|
+
|
|
216
|
+
Requer instalação: `npm install class-validator`
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
// gerado com classValidator: true
|
|
220
|
+
import { IsString, IsOptional, IsDate } from 'class-validator';
|
|
221
|
+
|
|
222
|
+
export class UserEntity {
|
|
223
|
+
@IsString()
|
|
224
|
+
email!: string;
|
|
225
|
+
|
|
226
|
+
@IsOptional()
|
|
227
|
+
@IsString()
|
|
228
|
+
name?: string | null;
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
---
|
|
233
|
+
|
|
234
|
+
### `classTransformer`
|
|
235
|
+
**Tipo:** `boolean` — **Padrão:** `false`
|
|
236
|
+
|
|
237
|
+
Quando `mode` é `"class"` ou `"both"`, adiciona decorators do `class-transformer`.
|
|
238
|
+
|
|
239
|
+
Requer instalação: `npm install class-transformer`
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
// gerado com classTransformer: true
|
|
243
|
+
import { Type } from 'class-transformer';
|
|
244
|
+
|
|
245
|
+
export class UserEntity {
|
|
246
|
+
@Type(() => PostEntity)
|
|
247
|
+
posts?: PostEntity[];
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
---
|
|
252
|
+
|
|
253
|
+
### `dryRun`
|
|
254
|
+
**Tipo:** `boolean` — **Padrão:** `false`
|
|
255
|
+
|
|
256
|
+
Simula a geração sem escrever arquivos no disco. Útil para visualizar o que seria gerado.
|
|
257
|
+
|
|
258
|
+
```bash
|
|
259
|
+
npx prisma-entity-gen --dry-run
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
---
|
|
263
|
+
|
|
264
|
+
### `logLevel`
|
|
265
|
+
**Tipo:** `"silent" | "info" | "verbose"` — **Padrão:** `"info"`
|
|
266
|
+
|
|
267
|
+
| Valor | Comportamento |
|
|
268
|
+
|---|---|
|
|
269
|
+
| `"silent"` | Sem output |
|
|
270
|
+
| `"info"` | Mostra arquivos gerados e resumo |
|
|
271
|
+
| `"verbose"` | Mostra detalhes de cada etapa |
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
|
|
275
|
+
## Flags CLI
|
|
276
|
+
|
|
277
|
+
Todas as opções do `.entitygenrc.json` podem ser passadas via CLI. Flags sobrescrevem o arquivo de configuração.
|
|
278
|
+
|
|
279
|
+
```bash
|
|
280
|
+
npx prisma-entity-gen [opções]
|
|
281
|
+
|
|
282
|
+
Opções:
|
|
283
|
+
-s, --schema <path> Caminho para o schema.prisma
|
|
284
|
+
-o, --output <dir> Diretório de saída
|
|
285
|
+
-m, --mode <mode> type | class | both
|
|
286
|
+
--relations <mode> optional | required
|
|
287
|
+
--enum-output <format> enum | union
|
|
288
|
+
--dry-run Simula sem escrever arquivos
|
|
289
|
+
--log-level <level> silent | info | verbose
|
|
290
|
+
-V, --version Exibe a versão
|
|
291
|
+
-h, --help Exibe ajuda
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
---
|
|
295
|
+
|
|
296
|
+
## Integração com Prisma generate
|
|
297
|
+
|
|
298
|
+
Adicione no `package.json` para rodar automaticamente após `prisma generate`:
|
|
299
|
+
|
|
300
|
+
```json
|
|
301
|
+
{
|
|
302
|
+
"scripts": {
|
|
303
|
+
"generate": "prisma generate && prisma-entity-gen"
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
---
|
|
309
|
+
|
|
310
|
+
## Uso com BaseRepository
|
|
311
|
+
|
|
312
|
+
A lib gera apenas as entities. O `BaseRepository` do seu projeto usa o `T` genérico:
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
// antes — tipo do Prisma
|
|
316
|
+
export class UserRepository extends BaseRepository<User> {}
|
|
317
|
+
|
|
318
|
+
// depois — entity gerada
|
|
319
|
+
export class UserRepository extends BaseRepository<UserEntity> {}
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
Os métodos do `BaseRepository` continuam funcionando com `Partial<T>` nos filtros:
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
// where tipado pela entity
|
|
326
|
+
const users = await userRepository.findMany({ email: 'test@test.com' });
|
|
327
|
+
// → UserEntity[]
|
|
328
|
+
|
|
329
|
+
const user = await userRepository.getById(id);
|
|
330
|
+
// → UserEntity
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
---
|
|
334
|
+
|
|
335
|
+
## Comportamento dos tipos
|
|
336
|
+
|
|
337
|
+
| Campo no schema | Entity gerada |
|
|
338
|
+
|---|---|
|
|
339
|
+
| `field String` | `field: string` |
|
|
340
|
+
| `field String?` | `field?: string \| null` |
|
|
341
|
+
| `field String @default(...)` | `field: string` |
|
|
342
|
+
| `field Model` (relação) com `relations: "optional"` | `field?: ModelEntity` |
|
|
343
|
+
| `field Model` (relação) com `relations: "required"` | `field: ModelEntity` |
|
|
344
|
+
| `field Model?` (relação opcional) | `field?: ModelEntity \| null` |
|
|
345
|
+
|
|
346
|
+
### Tipos escalares Prisma → TypeScript
|
|
347
|
+
|
|
348
|
+
| Prisma | TypeScript |
|
|
349
|
+
|---|---|
|
|
350
|
+
| `String` | `string` |
|
|
351
|
+
| `Boolean` | `boolean` |
|
|
352
|
+
| `Int` | `number` |
|
|
353
|
+
| `Float` | `number` |
|
|
354
|
+
| `BigInt` | `bigint` |
|
|
355
|
+
| `Decimal` | `string` |
|
|
356
|
+
| `DateTime` | `Date` |
|
|
357
|
+
| `Json` | `Record<string, unknown>` |
|
|
358
|
+
| `Bytes` | `Buffer` |
|
|
359
|
+
|
|
360
|
+
---
|
|
361
|
+
|
|
362
|
+
## Arquivos de configuração suportados
|
|
363
|
+
|
|
364
|
+
O gerador procura por arquivos de configuração nesta ordem:
|
|
365
|
+
|
|
366
|
+
1. `.entitygenrc.json`
|
|
367
|
+
2. `entitygen.config.json`
|
|
368
|
+
3. `.entitygenrc`
|