vsrepo 1.4.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +827 -1322
  2. package/README.pt-BR.md +833 -1325
  3. package/dist/VSRepoAdapter.d.ts +109 -0
  4. package/dist/VSRepoAdapter.js +18 -0
  5. package/dist/VSRepository.d.ts +166 -1201
  6. package/dist/VSRepository.js +327 -237
  7. package/dist/decorators/dynamic-method.decorator.d.ts +25 -0
  8. package/dist/decorators/dynamic-method.decorator.js +38 -0
  9. package/dist/decorators/query-method.decorator.d.ts +27 -0
  10. package/dist/decorators/query-method.decorator.js +45 -0
  11. package/dist/errors/VSRepoAdapterError.d.ts +22 -0
  12. package/dist/errors/VSRepoAdapterError.js +31 -0
  13. package/dist/errors/VSRepoError.d.ts +15 -0
  14. package/dist/errors/VSRepoError.js +21 -0
  15. package/dist/index.d.ts +38 -1
  16. package/dist/index.js +28 -15
  17. package/dist/internal/constants/debug-arg-symbol.constant.d.ts +1 -0
  18. package/dist/internal/constants/debug-arg-symbol.constant.js +4 -0
  19. package/dist/internal/constants/dynamic-methods-key.constant.d.ts +1 -0
  20. package/dist/internal/constants/query-methods-key.constant.d.ts +1 -0
  21. package/dist/internal/constants/query-methods-key.constant.js +4 -0
  22. package/dist/internal/enums/adapter-error-code.enum.d.ts +125 -0
  23. package/dist/internal/enums/adapter-error-code.enum.js +129 -0
  24. package/dist/internal/enums/transaction-isolation-level.enum.d.ts +16 -0
  25. package/dist/internal/enums/transaction-isolation-level.enum.js +20 -0
  26. package/dist/internal/enums/vs-log-level.enum.d.ts +18 -0
  27. package/dist/internal/enums/vs-log-level.enum.js +22 -0
  28. package/dist/internal/enums/vsrepo-error-type.enum.d.ts +19 -0
  29. package/dist/internal/enums/vsrepo-error-type.enum.js +23 -0
  30. package/dist/internal/resolvers/dynamic-methods.resolver.d.ts +23 -0
  31. package/dist/internal/resolvers/dynamic-methods.resolver.js +910 -0
  32. package/dist/internal/resolvers/merge-wheres.resolver.d.ts +7 -0
  33. package/dist/internal/resolvers/merge-wheres.resolver.js +26 -0
  34. package/dist/internal/utils/uncapitalize.util.d.ts +1 -0
  35. package/dist/internal/utils/vs-logger.util.d.ts +25 -0
  36. package/dist/internal/utils/vs-logger.util.js +139 -0
  37. package/dist/internal/validators/decorators.validator.d.ts +8 -0
  38. package/dist/internal/validators/decorators.validator.js +75 -0
  39. package/dist/internal/validators/schemas/ordering.schema.d.ts +3 -0
  40. package/dist/internal/validators/schemas/ordering.schema.js +38 -0
  41. package/dist/internal/validators/schemas/pagination.schema.d.ts +6 -0
  42. package/dist/internal/validators/schemas/pagination.schema.js +40 -0
  43. package/dist/internal/validators/schemas/where.schema.d.ts +7 -0
  44. package/dist/internal/validators/schemas/where.schema.js +42 -0
  45. package/dist/internal/validators/vsrepo.validator.d.ts +40 -0
  46. package/dist/internal/validators/vsrepo.validator.js +182 -0
  47. package/dist/types/adapter/adapter-method-options.type.d.ts +24 -0
  48. package/dist/types/adapter/adapter-query-options.type.d.ts +5 -0
  49. package/dist/types/decorators/dynamic-method-options.type.d.ts +14 -0
  50. package/dist/types/decorators/query-method-options.type.d.ts +15 -0
  51. package/dist/types/dynamic-methods/dynamic-method-customization.type.d.ts +7 -0
  52. package/dist/types/dynamic-methods/dynamic-method-info.type.d.ts +18 -0
  53. package/dist/types/dynamic-methods/dynamic-method-where-ops.type.d.ts +6 -0
  54. package/dist/types/utils/count-result.type.d.ts +9 -0
  55. package/dist/types/utils/decimal-like.type.d.ts +23 -0
  56. package/dist/types/utils/deep-partial.type.d.ts +14 -0
  57. package/dist/types/utils/keys-of-type.type.d.ts +20 -0
  58. package/dist/types/utils/methods-options.type.d.ts +23 -0
  59. package/dist/types/utils/numeric-keys.type.d.ts +24 -0
  60. package/dist/types/utils/numeric-like.type.d.ts +10 -0
  61. package/dist/types/utils/ordering.type.d.ts +39 -0
  62. package/dist/types/utils/pagination.type.d.ts +11 -0
  63. package/dist/types/utils/perform-data.type.d.ts +4 -0
  64. package/dist/types/utils/primitive.type.d.ts +7 -0
  65. package/dist/types/utils/query-method-arg.type.d.ts +27 -0
  66. package/dist/types/utils/restrict-method-options.type.d.ts +14 -0
  67. package/dist/types/utils/see-mode.type.d.ts +12 -0
  68. package/dist/types/vsrepo/vsrepo-args.type.d.ts +9 -0
  69. package/dist/types/vsrepo/vsrepo-method.type.d.ts +4 -0
  70. package/dist/types/vsrepo/vsrepo-method.type.js +2 -0
  71. package/dist/types/vsrepo/vsrepo-options.type.d.ts +34 -0
  72. package/dist/types/vsrepo/vsrepo-options.type.js +2 -0
  73. package/dist/types/vsrepo/vsrepo-orm-types.type.d.ts +17 -0
  74. package/dist/types/vsrepo/vsrepo-orm-types.type.js +2 -0
  75. package/dist/types/vsrepo/vsrepo-pretty-where.type.d.ts +7 -0
  76. package/dist/types/vsrepo/vsrepo-pretty-where.type.js +2 -0
  77. package/dist/types/vsrepo/vsrepo-query-options.type.d.ts +17 -0
  78. package/dist/types/vsrepo/vsrepo-query-options.type.js +2 -0
  79. package/dist/types/vsrepo/vsrepo-query.type.d.ts +5 -0
  80. package/dist/types/vsrepo/vsrepo-query.type.js +2 -0
  81. package/dist/types/vsrepo/vsrepo-relations.type.d.ts +26 -0
  82. package/dist/types/vsrepo/vsrepo-relations.type.js +2 -0
  83. package/dist/types/vsrepo/vsrepo-resolve-args-data.type.d.ts +19 -0
  84. package/dist/types/vsrepo/vsrepo-resolve-args-data.type.js +2 -0
  85. package/dist/types/vsrepo/vsrepo-select.type.d.ts +15 -0
  86. package/dist/types/vsrepo/vsrepo-select.type.js +2 -0
  87. package/dist/types/vsrepo/vsrepo-transaction-options.type.d.ts +12 -0
  88. package/dist/types/vsrepo/vsrepo-transaction-options.type.js +2 -0
  89. package/dist/types/vsrepo/vsrepo-ugly-where.type.d.ts +9 -0
  90. package/dist/types/vsrepo/vsrepo-ugly-where.type.js +2 -0
  91. package/dist/types/vsrepo/vsrepo-where.type.d.ts +99 -0
  92. package/dist/types/vsrepo/vsrepo-where.type.js +2 -0
  93. package/package.json +16 -37
  94. package/README-DynamicRepo.md +0 -625
  95. package/README-DynamicRepo.pt-BR.md +0 -625
  96. package/dist/DynamicRepository.d.ts +0 -497
  97. package/dist/DynamicRepository.js +0 -26
  98. package/dist/VSRepoError.d.ts +0 -83
  99. package/dist/VSRepoError.js +0 -17
  100. package/dist/internal/decorators/dynamic-method.decorator.js +0 -14
  101. package/dist/internal/decorators/query-method.decorator.js +0 -20
  102. package/dist/internal/entities/dynamic-method-metadata.entity.js +0 -26
  103. package/dist/internal/errors/vs-repo.error.js +0 -31
  104. package/dist/internal/resolvers/base-methods.resolve.js +0 -541
  105. package/dist/internal/resolvers/create-update-payloads-with-relations.resolve.js +0 -143
  106. package/dist/internal/resolvers/data-payload-with-relations.resolve.js +0 -60
  107. package/dist/internal/resolvers/dbAndPrismaArgs.resolve.js +0 -63
  108. package/dist/internal/resolvers/dynamic-method-customization.resolve.js +0 -57
  109. package/dist/internal/resolvers/dynamic-method-info.resolve.js +0 -279
  110. package/dist/internal/resolvers/dynamic-methods-metadata.resolve.js +0 -15
  111. package/dist/internal/resolvers/merge-wheres.resolve.js +0 -22
  112. package/dist/internal/resolvers/pretty-wheres.resolve.js +0 -87
  113. package/dist/internal/resolvers/select.resolve.js +0 -7
  114. package/dist/internal/resolvers/specific-where.resolve.js +0 -84
  115. package/dist/internal/resolvers/ugly-where.resolve.js +0 -178
  116. package/dist/internal/utils/logger.util.js +0 -21
  117. package/dist/internal/utils/schemas.util.js +0 -31
  118. package/dist/internal/validation/build-config.validate.js +0 -84
  119. package/dist/internal/validation/constructor-config.validate.js +0 -64
  120. package/dist/internal/validation/dynamic-method-config.validate.js +0 -19
  121. package/dist/internal/validation/extension.validate.js +0 -15
  122. package/dist/internal/validation/is-object.validate.js +0 -6
  123. package/dist/internal/validation/method-options.validate.js +0 -42
  124. package/dist/internal/validation/obj-with-relations.validate.js +0 -37
  125. package/dist/internal/validation/prisma-client.validate.js +0 -10
  126. package/dist/internal/validation/query-method-arg.validate.js +0 -22
  127. package/dist/internal/validation/query-method-options.validate.js +0 -24
  128. package/scripts/configure-prisma-import.mjs +0 -283
  129. package/scripts/copy-types.mjs +0 -24
  130. /package/dist/{internal/decorators/types/dynamic-method-config.type.js → types/adapter/adapter-method-options.type.js} +0 -0
  131. /package/dist/{internal/errors/types/vs-repo-error-type.type.js → types/adapter/adapter-query-options.type.js} +0 -0
  132. /package/dist/{internal/errors/types/vs-repo-runtime-error-code.type.js → types/decorators/dynamic-method-options.type.js} +0 -0
  133. /package/dist/{internal/validation/types → types/decorators}/query-method-options.type.js +0 -0
  134. /package/dist/{internal/resolvers/types → types/dynamic-methods}/dynamic-method-customization.type.js +0 -0
  135. /package/dist/{internal/resolvers/types → types/dynamic-methods}/dynamic-method-info.type.js +0 -0
  136. /package/dist/{internal/resolvers/types → types/dynamic-methods}/dynamic-method-where-ops.type.js +0 -0
  137. /package/dist/{internal/resolvers/types/base-method-function.type.js → types/utils/count-result.type.js} +0 -0
  138. /package/dist/{internal/resolvers/types/pretty-where.type.js → types/utils/decimal-like.type.js} +0 -0
  139. /package/dist/{internal/resolvers/types/prisma-args.type.js → types/utils/deep-partial.type.js} +0 -0
  140. /package/dist/{internal/resolvers/types/repository-build-instance.type.js → types/utils/keys-of-type.type.js} +0 -0
  141. /package/dist/{internal/resolvers/types/resolve-db-and-prisma-args-data.type.js → types/utils/methods-options.type.js} +0 -0
  142. /package/dist/{internal/resolvers/types/ugly-where.type.js → types/utils/numeric-keys.type.js} +0 -0
  143. /package/dist/{internal/validation/types/base-methods.type.js → types/utils/numeric-like.type.js} +0 -0
  144. /package/dist/{internal/validation/types/build-config.type.js → types/utils/ordering.type.js} +0 -0
  145. /package/dist/{internal/validation/types → types/utils}/pagination.type.js +0 -0
  146. /package/dist/{internal/validation/types/constructor-config.type.js → types/utils/perform-data.type.js} +0 -0
  147. /package/dist/{internal/validation/types/method-options.type.js → types/utils/primitive.type.js} +0 -0
  148. /package/dist/{internal/validation/types → types/utils}/query-method-arg.type.js +0 -0
  149. /package/dist/{internal/validation/types/method.type.js → types/utils/restrict-method-options.type.js} +0 -0
  150. /package/dist/{internal/validation/types → types/utils}/see-mode.type.js +0 -0
  151. /package/dist/{internal/validation/types/relation.type.js → types/vsrepo/vsrepo-args.type.js} +0 -0
