vsrepo 1.2.7 → 1.2.9

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
@@ -31,6 +31,7 @@ O VSRepository permite criar repositories fortemente tipados com:
31
31
  - [Configurando os métodos base](#configurando-os-métodos-base)
32
32
  - [Select Models](#select-models)
33
33
  - [Required Where](#requiredwhere)
34
+ - [Default Ordenation](#default-ordenation)
34
35
  - [Opção `see`](#opção-see)
35
36
  - [Métodos dinâmicos](#métodos-dinâmicos)
36
37
  - [Prefixos disponíveis](#prefixos-disponíveis)
@@ -485,7 +486,47 @@ const usuario = await usuarioRepository.findByEmail("joao@email.com");
485
486
 
486
487
  ---
487
488
 
488
- ## Opção `see`
489
+ ## Default Ordenation
490
+
491
+ `defaultOrdenation` define uma ordenação padrão aplicada automaticamente em todas as queries que aceitam `orderBy`, sem precisar repetir o argumento `order` em cada chamada.
492
+
493
+ ```ts
494
+ const usuarioRepository = setupVSRepo<Usuario, "usuario">()(({
495
+ tableName: "usuario",
496
+ pkName: "id",
497
+ defaultOrdenation: { criadoEm: "desc" },
498
+ }).build(prisma);
499
+ ```
500
+
501
+ Com isso, toda query de listagem já virá ordenada por `criadoEm` decrescente:
502
+
503
+ ```ts
504
+ // Internamente: ORDER BY criadoEm DESC
505
+ const usuarios = await usuarioRepository.getAll();
506
+
507
+ // Também aplica ao getAll com pagination
508
+ const paginados = await usuarioRepository.getAll({ pagination: { take: 10 } });
509
+ ```
510
+
511
+ **A `defaultOrdenation` é ignorada quando:**
512
+
513
+ - O método usa o sufixo `Ordered`, `OrderedAndPaginated` ou `PaginatedAndOrdered` — nesses casos o argumento `order` passado na chamada tem prioridade.
514
+ - O método dinâmico tem `injectOrdenation` configurado — a ordenação fixa do método prevalece.
515
+
516
+ ```ts
517
+ methods: {
518
+ findManyPaginatedAndOrdered: { map: true }, // ordem vem do argumento → defaultOrdenation ignorada
519
+ findManyByAtivo: { map: true }, // sem Ordered → defaultOrdenation aplicada
520
+ findManyByStatus: {
521
+ map: true,
522
+ injectOrdenation: { nome: "asc" }, // injectOrdenation → defaultOrdenation ignorada
523
+ },
524
+ }
525
+ ```
526
+
527
+ > `defaultOrdenation` aceita o mesmo tipo que o `orderBy` nativo do Prisma para o modelo — incluindo arrays de ordenações encadeadas.
528
+
529
+ ---
489
530
 
490
531
  Quando `softRemovekName` está configurado, todos os métodos base aceitam a opção `see` para controlar a visibilidade de registros soft-deletados:
491
532
 
@@ -1005,14 +1046,15 @@ type UsuarioPatchPayload = PatchObject<Prisma.UsuarioUpdateInput, typeof usuario
1005
1046
 
1006
1047
  ```ts
1007
1048
  setupVSRepo<TPayload, TTableName>()({
1008
- tableName: Uncapitalize<M>; // Nome da tabela no Prisma
1009
- pkName: keyof T; // Nome da primary key
1010
- softRemovekName?: keyof T & string; // Campo DateTime para soft-delete (opcional)
1011
- selectModels?: SelectModels<M>; // Projeções de dados nomeadas
1012
- defaultSelectModel?: keyof SM; // Select aplicado por padrão
1013
- requiredWhere?: WhereModel<M>; // Filtros sempre aplicados
1014
- relations?: RepositoryRelations<T>; // Configuração de relações
1015
- methods?: Record<string, MethodConfig<M, SM>>; // Métodos dinâmicos
1049
+ tableName: Uncapitalize<M>; // Nome da tabela no Prisma
1050
+ pkName: keyof T; // Nome da primary key
1051
+ softRemovekName?: keyof T & string; // Campo DateTime para soft-delete (opcional)
1052
+ selectModels?: SelectModels<M>; // Projeções de dados nomeadas
1053
+ defaultSelectModel?: keyof SM; // Select aplicado por padrão
1054
+ requiredWhere?: WhereModel<M>; // Filtros sempre aplicados
1055
+ defaultOrdenation?: OrdenationModel<M>; // Ordenação padrão para queries sem Ordered/injectOrdenation
1056
+ relations?: RepositoryRelations<T>; // Configuração de relações
1057
+ methods?: Record<string, MethodConfig<M, SM>>; // Métodos dinâmicos
1016
1058
  });
1017
1059
  ```
1018
1060
 
@@ -1106,4 +1148,6 @@ Para reportar problemas ou sugerir novas funcionalidades, abra uma **Issue**.
1106
1148
 
1107
1149
  **`softRemovekName` lança erro no build** — O campo informado deve ser do tipo `DateTime` no schema do Prisma. Tipos como `Boolean` ou `String` não são aceitos.
1108
1150
 
1109
- **`saveList`/`patchList` com `db` inválido** — O campo `db` nestes métodos aceita apenas `DbTransaction` (retorno de `prisma.$transaction`), não o cliente principal. Passar o `PrismaClient` diretamente causará comportamento inesperado.
1151
+ **`defaultOrdenation` não está sendo aplicada** — Verifique se o método não usa o sufixo `Ordered`, `OrderedAndPaginated` ou `PaginatedAndOrdered`, e se não possui `injectOrdenation` configurado. Ambos têm prioridade sobre a ordenação padrão.
1152
+
1153
+ **`saveList`/`patchList` com `db` inválido** — O campo `db` nestes métodos aceita apenas `DbTransaction` (retorno de `prisma.$transaction`), não o cliente principal. Passar o `PrismaClient` diretamente causará comportamento inesperado.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Tipos literais que representam os códigos de erro internos da biblioteca.
2
+ * Literal types representing the internal error codes of the library.
3
3
  */
4
4
  export type VSRepoErrorType =
5
5
  | 'VSREPO_CONFIG'
@@ -8,18 +8,18 @@ export type VSRepoErrorType =
8
8
  | 'VSREPO_RUNTIME';
9
9
 
10
10
  /**
11
- * Classe base para todos os erros lançados pelo Virtual Schema Repository.
11
+ * Base class for all errors thrown by the VSRepository.
12
12
  */
13
13
  export declare abstract class VSRepoError extends Error {
14
- /** Código interno usado para identificar a categoria do erro. */
14
+ /** Internal code used to identify the error category. */
15
15
  abstract readonly type: VSRepoErrorType;
16
16
 
17
17
  constructor(message: string, type: VSRepoErrorType);
18
18
  }
19
19
 
20
20
  /**
21
- * Lançado quando uma configuração inválida ou uma inconsistência de
22
- * configuração é detectada antes ou durante a inicialização do repositório.
21
+ * Thrown when an invalid configuration or a configuration inconsistency
22
+ * is detected before or during repository initialization.
23
23
  */
24
24
  export declare class VSRepoConfigError extends VSRepoError {
25
25
  readonly type: 'VSREPO_CONFIG';
@@ -27,8 +27,8 @@ export declare class VSRepoConfigError extends VSRepoError {
27
27
  }
28
28
 
29
29
  /**
30
- * Lançado quando a injeção da instância do Prisma falha ou quando o
31
- * repositório não pode ser finalizado por meio de `.build()`.
30
+ * Thrown when the Prisma instance injection fails or when the
31
+ * build configuration is incorrect in the `.build()`.
32
32
  */
33
33
  export declare class VSRepoBuildError extends VSRepoError {
34
34
  readonly type: 'VSREPO_BUILD';
@@ -36,8 +36,8 @@ export declare class VSRepoBuildError extends VSRepoError {
36
36
  }
37
37
 
38
38
  /**
39
- * Lançado quando ocorre um erro ao injetar novos métodos no repositório
40
- * por meio de `.extend()`.
39
+ * Thrown when an error occurs while injecting new methods into the repository
40
+ * via `.extend()`.
41
41
  */
42
42
  export declare class VSRepoExtendError extends VSRepoError {
43
43
  readonly type: 'VSREPO_EXTEND';
@@ -45,8 +45,8 @@ export declare class VSRepoExtendError extends VSRepoError {
45
45
  }
46
46
 
47
47
  /**
48
- * Lançado quando operações dinâmicas falham em tempo de execução, como
49
- * quando argumentos inválidos são passados para métodos.
48
+ * Thrown when dynamic operations fail at runtime, such as
49
+ * when invalid arguments are passed to methods.
50
50
  */
51
51
  export declare class VSRepoRuntimeError extends VSRepoError {
52
52
  readonly type: 'VSREPO_RUNTIME';
@@ -2,8 +2,8 @@ import { Prisma, PrismaClient } from '../generated/prisma/client';
2
2
  import { Decimal, JsonValue } from '@prisma/client/runtime/client';
3
3
 
4
4
  /**
5
- * Achata uma interseção de tipos em um único objeto,
6
- * evitando o erro "union type too complex to represent" do TypeScript.
5
+ * Flattens a type intersection into a single object,
6
+ * avoiding the TypeScript "union type too complex to represent" error.
7
7
  */
8
8
  type Simplify<T> = { [K in keyof T]: T[K] } & {};
9
9
 
@@ -16,17 +16,17 @@ type WidenField<T> =
16
16
  T;
17
17
 
18
18
  /**
19
- * Instância completa do Prisma Client usada para construir repositories.
19
+ * Full Prisma Client instance used to build repositories.
20
20
  */
21
21
  export type DbClient = PrismaClient;
22
22
 
23
23
  /**
24
- * Cliente transacional do Prisma retornado por `prisma.$transaction`.
24
+ * Prisma transactional client returned by `prisma.$transaction`.
25
25
  */
26
26
  export type DbTransaction = Prisma.TransactionClient;
27
27
 
28
28
  /**
29
- * Aceita tanto o cliente principal do Prisma quanto um cliente de transação.
29
+ * Accepts either the main Prisma client or a transaction client.
30
30
  */
31
31
  export type ClientOrTransaction = DbClient | DbTransaction;
32
32
 
@@ -37,32 +37,32 @@ type OrderPattern = {
37
37
  };
38
38
 
39
39
  /**
40
- * Opções de paginação aceitas pelos métodos com sufixo `Paginated`.
40
+ * Pagination options accepted by methods with the `Paginated` suffix.
41
41
  *
42
- * @template TCursor Tipo do cursor usado pelo modelo Prisma.
42
+ * @template TCursor Type of the cursor used by the Prisma model.
43
43
  */
44
44
  export type PaginationOptions<TCursor = unknown> = {
45
- /** Quantidade de registros a ignorar. */
45
+ /** Number of records to skip. */
46
46
  skip?: number;
47
- /** Quantidade máxima de registros retornados. */
47
+ /** Maximum number of records to return. */
48
48
  take?: number;
49
- /** Cursor tipado para paginação baseada em posição. */
49
+ /** Typed cursor for position-based pagination. */
50
50
  cursor?: TCursor;
51
51
  };
52
52
 
53
53
  /**
54
- * Ordenação aceita pelos métodos do repository.
54
+ * Ordering accepted by repository methods.
55
55
  *
56
- * Pode ser uma única ordenação ou uma lista de ordenações encadeadas.
56
+ * Can be a single ordering or a list of chained orderings.
57
57
  */
58
58
  export type OrderOptions = OrderPattern | OrderPattern[];
59
59
 
60
60
  /**
61
- * Modo de visibilidade para registros com soft-delete.
61
+ * Visibility mode for records with soft-delete.
62
62
  *
63
- * - `"active"` — retorna apenas registros não removidos (padrão).
64
- * - `"removed"` — retorna apenas registros removidos.
65
- * - `"all"` — retorna todos os registros, independentemente do status.
63
+ * - `"active"` — returns only non-deleted records (default).
64
+ * - `"removed"` — returns only deleted records.
65
+ * - `"all"` — returns all records regardless of their status.
66
66
  */
67
67
  export type SeeMode = 'active' | 'removed' | 'all';
68
68
 
@@ -195,7 +195,7 @@ type GetCreateManyInput<I> = I extends { createManyInput: infer CM } ? CM : unkn
195
195
  type GetUpdateManyInput<I> = I extends { updateManyInput: infer UM } ? UM : unknown;
196
196
  type GetWhereInput<I> = I extends { whereInput: infer W } ? NonNullable<W> : unknown;
197
197
  type GetCursorInput<I> = I extends { cursorInput: infer C } ? C : unknown;
198
- type GetOrderByInput<I> = I extends { orderByInput: infer OB } ? OB : OrderOptions;
198
+ type GetOrderByInput<I> = I extends { orderByInput: infer OB } ? NonNullable<OB> : OrderOptions;
199
199
 
200
200
  type ExtraArgs<M extends string, R extends string, I> = [
201
201
  ...(M extends 'upsertBy' ? [update: GetUpdateInput<I>, create: GetCreateInput<I>]
@@ -239,41 +239,41 @@ type CleanFields<R extends string> =
239
239
  R extends `${infer F}SkipDuplicates` ? F : R;
240
240
 
241
241
  /**
242
- * Opções adicionais aceitas pelos métodos do repository.
242
+ * Additional options accepted by repository methods.
243
243
  *
244
- * @template S Chaves disponíveis em `selectModels`.
244
+ * @template S Available keys in `selectModels`.
245
245
  */
246
246
  export type MethodOptions<S> = {
247
247
  /**
248
- * Select model a ser aplicado na operação.
248
+ * Select model to apply to the operation.
249
249
  *
250
- * @note Use `false` para retornar o payload completo do Prisma, sem select.
250
+ * @note Use `false` to return the full Prisma payload without a select.
251
251
  */
252
252
  selectModel?: S | false;
253
253
  /**
254
- * Cliente Prisma ou transação que deve executar a operação.
254
+ * Prisma client or transaction to use for the operation.
255
255
  */
256
256
  db?: ClientOrTransaction;
257
257
  /**
258
- * Modo de visibilidade para registros com soft-delete.
258
+ * Visibility mode for records with soft-delete.
259
259
  *
260
- * Só tem efeito se `softRemovekName` estiver configurado no repository.
260
+ * Only takes effect if `softRemovekName` is configured on the repository.
261
261
  *
262
- * - `"active"` — retorna apenas registros não removidos (padrão).
263
- * - `"removed"` — retorna apenas registros removidos.
264
- * - `"all"` — retorna todos os registros, ignorando o status de remoção.
262
+ * - `"active"` — returns only non-deleted records (default).
263
+ * - `"removed"` — returns only deleted records.
264
+ * - `"all"` — returns all records, ignoring deletion status.
265
265
  */
266
266
  see?: SeeMode;
267
267
  };
268
268
 
269
269
  /**
270
- * Versão de `MethodOptions` derivada diretamente de uma instância configurada de `VSRepository`.
270
+ * Version of `MethodOptions` derived directly from a configured `VSRepository` instance.
271
271
  *
272
- * @template TRepo Instância de `VSRepository` configurada (use `typeof meuVSRepo`).
272
+ * @template TRepo Configured `VSRepository` instance (use `typeof myVSRepo`).
273
273
  *
274
274
  * @example
275
- * const usuarioVSRepo = setupVSRepo<Usuario, "usuario">()(config);
276
- * type Opts = MethodOptionsModel<typeof usuarioVSRepo>;
275
+ * const userVSRepo = setupVSRepo<User, "user">()(config);
276
+ * type Opts = MethodOptionsModel<typeof userVSRepo>;
277
277
  */
278
278
  export type MethodOptionsModel<TRepo> =
279
279
  TRepo extends VSRepository<any, any, infer Config>
@@ -335,7 +335,7 @@ type ExtractPatternBase<K extends string> =
335
335
  type MethodFactory<T, M extends Prisma.ModelName, K extends string, SelectModels, DefaultSelect extends keyof SelectModels | false, I, MethodConf> =
336
336
  K extends `findWhere${string}`
337
337
  ? {
338
- /** @deprecated Use findOneWhere em seu lugar. */
338
+ /** @deprecated Use findOneWhere instead. */
339
339
  <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>>>;
340
340
  }
341
341
  : MethodFn<GetMappedMethod<K, MethodConf>, T, M, ExtractPatternBase<K>, SelectModels, DefaultSelect, I>;
@@ -349,6 +349,7 @@ type ExtractSelectModels<Config> = Config extends { selectModels: infer SM } ? S
349
349
  type ExtractDefaultSelect<Config> = Config extends { defaultSelectModel: infer D } ? D : never;
350
350
  type ExtractRelations<Config> = Config extends { relations: infer R } ? (R extends object ? R : {}) : {};
351
351
  type ExtractSoftRemovekName<Config> = Config extends { softRemovekName: infer S } ? S : never;
352
+ type ExtractDefaultOrdenation<Config> = Config extends { defaultOrdenation: infer O } ? O : never;
352
353
 
353
354
  type AggregateMethod<M extends Prisma.ModelName> = <A extends Prisma.TypeMap['model'][M]['operations']['aggregate']['args']>(
354
355
  prismaArgs: A,
@@ -377,148 +378,148 @@ type DynamicMethods<T, M extends Prisma.ModelName, Config, I> = Config extends {
377
378
  : {};
378
379
 
379
380
  /**
380
- * Agrupa os principais tipos de input do Prisma derivados de um modelo.
381
+ * Groups the main Prisma input types derived from a model.
381
382
  *
382
- * @template M Nome do modelo Prisma.
383
+ * @template M Prisma model name.
383
384
  */
384
385
  export type PrismaModelInputs<M extends Prisma.ModelName> = {
385
- /** Tipo do argumento `select` usado em consultas do modelo. */
386
+ /** Type of the `select` argument used in model queries. */
386
387
  select: Prisma.TypeMap['model'][M]['operations']['findMany']['args']['select'];
387
- /** Tipo do `data` usado em `create`. */
388
+ /** Type of the `data` used in `create`. */
388
389
  createInput: Prisma.TypeMap['model'][M]['operations']['create']['args']['data'];
389
- /** Tipo do `data` usado em `createMany`. */
390
+ /** Type of the `data` used in `createMany`. */
390
391
  createManyInput: Prisma.TypeMap['model'][M]['operations']['createMany']['args']['data'];
391
- /** Tipo do `data` usado em `update`. */
392
+ /** Type of the `data` used in `update`. */
392
393
  updateInput: Prisma.TypeMap['model'][M]['operations']['update']['args']['data'];
393
- /** Tipo do `data` usado em `updateMany`. */
394
+ /** Type of the `data` used in `updateMany`. */
394
395
  updateManyInput: Prisma.TypeMap['model'][M]['operations']['updateMany']['args']['data'];
395
- /** Tipo do `where` usado nas buscas do modelo. */
396
+ /** Type of the `where` used in model queries. */
396
397
  whereInput: Prisma.TypeMap['model'][M]['operations']['findMany']['args']['where'];
397
- /** Tipo do `orderBy` usado nas buscas do modelo. */
398
+ /** Type of the `orderBy` used in model queries. */
398
399
  orderByInput: Prisma.TypeMap['model'][M]['operations']['findMany']['args']['orderBy'];
399
- /** Tipo do cursor usado nas buscas do modelo. */
400
+ /** Type of the cursor used in model queries. */
400
401
  cursorInput: Prisma.TypeMap['model'][M]['operations']['findMany']['args']['cursor'];
401
- /** Tipo do payload `create` usado em `upsert`. */
402
+ /** Type of the `create` payload used in `upsert`. */
402
403
  upsertCreateInput: Prisma.TypeMap['model'][M]['operations']['upsert']['args']['create'];
403
- /** Tipo do payload `update` usado em `upsert`. */
404
+ /** Type of the `update` payload used in `upsert`. */
404
405
  upsertUpdateInput: Prisma.TypeMap['model'][M]['operations']['upsert']['args']['update'];
405
406
  };
406
407
 
407
408
  /**
408
- * Tipo do objeto `select` de um modelo Prisma.
409
+ * Type of the `select` object of a Prisma model.
409
410
  */
410
411
  export type SelectModel<M extends Prisma.ModelName> = PrismaModelInputs<M>['select'];
411
412
 
412
413
  /**
413
- * Mapa de selects nomeados e reutilizáveis para um modelo Prisma.
414
+ * Map of named, reusable selects for a Prisma model.
414
415
  */
415
416
  export type SelectModels<M extends Prisma.ModelName> = Record<string, SelectModel<M>>;
416
417
 
417
418
  /**
418
- * Tipo do objeto `where` de um modelo Prisma.
419
+ * Type of the `where` object of a Prisma model.
419
420
  */
420
421
  export type WhereModel<M extends Prisma.ModelName> = PrismaModelInputs<M>['whereInput'];
421
422
 
422
423
  /**
423
- * Tipo do objeto `orderBy` de um modelo Prisma.
424
+ * Type of the `orderBy` object of a Prisma model.
424
425
  */
425
426
  export type OrdenationModel<M extends Prisma.ModelName> = PrismaModelInputs<M>['orderByInput'];
426
427
 
427
428
  /**
428
- * Opções de paginação com cursor tipado para um modelo Prisma.
429
+ * Pagination options with typed cursor for a Prisma model.
429
430
  */
430
431
  export type PaginationModel<M extends Prisma.ModelName> = PaginationOptions<PrismaModelInputs<M>['cursorInput']>;
431
432
 
432
433
  /**
433
- * Payload base usado para criar um registro no `save`/`upsert` do modelo.
434
+ * Base payload used to create a record in the model's `save`/`upsert`.
434
435
  */
435
436
  export type ModelUpsertInput<M extends Prisma.ModelName> = PrismaModelInputs<M>['upsertCreateInput'];
436
437
 
437
438
  /**
438
- * Configuração de um método dinâmico definido em `methods`.
439
+ * Configuration for a dynamic method defined in `methods`.
439
440
  *
440
- * @template M Nome do modelo Prisma.
441
- * @template SelectModels Mapa de select models disponíveis no repository.
441
+ * @template M Prisma model name.
442
+ * @template SelectModels Map of select models available in the repository.
442
443
  */
443
444
  export type MethodConfig<M extends Prisma.ModelName, SelectModels = any> = {
444
- /** Define se o método será exposto no repository. */
445
+ /** Defines whether the method will be exposed on the repository. */
445
446
  readonly map: boolean;
446
- /** Sobrescreve o `defaultSelectModel` apenas para este método. */
447
+ /** Overrides `defaultSelectModel` for this method only. */
447
448
  readonly selectModel?: string | false;
448
- /** Controla se o método combina (`extending`) ou sobrescreve (`overwrite`) o `requiredWhere`. */
449
+ /** Controls whether the method combines (`extending`) or overwrites (`overwrite`) the `requiredWhere`. */
449
450
  readonly whereType?: 'overwrite' | 'extending';
450
- /** Redireciona a lógica para outro padrão de método válido. */
451
+ /** Redirects the logic to another valid method pattern. */
451
452
  readonly proxyTo?: ValidMethodPatterns;
452
- /** Adiciona um `where` extra além do `requiredWhere`. */
453
+ /** Adds an extra `where` on top of `requiredWhere`. */
453
454
  readonly pushWhere?: WhereModel<M>;
454
455
  /**
455
- * Define se `findBy` retorna um item (`one`) ou uma lista (`list`).
456
- * @deprecated Use `findOneBy` se quiser retornar um único resultado.
456
+ * Defines whether `findBy` returns a single item (`one`) or a list (`list`).
457
+ * @deprecated Use `findOneBy` if you want to return a single result.
457
458
  */
458
459
  readonly fbMode?: 'one' | 'list';
459
- /** Injeta uma ordenação fixa automaticamente na query. */
460
+ /** Injects a fixed ordering automatically into the query. */
460
461
  readonly injectOrdenation?: OrdenationModel<M>;
461
- /** Injeta uma paginação fixa automaticamente na query. */
462
+ /** Injects a fixed pagination automatically into the query. */
462
463
  readonly injectPagination?: PaginationModel<M>;
463
464
  };
464
465
 
465
466
  type BaseMethodConfig<TSelectKeys extends PropertyKey = string> = {
466
- /** Ativa ou desativa o método base no `build`. */
467
+ /** Enables or disables the base method in the `build`. */
467
468
  active?: boolean;
468
- /** Select model padrão usado pelo método base. */
469
+ /** Default select model used by the base method. */
469
470
  defaultSelect?: TSelectKeys;
470
- /** Ignora o `requiredWhere`. */
471
+ /** Ignores the `requiredWhere`. */
471
472
  ignoreRequiredWhere?: boolean;
472
473
  };
473
474
 
474
475
  /**
475
- * Configuração aplicada durante o `.build(prisma, config?)`.
476
+ * Configuration applied during `.build(prisma, config?)`.
476
477
  *
477
- * @template TSelectKeys Chaves válidas de `selectModels`.
478
+ * @template TSelectKeys Valid keys of `selectModels`.
478
479
  */
479
480
  export type BuildConfig<TSelectKeys extends PropertyKey = string> = {
480
481
  /**
481
- * Congela o objeto final do repository com `Object.freeze`.
482
- * @deprecated Não tem mais efeito prático na nova versão — o freeze é sempre aplicado.
482
+ * Freezes the final repository object with `Object.freeze`.
483
+ * @deprecated No longer has any practical effect in the next version — freeze will be always applied.
483
484
  */
484
485
  freeze?: boolean;
485
- /** Exibe logs internos de funcionamento no console. */
486
+ /** Prints internal working logs to the console. */
486
487
  showWorking?: boolean;
487
- /** Personaliza o comportamento dos métodos base automáticos. */
488
+ /** Customizes the behavior of the automatic base methods. */
488
489
  baseMethods?: {
489
- /** Configuração do método `get`. */
490
+ /** Configuration for the `get` method. */
490
491
  get?: BaseMethodConfig<TSelectKeys>;
491
- /** Configuração do método `getOrThrow`. */
492
+ /** Configuration for the `getOrThrow` method. */
492
493
  getOrThrow?: BaseMethodConfig<TSelectKeys>;
493
- /** Configuração do método `getList` (busca por lista de PKs). */
494
+ /** Configuration for the `getList` method (fetch by list of PKs). */
494
495
  getList?: BaseMethodConfig<TSelectKeys>;
495
- /** Configuração do método `remove`. */
496
+ /** Configuration for the `remove` method. */
496
497
  remove?: BaseMethodConfig<TSelectKeys>;
497
- /** Configuração do método `save`. */
498
+ /** Configuration for the `save` method. */
498
499
  save?: BaseMethodConfig<TSelectKeys>;
499
- /** Configuração do método `patch`. */
500
+ /** Configuration for the `patch` method. */
500
501
  patch?: BaseMethodConfig<TSelectKeys>;
501
- /** Configuração do método `merge`. */
502
+ /** Configuration for the `merge` method. */
502
503
  merge?: BaseMethodConfig<TSelectKeys>;
503
- /** Configuração do método `removeList` (exclusão em lote). Não aceita select. */
504
+ /** Configuration for the `removeList` method (batch deletion). Does not accept select. */
504
505
  removeList?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
505
- /** Configuração do método `getAll` (listagem total). */
506
+ /** Configuration for the `getAll` method (full listing). */
506
507
  getAll?: BaseMethodConfig<TSelectKeys>;
507
- /** Configuração do método `total` (contagem). Não aceita select. */
508
+ /** Configuration for the `total` method (count). Does not accept select. */
508
509
  total?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
509
- /** Configuração do método `has` (verificação de existência). Não aceita select. */
510
+ /** Configuration for the `has` method (existence check). Does not accept select. */
510
511
  has?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
511
- /** Configuração do método `saveList` (salvar em lote via transação). */
512
+ /** Configuration for the `saveList` method (batch save via transaction). */
512
513
  saveList?: BaseMethodConfig<TSelectKeys>;
513
- /** Configuração do método `patchList` (atualizar em lote via transação). */
514
+ /** Configuration for the `patchList` method (batch update via transaction). */
514
515
  patchList?: BaseMethodConfig<TSelectKeys>;
515
- /** Configuração do método `softRemove`. Só existe se `softRemovekName` estiver configurado. */
516
+ /** Configuration for the `softRemove` method. Only available if `softRemovekName` is configured. */
516
517
  softRemove?: BaseMethodConfig<TSelectKeys>;
517
- /** Configuração do método `softRemoveList`. Não aceita select. Só existe se `softRemovekName` estiver configurado. */
518
+ /** Configuration for the `softRemoveList` method. Does not accept select. Only available if `softRemovekName` is configured. */
518
519
  softRemoveList?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
519
- /** Configuração do método `restore`. Só existe se `softRemovekName` estiver configurado. */
520
+ /** Configuration for the `restore` method. Only available if `softRemovekName` is configured. */
520
521
  restore?: BaseMethodConfig<TSelectKeys>;
521
- /** Configuração do método `restoreList`. Não aceita select. Só existe se `softRemovekName` estiver configurado. */
522
+ /** Configuration for the `restoreList` method. Does not accept select. Only available if `softRemovekName` is configured. */
522
523
  restoreList?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
523
524
  };
524
525
  };
@@ -541,11 +542,11 @@ type ResolveCurrentReturn<M extends Prisma.ModelName, Models, S, D> =
541
542
  ? ([D] extends [never] ? FullModelType<M> : SelectedModel<M, D, Models>)
542
543
  : SelectedModel<M, S, Models>;
543
544
 
544
- // ─── helpers reutilizados dentro do tipo mapeado ────────────────────────────
545
- // ─── tipos de payload para relações ─────────────────────────────────────────
545
+ // ─── helpers reused within the mapped type ───────────────────────────────────
546
+ // ─── relation payload types ──────────────────────────────────────────────────
546
547
 
547
548
  /**
548
- * Versão distributiva de `Omit`, preservando unions ao remover propriedades.
549
+ * Distributive version of `Omit`, preserving unions when removing properties.
549
550
  */
550
551
  type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
551
552
  type ExtractUnionProp<T, K extends PropertyKey> = T extends any ? (K extends keyof T ? T[K] : never) : never;
@@ -564,18 +565,18 @@ type RelationPayload<TField, TRelationConfig, M extends Prisma.ModelName, K exte
564
565
  type TransformCreatePayload<U, T, M extends Prisma.ModelName, TRelations> =
565
566
  Omit<U, keyof TRelations> &
566
567
  {
567
- // Campos que são OBRIGATÓRIOS nesta ramificação específica da união do Prisma
568
+ // Fields that are REQUIRED in this specific branch of the Prisma union
568
569
  [K in Extract<keyof TRelations, keyof U> as {} extends Pick<U, K> ? never : K]:
569
570
  K extends keyof T ? RelationPayload<T[K], TRelations[K], M, K> : never;
570
571
  } &
571
572
  {
572
- // Campos que são OPCIONAIS nesta ramificação ou que não pertencem originalmente a ela
573
+ // Fields that are OPTIONAL in this branch or do not originally belong to it
573
574
  [K in keyof TRelations as K extends keyof U ? ({} extends Pick<U, K> ? K : never) : K]?:
574
575
  K extends keyof T ? RelationPayload<T[K], TRelations[K], M, K> : never;
575
576
  };
576
577
 
577
578
  /**
578
- * Payload aceito pelo `save` quando o repository possui relações configuradas.
579
+ * Payload accepted by `save` when the repository has configured relations.
579
580
  */
580
581
  type UpsertWithRelations<T, M extends Prisma.ModelName, TRelations> =
581
582
  ModelUpsertInput<M> extends infer U
@@ -602,7 +603,7 @@ type RelationUpdatePayload<TField, TRelationConfig, M extends Prisma.ModelName,
602
603
  : never;
603
604
 
604
605
  /**
605
- * Payload aceito pelo `patch` quando o repository possui relações configuradas.
606
+ * Payload accepted by `patch` when the repository has configured relations.
606
607
  */
607
608
  type UpdateWithRelations<T, M extends Prisma.ModelName, TRelations> =
608
609
  DistributiveOmit<PrismaModelInputs<M>['updateInput'], keyof TRelations> & {
@@ -610,7 +611,7 @@ type UpdateWithRelations<T, M extends Prisma.ModelName, TRelations> =
610
611
  };
611
612
 
612
613
  /**
613
- * Extrai o tipo de payload do método `save` a partir de uma instância de VSRepository configurada.
614
+ * Extracts the payload type of the `save` method from a configured VSRepository instance.
614
615
  */
615
616
  export type SaveObject<TInput, TRepo> =
616
617
  TRepo extends VSRepository<infer T, infer M, infer Config>
@@ -624,7 +625,7 @@ export type SaveObject<TInput, TRepo> =
624
625
  : never;
625
626
 
626
627
  /**
627
- * Extrai o tipo de payload do método `patch` a partir de uma instância de VSRepository configurada.
628
+ * Extracts the payload type of the `patch` method from a configured VSRepository instance.
628
629
  */
629
630
  export type PatchObject<TInput, TRepo> =
630
631
  TRepo extends VSRepository<infer T, infer M, infer Config>
@@ -644,8 +645,9 @@ type _Sel<Config> = ExtractSelectModels<Config>;
644
645
  type _Def<Config> = ExtractDefaultSelect<Config>;
645
646
  type _Rel<Config> = ExtractRelations<Config>;
646
647
  type _Soft<Config> = ExtractSoftRemovekName<Config>;
648
+ type _DOrd<Config> = ExtractDefaultOrdenation<Config>;
647
649
 
648
- // ─── tipo mapeado refatorado — otimizado para o compilador TS ────────────────
650
+ // ─── refactored mapped type — optimized for the TS compiler ──────────────────
649
651
 
650
652
  type AllBaseMethods<
651
653
  T,
@@ -657,84 +659,90 @@ type AllBaseMethods<
657
659
  TPk = ExtractPkName<T, Config>,
658
660
  TRelations = _Rel<Config>,
659
661
  TSoftKey = _Soft<Config>,
660
- I = PrismaModelInputs<M>
662
+ I = PrismaModelInputs<M>,
663
+ TDefaultOrdenation = _DOrd<Config>
661
664
  > = {
662
- /** Busca um registro pela chave primária (PK). */
665
+ /** Fetches a record by its primary key (PK). */
663
666
  get: <S extends keyof TSelects | false = _DS<Config, C, 'get', TSelects>>(
664
667
  pk: _Pk<T, Config>, options?: MethodOptions<S>
665
668
  ) => Promise<_Ret<M, TSelects, S, TDefault> | null>;
666
669
 
667
- /** Busca um registro pela PK e lança `VSRepoRuntimeError` se não encontrado. */
670
+ /** Fetches a record by PK and throws `VSRepoRuntimeError` if not found. */
668
671
  getOrThrow: <S extends keyof TSelects | false = _DS<Config, C, 'getOrThrow', TSelects>>(
669
672
  pk: _Pk<T, Config>, options?: MethodOptions<S>
670
673
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
671
674
 
672
- /** Busca múltiplos registros por uma lista de chaves primárias (PKs). */
675
+ /** Fetches multiple records by a list of primary keys (PKs). */
673
676
  getList: <S extends keyof TSelects | false = _DS<Config, C, 'getList', TSelects>>(
674
677
  pks: _Pk<T, Config>[], options?: MethodOptions<S>
675
678
  ) => Promise<_Ret<M, TSelects, S, TDefault>[]>;
676
679
 
677
- /** Remove um registro identificado pela chave primária (PK). */
680
+ /** Deletes a record identified by its primary key (PK). */
678
681
  remove: <S extends keyof TSelects | false = _DS<Config, C, 'remove', TSelects>>(
679
682
  pk: _Pk<T, Config>, options?: MethodOptions<S>
680
683
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
681
684
 
682
- /** Insere ou atualiza (upsert) um registro. */
685
+ /** Inserts or updates (upsert) a record. */
683
686
  save: <S extends keyof TSelects | false = _DS<Config, C, 'save', TSelects>>(
684
687
  obj: UpsertWithRelations<T, M, TRelations>, options?: MethodOptions<S>
685
688
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
686
689
 
687
- /** Salva um array de objetos em uma única transação automática. */
690
+ /** Saves an array of objects in a single automatic transaction. */
688
691
  saveList: <S extends keyof TSelects | false = _DS<Config, C, 'saveList', TSelects>>(
689
692
  objs: UpsertWithRelations<T, M, TRelations>[], options?: Omit<MethodOptions<S>, 'db'> & { db?: DbTransaction }
690
693
  ) => Promise<_Ret<M, TSelects, S, TDefault>[]>;
691
694
 
692
- /** Atualiza parcialmente (patch) um registro existente pela chave primária (PK). */
695
+ /** Partially updates (patch) an existing record by its primary key (PK). */
693
696
  patch: <S extends keyof TSelects | false = _DS<Config, C, 'patch', TSelects>>(
694
697
  pk: _Pk<T, Config>, obj: UpdateWithRelations<T, M, TRelations>, options?: MethodOptions<S>
695
698
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
696
699
 
697
- /** Atualiza parcialmente múltiplos registros via tuplas `[pk, obj]` em transação automática. */
700
+ /** Partially updates multiple records via `[pk, obj]` tuples in an automatic transaction. */
698
701
  patchList: <S extends keyof TSelects | false = _DS<Config, C, 'patchList', TSelects>>(
699
702
  tuples: [pk: _Pk<T, Config>, obj: UpdateWithRelations<T, M, TRelations>][], options?: Omit<MethodOptions<S>, 'db'> & { db?: DbTransaction }
700
703
  ) => Promise<_Ret<M, TSelects, S, TDefault>[]>;
701
704
 
702
- /** Busca um registro pela PK e faz deep merge com o objeto fornecido **em memória**. */
705
+ /** Fetches a record by PK and deep-merges it with the provided object **in memory**. */
703
706
  merge: <S extends keyof TSelects | false = _DS<Config, C, 'merge', TSelects>>(
704
707
  pk: _Pk<T, Config>, obj: UpdateWithRelations<T, M, TRelations>, options?: MethodOptions<S>
705
708
  ) => Promise<_Ret<M, TSelects, S, TDefault> | null>;
706
709
 
707
- /** Remove múltiplos registros pelas suas chaves primárias. */
710
+ /** Deletes multiple records by their primary keys. */
708
711
  removeList: (pks: _Pk<T, Config>[], options?: { db?: ClientOrTransaction }) => Promise<{ count: number }>;
709
712
 
710
- /** Busca todos os registros (respeita `requiredWhere` quando aplicado). */
713
+ /** Fetches all records (respects `requiredWhere` when set). */
711
714
  getAll: <S extends keyof TSelects | false = _DS<Config, C, 'getAll', TSelects>>(
712
715
  options?: MethodOptions<S> & {
713
716
  pagination?: PaginationOptions<I extends { cursorInput: infer Curs } ? Curs : unknown>;
717
+ /**
718
+ * Ordering to apply to the query.
719
+ * When omitted and `defaultOrdenation` is configured on the repository,
720
+ * the default ordering is applied automatically.
721
+ */
714
722
  order?: I extends { orderByInput: infer OB } ? OB : OrderOptions;
715
723
  }
716
724
  ) => Promise<_Ret<M, TSelects, S, TDefault>[]>;
717
725
 
718
- /** Retorna a quantidade total de registros. */
726
+ /** Returns the total number of records. */
719
727
  total: (options?: { db?: ClientOrTransaction; see?: SeeMode }) => Promise<number>;
720
728
 
721
- /** Verifica se um registro existe pela chave primária (PK). */
729
+ /** Checks whether a record exists by its primary key (PK). */
722
730
  has: (pk: _Pk<T, Config>, options?: { db?: ClientOrTransaction; see?: SeeMode }) => Promise<boolean>;
723
731
 
724
- /** Marca um registro como removido (soft-delete). */
732
+ /** Marks a record as deleted (soft-delete). */
725
733
  softRemove: <S extends keyof TSelects | false = _DS<Config, C, 'softRemove', TSelects>>(
726
734
  pk: _Pk<T, Config>, options?: Omit<MethodOptions<S>, 'see'>
727
735
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
728
736
 
729
- /** Marca múltiplos registros como removidos (soft-delete) em lote. */
737
+ /** Marks multiple records as deleted (soft-delete) in batch. */
730
738
  softRemoveList: (pks: _Pk<T, Config>[], options?: { db?: ClientOrTransaction }) => Promise<{ count: number }>;
731
739
 
732
- /** Restaura um registro marcado como removido (soft-delete). */
740
+ /** Restores a record previously marked as deleted (soft-delete). */
733
741
  restore: <S extends keyof TSelects | false = _DS<Config, C, 'restore', TSelects>>(
734
742
  pk: _Pk<T, Config>, options?: Omit<MethodOptions<S>, 'see'>
735
743
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
736
744
 
737
- /** Restaura múltiplos registros marcados como removidos (soft-delete) em lote. */
745
+ /** Restores multiple records previously marked as deleted (soft-delete) in batch. */
738
746
  restoreList: (pks: _Pk<T, Config>[], options?: { db?: ClientOrTransaction }) => Promise<{ count: number }>;
739
747
  };
740
748
 
@@ -748,9 +756,10 @@ type InjectedBaseMethods<
748
756
  TPk = ExtractPkName<T, Config>,
749
757
  TRelations = _Rel<Config>,
750
758
  TSoftKey = _Soft<Config>,
751
- I = PrismaModelInputs<M>
759
+ I = PrismaModelInputs<M>,
760
+ TDefaultOrdenation = _DOrd<Config>
752
761
  > = Pick<
753
- AllBaseMethods<T, M, Config, C, TSelects, TDefault, TPk, TRelations, TSoftKey, I>,
762
+ AllBaseMethods<T, M, Config, C, TSelects, TDefault, TPk, TRelations, TSoftKey, I, TDefaultOrdenation>,
754
763
  | (C extends { baseMethods: { get: { active: false } } } ? never : 'get')
755
764
  | (C extends { baseMethods: { getOrThrow: { active: false } } } ? never : 'getOrThrow')
756
765
  | (C extends { baseMethods: { getList: { active: false } } } ? never : 'getList')
@@ -772,56 +781,56 @@ type InjectedBaseMethods<
772
781
 
773
782
 
774
783
  /**
775
- * Configuração de relação para One-to-Many ou Many-to-Many.
784
+ * Relation configuration for One-to-Many or Many-to-Many.
776
785
  *
777
- * @template TItem O tipo da entidade relacionada.
786
+ * @template TItem Type of the related entity.
778
787
  */
779
788
  export type ManyRelationConfig<TItem> = {
780
- /** A chave primária (Primary Key) da entidade relacionada. */
789
+ /** Primary key of the related entity. */
781
790
  pk: keyof TItem;
782
- /** Tipo de relação: `otm` (One-to-Many) ou `mtm` (Many-to-Many). */
791
+ /** Relation type: `otm` (One-to-Many) or `mtm` (Many-to-Many). */
783
792
  mode: 'otm' | 'mtm';
784
- /** Comportamento de mutação: `set` (substitui tudo) ou `add` (adiciona aos existentes). */
793
+ /** Mutation behavior: `set` (replaces all) or `add` (appends to existing). */
785
794
  restriction: 'set' | 'add';
786
795
  };
787
796
 
788
797
  /**
789
- * Configuração de relação One-to-One.
798
+ * One-to-One relation configuration.
790
799
  *
791
- * @template TItem O tipo da entidade relacionada.
800
+ * @template TItem Type of the related entity.
792
801
  */
793
802
  export type OneToOneRelationConfig<TItem> = {
794
- /** A chave primária (Primary Key) da entidade relacionada. */
803
+ /** Primary key of the related entity. */
795
804
  pk: keyof TItem;
796
- /** Tipo de relação: `oto` (One-to-One). */
805
+ /** Relation type: `oto` (One-to-One). */
797
806
  mode: 'oto';
798
- /** Comportamento de mutação permitido para salvar. */
807
+ /** Allowed mutation behavior for saving. */
799
808
  restriction: 'set' | 'add';
800
809
  };
801
810
 
802
811
  /**
803
- * Configuração de relação Many-to-One.
812
+ * Many-to-One relation configuration.
804
813
  *
805
- * @template TItem O tipo da entidade relacionada.
814
+ * @template TItem Type of the related entity.
806
815
  */
807
816
  export type ManyToOneRelationConfig<TItem> = {
808
- /** A chave primária (Primary Key) da entidade relacionada. */
817
+ /** Primary key of the related entity. */
809
818
  pk: keyof TItem;
810
- /** Tipo de relação: `mto` (Many-to-One). */
819
+ /** Relation type: `mto` (Many-to-One). */
811
820
  mode: 'mto';
812
- /** Comportamento de mutação permitido para salvar. */
821
+ /** Allowed mutation behavior for saving. */
813
822
  restriction: 'set' | 'add';
814
823
  /**
815
- * Habilita a possibilidade de desvincular a relação, tornando a chave estrangeira nula.
816
- * @deprecated Use `nullable` (com letras minúsculas) em vez de `nullAble`.
824
+ * Enables the ability to unlink the relation, setting the foreign key to null.
825
+ * @deprecated Use `nullable` (lowercase) instead of `nullAble`.
817
826
  */
818
827
  nullAble?: boolean;
819
- /** Habilita a possibilidade de desvincular a relação, tornando a chave estrangeira nula. */
828
+ /** Enables the ability to unlink the relation, setting the foreign key to null. */
820
829
  nullable?: boolean;
821
830
  };
822
831
 
823
832
  /**
824
- * Infere automaticamente a configuração de relação possível a partir de um campo.
833
+ * Automatically infers the possible relation configuration from a field.
825
834
  */
826
835
  export type ExtractRelationConfig<TField> = NonNullable<TField> extends infer NonNull
827
836
  ? NonNull extends Date | Buffer | Uint8Array | Decimal | JsonValue ? never
@@ -831,7 +840,7 @@ export type ExtractRelationConfig<TField> = NonNullable<TField> extends infer No
831
840
  : never;
832
841
 
833
842
  /**
834
- * Mapa das relações configuráveis de um tipo de entidade.
843
+ * Map of configurable relations for an entity type.
835
844
  */
836
845
  export type RepositoryRelations<T> = {
837
846
  [K in keyof T as ExtractRelationConfig<T[K]> extends never ? never : K]?: ExtractRelationConfig<T[K]>;
@@ -840,67 +849,62 @@ export type RepositoryRelations<T> = {
840
849
  type AnySelect<M extends Prisma.ModelName> = Prisma.TypeMap['model'][M]['operations']['findMany']['args']['select'];
841
850
 
842
851
  /**
843
- * Configuração principal usada em `setupVSRepo<T, M>()(config)`.
852
+ * Main configuration used in `setupVSRepo<T, M>()(config)`.
844
853
  *
845
- * @template T Tipo da entidade manipulada pelo repository.
846
- * @template M Nome do modelo Prisma.
847
- * @template SM Mapa de select models nomeados.
854
+ * @template T Type of the entity managed by the repository.
855
+ * @template M Prisma model name.
856
+ * @template SM Map of named select models.
848
857
  */
849
858
  export type RepoConfig<T, M extends Prisma.ModelName, SM extends Record<string, AnySelect<M>> = Record<string, AnySelect<M>>> = {
850
859
  tableName: Uncapitalize<M>;
851
860
  pkName: keyof T;
852
- /**
853
- * Nome do campo `DateTime` usado para soft-delete.
854
- *
855
- * Quando configurado, habilita os métodos `softRemove`, `softRemoveList`, `restore` e `restoreList`.
856
- * O campo **deve** ser do tipo `DateTime` no schema do Prisma — o VSRepository valida isso no `build`.
857
- */
858
861
  softRemovekName?: keyof T & string;
859
862
  selectModels?: SM;
860
863
  defaultSelectModel?: Extract<keyof SM, string>;
861
864
  requiredWhere?: WhereModel<M>;
865
+ defaultOrdenation?: OrdenationModel<M>;
862
866
  relations?: RepositoryRelations<T>;
863
867
  methods?: Record<string, MethodConfig<M, SM>>;
864
868
  };
865
869
 
866
870
  /**
867
- * Tipo final retornado por `.build(prisma)`.
871
+ * Final type returned by `.build(prisma)`.
868
872
  *
869
- * Combina métodos dinâmicos, métodos base e extensões personalizadas.
873
+ * Combines dynamic methods, base methods, and custom extensions.
870
874
  */
871
875
  type BuiltRepository<T extends object, M extends Prisma.ModelName, Config extends RepoConfig<T, M, any>, C extends BuildConfig<any> | undefined> = {
872
876
  /**
873
- * Estende o repository com métodos personalizados sem perder a tipagem.
877
+ * Extends the repository with custom methods without losing type inference.
874
878
  */
875
879
  extend<E>(extensionFunc: (repo: BuiltRepository<T, M, Config, C>) => E): BuiltRepository<T, M, Config, C> & E;
876
880
 
877
881
  /**
878
- * Instância do Prisma Client passada no `build`.
882
+ * The Prisma Client instance passed to `build`.
879
883
  */
880
884
  readonly prisma: DbClient;
881
885
  } & DynamicMethods<T, M, Config, PrismaModelInputs<M>> & InjectedBaseMethods<T, M, Config, C>;
882
886
 
883
887
  /**
884
- * Fábrica tipada de repositories baseada na configuração do modelo Prisma.
888
+ * Typed repository factory based on the Prisma model configuration.
885
889
  */
886
890
  export declare class VSRepository<T extends object, M extends Prisma.ModelName, const Config extends RepoConfig<T, M, any> = RepoConfig<T, M, any>> {
887
- /** Configuração original informada no `setupVSRepo`. */
891
+ /** Original configuration provided to `setupVSRepo`. */
888
892
  readonly config: Config;
889
893
  /**
890
- * Cria uma instância configurável de `VSRepository`.
894
+ * Creates a configurable instance of `VSRepository`.
891
895
  */
892
896
  constructor(config: Config);
893
897
  /**
894
- * Constrói o repository final com os métodos base e dinâmicos.
898
+ * Builds the final repository with base and dynamic methods.
895
899
  */
896
900
  build<C extends BuildConfig<keyof ExtractSelectModels<Config>>>(prisma: DbClient, config?: C): BuiltRepository<T, M, Config, C>;
897
901
  vsrepocache: never;
898
902
  }
899
903
 
900
904
  /**
901
- * Infere o tipo de um repository já configurado a partir de uma instância de `VSRepository`.
905
+ * Infers the type of an already-configured repository from a `VSRepository` instance.
902
906
  *
903
- * Também permite informar manualmente o `BuildConfig` e o tipo de extensões.
907
+ * Also allows manually providing the `BuildConfig` and extensions type.
904
908
  */
905
909
  export type RepositoryOf<TRepo, C extends BuildConfig<any> | undefined = undefined, E = unknown> =
906
910
  TRepo extends VSRepository<infer T, infer M, infer Config>
@@ -908,16 +912,67 @@ export type RepositoryOf<TRepo, C extends BuildConfig<any> | undefined = undefin
908
912
  : never;
909
913
 
910
914
  /**
911
- * Tipo utilitário usado para validar a configuração de um repository em tempo de compilação.
915
+ * Utility type used to validate a repository configuration at compile time.
912
916
  */
913
917
  export type ValidateRepoConfig<T extends object, M extends Prisma.ModelName, Config> = {
918
+ /**
919
+ * Name of the table mapped by Prisma (usually uncapitalized).
920
+ */
914
921
  tableName: Uncapitalize<M>;
922
+
923
+ /**
924
+ * Name of the field that represents the entity's primary key (Primary Key).
925
+ */
915
926
  pkName: keyof T;
927
+
928
+ /**
929
+ * Name of the `DateTime` field used for soft-delete.
930
+ *
931
+ * When configured, enables the `softRemove`, `softRemoveList`, `restore`, and `restoreList` methods.
932
+ * The field **must** be of type `DateTime` in the Prisma schema — VSRepository validates this during `build`.
933
+ */
916
934
  softRemovekName?: keyof T & string;
935
+
936
+ /**
937
+ * Defines named and reusable data projections (selects).
938
+ * Allows creating different views of the same entity (e.g., `public`, `minimal`, `internal`).
939
+ */
917
940
  selectModels?: SelectModels<M>;
941
+
942
+ /**
943
+ * Defines which select (a key from `selectModels`) will be used automatically
944
+ * when none is specified in the method call.
945
+ * It is highly recommended to define it whenever `selectModels` are used.
946
+ */
918
947
  defaultSelectModel?: string;
948
+
949
+ /**
950
+ * Defines global filters that will be automatically applied to all repository queries.
951
+ * Useful for tenant isolation (multi-tenancy) or base restrictions (e.g., `isActive: true`).
952
+ */
919
953
  requiredWhere?: WhereModel<M>;
954
+
955
+ /**
956
+ * Default ordering automatically injected into all queries that accept `orderBy`,
957
+ * unless the method already has `injectOrdenation` configured or uses the `Ordered` suffix.
958
+ *
959
+ * Useful for ensuring a consistent sort order across the repository without repeating
960
+ * the `order` argument on every call.
961
+ */
962
+ defaultOrdenation?: OrdenationModel<M>;
963
+
964
+ /**
965
+ * Configures automatic relation management.
966
+ * When configured, allows the `save`, `saveList`, `patch`, and `patchList` methods
967
+ * to automatically handle linking, creation, or cascading deletion of related records.
968
+ */
920
969
  relations?: RepositoryRelations<T>;
970
+
971
+ /**
972
+ * Definition of dynamic repository methods.
973
+ * Behaviors and return types are automatically inferred from the method's name
974
+ * (e.g., `findOneByEmail`, `findManyPaginated`) or proxied via the `proxyTo` property.
975
+ */
921
976
  methods?: {
922
977
  [K in keyof (Config extends { methods: infer Meth } ? Meth : {})]: K extends string
923
978
  ? MethodConfig<M, Config extends { selectModels: infer SM } ? SM : any> & (K extends ValidMethodPatterns ? {} : { proxyTo: ValidMethodPatterns })
@@ -926,8 +981,8 @@ export type ValidateRepoConfig<T extends object, M extends Prisma.ModelName, Con
926
981
  };
927
982
 
928
983
  /**
929
- * Função para inicializar e configurar o `repository`.
930
- * As configurações passadas nele são as que serão lidas ao executar o `.build()`.
984
+ * Function to initialize and configure the `repository`.
985
+ * The configuration passed here is what will be read when `.build()` is called.
931
986
  */
932
987
  export declare function setupVSRepo<T extends object, M extends Prisma.ModelName>(): <
933
988
  const SM extends Record<string, SelectModel<M>>,
@@ -39,6 +39,7 @@ class VSRepository {
39
39
  requiredWhere;
40
40
  relations;
41
41
  methods;
42
+ defaultOrdenation;
42
43
  constructor(config) {
43
44
  const validatedConfig = (0, constructor_config_validate_1.validateConstructorConfig)(config);
44
45
  this.vsrepocache = new Map();
@@ -50,6 +51,7 @@ class VSRepository {
50
51
  this.relations = validatedConfig.relations;
51
52
  this.requiredWhere = validatedConfig.requiredWhere;
52
53
  this.methods = validatedConfig.methods;
54
+ this.defaultOrdenation = validatedConfig.defaultOrdenation;
53
55
  }
54
56
  extend(extensionFunc) {
55
57
  const extension = (0, extension_validate_1.validateExtension)(extensionFunc, this);
@@ -139,6 +141,7 @@ class VSRepository {
139
141
  updatePayload: dinamicMethodInfo.updateIndex !== undefined
140
142
  ? args.at(dinamicMethodInfo.updateIndex)
141
143
  : undefined,
144
+ withOrdenationAndPagination: !dinamicMethodInfo.ignoreOrderByAndPagination,
142
145
  };
143
146
  if (!dinamicMethodInfo.ignoreWhere) {
144
147
  resolveDbAndPrismaArgsData.specificWhere = (0, specific_where_resolve_1.resolveSpecificWhere)(args, dinamicMethodWhereOps.prettyWheres);
@@ -92,6 +92,7 @@ function resolveBaseMethods(instance, config) {
92
92
  options: restOptions,
93
93
  pagination,
94
94
  ordenation: order,
95
+ withOrdenationAndPagination: true,
95
96
  });
96
97
  const start = showWorking
97
98
  ? (0, logger_util_1.performanceLoggerStart)(tableName, "getAll", prismaArgs)
@@ -5,7 +5,7 @@ const method_options_validate_1 = require("../validation/method-options.validate
5
5
  const merge_wheres_resolve_1 = require("./merge-wheres.resolve");
6
6
  const select_resolve_1 = require("./select.resolve");
7
7
  function resolveDbAndPrismaArgs(data) {
8
- const { baseConfig, instance, options, wherePkValue, withoutSelect, withoutWhere, specificSelect, dataPayload, createPayload, updatePayload, alreadyValidatedOptions, specificWhere, pushWhere, ordenation, pagination, skipDuplicates, forceSeeMode, } = data;
8
+ const { baseConfig, instance, options, wherePkValue, withoutSelect, withoutWhere, specificSelect, dataPayload, createPayload, updatePayload, alreadyValidatedOptions, specificWhere, pushWhere, ordenation, pagination, skipDuplicates, forceSeeMode, withOrdenationAndPagination, } = data;
9
9
  const validatedOptions = (alreadyValidatedOptions && options)
10
10
  ? options
11
11
  : (0, method_options_validate_1.validateMethodOptions)(options, instance);
@@ -31,13 +31,15 @@ function resolveDbAndPrismaArgs(data) {
31
31
  if (updatePayload) {
32
32
  prismaArgs.update = updatePayload;
33
33
  }
34
- if (ordenation) {
35
- prismaArgs.orderBy = ordenation;
36
- }
37
- if (pagination) {
38
- prismaArgs.skip = pagination.skip;
39
- prismaArgs.take = pagination.take;
40
- prismaArgs.cursor = pagination.cursor;
34
+ if (withOrdenationAndPagination) {
35
+ if (instance.defaultOrdenation || ordenation) {
36
+ prismaArgs.orderBy = ordenation ?? instance.defaultOrdenation;
37
+ }
38
+ if (pagination) {
39
+ prismaArgs.skip = pagination.skip;
40
+ prismaArgs.take = pagination.take;
41
+ prismaArgs.cursor = pagination.cursor;
42
+ }
41
43
  }
42
44
  if (skipDuplicates !== undefined) {
43
45
  prismaArgs.skipDuplicates = skipDuplicates;
@@ -37,6 +37,7 @@ function validateConstructorConfig(config) {
37
37
  injectPagination: schemas_util_1.objectSchema.optional(),
38
38
  }))
39
39
  .optional(),
40
+ defaultOrdenation: schemas_util_1.objectSchema.or(zod_1.default.array(schemas_util_1.objectSchema)).optional(),
40
41
  })
41
42
  .superRefine((config, ctx) => {
42
43
  if (config.defaultSelectModel && !config.selectModels?.[config.defaultSelectModel]) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vsrepo",
3
- "version": "1.2.7",
3
+ "version": "1.2.9",
4
4
  "description": "Uma biblioteca de repository pattern para Prisma",
5
5
  "homepage": "https://github.com/jaobrabo123/VSRepository#readme",
6
6
  "repository": {