vsrepo 1.2.4 → 1.2.6
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
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|

|
|
4
4
|

|
|
5
|
-

|
|
6
6
|
|
|
7
7
|
Biblioteca de repository pattern para projetos que usam **Prisma**, com suporte completo a **TypeScript** e **type inference** automático.
|
|
8
8
|
|
|
@@ -362,7 +362,7 @@ usuarioVSRepo.build(prisma, {
|
|
|
362
362
|
ignoreRequiredWhere: false, // Aplica o requiredWhere no remove (padrão = false)
|
|
363
363
|
},
|
|
364
364
|
save: {
|
|
365
|
-
ignoreRequiredWhere: true, // Não aplica requiredWhere no save
|
|
365
|
+
ignoreRequiredWhere: true, // Não aplica requiredWhere no upsert do save
|
|
366
366
|
},
|
|
367
367
|
patch: {
|
|
368
368
|
defaultSelect: "minimal",
|
|
@@ -433,10 +433,10 @@ Métodos dinâmicos são definidos na propriedade `methods` e têm seus comporta
|
|
|
433
433
|
|
|
434
434
|
```ts
|
|
435
435
|
methods: {
|
|
436
|
-
|
|
437
|
-
findManyPaginated:
|
|
438
|
-
updateById:
|
|
439
|
-
deleteManyByIdIn:
|
|
436
|
+
findOneByEmail: { map: true },
|
|
437
|
+
findManyPaginated: { map: true },
|
|
438
|
+
updateById: { map: true },
|
|
439
|
+
deleteManyByIdIn: { map: true },
|
|
440
440
|
}
|
|
441
441
|
```
|
|
442
442
|
|
|
@@ -448,7 +448,8 @@ O prefixo do nome do método determina qual operação Prisma será chamada e qu
|
|
|
448
448
|
|
|
449
449
|
| Prefixo | Operação Prisma | Retorno | Observações |
|
|
450
450
|
| ------------------------- | ------------------------ | ---------------------- | -------------------------------------------------------- |
|
|
451
|
-
| `findBy` | `findMany` / `findFirst` | `T[]` ou `T \| null` | Padrão é lista; use `fbMode: "one"` para retorno único
|
|
451
|
+
| `findBy` | `findMany` / `findFirst` | `T[]` ou `T \| null` | Padrão é lista; use `fbMode: "one"` (obsoleto, use `findOneBy`) para retorno único |
|
|
452
|
+
| `findOneBy` | `findFirst` | `T \| null` | Faz o mesmo que `findBy` com `fbMode: "one"`. Retorno único. |
|
|
452
453
|
| `findUniqueBy` | `findUnique` | `T \| null` | |
|
|
453
454
|
| `findUniqueOrThrowBy` | `findUniqueOrThrow` | `T` | Lança erro se não encontrar |
|
|
454
455
|
| `findFirstBy` | `findFirst` | `T \| null` | Aceita campos como filtro |
|
|
@@ -457,9 +458,11 @@ O prefixo do nome do método determina qual operação Prisma será chamada e qu
|
|
|
457
458
|
| `findFirstOrThrow` | `findFirstOrThrow` | `T` | Sem filtros de campo; aplica só `requiredWhere` e `pushWhere`; lança erro se não encontrar |
|
|
458
459
|
| `findManyBy` | `findMany` | `T[]` | Aceita campos como filtro |
|
|
459
460
|
| `findMany` | `findMany` | `T[]` | Sem filtros de campo; aplica só `requiredWhere` e `pushWhere` |
|
|
460
|
-
| `findWhere` | `findFirst` | `T \| null` | Recebe um objeto `where` explícito como argumento
|
|
461
|
+
| `findWhere` | `findFirst` | `T \| null` | (**Obsoleto, use `findOneWhere`**) Recebe um objeto `where` explícito como argumento |
|
|
462
|
+
| `findOneWhere` | `findFirst` | `T \| null` | Recebe um objeto `where` explícito como argumento |
|
|
461
463
|
| `findListWhere` | `findMany` | `T[]` | Recebe um objeto `where` explícito como argumento |
|
|
462
464
|
| `existsBy` | `findFirst` | `boolean` | Retorna `true` se encontrar, `false` caso contrário |
|
|
465
|
+
| `existsWhere` | `findFirst` | `boolean` | Recebe um objeto `where` explícito como argumento e retorna se existe |
|
|
463
466
|
| `countBy` | `count` | `number` | Aceita campos como filtro |
|
|
464
467
|
| `countWhere` | `count` | `number` | Recebe um objeto `where` explícito como argumento |
|
|
465
468
|
| `count` | `count` | `number` | Sem filtros de campo; aplica só `requiredWhere` e `pushWhere` |
|
|
@@ -468,10 +471,13 @@ O prefixo do nome do método determina qual operação Prisma será chamada e qu
|
|
|
468
471
|
| `createManyAndReturn` | `createManyAndReturn` | `T[]` | Recebe `data` como argumento; suporta `SkipDuplicates` |
|
|
469
472
|
| `updateBy` | `update` | `T` | Recebe `data` como argumento |
|
|
470
473
|
| `updateManyBy` | `updateMany` | `{ count: number }` | Recebe `data` como argumento |
|
|
474
|
+
| `updateManyWhere` | `updateMany` | `{ count: number }` | Recebe um objeto `where` e um objeto `data` como argumentos |
|
|
471
475
|
| `updateManyAndReturnBy` | `updateManyAndReturn` | `T[]` | Recebe `data` como argumento |
|
|
476
|
+
| `updateManyAndReturnWhere` | `updateManyAndReturn` | `T[]` | Recebe um objeto `where` e um objeto `data` como argumentos |
|
|
472
477
|
| `upsertBy` | `upsert` | `T` | Recebe `update` e `create` como argumentos |
|
|
473
478
|
| `deleteBy` | `delete` | `T` | |
|
|
474
479
|
| `deleteManyBy` | `deleteMany` | `{ count: number }` | |
|
|
480
|
+
| `deleteManyWhere` | `deleteMany` | `{ count: number }` | Recebe um objeto `where` explícito como argumento |
|
|
475
481
|
| `aggregate` | `aggregate` | `Dinâmico` | Nome deve ser exato; recebe args nativos do Prisma; ignora `selectModels`, `pushWhere` e `requiredWhere` |
|
|
476
482
|
| `groupBy` | `groupBy` | `Dinâmico[]` | Nome deve ser exato; recebe args nativos do Prisma; ignora `selectModels`, `pushWhere` e `requiredWhere` |
|
|
477
483
|
|
|
@@ -556,7 +562,7 @@ findByNomeOptionalAndEmail // nome é opcional (pode ser passado como undefined
|
|
|
556
562
|
|
|
557
563
|
| Operador | Uso no nome | Exemplo |
|
|
558
564
|
| --------- | ---------------------------- | -------------------------------- |
|
|
559
|
-
| `And` | entre dois campos | `
|
|
565
|
+
| `And` | entre dois campos | `findOneByIdAndEmail` |
|
|
560
566
|
| `Or` | entre dois campos | `findByNomeOrEmail` |
|
|
561
567
|
| `AND` | separa bloco final em `AND` | `findByEmailOrNameANDActiveStatus` |
|
|
562
568
|
|
|
@@ -570,20 +576,20 @@ Exemplo:
|
|
|
570
576
|
|
|
571
577
|
```ts
|
|
572
578
|
methods: {
|
|
573
|
-
|
|
579
|
+
findOneByIdAndEmail: { map: true },
|
|
574
580
|
findByNomeOrEmail: { map: true },
|
|
575
581
|
findUniqueByIdOrEmailAndNome: { map: true },
|
|
576
582
|
findByEmailOrNameANDActiveStatusAndIdadeGreaterThan: { map: true }
|
|
577
583
|
}
|
|
578
584
|
|
|
579
585
|
// Uso
|
|
580
|
-
await usuarioRepository.
|
|
586
|
+
await usuarioRepository.findOneByIdAndEmail(1, "joao@email.com");
|
|
581
587
|
await usuarioRepository.findByNomeOrEmail("Joao", "joao@email.com");
|
|
582
588
|
await usuarioRepository.findUniqueByIdOrEmailAndNome(1, "joao@email.com", "Joao");
|
|
583
589
|
await usuarioRepository.findByEmailOrNameANDActiveStatusAndIdadeGreaterThan("joao@email.com", "Joao", true, 17)
|
|
584
590
|
```
|
|
585
591
|
|
|
586
|
-
Gera (`
|
|
592
|
+
Gera (`findOneByIdAndEmail`):
|
|
587
593
|
|
|
588
594
|
```ts
|
|
589
595
|
{
|
|
@@ -638,6 +644,12 @@ Gera (`findByEmailOrNameANDActiveStatusAndIdadeGreaterThan`):
|
|
|
638
644
|
|
|
639
645
|
Permitem filtrar por campos de modelos relacionados.
|
|
640
646
|
|
|
647
|
+
> [!IMPORTANT]
|
|
648
|
+
> - **Tipagem de relação**: Para que o TypeScript reconheça os tipos dos campos de relação nos métodos dinâmicos, o tipo genérico da entidade passado no `setupVSRepo` deve incluir as relações estruturadas (ex: usando `UsuarioGetPayload<{ include: { perfil: true, postagens: true } }>` do Prisma).
|
|
649
|
+
> - **Compatibilidade de sufixos**:
|
|
650
|
+
> - Os sufixos `Some`, `Every` e `None` só funcionam para relações **to-many** (`many-to-many` e `one-to-many`).
|
|
651
|
+
> - Os sufixos `With` e `Without` só funcionam para relações **to-one** (`one-to-one` e `many-to-one`).
|
|
652
|
+
|
|
641
653
|
| Sufixo de relação | Operador Prisma | Observação |
|
|
642
654
|
| ---------------------- | --------------- | -------------------------------------------------- |
|
|
643
655
|
| `Some` | `some: {}` | Relação tem *algum* registro |
|
|
@@ -664,7 +676,7 @@ methods: {
|
|
|
664
676
|
```
|
|
665
677
|
|
|
666
678
|
> [!NOTE]
|
|
667
|
-
> Teoricamente você pode usar `Every` sem `Field` (ele geraria { every: {} }), porém isso não produz um filtro efetivo. A condição é considerada verdadeira para qualquer relação, inclusive quando não existem registros relacionados, tornando o resultado equivalente a não aplicar filtro algum.
|
|
679
|
+
> Teoricamente você pode usar `Every` sem `Field` (ele geraria { every: { } }), porém isso não produz um filtro efetivo. A condição é considerada verdadeira para qualquer relação, inclusive quando não existem registros relacionados, tornando o resultado equivalente a não aplicar filtro algum.
|
|
668
680
|
|
|
669
681
|
---
|
|
670
682
|
|
|
@@ -733,7 +745,7 @@ Cada entrada em `methods` aceita as seguintes opções:
|
|
|
733
745
|
| `map` | `boolean` | — | **Obrigatório.** Define se o método será exposto no repository. |
|
|
734
746
|
| `whereType` | `'extending'` \| `'overwrite'` | `extending` | `extending` combina com `requiredWhere`. `overwrite` ignora o `requiredWhere`. |
|
|
735
747
|
| `selectModel` | `keyof SelectModels \| false` | — | Sobrescreve o `defaultSelectModel` para este método. |
|
|
736
|
-
| `fbMode` | `'one'` \| `'list'` | `'list'` | Somente para `findBy`. `'one'` retorna `T \| null`; `'list'` retorna `T[]`.
|
|
748
|
+
| `fbMode` | `'one'` \| `'list'` | `'list'` | (**Obsoleto. Use `findOneBy`**) Somente para `findBy`. `'one'` retorna `T \| null`; `'list'` retorna `T[]`. |
|
|
737
749
|
| `proxyTo` | `Padrão de método válido` | — | Delega a lógica para outro padrão de método válido. Útil para methods com nomes personalizados. |
|
|
738
750
|
| `pushWhere` | `WhereModel<M>` | — | Where extra adicionado à query além do `requiredWhere`. |
|
|
739
751
|
| `injectOrdenation` | `OrdenationModel<M>` | — | Ordenação fixa injetada automaticamente na query. |
|
|
@@ -743,8 +755,8 @@ Exemplos:
|
|
|
743
755
|
|
|
744
756
|
```ts
|
|
745
757
|
methods: {
|
|
746
|
-
// Retorna um único resultado
|
|
747
|
-
|
|
758
|
+
// Retorna um único resultado
|
|
759
|
+
findOneByEmail: { map: true },
|
|
748
760
|
|
|
749
761
|
// Ignora o requiredWhere
|
|
750
762
|
deleteManyByIdIn: { map: true, whereType: "overwrite" },
|
|
@@ -878,7 +890,6 @@ await usuarioRepository.save({
|
|
|
878
890
|
email: "maria@email.com",
|
|
879
891
|
senha: "password",
|
|
880
892
|
perfil: {
|
|
881
|
-
id: 1,
|
|
882
893
|
bio: "Bio da Maria",
|
|
883
894
|
},
|
|
884
895
|
postagens: [
|
|
@@ -888,7 +899,6 @@ await usuarioRepository.save({
|
|
|
888
899
|
|
|
889
900
|
await usuarioRepository.patch(1, {
|
|
890
901
|
perfil: {
|
|
891
|
-
id: 1,
|
|
892
902
|
bio: "Bio atualizada",
|
|
893
903
|
},
|
|
894
904
|
postagens: [
|
|
@@ -983,8 +993,8 @@ try {
|
|
|
983
993
|
|
|
984
994
|
| Classe | Quando é lançada |
|
|
985
995
|
| -------------------- | ------------------------------------------------------- |
|
|
986
|
-
| `VSRepoConfigError` | Configuração inválida em `setupVSRepo`
|
|
987
|
-
| `VSRepoBuildError` | Nome de método
|
|
996
|
+
| `VSRepoConfigError` | Configuração inválida em `setupVSRepo` |
|
|
997
|
+
| `VSRepoBuildError` | Nome de método ou configuração inválida no `build` |
|
|
988
998
|
| `VSRepoExtendError` | Argumento inválido em `extend` |
|
|
989
999
|
| `VSRepoRuntimeError` | Erro em tempo de execução durante uma operação |
|
|
990
1000
|
|
|
@@ -81,7 +81,7 @@ export function validateConfig(config) {
|
|
|
81
81
|
if(!configParsed.success) {
|
|
82
82
|
const firstIssue = configParsed.error.issues[0];
|
|
83
83
|
const path = firstIssue.path.length ? firstIssue.path.join(".") : "config";
|
|
84
|
-
throw new VSRepoConfigError(`[VSRepository] (config) ${path}: ${firstIssue.message}`)
|
|
84
|
+
throw new VSRepoConfigError(`[VSRepository] (${config.tableName}: config) ${path}: ${firstIssue.message}`)
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
return configParsed.data;
|
|
@@ -123,6 +123,11 @@ export function validateBuildConfig(buildConfig, buildInstance) {
|
|
|
123
123
|
defaultSelect: defaultSelectSchema,
|
|
124
124
|
ignoreRequiredWhere: ignoreRequiredWhereSchema
|
|
125
125
|
}).optional(),
|
|
126
|
+
patch: z.strictObject({
|
|
127
|
+
active: activeSchema,
|
|
128
|
+
defaultSelect: defaultSelectSchema,
|
|
129
|
+
ignoreRequiredWhere: ignoreRequiredWhereSchema
|
|
130
|
+
}).optional(),
|
|
126
131
|
removeList: z.strictObject({
|
|
127
132
|
active: activeSchema,
|
|
128
133
|
ignoreRequiredWhere: ignoreRequiredWhereSchema
|
|
@@ -143,7 +148,7 @@ export function validateBuildConfig(buildConfig, buildInstance) {
|
|
|
143
148
|
if(!buildConfigParsed.success) {
|
|
144
149
|
const firstIssue = buildConfigParsed.error.issues[0];
|
|
145
150
|
const path = firstIssue.path.length ? firstIssue.path.join(".") : "config";
|
|
146
|
-
throw new VSRepoBuildError(`[VSRepository] (build) ${path}: ${firstIssue.message}`)
|
|
151
|
+
throw new VSRepoBuildError(`[VSRepository] (${config.tableName}: build) ${path}: ${firstIssue.message}`)
|
|
147
152
|
}
|
|
148
153
|
|
|
149
154
|
return buildConfigParsed.data;
|
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
import { Prisma, PrismaClient } from '@vsrepo/prisma/types';
|
|
2
|
+
import { Decimal, JsonValue } from '@prisma/client/runtime/client';
|
|
3
|
+
|
|
4
|
+
type WidenField<T> =
|
|
5
|
+
T extends bigint ? bigint | number :
|
|
6
|
+
T extends Date ? Date | string :
|
|
7
|
+
T extends Decimal ? Decimal | string | number :
|
|
8
|
+
T extends Array<infer U> ? WidenField<U>[] :
|
|
9
|
+
T extends readonly [infer U, infer V] ? [WidenField<U>, WidenField<V>] :
|
|
10
|
+
T;
|
|
2
11
|
|
|
3
12
|
/**
|
|
4
13
|
* Instância completa do Prisma Client usada para construir repositories.
|
|
@@ -53,6 +62,8 @@ type ValidMethodPatterns =
|
|
|
53
62
|
| `updateBy${string}` | `upsertBy${string}` | `deleteManyBy${string}`
|
|
54
63
|
| `deleteBy${string}` | `countBy${string}` | `count${string}` | `countWhere${string}`
|
|
55
64
|
| `findWhere${string}` | `findListWhere${string}`
|
|
65
|
+
| `existsWhere${string}` | `updateManyWhere${string}` | `deleteManyWhere${string}`
|
|
66
|
+
| `findOneWhere${string}` | `findOneBy${string}` | `updateManyAndReturnWhere${string}`
|
|
56
67
|
| 'aggregate' | 'groupBy';
|
|
57
68
|
|
|
58
69
|
type StripModifier<S extends string> =
|
|
@@ -98,21 +109,23 @@ type ParseRelation<S extends string> =
|
|
|
98
109
|
S extends `${infer Rel}Every${infer Rest}` ? [Uncapitalize<Rel>, 'every', Rest] :
|
|
99
110
|
S extends `${infer Rel}None${infer Rest}` ? [Uncapitalize<Rel>, 'none', Rest] : null;
|
|
100
111
|
|
|
101
|
-
type GetFieldType<T, S extends string, I> =
|
|
102
|
-
|
|
103
|
-
?
|
|
104
|
-
?
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
?
|
|
112
|
+
type GetFieldType<T, S extends string, I> = WidenField<
|
|
113
|
+
ExtractFieldName<S> extends infer FieldName
|
|
114
|
+
? FieldName extends keyof T
|
|
115
|
+
? IsArrayFilter<S> extends true
|
|
116
|
+
? T[FieldName][]
|
|
117
|
+
: IsBetweenFilter<S> extends true
|
|
118
|
+
? [NonNullable<T[FieldName]>, NonNullable<T[FieldName]>]
|
|
119
|
+
: NonNullable<T[FieldName]> extends object | any[]
|
|
120
|
+
? I extends { whereInput: infer W }
|
|
121
|
+
? FieldName extends keyof NonNullable<W> ? Exclude<NonNullable<W>[FieldName], undefined> : T[FieldName]
|
|
122
|
+
: T[FieldName]
|
|
110
123
|
: T[FieldName]
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
124
|
+
: ParseRelation<S> extends [infer Rel extends keyof T, any, infer Rest extends string]
|
|
125
|
+
? GetFieldType<NonNullable<T[Rel]> extends any[] ? NonNullable<T[Rel]>[number] : NonNullable<T[Rel]>, Rest, unknown>
|
|
126
|
+
: unknown
|
|
127
|
+
: unknown
|
|
128
|
+
>;
|
|
116
129
|
|
|
117
130
|
type NoArgModifiers = 'IsNull' | 'IsNotNull' | 'IsTrue' | 'IsFalse' | 'None' | 'Some' | 'Every' | 'Without';
|
|
118
131
|
|
|
@@ -156,10 +169,10 @@ type FilterNonEmpty<T extends unknown[]> =
|
|
|
156
169
|
: [];
|
|
157
170
|
|
|
158
171
|
type ResolveReturnType<M extends string, TSelected> =
|
|
159
|
-
M extends 'existsBy' ? boolean :
|
|
160
|
-
M extends 'createMany' | 'updateManyBy' | 'deleteManyBy' ? { count: number } :
|
|
161
|
-
M extends 'findMany' | 'createManyAndReturn' | 'updateManyAndReturnBy' | 'findListWhere' | 'findByList' ? TSelected[] :
|
|
162
|
-
M extends 'findUnique' | 'findFirst' | 'findWhere' | 'findByOne' ? TSelected | null :
|
|
172
|
+
M extends 'existsBy' | 'existsWhere' ? boolean :
|
|
173
|
+
M extends 'createMany' | 'updateManyBy' | 'deleteManyBy' | 'updateManyWhere' | 'deleteManyWhere' ? { count: number } :
|
|
174
|
+
M extends 'findMany' | 'createManyAndReturn' | 'updateManyAndReturnBy' | 'updateManyAndReturnWhere' | 'findListWhere' | 'findByList' ? TSelected[] :
|
|
175
|
+
M extends 'findUnique' | 'findFirst' | 'findWhere' | 'findByOne' | 'findOneBy' | 'findOneWhere' ? TSelected | null :
|
|
163
176
|
M extends 'findUniqueOrThrow' | 'findFirstOrThrow' | 'create' | 'updateBy' | 'upsertBy' | 'deleteBy' ? TSelected :
|
|
164
177
|
M extends 'count' | 'countWhere' ? number : never;
|
|
165
178
|
|
|
@@ -177,7 +190,8 @@ type ExtraArgs<M extends string, R extends string, I> = [
|
|
|
177
190
|
: M extends 'updateBy' ? [data: GetUpdateInput<I>]
|
|
178
191
|
: M extends 'createMany' | 'createManyAndReturn' ? [data: GetCreateManyInput<I>]
|
|
179
192
|
: M extends 'updateManyBy' | 'updateManyAndReturnBy' ? [data: GetUpdateManyInput<I>]
|
|
180
|
-
: M extends 'findWhere' | 'findListWhere' | 'countWhere' ? [where: GetWhereInput<I>]
|
|
193
|
+
: M extends 'findWhere' | 'findListWhere' | 'countWhere' | 'existsWhere' | 'deleteManyWhere' | 'findOneWhere' ? [where: GetWhereInput<I>]
|
|
194
|
+
: M extends 'updateManyWhere' | 'updateManyAndReturnWhere' ? [where: GetWhereInput<I>, data: GetUpdateManyInput<I>]
|
|
181
195
|
: []),
|
|
182
196
|
...(R extends `${string}PaginatedAndOrdered` ? [pagination: PaginationOptions<GetCursorInput<I>>, order: GetOrderByInput<I>]
|
|
183
197
|
: R extends `${string}OrderedAndPaginated` ? [order: GetOrderByInput<I>, pagination: PaginationOptions<GetCursorInput<I>>]
|
|
@@ -248,7 +262,9 @@ type MethodFn<MethodName extends string, T, M extends Prisma.ModelName, R extend
|
|
|
248
262
|
|
|
249
263
|
type GetMappedMethod<K extends string, MethodConf> =
|
|
250
264
|
K extends `findBy${string}` ? (MethodConf extends { fbMode: 'one' } ? 'findByOne' : 'findByList') :
|
|
265
|
+
K extends `findOneBy${string}` ? 'findOneBy' :
|
|
251
266
|
K extends `existsBy${string}` ? 'existsBy' :
|
|
267
|
+
K extends `existsWhere${string}` ? 'existsWhere' :
|
|
252
268
|
K extends `findUniqueOrThrowBy${string}` ? 'findUniqueOrThrow' :
|
|
253
269
|
K extends `findUniqueBy${string}` ? 'findUnique' :
|
|
254
270
|
K extends `findFirstOrThrowBy${string}` | `findFirstOrThrow${string}` ? 'findFirstOrThrow' :
|
|
@@ -258,14 +274,18 @@ type GetMappedMethod<K extends string, MethodConf> =
|
|
|
258
274
|
K extends `createMany${string}` ? 'createMany' :
|
|
259
275
|
K extends `create${string}` ? 'create' :
|
|
260
276
|
K extends `updateManyAndReturnBy${string}` ? 'updateManyAndReturnBy' :
|
|
277
|
+
K extends `updateManyAndReturnWhere${string}` ? 'updateManyAndReturnWhere' :
|
|
261
278
|
K extends `updateManyBy${string}` ? 'updateManyBy' :
|
|
279
|
+
K extends `updateManyWhere${string}` ? 'updateManyWhere' :
|
|
262
280
|
K extends `updateBy${string}` ? 'updateBy' :
|
|
263
281
|
K extends `upsertBy${string}` ? 'upsertBy' :
|
|
264
282
|
K extends `deleteManyBy${string}` ? 'deleteManyBy' :
|
|
283
|
+
K extends `deleteManyWhere${string}` ? 'deleteManyWhere' :
|
|
265
284
|
K extends `deleteBy${string}` ? 'deleteBy' :
|
|
266
285
|
K extends `countWhere${string}` ? 'countWhere' :
|
|
267
286
|
K extends `countBy${string}` | `count${string}` ? 'count' :
|
|
268
287
|
K extends `findListWhere${string}` ? 'findListWhere' :
|
|
288
|
+
K extends `findOneWhere${string}` ? 'findOneWhere' :
|
|
269
289
|
K extends `findWhere${string}` ? 'findWhere' :
|
|
270
290
|
K extends 'aggregate' ? 'aggregate' :
|
|
271
291
|
K extends 'groupBy' ? 'groupBy' :
|
|
@@ -282,10 +302,20 @@ type ExtractPatternBase<K extends string> =
|
|
|
282
302
|
K extends `countWhere${infer R}` ? R :
|
|
283
303
|
K extends `count${infer R}` ? R :
|
|
284
304
|
K extends `findListWhere${infer R}` ? R :
|
|
285
|
-
K extends `
|
|
305
|
+
K extends `findOneWhere${infer R}` ? R :
|
|
306
|
+
K extends `findWhere${infer R}` ? R :
|
|
307
|
+
K extends `existsWhere${infer R}` ? R :
|
|
308
|
+
K extends `updateManyWhere${infer R}` ? R :
|
|
309
|
+
K extends `updateManyAndReturnWhere${infer R}` ? R :
|
|
310
|
+
K extends `deleteManyWhere${infer R}` ? R : '';
|
|
286
311
|
|
|
287
312
|
type MethodFactory<T, M extends Prisma.ModelName, K extends string, SelectModels, DefaultSelect extends keyof SelectModels | false, I, MethodConf> =
|
|
288
|
-
|
|
313
|
+
K extends `findWhere${string}`
|
|
314
|
+
? {
|
|
315
|
+
/** @deprecated Use findOneWhere em seu lugar. */
|
|
316
|
+
<S extends keyof SelectModels | false = DefaultSelect>(...args: [...ExtractFields<T, CleanFields<ExtractPatternBase<K>>, I>, ...ExtraArgs<GetMappedMethod<K, MethodConf>, ExtractPatternBase<K>, I>, options?: MethodOptions<S>]): Promise<ResolveReturnType<GetMappedMethod<K, MethodConf>, SelectedModel<M, S, SelectModels>>>;
|
|
317
|
+
}
|
|
318
|
+
: MethodFn<GetMappedMethod<K, MethodConf>, T, M, ExtractPatternBase<K>, SelectModels, DefaultSelect, I>;
|
|
289
319
|
|
|
290
320
|
type ResolveSelectModel<MethodConf, GlobalConf, SelectModels> =
|
|
291
321
|
MethodConf extends { selectModel: infer S } ? (S extends false ? false : S extends keyof SelectModels ? S : never) :
|
|
@@ -390,14 +420,17 @@ export type MethodConfig<M extends Prisma.ModelName, SelectModels = any> = {
|
|
|
390
420
|
/** Define se o método será exposto no repository. */
|
|
391
421
|
readonly map: boolean;
|
|
392
422
|
/** Sobrescreve o `defaultSelectModel` apenas para este método. */
|
|
393
|
-
readonly selectModel?:
|
|
423
|
+
readonly selectModel?: string | false;
|
|
394
424
|
/** Controla se o método combina (`extending`) ou sobrescreve (`overwrite`) o `requiredWhere`. */
|
|
395
425
|
readonly whereType?: 'overwrite' | 'extending';
|
|
396
426
|
/** Redireciona a lógica para outro padrão de método válido. */
|
|
397
427
|
readonly proxyTo?: ValidMethodPatterns;
|
|
398
428
|
/** Adiciona um `where` extra além do `requiredWhere`. */
|
|
399
429
|
readonly pushWhere?: WhereModel<M>;
|
|
400
|
-
/**
|
|
430
|
+
/**
|
|
431
|
+
* Define se `findBy` retorna um item (`one`) ou uma lista (`list`).
|
|
432
|
+
* @deprecated Use findOneBy se só quiser retornar um.
|
|
433
|
+
*/
|
|
401
434
|
readonly fbMode?: 'one' | 'list';
|
|
402
435
|
/** Injeta uma ordenação fixa automaticamente na query. */
|
|
403
436
|
readonly injectOrdenation?: OrdenationModel<M>;
|
|
@@ -465,12 +498,6 @@ type ResolveCurrentReturn<M extends Prisma.ModelName, Models, S, D> =
|
|
|
465
498
|
? ([D] extends [never] ? FullModelType<M> : SelectedModel<M, D, Models>)
|
|
466
499
|
: SelectedModel<M, S, Models>;
|
|
467
500
|
|
|
468
|
-
type RefineSaveResult<R, O> = {
|
|
469
|
-
[K in keyof R]: K extends keyof O
|
|
470
|
-
? (undefined extends O[K] ? R[K] : null extends O[K] ? R[K] : NonNullable<R[K]>)
|
|
471
|
-
: R[K];
|
|
472
|
-
};
|
|
473
|
-
|
|
474
501
|
type InjectedGet<
|
|
475
502
|
T, M extends Prisma.ModelName, Config, C extends BuildConfig<any> | undefined,
|
|
476
503
|
TSelects = ExtractSelectModels<Config>,
|
|
@@ -484,7 +511,7 @@ type InjectedGet<
|
|
|
484
511
|
* @returns O registro selecionado ou `null` se não encontrado.
|
|
485
512
|
*/
|
|
486
513
|
get<S extends keyof TSelects | false = ResolveMethodDefaultSelect<Config, C, 'get', TSelects>>(
|
|
487
|
-
pk: T[TPk extends keyof T ? TPk : never]
|
|
514
|
+
pk: WidenField<T[TPk extends keyof T ? TPk : never]>, options?: MethodOptions<S>
|
|
488
515
|
): Promise<ResolveCurrentReturn<M, TSelects, S, TDefault> | null>;
|
|
489
516
|
};
|
|
490
517
|
|
|
@@ -501,7 +528,7 @@ type InjectedGetOrThrow<
|
|
|
501
528
|
* @returns O registro selecionado.
|
|
502
529
|
*/
|
|
503
530
|
getOrThrow<S extends keyof TSelects | false = ResolveMethodDefaultSelect<Config, C, 'getOrThrow', TSelects>>(
|
|
504
|
-
pk: T[TPk extends keyof T ? TPk : never]
|
|
531
|
+
pk: WidenField<T[TPk extends keyof T ? TPk : never]>, options?: MethodOptions<S>
|
|
505
532
|
): Promise<ResolveCurrentReturn<M, TSelects, S, TDefault>>;
|
|
506
533
|
};
|
|
507
534
|
|
|
@@ -518,7 +545,7 @@ type InjectedRemove<
|
|
|
518
545
|
* @returns O registro removido.
|
|
519
546
|
*/
|
|
520
547
|
remove<S extends keyof TSelects | false = ResolveMethodDefaultSelect<Config, C, 'remove', TSelects>>(
|
|
521
|
-
pk: T[TPk extends keyof T ? TPk : never]
|
|
548
|
+
pk: WidenField<T[TPk extends keyof T ? TPk : never]>, options?: MethodOptions<S>
|
|
522
549
|
): Promise<ResolveCurrentReturn<M, TSelects, S, TDefault>>;
|
|
523
550
|
};
|
|
524
551
|
|
|
@@ -593,7 +620,7 @@ export type SaveObject<TInput, TRepo> =
|
|
|
593
620
|
/**
|
|
594
621
|
* Extrai o tipo de payload do método `patch` a partir de uma instância de VSRepository configurada.
|
|
595
622
|
*/
|
|
596
|
-
export type
|
|
623
|
+
export type PatchObject<TInput, TRepo> =
|
|
597
624
|
TRepo extends VSRepository<infer T, infer M, infer Config>
|
|
598
625
|
? (Config extends { relations: infer R } ? (R extends object ? R : {}) : {}) extends infer TRelations
|
|
599
626
|
? DistributiveOmit<TInput, keyof TRelations> & {
|
|
@@ -615,12 +642,12 @@ type InjectedSave<
|
|
|
615
642
|
* @returns O registro salvo com tipos refinados conforme a entrada.
|
|
616
643
|
*/
|
|
617
644
|
save<
|
|
618
|
-
O,
|
|
645
|
+
O,
|
|
619
646
|
S extends keyof TSelects | false = ResolveMethodDefaultSelect<Config, C, 'save', TSelects>
|
|
620
647
|
>(
|
|
621
|
-
obj: O & UpsertWithRelations<T, M, TRelations>,
|
|
648
|
+
obj: O & UpsertWithRelations<T, M, TRelations>,
|
|
622
649
|
options?: MethodOptions<S>
|
|
623
|
-
): Promise<
|
|
650
|
+
): Promise<ResolveCurrentReturn<M, TSelects, S, TDefault>>;
|
|
624
651
|
};
|
|
625
652
|
|
|
626
653
|
type InjectedPatch<
|
|
@@ -641,10 +668,10 @@ type InjectedPatch<
|
|
|
641
668
|
O,
|
|
642
669
|
S extends keyof TSelects | false = ResolveMethodDefaultSelect<Config, C, 'patch', TSelects>
|
|
643
670
|
>(
|
|
644
|
-
pk: T[TPk extends keyof T ? TPk : never]
|
|
671
|
+
pk: WidenField<T[TPk extends keyof T ? TPk : never]>,
|
|
645
672
|
obj: O & UpdateWithRelations<T, M, TRelations>,
|
|
646
673
|
options?: MethodOptions<S>
|
|
647
|
-
): Promise<
|
|
674
|
+
): Promise<ResolveCurrentReturn<M, TSelects, S, TDefault>>;
|
|
648
675
|
};
|
|
649
676
|
|
|
650
677
|
type InjectedRemoveList<
|
|
@@ -658,7 +685,7 @@ type InjectedRemoveList<
|
|
|
658
685
|
* @returns Objeto com a contagem de registros removidos.
|
|
659
686
|
*/
|
|
660
687
|
removeList(
|
|
661
|
-
pks: T[TPk extends keyof T ? TPk : never][],
|
|
688
|
+
pks: WidenField<T[TPk extends keyof T ? TPk : never]>[],
|
|
662
689
|
options?: { db?: ClientOrTransaction }
|
|
663
690
|
): Promise<{ count: number }>;
|
|
664
691
|
};
|
|
@@ -704,7 +731,7 @@ type InjectedHas<
|
|
|
704
731
|
* @returns `true` se existir, caso contrário `false`.
|
|
705
732
|
*/
|
|
706
733
|
has(
|
|
707
|
-
pk: T[TPk extends keyof T ? TPk : never]
|
|
734
|
+
pk: WidenField<T[TPk extends keyof T ? TPk : never]>,
|
|
708
735
|
options?: { db?: ClientOrTransaction }
|
|
709
736
|
): Promise<boolean>;
|
|
710
737
|
};
|
|
@@ -768,7 +795,7 @@ export type ManyToOneRelationConfig<TItem> = {
|
|
|
768
795
|
* Infere automaticamente a configuração de relação possível a partir de um campo.
|
|
769
796
|
*/
|
|
770
797
|
export type ExtractRelationConfig<TField> = NonNullable<TField> extends infer NonNull
|
|
771
|
-
? NonNull extends Date | Buffer | Uint8Array ? never
|
|
798
|
+
? NonNull extends Date | Buffer | Uint8Array | Decimal | JsonValue ? never
|
|
772
799
|
: NonNull extends any[] ? (NonNull[number] extends object ? ManyRelationConfig<NonNull[number]> : never)
|
|
773
800
|
: NonNull extends object ? (OneToOneRelationConfig<NonNull> | ManyToOneRelationConfig<NonNull>)
|
|
774
801
|
: never
|
|
@@ -791,19 +818,12 @@ type AnySelect<M extends Prisma.ModelName> = Prisma.TypeMap['model'][M]['operati
|
|
|
791
818
|
* @template SM Mapa de select models nomeados.
|
|
792
819
|
*/
|
|
793
820
|
export type RepoConfig<T, M extends Prisma.ModelName, SM extends Record<string, AnySelect<M>> = Record<string, AnySelect<M>>> = {
|
|
794
|
-
/** Nome da tabela/modelo no Prisma. */
|
|
795
821
|
tableName: Uncapitalize<M>;
|
|
796
|
-
/** Nome da chave primária da entidade. */
|
|
797
822
|
pkName: keyof T;
|
|
798
|
-
/** Projeções de dados nomeadas e reutilizáveis. */
|
|
799
823
|
selectModels?: SM;
|
|
800
|
-
/** Select model aplicado por padrão quando nenhum for informado. */
|
|
801
824
|
defaultSelectModel?: Extract<keyof SM, string>;
|
|
802
|
-
/** Filtros aplicados automaticamente em todas as queries do repository. */
|
|
803
825
|
requiredWhere?: WhereModel<M>;
|
|
804
|
-
/** Configuração das relações gerenciadas pelo `save`. */
|
|
805
826
|
relations?: RepositoryRelations<T>;
|
|
806
|
-
/** Métodos dinâmicos expostos pelo repository. */
|
|
807
827
|
methods?: Record<string, MethodConfig<M, SM>>;
|
|
808
828
|
};
|
|
809
829
|
|
|
@@ -867,7 +887,7 @@ export type ValidateRepoConfig<T extends object, M extends Prisma.ModelName, Con
|
|
|
867
887
|
requiredWhere?: WhereModel<M>;
|
|
868
888
|
/** Relações gerenciadas automaticamente pelo `save` e pelo `patch`. */
|
|
869
889
|
relations?: RepositoryRelations<T>;
|
|
870
|
-
/** Mapa dos métodos dinâmicos e suas
|
|
890
|
+
/** Mapa dos métodos dinâmicos e suas configurações. */
|
|
871
891
|
methods?: {
|
|
872
892
|
[K in keyof (Config extends { methods: infer Meth } ? Meth : {})]: K extends string
|
|
873
893
|
? MethodConfig<M, Config extends { selectModels: infer SM } ? SM : any> & (K extends ValidMethodPatterns ? {} : { proxyTo: ValidMethodPatterns })
|
|
@@ -43,11 +43,11 @@ export class VSRepository {
|
|
|
43
43
|
|
|
44
44
|
extend(extensionFunc) {
|
|
45
45
|
if(typeof extensionFunc !== 'function'){
|
|
46
|
-
throw new VSRepoExtendError(`[VSRepository] (extend) 'extensionFunc' must be a valid funcion.`);
|
|
46
|
+
throw new VSRepoExtendError(`[VSRepository] (${this.tableName}: extend) 'extensionFunc' must be a valid funcion.`);
|
|
47
47
|
}
|
|
48
48
|
const extension = extensionFunc(this);
|
|
49
49
|
if(typeof extension !== 'object' || extension === null){
|
|
50
|
-
throw new VSRepoExtendError(`[VSRepository] (extend) The return of the 'extensionFunc' must be a valid object.`)
|
|
50
|
+
throw new VSRepoExtendError(`[VSRepository] (${this.tableName}: extend) The return of the 'extensionFunc' must be a valid object.`)
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
const extended = Object.assign(Object.create(this), extension);
|
|
@@ -61,7 +61,7 @@ export class VSRepository {
|
|
|
61
61
|
|
|
62
62
|
build(prisma, config = { freeze: true, showWorking: false }) {
|
|
63
63
|
if(typeof prisma !== 'object' || prisma === null) {
|
|
64
|
-
throw new VSRepoBuildError(`[VSRepository] (build) 'prisma' must be a valid Prisma Client.`);
|
|
64
|
+
throw new VSRepoBuildError(`[VSRepository] (${this.tableName}: build) 'prisma' must be a valid Prisma Client.`);
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
const buildInstance = Object.create(this);
|
|
@@ -76,7 +76,7 @@ export class VSRepository {
|
|
|
76
76
|
const repositoryKeysToMap = Object.keys(methods);
|
|
77
77
|
|
|
78
78
|
if(showWorking) {
|
|
79
|
-
console.log(`[VSRepository] (build) Keys to map:`, JSON.stringify(repositoryKeysToMap, null, 2));
|
|
79
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: build) Keys to map:`, JSON.stringify(repositoryKeysToMap, null, 2));
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
for (let keyToMap of repositoryKeysToMap) {
|
|
@@ -170,6 +170,16 @@ export class VSRepository {
|
|
|
170
170
|
ignoreSelect = true;
|
|
171
171
|
existsMode = true;
|
|
172
172
|
method = 'findFirst';
|
|
173
|
+
} else if(keyToMap.startsWith('existsWhere')) {
|
|
174
|
+
keyToMapReplaced = keyToMap.replace('existsWhere', '');
|
|
175
|
+
ignoreSelect = true;
|
|
176
|
+
existsMode = true;
|
|
177
|
+
ignoreWhere = true;
|
|
178
|
+
onlyBaseWheres = true;
|
|
179
|
+
method = 'findFirst';
|
|
180
|
+
whereIndex = 0;
|
|
181
|
+
otherParams.push('where');
|
|
182
|
+
argsCount += 1;
|
|
173
183
|
} else if(keyToMap.startsWith('findManyBy')) {
|
|
174
184
|
keyToMapReplaced = keyToMap.replace('findManyBy', '');
|
|
175
185
|
ignoreOrderByAndPagination = false;
|
|
@@ -210,6 +220,15 @@ export class VSRepository {
|
|
|
210
220
|
dataIndex = -2;
|
|
211
221
|
otherParams.push('data');
|
|
212
222
|
argsCount++;
|
|
223
|
+
} else if(keyToMap.startsWith('updateManyAndReturnWhere')) {
|
|
224
|
+
keyToMapReplaced = keyToMap.replace('updateManyAndReturnWhere', '')
|
|
225
|
+
ignoreWhere = true;
|
|
226
|
+
onlyBaseWheres = true;
|
|
227
|
+
method = 'updateManyAndReturn';
|
|
228
|
+
dataIndex = -2;
|
|
229
|
+
whereIndex = 0;
|
|
230
|
+
otherParams.push('where', 'data');
|
|
231
|
+
argsCount += 2;
|
|
213
232
|
} else if(keyToMap.startsWith('updateManyBy')) {
|
|
214
233
|
keyToMapReplaced = keyToMap.replace('updateManyBy', '')
|
|
215
234
|
ignoreSelect = true;
|
|
@@ -217,6 +236,16 @@ export class VSRepository {
|
|
|
217
236
|
dataIndex = -2;
|
|
218
237
|
otherParams.push('data');
|
|
219
238
|
argsCount++;
|
|
239
|
+
} else if(keyToMap.startsWith('updateManyWhere')) {
|
|
240
|
+
keyToMapReplaced = keyToMap.replace('updateManyWhere', '')
|
|
241
|
+
ignoreSelect = true;
|
|
242
|
+
ignoreWhere = true;
|
|
243
|
+
onlyBaseWheres = true;
|
|
244
|
+
method = 'updateMany';
|
|
245
|
+
dataIndex = -2;
|
|
246
|
+
whereIndex = 0;
|
|
247
|
+
otherParams.push('where', 'data');
|
|
248
|
+
argsCount += 2;
|
|
220
249
|
} else if(keyToMap.startsWith('updateBy')) {
|
|
221
250
|
keyToMapReplaced = keyToMap.replace('updateBy', '')
|
|
222
251
|
method = 'update';
|
|
@@ -235,6 +264,15 @@ export class VSRepository {
|
|
|
235
264
|
keyToMapReplaced = keyToMap.replace('deleteManyBy', '')
|
|
236
265
|
ignoreSelect = true;
|
|
237
266
|
method = 'deleteMany';
|
|
267
|
+
} else if(keyToMap.startsWith('deleteManyWhere')) {
|
|
268
|
+
keyToMapReplaced = keyToMap.replace('deleteManyWhere', '')
|
|
269
|
+
ignoreSelect = true;
|
|
270
|
+
ignoreWhere = true;
|
|
271
|
+
onlyBaseWheres = true;
|
|
272
|
+
method = 'deleteMany';
|
|
273
|
+
whereIndex = 0;
|
|
274
|
+
otherParams.push('where');
|
|
275
|
+
argsCount += 1;
|
|
238
276
|
} else if(keyToMap.startsWith('deleteBy')) {
|
|
239
277
|
keyToMapReplaced = keyToMap.replace('deleteBy', '')
|
|
240
278
|
method = 'delete';
|
|
@@ -247,6 +285,15 @@ export class VSRepository {
|
|
|
247
285
|
whereIndex = 0;
|
|
248
286
|
otherParams.push('where');
|
|
249
287
|
argsCount += 1;
|
|
288
|
+
} else if(keyToMap.startsWith('findOneWhere')) {
|
|
289
|
+
keyToMapReplaced = keyToMap.replace('findOneWhere', '');
|
|
290
|
+
ignoreOrderByAndPagination = false;
|
|
291
|
+
ignoreWhere = true;
|
|
292
|
+
onlyBaseWheres = true;
|
|
293
|
+
method = 'findFirst';
|
|
294
|
+
whereIndex = 0;
|
|
295
|
+
otherParams.push('where');
|
|
296
|
+
argsCount += 1;
|
|
250
297
|
} else if(keyToMap.startsWith('findListWhere')) {
|
|
251
298
|
keyToMapReplaced = keyToMap.replace('findListWhere', '');
|
|
252
299
|
ignoreOrderByAndPagination = false;
|
|
@@ -260,8 +307,12 @@ export class VSRepository {
|
|
|
260
307
|
keyToMapReplaced = keyToMap.replace('findBy', '');
|
|
261
308
|
ignoreOrderByAndPagination = false;
|
|
262
309
|
method = methods[originalKey].fbMode === 'one' ? 'findFirst' : 'findMany';
|
|
310
|
+
} else if(keyToMap.startsWith('findOneBy')) {
|
|
311
|
+
keyToMapReplaced = keyToMap.replace('findOneBy', '');
|
|
312
|
+
ignoreOrderByAndPagination = false;
|
|
313
|
+
method = 'findFirst';
|
|
263
314
|
} else {
|
|
264
|
-
throw new VSRepoBuildError(`[VSRepository] (build) Unknown method: ${keyToMap}.`);
|
|
315
|
+
throw new VSRepoBuildError(`[VSRepository] (${buildInstance.tableName}: build) Unknown method: ${keyToMap}.`);
|
|
265
316
|
}
|
|
266
317
|
|
|
267
318
|
|
|
@@ -573,7 +624,7 @@ export class VSRepository {
|
|
|
573
624
|
return { context, otherProps, argName, autoVal: arg.autoInjectVal, betweenMode: arg.betweenMode };
|
|
574
625
|
});
|
|
575
626
|
if(showWorking) {
|
|
576
|
-
console.log(`[VSRepository] (build) Where object resolved to ${keyToMap}:\n`, JSON.stringify(whereResolved, null, 2));
|
|
627
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: build) Where object resolved to ${keyToMap}:\n`, JSON.stringify(whereResolved, null, 2));
|
|
577
628
|
}
|
|
578
629
|
}
|
|
579
630
|
|
|
@@ -730,7 +781,7 @@ export class VSRepository {
|
|
|
730
781
|
let optionsSelectModel;
|
|
731
782
|
if(args.length < argsCount) {
|
|
732
783
|
const missingParams = whereParams.concat(otherParams).slice(args.length);
|
|
733
|
-
throw new VSRepoRuntimeError(`[VSRepository] (runtime) Missing parameters: ${missingParams.join(', ')}`);
|
|
784
|
+
throw new VSRepoRuntimeError(`[VSRepository] (${buildInstance.tableName}: runtime) Missing parameters: ${missingParams.join(', ')}`);
|
|
734
785
|
} else if(args.length > argsCount) {
|
|
735
786
|
const optionsArg = args[args.length - 1];
|
|
736
787
|
db = optionsArg.db ?? db;
|
|
@@ -743,8 +794,8 @@ export class VSRepository {
|
|
|
743
794
|
|
|
744
795
|
let start;
|
|
745
796
|
if(showWorking){
|
|
746
|
-
console.log(`[VSRepository] (runtime) Executing ${method}
|
|
747
|
-
console.log(`[VSRepository] (runtime) Built arguments to ${method}
|
|
797
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing ${method}.`);
|
|
798
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to ${method}:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
748
799
|
start = performance.now();
|
|
749
800
|
}
|
|
750
801
|
|
|
@@ -754,7 +805,7 @@ export class VSRepository {
|
|
|
754
805
|
if(showWorking) {
|
|
755
806
|
const end = performance.now();
|
|
756
807
|
const duration = (end - start).toFixed(2);
|
|
757
|
-
console.log(`[VSRepository] (runtime) Executed ${method}
|
|
808
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed ${method} (took: ${duration}ms).`);
|
|
758
809
|
}
|
|
759
810
|
|
|
760
811
|
if(existsMode) {
|
|
@@ -762,7 +813,7 @@ export class VSRepository {
|
|
|
762
813
|
}
|
|
763
814
|
return result;
|
|
764
815
|
} catch (err) {
|
|
765
|
-
console.log(`[VSRepository] (runtime) Fatal error when executing ${method}
|
|
816
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when executing ${method}:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
766
817
|
throw err;
|
|
767
818
|
}
|
|
768
819
|
|
|
@@ -788,8 +839,8 @@ export class VSRepository {
|
|
|
788
839
|
|
|
789
840
|
let start;
|
|
790
841
|
if(showWorking){
|
|
791
|
-
console.log(`[VSRepository] (runtime) Executing get
|
|
792
|
-
console.log(`[VSRepository] (runtime) Built arguments to get
|
|
842
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing get.`);
|
|
843
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to get:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
793
844
|
start = performance.now();
|
|
794
845
|
}
|
|
795
846
|
|
|
@@ -799,12 +850,12 @@ export class VSRepository {
|
|
|
799
850
|
if(showWorking) {
|
|
800
851
|
const end = performance.now();
|
|
801
852
|
const duration = (end - start).toFixed(2);
|
|
802
|
-
console.log(`[VSRepository] (runtime) Executed get
|
|
853
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed get (took: ${duration}ms).`);
|
|
803
854
|
}
|
|
804
855
|
|
|
805
856
|
return result;
|
|
806
857
|
} catch (err) {
|
|
807
|
-
console.log(`[VSRepository] (runtime) Fatal error when trying to get
|
|
858
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when trying to get:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
808
859
|
throw err;
|
|
809
860
|
}
|
|
810
861
|
}
|
|
@@ -827,8 +878,8 @@ export class VSRepository {
|
|
|
827
878
|
|
|
828
879
|
let start;
|
|
829
880
|
if(showWorking){
|
|
830
|
-
console.log(`[VSRepository] (runtime) Executing getOrThrow
|
|
831
|
-
console.log(`[VSRepository] (runtime) Built arguments to getOrThrow
|
|
881
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing getOrThrow.`);
|
|
882
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to getOrThrow:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
832
883
|
start = performance.now();
|
|
833
884
|
}
|
|
834
885
|
|
|
@@ -838,12 +889,12 @@ export class VSRepository {
|
|
|
838
889
|
if(showWorking) {
|
|
839
890
|
const end = performance.now();
|
|
840
891
|
const duration = (end - start).toFixed(2);
|
|
841
|
-
console.log(`[VSRepository] (runtime) Executed getOrThrow
|
|
892
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed getOrThrow (took: ${duration}ms).`);
|
|
842
893
|
}
|
|
843
894
|
|
|
844
895
|
return result;
|
|
845
896
|
} catch (err) {
|
|
846
|
-
console.log(`[VSRepository] (runtime) Fatal error when trying to getOrThrow
|
|
897
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when trying to getOrThrow:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
847
898
|
throw err;
|
|
848
899
|
}
|
|
849
900
|
}
|
|
@@ -866,8 +917,8 @@ export class VSRepository {
|
|
|
866
917
|
|
|
867
918
|
let start;
|
|
868
919
|
if(showWorking){
|
|
869
|
-
console.log(`[VSRepository] (runtime) Executing remove
|
|
870
|
-
console.log(`[VSRepository] (runtime) Built arguments to remove
|
|
920
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing remove.`);
|
|
921
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to remove:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
871
922
|
start = performance.now();
|
|
872
923
|
}
|
|
873
924
|
try {
|
|
@@ -876,12 +927,12 @@ export class VSRepository {
|
|
|
876
927
|
if(showWorking) {
|
|
877
928
|
const end = performance.now();
|
|
878
929
|
const duration = (end - start).toFixed(2);
|
|
879
|
-
console.log(`[VSRepository] (runtime) Executed remove
|
|
930
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed remove (took: ${duration}ms).`);
|
|
880
931
|
}
|
|
881
932
|
|
|
882
933
|
return result;
|
|
883
934
|
} catch (err) {
|
|
884
|
-
console.log(`[VSRepository] (runtime) Fatal error when trying to remove
|
|
935
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when trying to remove:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
885
936
|
throw err;
|
|
886
937
|
}
|
|
887
938
|
}
|
|
@@ -898,7 +949,7 @@ export class VSRepository {
|
|
|
898
949
|
|
|
899
950
|
let start;
|
|
900
951
|
if(showWorking){
|
|
901
|
-
console.log(`[VSRepository] (runtime) Executing save
|
|
952
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing save.`);
|
|
902
953
|
start = performance.now();
|
|
903
954
|
}
|
|
904
955
|
|
|
@@ -1030,7 +1081,7 @@ export class VSRepository {
|
|
|
1030
1081
|
prismaArgs.where = where;
|
|
1031
1082
|
|
|
1032
1083
|
if(showWorking) {
|
|
1033
|
-
console.log(`[VSRepository] (runtime) Built arguments to save
|
|
1084
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to save:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
1034
1085
|
}
|
|
1035
1086
|
|
|
1036
1087
|
result = await db[buildInstance.tableName].upsert(prismaArgs);
|
|
@@ -1081,7 +1132,7 @@ export class VSRepository {
|
|
|
1081
1132
|
}
|
|
1082
1133
|
|
|
1083
1134
|
if(showWorking) {
|
|
1084
|
-
console.log(`[VSRepository] (runtime) Built arguments to save
|
|
1135
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to save:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
1085
1136
|
}
|
|
1086
1137
|
|
|
1087
1138
|
result = await db[buildInstance.tableName].create(prismaArgs);
|
|
@@ -1090,12 +1141,12 @@ export class VSRepository {
|
|
|
1090
1141
|
if(showWorking) {
|
|
1091
1142
|
const end = performance.now();
|
|
1092
1143
|
const duration = (end - start).toFixed(2);
|
|
1093
|
-
console.log(`[VSRepository] (runtime) Executed save
|
|
1144
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed save (took: ${duration}ms).`);
|
|
1094
1145
|
}
|
|
1095
1146
|
|
|
1096
1147
|
return result;
|
|
1097
1148
|
} catch (err) {
|
|
1098
|
-
console.log(`[VSRepository] (runtime) Fatal error when trying to save
|
|
1149
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when trying to save:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
1099
1150
|
throw err;
|
|
1100
1151
|
}
|
|
1101
1152
|
}
|
|
@@ -1113,19 +1164,19 @@ export class VSRepository {
|
|
|
1113
1164
|
|
|
1114
1165
|
let start;
|
|
1115
1166
|
if(showWorking){
|
|
1116
|
-
console.log(`[VSRepository] (runtime) Executing removeList
|
|
1117
|
-
console.log(`[VSRepository] (runtime) Built arguments to removeList
|
|
1167
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing removeList.`);
|
|
1168
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to removeList:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
1118
1169
|
start = performance.now();
|
|
1119
1170
|
}
|
|
1120
1171
|
try {
|
|
1121
1172
|
const result = await db[buildInstance.tableName].deleteMany(prismaArgs);
|
|
1122
1173
|
if(showWorking) {
|
|
1123
1174
|
const end = performance.now();
|
|
1124
|
-
console.log(`[VSRepository] (runtime) Executed removeList
|
|
1175
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed removeList (took: ${(end - start).toFixed(2)}ms).`);
|
|
1125
1176
|
}
|
|
1126
1177
|
return result;
|
|
1127
1178
|
} catch (err) {
|
|
1128
|
-
console.log(`[VSRepository] (runtime) Fatal error when trying to removeList
|
|
1179
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when trying to removeList:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
1129
1180
|
throw err;
|
|
1130
1181
|
}
|
|
1131
1182
|
}
|
|
@@ -1155,19 +1206,19 @@ export class VSRepository {
|
|
|
1155
1206
|
|
|
1156
1207
|
let start;
|
|
1157
1208
|
if(showWorking){
|
|
1158
|
-
console.log(`[VSRepository] (runtime) Executing getAll
|
|
1159
|
-
console.log(`[VSRepository] (runtime) Built arguments to getAll
|
|
1209
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing getAll.`);
|
|
1210
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to getAll:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
1160
1211
|
start = performance.now();
|
|
1161
1212
|
}
|
|
1162
1213
|
try {
|
|
1163
1214
|
const result = await db[buildInstance.tableName].findMany(prismaArgs);
|
|
1164
1215
|
if(showWorking) {
|
|
1165
1216
|
const end = performance.now();
|
|
1166
|
-
console.log(`[VSRepository] (runtime) Executed getAll
|
|
1217
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed getAll (took: ${(end - start).toFixed(2)}ms).`);
|
|
1167
1218
|
}
|
|
1168
1219
|
return result;
|
|
1169
1220
|
} catch (err) {
|
|
1170
|
-
console.log(`[VSRepository] (runtime) Fatal error when trying to getAll
|
|
1221
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when trying to getAll:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
1171
1222
|
throw err;
|
|
1172
1223
|
}
|
|
1173
1224
|
}
|
|
@@ -1183,19 +1234,19 @@ export class VSRepository {
|
|
|
1183
1234
|
|
|
1184
1235
|
let start;
|
|
1185
1236
|
if(showWorking){
|
|
1186
|
-
console.log(`[VSRepository] (runtime) Executing total
|
|
1187
|
-
console.log(`[VSRepository] (runtime) Built arguments to total
|
|
1237
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing total.`);
|
|
1238
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to total:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
1188
1239
|
start = performance.now();
|
|
1189
1240
|
}
|
|
1190
1241
|
try {
|
|
1191
1242
|
const result = await db[buildInstance.tableName].count(prismaArgs);
|
|
1192
1243
|
if(showWorking) {
|
|
1193
1244
|
const end = performance.now();
|
|
1194
|
-
console.log(`[VSRepository] (runtime) Executed total
|
|
1245
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed total (took: ${(end - start).toFixed(2)}ms).`);
|
|
1195
1246
|
}
|
|
1196
1247
|
return result;
|
|
1197
1248
|
} catch (err) {
|
|
1198
|
-
console.log(`[VSRepository] (runtime) Fatal error when trying to total
|
|
1249
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when trying to total:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
1199
1250
|
throw err;
|
|
1200
1251
|
}
|
|
1201
1252
|
}
|
|
@@ -1214,19 +1265,19 @@ export class VSRepository {
|
|
|
1214
1265
|
|
|
1215
1266
|
let start;
|
|
1216
1267
|
if(showWorking){
|
|
1217
|
-
console.log(`[VSRepository] (runtime) Executing has
|
|
1218
|
-
console.log(`[VSRepository] (runtime) Built arguments to has
|
|
1268
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing has.`);
|
|
1269
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to has:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
1219
1270
|
start = performance.now();
|
|
1220
1271
|
}
|
|
1221
1272
|
try {
|
|
1222
1273
|
const result = await db[buildInstance.tableName].findUnique(prismaArgs);
|
|
1223
1274
|
if(showWorking) {
|
|
1224
1275
|
const end = performance.now();
|
|
1225
|
-
console.log(`[VSRepository] (runtime) Executed has
|
|
1276
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed has (took: ${(end - start).toFixed(2)}ms).`);
|
|
1226
1277
|
}
|
|
1227
1278
|
return !!result;
|
|
1228
1279
|
} catch (err) {
|
|
1229
|
-
console.log(`[VSRepository] (runtime) Fatal error when trying to has
|
|
1280
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when trying to has:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
1230
1281
|
throw err;
|
|
1231
1282
|
}
|
|
1232
1283
|
}
|
|
@@ -1243,7 +1294,7 @@ export class VSRepository {
|
|
|
1243
1294
|
|
|
1244
1295
|
let start;
|
|
1245
1296
|
if(showWorking){
|
|
1246
|
-
console.log(`[VSRepository] (runtime) Executing patch
|
|
1297
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executing patch.`);
|
|
1247
1298
|
start = performance.now();
|
|
1248
1299
|
}
|
|
1249
1300
|
|
|
@@ -1364,7 +1415,7 @@ export class VSRepository {
|
|
|
1364
1415
|
prismaArgs.where = where;
|
|
1365
1416
|
|
|
1366
1417
|
if(showWorking) {
|
|
1367
|
-
console.log(`[VSRepository] (runtime) Built arguments to patch
|
|
1418
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Built arguments to patch:\n`, JSON.stringify(prismaArgs, null, 2));
|
|
1368
1419
|
}
|
|
1369
1420
|
|
|
1370
1421
|
result = await db[buildInstance.tableName].update(prismaArgs);
|
|
@@ -1372,12 +1423,12 @@ export class VSRepository {
|
|
|
1372
1423
|
if(showWorking) {
|
|
1373
1424
|
const end = performance.now();
|
|
1374
1425
|
const duration = (end - start).toFixed(2);
|
|
1375
|
-
console.log(`[VSRepository] (runtime) Executed patch
|
|
1426
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Executed patch (took: ${duration}ms).`);
|
|
1376
1427
|
}
|
|
1377
1428
|
|
|
1378
1429
|
return result;
|
|
1379
1430
|
} catch (err) {
|
|
1380
|
-
console.log(`[VSRepository] (runtime) Fatal error when trying to patch
|
|
1431
|
+
console.log(`[VSRepository] (${buildInstance.tableName}: runtime) Fatal error when trying to patch:\n`, JSON.stringify({ prismaArgs }, null, 2));
|
|
1381
1432
|
throw err;
|
|
1382
1433
|
}
|
|
1383
1434
|
}
|
package/package.json
CHANGED
|
@@ -20,15 +20,16 @@ const GENERATED_HEADER = `/**
|
|
|
20
20
|
|
|
21
21
|
`;
|
|
22
22
|
|
|
23
|
-
const command = args[0]
|
|
24
|
-
const commandArgs = command === 'generate' && args[0] !== command ? args : args.slice(1);
|
|
23
|
+
const command = args[0] || 'generate';
|
|
25
24
|
|
|
26
25
|
if (command !== 'generate') {
|
|
27
26
|
console.error(`Comando desconhecido: ${command}`);
|
|
28
|
-
console.error('
|
|
27
|
+
console.error('Use: vsrepo generate --output <dir-output> --prisma <path-prisma>');
|
|
29
28
|
process.exit(1);
|
|
30
29
|
}
|
|
31
30
|
|
|
31
|
+
const commandArgs = command === args[0] ? args.slice(1) : args;
|
|
32
|
+
|
|
32
33
|
const outputFlagIndex = commandArgs.findIndex((arg) => arg === '--output' || arg === '-o');
|
|
33
34
|
const prismaFlagIndex = commandArgs.findIndex((arg) => arg === '--prisma' || arg === '-p');
|
|
34
35
|
|
|
@@ -194,8 +195,8 @@ if (fs.existsSync(readmeSource)) {
|
|
|
194
195
|
}
|
|
195
196
|
|
|
196
197
|
console.log('\nVSRepository gerado com tipagem do Prisma.');
|
|
197
|
-
console.log(`Output: ${outputDir}`);
|
|
198
|
-
console.log(`Prisma usado em: ${prismaTargetPath}`);
|
|
198
|
+
console.log(`Output: ${path.relative(workspaceRoot, outputDir)}`);
|
|
199
|
+
console.log(`Prisma usado em: ${path.relative(workspaceRoot, prismaTargetPath)}`);
|
|
199
200
|
|
|
200
201
|
function stripKnownExtension(inputPath) {
|
|
201
202
|
return inputPath.replace(/\.(?:d\.ts|ts|js|mjs|cjs)$/i, '');
|