@@ -1,497 +0,0 @@
1
- import {
2
- BuildConfig,
3
- ClientOrTransaction,
4
- DbClient,
5
- DbTransaction,
6
- DistributiveOmit,
7
- ExtractNestedCreateInput,
8
- ExtractNestedUpdateInput,
9
- IncludeModel,
10
- ModelUpsertInput,
11
- OrderingModel,
12
- PaginationModel,
13
- PaginationOptions,
14
- PrismaModelInputs,
15
- PrismaModelName,
16
- RepositoryRelations,
17
- SeeMode,
18
- SelectModel,
19
- WhereModel,
20
- } from "./VSRepository.d";
21
-
22
- /**
23
- * Flattens a type intersection into a single object,
24
- * avoiding the TypeScript "union type too complex to represent" error.
25
- */
26
- type Simplify<T> = { [K in keyof T]: T[K] } & {};
27
-
28
- /**
29
- * Resolves `WRelations` to a concrete relation map, falling back to `{}` when no
30
- * relations were flagged (mirrors `VSRepository`'s own internal fallback).
31
- */
32
- type ResolveRelations<WRelations> = WRelations extends object ? WRelations : {};
33
-
34
- /**
35
- * Payload accepted for a relation field mapped as `true` in `WRelations`, used to build
36
- * the `create`-shaped payload for `save`/`saveList`/`patch`/`patchList`.
37
- *
38
- * To-many relations (array fields) resolve to a list of Prisma's own nested `create`
39
- * payload. To-one relations (object fields) resolve to that same nested `create` payload,
40
- * but **always also accept `null`** by default — since `WRelations` only flags *which*
41
- * fields are relations (not their `mode`/`restriction`/`nullable` config), every to-one
42
- * relation here is treated as unlinkable.
43
- */
44
- type DynamicRelationCreatePayload<TField, M extends PrismaModelName, K extends PropertyKey> =
45
- NonNullable<TField> extends any[]
46
- ? ExtractNestedCreateInput<M, K>[]
47
- : NonNullable<TField> extends object
48
- ? ExtractNestedCreateInput<M, K> | null
49
- : never;
50
-
51
- /**
52
- * Same as `DynamicRelationCreatePayload`, but built from Prisma's nested `update` payload
53
- * instead of `create` — used by `merge`. To-one relations still accept `null` by default.
54
- */
55
- type DynamicRelationUpdatePayload<TField, M extends PrismaModelName, K extends PropertyKey> =
56
- NonNullable<TField> extends any[]
57
- ? ExtractNestedUpdateInput<M, K>[]
58
- : NonNullable<TField> extends object
59
- ? ExtractNestedUpdateInput<M, K> | null
60
- : never;
61
-
62
- /**
63
- * Distributes over the branches of Prisma's own upsert/create union for `UName`, replacing
64
- * every field flagged in `TRelations` with `DynamicRelationCreatePayload`.
65
- */
66
- type DynamicTransformCreatePayload<U, T, M extends PrismaModelName, TRelations> = Omit<
67
- U,
68
- keyof TRelations
69
- > & {
70
- // Fields that are REQUIRED in this specific branch of the Prisma union
71
- [K in Extract<keyof TRelations, keyof U> as {} extends Pick<U, K>
72
- ? never
73
- : K]: K extends keyof T ? DynamicRelationCreatePayload<T[K], M, K> : never;
74
- } & {
75
- // Fields that are OPTIONAL in this branch or do not originally belong to it
76
- [K in keyof TRelations as K extends keyof U
77
- ? {} extends Pick<U, K>
78
- ? K
79
- : never
80
- : K]?: K extends keyof T ? DynamicRelationCreatePayload<T[K], M, K> : never;
81
- };
82
-
83
- /**
84
- * Payload accepted by the `save`/`saveList` methods.
85
- *
86
- * Built directly from Prisma's own upsert/create input for `UName`, exactly like
87
- * `VSRepository`'s `save`: fields flagged as relations via `WRelations` are resolved
88
- * into their nested `create` payload shape instead of `TEntity`'s own shape (to-one
89
- * relations also accept `null` by default); every other field keeps Prisma's own
90
- * validated create input shape.
91
- */
92
- export type DynamicSaveInput<TEntity, UName extends PrismaModelName, WRelations = undefined> =
93
- ModelUpsertInput<UName> extends infer U
94
- ? U extends any
95
- ? Simplify<
96
- DynamicTransformCreatePayload<U, TEntity, UName, ResolveRelations<WRelations>>
97
- >
98
- : never
99
- : never;
100
-
101
- /**
102
- * Payload accepted by the `patch`/`patchList` methods.
103
- *
104
- * Built from Prisma's own `update` input for `UName` (so every field is already
105
- * optional); fields flagged as relations via `WRelations` are resolved into their
106
- * nested `create` payload shape, the same way as in `DynamicSaveInput` (to-one
107
- * relations also accept `null` by default).
108
- */
109
- export type DynamicPatchInput<
110
- TEntity,
111
- UName extends PrismaModelName,
112
- WRelations = undefined,
113
- > = Simplify<
114
- DistributiveOmit<
115
- PrismaModelInputs<UName>["updateInput"],
116
- keyof ResolveRelations<WRelations>
117
- > & {
118
- [K in Extract<
119
- keyof ResolveRelations<WRelations>,
120
- keyof TEntity
121
- >]?: DynamicRelationCreatePayload<TEntity[K], UName, K>;
122
- }
123
- >;
124
-
125
- /**
126
- * Payload accepted by the `merge` method.
127
- *
128
- * Built from Prisma's own `update` input for `UName` (so every field is already
129
- * optional); fields flagged as relations via `WRelations` are resolved into their
130
- * nested `update` payload shape (to-one relations also accept `null` by default).
131
- */
132
- export type DynamicMergeInput<
133
- TEntity,
134
- UName extends PrismaModelName,
135
- WRelations = undefined,
136
- > = Simplify<
137
- DistributiveOmit<
138
- PrismaModelInputs<UName>["updateInput"],
139
- keyof ResolveRelations<WRelations>
140
- > & {
141
- [K in Extract<
142
- keyof ResolveRelations<WRelations>,
143
- keyof TEntity
144
- >]?: DynamicRelationUpdatePayload<TEntity[K], UName, K>;
145
- }
146
- >;
147
-
148
- /**
149
- * Base options accepted by most `DynamicRepository` methods.
150
- */
151
- export type DynamicMethodOptions<TName extends PrismaModelName = PrismaModelName> = {
152
- /** Database client or transaction to use for this operation. */
153
- db?: ClientOrTransaction;
154
-
155
- /**
156
- * Controls visibility of soft-deleted records.
157
- * Only takes effect if `softRemovekName` is configured.
158
- */
159
- see?: SeeMode;
160
-
161
- /** Raw Prisma `include`. Cannot be used together with `select`. */
162
- include?: IncludeModel<TName>;
163
-
164
- /** Raw Prisma `select`. Cannot be used together with `include`. */
165
- select?: SelectModel<TName>;
166
- };
167
-
168
- /**
169
- * Configuration for an individual base method exposed by `DynamicRepository`.
170
- *
171
- * Unlike `VSRepository`'s `BuildConfig`, this configuration does not accept
172
- * `active` (base methods are always available) nor `defaultSelect`
173
- * (`DynamicRepository` has no select models).
174
- */
175
- type StrippedBaseMethods<TSelectKeys extends PropertyKey = string> = {
176
- [K in keyof NonNullable<BuildConfig<TSelectKeys>["baseMethods"]>]: Omit<
177
- NonNullable<NonNullable<BuildConfig<TSelectKeys>["baseMethods"]>[K]>,
178
- "active" | "defaultSelect"
179
- >;
180
- };
181
-
182
- /**
183
- * Configuration applied during the construction of a `DynamicRepository`.
184
- *
185
- * Equivalent to `VSRepository`'s `BuildConfig`, but without `freeze`
186
- * (no longer configurable) and without `active`/`defaultSelect` on each
187
- * base method (base methods are always active and there are no select models).
188
- */
189
- export type DynamicRepositoryBuildConfig = Omit<BuildConfig, "freeze" | "baseMethods"> & {
190
- /** Customizes the behavior of the automatic base methods. */
191
- baseMethods?: StrippedBaseMethods;
192
- };
193
-
194
- /**
195
- * Configuration used to construct a `DynamicRepository`.
196
- *
197
- * @template T Type of the entity managed by the repository.
198
- * @template U Prisma model name.
199
- */
200
- export interface DynamicRepositoryConstructorConfig<T, U extends PrismaModelName> {
201
- /**
202
- * Name of the table mapped by Prisma (usually uncapitalized).
203
- */
204
- tableName: Uncapitalize<U>;
205
-
206
- /**
207
- * Name of the field that represents the entity's primary key (Primary Key).
208
- */
209
- pkName: keyof T;
210
-
211
- /**
212
- * Name of the `DateTime` field used for soft-delete.
213
- *
214
- * When configured, enables the `softRemove`, `softRemoveList`, `restore`, and `restoreList` methods.
215
- * The field **must** be of type `DateTime` in the Prisma schema — VSRepository validates this during `build`.
216
- */
217
- softRemovekName?: keyof T;
218
-
219
- /**
220
- * Defines global filters that will be automatically applied to all repository queries.
221
- * Useful for tenant isolation (multi-tenancy) or base restrictions (e.g., `isActive: true`).
222
- */
223
- requiredWhere?: WhereModel<U>;
224
-
225
- /**
226
- * Default ordering automatically injected into all queries that accept `orderBy`,
227
- * unless the method already has `injectOrdering` configured or uses the `Ordered` suffix.
228
- *
229
- * Useful for ensuring a consistent sort order across the repository without repeating
230
- * the `order` argument on every call.
231
- */
232
- defaultOrdering?: OrderingModel<U>;
233
-
234
- /**
235
- * Default ordering automatically injected into all queries that accept `orderBy`,
236
- * unless the method already has `injectOrdering` configured or uses the `Ordered` suffix.
237
- *
238
- * Useful for ensuring a consistent sort order across the repository without repeating
239
- * the `order` argument on every call.
240
- *
241
- * @deprecated Use `defaultOrdering` instead.
242
- */
243
- defaultOrdenation?: OrderingModel<U>;
244
-
245
- /**
246
- * Configures automatic relation management.
247
- * When configured, allows the `save`, `saveList`, `patch`, and `patchList` methods
248
- * to automatically handle linking, creation, or cascading deletion of related records.
249
- */
250
- relations?: RepositoryRelations<T>;
251
-
252
- /**
253
- * Customizes the behavior of the automatic base methods when the repository is built.
254
- */
255
- build?: DynamicRepositoryBuildConfig;
256
- }
257
-
258
- /**
259
- * Base repository built from a fixed configuration, exposing a complete set of
260
- * ready-to-use CRUD and soft-delete methods around a Prisma model.
261
- *
262
- * @template TEntity Type of the entity managed by the repository.
263
- * @template UName Prisma model name.
264
- * @template VPKType Type of the entity's primary key value.
265
- * @template WRelations Keys of `TEntity` configured as relations (flags only, `true`
266
- * per relation field). The actual relation behavior (`mode`, `restriction`, `nullable`)
267
- * still comes from `relations` in the constructor config; `WRelations` here only tells
268
- * `DynamicSaveInput`/`DynamicPatchInput`/`DynamicMergeInput` which fields to resolve
269
- * into their nested Prisma create/update payload shape instead of `TEntity`'s own shape.
270
- */
271
- export declare abstract class DynamicRepository<
272
- TEntity extends object,
273
- UName extends PrismaModelName,
274
- VPKType,
275
- WRelations extends Partial<Record<keyof TEntity, true>> | undefined = undefined,
276
- > {
277
- /**
278
- * Creates a configured instance of `DynamicRepository`.
279
- */
280
- constructor(prisma: DbClient, config: DynamicRepositoryConstructorConfig<TEntity, UName>);
281
-
282
- /**
283
- * The Prisma Client instance passed to constructor.
284
- */
285
- readonly prisma: DbClient;
286
-
287
- /** Fetches a record by its primary key (PK). */
288
- get(pk: VPKType, options?: DynamicMethodOptions<UName>): Promise<TEntity | null>;
289
-
290
- /** Fetches a record by PK and throws `VSRepoRuntimeError` if not found. */
291
- getOrThrow(pk: VPKType, options?: DynamicMethodOptions<UName>): Promise<TEntity>;
292
-
293
- /** Fetches multiple records by a list of primary keys (PKs). */
294
- getList(pks: VPKType[], options?: DynamicMethodOptions<UName>): Promise<TEntity[]>;
295
-
296
- /** Deletes a record identified by its primary key (PK). */
297
- remove(pk: VPKType, options?: DynamicMethodOptions<UName>): Promise<TEntity>;
298
-
299
- /** Inserts or updates (upsert) a record. */
300
- save(
301
- obj: DynamicSaveInput<TEntity, UName, WRelations>,
302
- options?: DynamicMethodOptions<UName>,
303
- ): Promise<TEntity>;
304
-
305
- /** Saves an array of objects in a single automatic transaction. */
306
- saveList(
307
- objs: DynamicSaveInput<TEntity, UName, WRelations>[],
308
- options?: Omit<DynamicMethodOptions<UName>, "include" | "select"> & {
309
- /** Transaction client to use for this operation. */
310
- db?: DbTransaction;
311
- },
312
- ): Promise<TEntity[]>;
313
-
314
- /** Partially updates (patch) an existing record by its primary key (PK). */
315
- patch(
316
- pk: VPKType,
317
- obj: DynamicPatchInput<TEntity, UName, WRelations>,
318
- options?: DynamicMethodOptions<UName>,
319
- ): Promise<TEntity>;
320
-
321
- /** Partially updates multiple records via `[pk, obj]` tuples in an automatic transaction. */
322
- patchList(
323
- tuples: [pk: VPKType, obj: DynamicPatchInput<TEntity, UName, WRelations>][],
324
- options?: Omit<DynamicMethodOptions<UName>, "include" | "select"> & {
325
- /** Transaction client to use for this operation. */
326
- db?: DbTransaction;
327
- },
328
- ): Promise<TEntity[]>;
329
-
330
- /** Fetches a record by PK and deep-merges it with the provided object **in memory**. */
331
- merge(
332
- pk: VPKType,
333
- obj: DynamicMergeInput<TEntity, UName, WRelations>,
334
- options?: DynamicMethodOptions<UName>,
335
- ): Promise<TEntity | null>;
336
-
337
- /** Deletes multiple records by their primary keys. */
338
- removeList(
339
- pks: VPKType[],
340
- options?: Omit<DynamicMethodOptions<UName>, "include" | "select">,
341
- ): Promise<{ count: number }>;
342
-
343
- /** Fetches all records (respects `requiredWhere` when set). */
344
- getAll(
345
- options?: DynamicMethodOptions<UName> & {
346
- /** Pagination options for the query. */
347
- pagination?: PaginationOptions;
348
- /**
349
- * Ordering to apply to the query.
350
- * When omitted and `defaultOrdering` is configured on the repository,
351
- * the default ordering is applied automatically.
352
- */
353
- order?: OrderingModel<UName>;
354
- },
355
- ): Promise<TEntity[]>;
356
-
357
- /** Returns the total number of records. */
358
- total(options?: Omit<DynamicMethodOptions<UName>, "include" | "select">): Promise<number>;
359
-
360
- /** Checks whether a record exists by its primary key (PK). */
361
- has(pk: VPKType, options?: Omit<DynamicMethodOptions<UName>, "include" | "select">): Promise<boolean>;
362
-
363
- /** Marks a record as deleted (soft-delete). */
364
- softRemove(pk: VPKType, options?: Omit<DynamicMethodOptions<UName>, "see">): Promise<TEntity>;
365
-
366
- /** Marks multiple records as deleted (soft-delete) in batch. */
367
- softRemoveList(
368
- pks: VPKType[],
369
- options?: Omit<DynamicMethodOptions<UName>, "see" | "include" | "select">,
370
- ): Promise<{ count: number }>;
371
-
372
- /** Restores a record previously marked as deleted (soft-delete). */
373
- restore(pk: VPKType, options?: Omit<DynamicMethodOptions<UName>, "see">): Promise<TEntity>;
374
-
375
- /** Restores multiple records previously marked as deleted (soft-delete) in batch. */
376
- restoreList(
377
- pks: VPKType[],
378
- options?: Omit<DynamicMethodOptions<UName>, "see" | "include" | "select">,
379
- ): Promise<{ count: number }>;
380
- }
381
-
382
- export type DynamicMethodConfig<M extends PrismaModelName = PrismaModelName> = {
383
- /** Redirects the logic to another valid method pattern. */
384
- proxyTo?: string;
385
-
386
- /** Controls whether the method combines (`extending`) or overwrites (`overwrite`) the `requiredWhere`. */
387
- whereType?: "overwrite" | "extending";
388
-
389
- /** Adds an extra `where` on top of `requiredWhere`. */
390
- pushWhere?: WhereModel<M>;
391
-
392
- /**
393
- * Defines whether the method returns a single item (`one`) or a list (`list`).
394
- * @deprecated Use `findOneBy` if you want to return a single result.
395
- */
396
- fbMode?: "one" | "list";
397
-
398
- /** Injects a fixed ordering automatically into the query. */
399
- injectOrdering?: OrderingModel<M>;
400
-
401
- /**
402
- * Injects a fixed ordering automatically into the query.
403
- * @deprecated Use `injectOrdering` instead.
404
- */
405
- injectOrdenation?: OrderingModel<M>;
406
-
407
- /** Injects a fixed pagination automatically into the query. */
408
- injectPagination?: PaginationModel<M>;
409
- };
410
-
411
- /**
412
- * Property decorator used to declare a dynamic method on a `DynamicRepository` subclass.
413
- *
414
- * Applied to a `declare` class field whose name follows one of the supported method
415
- * patterns (e.g. `findByEmail`, `findManyByStatusPaginated`); the method's behavior and
416
- * return type are inferred from the field name, optionally adjusted via `config`.
417
- *
418
- * @template M Prisma model name the decorated method operates on.
419
- *
420
- * @example
421
- * ```typescript
422
- * class UserRepository extends DynamicRepository<User, "User", string> {
423
- * `@DynamicMethod()`
424
- * declare findOneByEmail: (email: string) => Promise<User | null>;
425
- *
426
- * @DynamicMethod<"User">({ injectOrdering: { createdAt: "desc" } })
427
- * declare findByAge: (email: number) => Promise<User[]>;
428
- * }
429
- * ```
430
- */
431
- export declare function DynamicMethod<M extends PrismaModelName = PrismaModelName>(
432
- config?: DynamicMethodConfig<M>,
433
- ): PropertyDecorator;
434
-
435
- /**
436
- * Single argument accepted by a method declared with `@QueryMethod`.
437
- *
438
- * `args` are injected positionally into the raw SQL statement (`$1`, `$2`, ...),
439
- * exactly like Prisma's `$queryRawUnsafe`/`$executeRawUnsafe` parameters — this is
440
- * what allows safe parameter injection instead of string-concatenating values into
441
- * the SQL text.
442
- *
443
- * @template T Tuple type of the positional SQL parameters, e.g. `[email: string]`.
444
- *
445
- * @example
446
- * ```typescript
447
- * declare findByEmail: (arg: QueryMethodArg<[email: string]>) => Promise<User[]>;
448
- * ```
449
- */
450
- export type QueryMethodArg<T extends Array<any>> = {
451
- /** Positional parameters injected into the SQL placeholders (`$1`, `$2`, ...). */
452
- args: T;
453
- /** Transaction client to run this query in, instead of the repository's default client. */
454
- db?: ClientOrTransaction;
455
- };
456
-
457
- /**
458
- * Options accepted by the `@QueryMethod` decorator.
459
- */
460
- export type QueryMethodOptions = {
461
- /**
462
- * When `true`, the SQL is executed with `$executeRawUnsafe` (INSERT/UPDATE/DELETE)
463
- * and the decorated method must resolve to `number` (the count of affected rows).
464
- * When `false`/omitted, the SQL is executed with `$queryRawUnsafe` and the method
465
- * resolves to whatever return type you declare on the field.
466
- *
467
- * @default false
468
- */
469
- modifying?: boolean;
470
- };
471
-
472
- /**
473
- * Property decorator used to declare a **raw SQL query method** on a `DynamicRepository`
474
- * subclass, bypassing name-based method parsing entirely.
475
- *
476
- * Applied to a `declare` class field, it executes `value` directly through Prisma
477
- * (`$queryRawUnsafe` or `$executeRawUnsafe`, depending on `options.modifying`), with
478
- * parameters injected positionally via `QueryMethodArg["args"]`. Since the SQL result
479
- * isn't statically known, the field's own declared function type is what determines
480
- * the method's return type — for `modifying: true` it must always resolve to `number`.
481
- *
482
- * @param value Raw SQL statement to execute. Use `$1`, `$2`, ... placeholders for the
483
- * values that will be passed via `args` — never interpolate values directly into `value`.
484
- * @param options Optional configuration; set `modifying: true` for `INSERT`/`UPDATE`/`DELETE` statements.
485
- *
486
- * @example
487
- * ```typescript
488
- * class UserRepository extends DynamicRepository<User, "User", string> {
489
- * @QueryMethod('SELECT * FROM "user" WHERE email = $1')
490
- * declare findByEmailRaw: (arg: QueryMethodArg<[email: string]>) => Promise<User[]>;
491
- *
492
- * @QueryMethod('UPDATE "user" SET active = true WHERE id = $1', { modifying: true })
493
- * declare activateUser: (arg: QueryMethodArg<[id: string]>) => Promise<number>;
494
- * }
495
- * ```
496
- */
497
- export declare function QueryMethod(value: string, options?: QueryMethodOptions): PropertyDecorator;
@@ -1,26 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DynamicRepository = exports.QueryMethod = exports.DynamicMethod = void 0;
4
- const dynamic_methods_metadata_resolve_1 = require("./internal/resolvers/dynamic-methods-metadata.resolve");
5
- const build_config_validate_1 = require("./internal/validation/build-config.validate");
6
- const is_object_validate_1 = require("./internal/validation/is-object.validate");
7
- const VSRepository_1 = require("./VSRepository");
8
- require("reflect-metadata");
9
- var dynamic_method_decorator_1 = require("./internal/decorators/dynamic-method.decorator");
10
- Object.defineProperty(exports, "DynamicMethod", { enumerable: true, get: function () { return dynamic_method_decorator_1.DynamicMethod; } });
11
- var query_method_decorator_1 = require("./internal/decorators/query-method.decorator");
12
- Object.defineProperty(exports, "QueryMethod", { enumerable: true, get: function () { return query_method_decorator_1.QueryMethod; } });
13
- class DynamicRepository extends VSRepository_1.VSRepository {
14
- constructor(prisma, config) {
15
- if (!(0, is_object_validate_1.isObject)(config)) {
16
- throw new VSRepository_1.VSRepoConfigError(`[VSRepository] (unknown: config) 'config' must be a valid object`);
17
- }
18
- const { build: buildConfig = {}, ...constructorConfig } = config;
19
- super(constructorConfig);
20
- const dynamicMethodsMetadata = (0, dynamic_methods_metadata_resolve_1.resolveDynamicMethodsMetadata)(this.constructor.prototype);
21
- this.methods = dynamicMethodsMetadata;
22
- const buildConfigValidated = (0, build_config_validate_1.validateBuildConfig)(buildConfig, this);
23
- this.build(prisma, { ...buildConfigValidated, freeze: false }, this);
24
- }
25
- }
26
- exports.DynamicRepository = DynamicRepository;
@@ -1,83 +0,0 @@
1
- /**
2
- * Literal types representing the internal error codes of the library.
3
- */
4
- export type VSRepoErrorType =
5
- | 'VSREPO_CONFIG'
6
- | 'VSREPO_BUILD'
7
- | 'VSREPO_EXTEND'
8
- | 'VSREPO_RUNTIME'
9
- | 'VSREPO_DECORATOR';
10
-
11
- /**
12
- * Catalog of the internal codes used by `VSRepoRuntimeError`. Each code identifies
13
- * a category of runtime failure, so consuming code can discriminate on
14
- * `error.code` without parsing the (human-readable) message. See the
15
- * "Error handling" section of the README for the full description of each code.
16
- */
17
- export type VSRepoRuntimeErrorCode =
18
- /** A required argument is missing or has an invalid shape (e.g. missing `pk`, `pks`/`objs`/`tuples` that aren't an array, or `options`/`obj` that isn't a valid object). */
19
- | '65706'
20
- /** No record was found for the provided primary key (`getOrThrow` when fetching the base record). */
21
- | '20727'
22
- /** Validation (zod) of a method's `options`, or of a `@QueryMethod` argument, failed. */
23
- | '67542'
24
- /** A relation passed to `save`/`patch`/`merge` has an invalid shape for the configured `mode`/`restriction`. */
25
- | '91868'
26
- /** A dynamic method (`config.methods`) was called with fewer positional arguments than its `where` fields require. */
27
- | '48670';
28
-
29
- /**
30
- * Base class for all errors thrown by the VSRepository.
31
- */
32
- export declare abstract class VSRepoError extends Error {
33
- /** Internal code used to identify the error category. */
34
- abstract readonly type: VSRepoErrorType;
35
-
36
- constructor(message: string, type: VSRepoErrorType);
37
- }
38
-
39
- /**
40
- * Thrown when an invalid configuration or a configuration inconsistency
41
- * is detected before or during repository initialization.
42
- */
43
- export declare class VSRepoConfigError extends VSRepoError {
44
- readonly type: 'VSREPO_CONFIG';
45
- constructor(message: string);
46
- }
47
-
48
- /**
49
- * Thrown when the Prisma instance injection fails or when the
50
- * build configuration is incorrect in the `.build()`.
51
- */
52
- export declare class VSRepoBuildError extends VSRepoError {
53
- readonly type: 'VSREPO_BUILD';
54
- constructor(message: string);
55
- }
56
-
57
- /**
58
- * Thrown when an error occurs while injecting new methods into the repository
59
- * via `.extend()`.
60
- */
61
- export declare class VSRepoExtendError extends VSRepoError {
62
- readonly type: 'VSREPO_EXTEND';
63
- constructor(message: string);
64
- }
65
-
66
- /**
67
- * Thrown when invalid arguments are passed to a decorator.
68
- */
69
- export declare class VSRepoDecoratorError extends VSRepoError {
70
- readonly type: 'VSREPO_DECORATOR';
71
- constructor(message: string);
72
- }
73
-
74
- /**
75
- * Thrown when dynamic operations fail at runtime, such as
76
- * when invalid arguments are passed to methods.
77
- */
78
- export declare class VSRepoRuntimeError extends VSRepoError {
79
- readonly type: 'VSREPO_RUNTIME';
80
- /** Internal code identifying the category of runtime failure. See {@link VSRepoRuntimeErrorCode}. */
81
- readonly code: VSRepoRuntimeErrorCode;
82
- constructor(message: string, code: VSRepoRuntimeErrorCode);
83
- }
@@ -1,17 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./internal/errors/vs-repo.error"), exports);
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DynamicMethod = DynamicMethod;
4
- const dynamic_methods_key_constant_1 = require("../constants/dynamic-methods-key.constant");
5
- const dynamic_method_metadata_entity_1 = require("../entities/dynamic-method-metadata.entity");
6
- const dynamic_method_config_validate_1 = require("../validation/dynamic-method-config.validate");
7
- function DynamicMethod(config) {
8
- const validatedConfig = config ? (0, dynamic_method_config_validate_1.validateDynamicMethodConfig)(config) : undefined;
9
- return (target, propertyKey) => {
10
- const methods = Reflect.getMetadata(dynamic_methods_key_constant_1.DYNAMIC_METHODS_KEY, target) ?? [];
11
- methods.push(new dynamic_method_metadata_entity_1.DynamicMethodMetadata(propertyKey, true, validatedConfig?.proxyTo, validatedConfig?.whereType, validatedConfig?.pushWhere, validatedConfig?.fbMode, validatedConfig?.injectOrdering, validatedConfig?.injectPagination));
12
- Reflect.defineMetadata(dynamic_methods_key_constant_1.DYNAMIC_METHODS_KEY, methods, target);
13
- };
14
- }
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QueryMethod = QueryMethod;
4
- const dynamic_methods_key_constant_1 = require("../constants/dynamic-methods-key.constant");
5
- const dynamic_method_metadata_entity_1 = require("../entities/dynamic-method-metadata.entity");
6
- const vs_repo_error_1 = require("../errors/vs-repo.error");
7
- const query_method_options_validate_1 = require("../validation/query-method-options.validate");
8
- function QueryMethod(value, options) {
9
- if (typeof value !== "string") {
10
- throw new vs_repo_error_1.VSRepoDecoratorError(`[VSRepository] (unknown: decorator) 'value' must be a valid string`);
11
- }
12
- const validatedConfig = options
13
- ? (0, query_method_options_validate_1.validateQueryMethodOptions)(options)
14
- : { modifying: false };
15
- return (target, propertyKey) => {
16
- const methods = Reflect.getMetadata(dynamic_methods_key_constant_1.DYNAMIC_METHODS_KEY, target) ?? [];
17
- methods.push(new dynamic_method_metadata_entity_1.DynamicMethodMetadata(propertyKey, true, undefined, undefined, undefined, undefined, undefined, undefined, { value, ...validatedConfig }));
18
- Reflect.defineMetadata(dynamic_methods_key_constant_1.DYNAMIC_METHODS_KEY, methods, target);
19
- };
20
- }