Skip to content

Commit 397d2ab

Browse files
authored
fix(orm): improve result field extension plugin's typing (#2492)
1 parent d982cc5 commit 397d2ab

4 files changed

Lines changed: 560 additions & 413 deletions

File tree

‎packages/orm/src/client/contract.ts‎

Lines changed: 69 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,16 @@ import type {
4040
} from './crud-types';
4141
import type { Diagnostics } from './diagnostics';
4242
import type { ClientOptions, QueryOptions } from './options';
43-
import type { ExtClientMembersBase, ExtQueryArgsBase, ExtResultBase, RuntimePlugin } from './plugin';
43+
import type {
44+
ExtClientMembersBase,
45+
ExtQueryArgsBase,
46+
ExtResultBase,
47+
ExtResultInferenceArgs,
48+
RuntimePlugin,
49+
} from './plugin';
4450
import type { ZenStackPromise } from './promise';
4551
import type { ToKysely } from './query-builder';
46-
import type {
47-
GetSlicedModels,
48-
GetSlicedOperations,
49-
GetSlicedProcedures,
50-
ModelAllowsCreate,
51-
} from './type-utils';
52+
import type { GetSlicedModels, GetSlicedOperations, GetSlicedProcedures, ModelAllowsCreate } from './type-utils';
5253
import type { ZodSchemaFactory } from './zod/factory';
5354

5455
type TransactionUnsupportedMethods = (typeof TRANSACTION_UNSUPPORTED_METHODS)[number];
@@ -128,12 +129,20 @@ export type ClientContract<
128129
get $auth(): AuthType<Schema> | undefined;
129130

130131
/**
131-
* Sets the current user identity.
132+
* Returns a new client bound to the specified user identity. The original client remains unchanged.
133+
*
134+
* @example
135+
* ```
136+
* const userClient = db.$setAuth({ id: 'user-id' });
137+
* ```
132138
*/
133-
$setAuth(auth: AuthType<Schema> | undefined): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
139+
$setAuth(
140+
auth: AuthType<Schema> | undefined,
141+
): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
134142

135143
/**
136-
* Returns a new client with new options applied.
144+
* Returns a new client with new options applied. The original client remains unchanged.
145+
*
137146
* @example
138147
* ```
139148
* const dbNoValidation = db.$setOptions({ ...db.$options, validateInput: false });
@@ -144,14 +153,19 @@ export type ClientContract<
144153
): ClientContract<Schema, NewOptions, ExtQueryArgs, ExtClientMembers, ExtResult>;
145154

146155
/**
147-
* Returns a new client enabling/disabling query args validation.
156+
* Returns a new client enabling/disabling query args validation. The original client remains unchanged.
148157
*
149158
* @deprecated Use {@link $setOptions} instead.
150159
*/
151160
$setInputValidation(enable: boolean): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
152161

153162
/**
154163
* The Kysely query builder instance.
164+
*
165+
* @example
166+
* ```
167+
* db.$qb.selectFrom('User').selectAll().where('id', '=', 1).execute();
168+
* ```
155169
*/
156170
readonly $qb: ToKysely<Schema>;
157171

@@ -162,39 +176,68 @@ export type ClientContract<
162176

163177
/**
164178
* Starts an interactive transaction.
179+
*
180+
* @example
181+
* ```
182+
* await db.$transaction(async (tx) => {
183+
* const user = await tx.user.update({ where: { id: 1 }, data: { name: 'Alice' } });
184+
* const post = await tx.post.create({ data: { title: 'Hello World', authorId: user.id } });
185+
* return { user, posts: [post] };
186+
* ```
165187
*/
166188
$transaction<T>(
167-
callback: (tx: TransactionClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>) => Promise<T>,
189+
callback: (
190+
tx: TransactionClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>,
191+
) => Promise<T>,
168192
options?: { isolationLevel?: TransactionIsolationLevel },
169193
): Promise<T>;
170194

171195
/**
172-
* Starts a sequential transaction.
196+
* Starts a sequential transaction that runs the provided operations in order.
197+
*
198+
* @example
199+
* ```
200+
* await db.$transaction([
201+
* db.user.update({ where: { id: 1 }, data: { name: 'Alice' } }),
202+
* db.post.create({ data: { title: 'Hello World', authorId: 1 } }),
203+
* ]);
173204
*/
174205
$transaction<P extends ZenStackPromise<Schema, any>[]>(
175206
arg: [...P],
176207
options?: { isolationLevel?: TransactionIsolationLevel },
177208
): Promise<UnwrapTuplePromises<P>>;
178209

179210
/**
180-
* Returns a new client with the specified plugin installed.
211+
* Returns a new client with the specified plugin installed. The original client remains unchanged.
212+
*
213+
* @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation}
181214
*/
182215
$use<
183216
PluginSchema extends SchemaDef = Schema,
184217
PluginExtQueryArgs extends ExtQueryArgsBase = {},
185218
PluginExtClientMembers extends ExtClientMembersBase = {},
186219
PluginExtResult extends ExtResultBase<PluginSchema> = {},
220+
_R = {}, // auxiliary type for inferring precise typing for `PluginExtResult`
187221
>(
188-
plugin: RuntimePlugin<PluginSchema, PluginExtQueryArgs, PluginExtClientMembers, PluginExtResult>,
189-
): ClientContract<Schema, Options, ExtQueryArgs & PluginExtQueryArgs, ExtClientMembers & PluginExtClientMembers, ExtResult & PluginExtResult>;
222+
plugin: RuntimePlugin<PluginSchema, PluginExtQueryArgs, PluginExtClientMembers, PluginExtResult> & {
223+
// intersect with the `result` extension field for precise typing
224+
result?: ExtResultInferenceArgs<Schema, _R>;
225+
},
226+
): ClientContract<
227+
Schema,
228+
Options,
229+
ExtQueryArgs & PluginExtQueryArgs,
230+
ExtClientMembers & PluginExtClientMembers,
231+
ExtResult & PluginExtResult
232+
>;
190233

191234
/**
192-
* Returns a new client with the specified plugin removed.
235+
* Returns a new client with the specified plugin removed. The original client remains unchanged.
193236
*/
194237
$unuse(pluginId: string): ClientContract<Schema, Options, ExtQueryArgs, ExtClientMembers, ExtResult>;
195238

196239
/**
197-
* Returns a new client with all plugins removed.
240+
* Returns a new client with all plugins removed. The original client remains unchanged.
198241
*/
199242
$unuseAll(): ClientContract<Schema, Options>;
200243

@@ -224,7 +267,13 @@ export type ClientContract<
224267
*/
225268
get $diagnostics(): Promise<Diagnostics>;
226269
} & {
227-
[Key in GetSlicedModels<Schema, Options> as Uncapitalize<Key>]: ModelOperations<Schema, Key, Options, ExtQueryArgs, ExtResult>;
270+
[Key in GetSlicedModels<Schema, Options> as Uncapitalize<Key>]: ModelOperations<
271+
Schema,
272+
Key,
273+
Options,
274+
ExtQueryArgs,
275+
ExtResult
276+
>;
228277
} & ProcedureOperations<Schema, Options> &
229278
ExtClientMembers;
230279

@@ -297,7 +346,7 @@ type SliceOperations<
297346
[Key in keyof T as Key extends GetSlicedOperations<Schema, Model, Options> ? Key : never]: T[Key];
298347
},
299348
// exclude create operations for models that don't allow create (delegate models, required Unsupported fields)
300-
| (ModelAllowsCreate<Schema, Model> extends true ? never : OperationsRequiringCreate)
349+
ModelAllowsCreate<Schema, Model> extends true ? never : OperationsRequiringCreate
301350
>;
302351

303352
export type AllModelOperations<

‎packages/orm/src/client/crud-types.ts‎

Lines changed: 39 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,7 @@ export type ModelResult<
238238
: Args extends { omit: infer O } & Record<string, unknown>
239239
? DefaultModelResult<Schema, Model, O, Options, false, false>
240240
: DefaultModelResult<Schema, Model, undefined, Options, false, false>) &
241+
// intersect with fields contributed by result extension plugins
241242
SelectAwareExtResult<ExtResult, Model & string, Args>,
242243
Optional,
243244
Array
@@ -960,7 +961,10 @@ export type SelectIncludeOmit<
960961
/**
961962
* Explicitly select fields and relations to be returned by the query.
962963
*/
963-
select?: (SelectInput<Schema, Model, Options, AllowCount, AllowRelation, ExtResult> & ExtResultSelectOmitFields<ExtResult, Model & string>) | null;
964+
select?:
965+
| (SelectInput<Schema, Model, Options, AllowCount, AllowRelation, ExtResult> &
966+
ExtResultSelectOmitFields<ExtResult, Model & string>)
967+
| null;
964968

965969
/**
966970
* Explicitly omit fields from the query result.
@@ -1389,7 +1393,9 @@ type CreateRelationFieldPayload<
13891393
// no "createMany" for non-array fields
13901394
| (FieldIsArray<Schema, Model, Field> extends true ? never : 'createMany')
13911395
// exclude create operations for models that don't allow create
1392-
| (RelationModelAllowsCreate<Schema, Model, Field> extends true ? never : 'create' | 'createMany' | 'connectOrCreate')
1396+
| (RelationModelAllowsCreate<Schema, Model, Field> extends true
1397+
? never
1398+
: 'create' | 'createMany' | 'connectOrCreate')
13931399
>;
13941400

13951401
type CreateRelationPayload<
@@ -1747,7 +1753,9 @@ type ToManyRelationUpdateInput<
17471753
set?: SetRelationInput<Schema, Model, Field, Options>;
17481754
},
17491755
// exclude create operations for models that don't allow create
1750-
| (RelationModelAllowsCreate<Schema, Model, Field> extends true ? never : 'create' | 'createMany' | 'connectOrCreate' | 'upsert')
1756+
RelationModelAllowsCreate<Schema, Model, Field> extends true
1757+
? never
1758+
: 'create' | 'createMany' | 'connectOrCreate' | 'upsert'
17511759
>;
17521760

17531761
type ToOneRelationUpdateInput<
@@ -1795,7 +1803,7 @@ type ToOneRelationUpdateInput<
17951803
}
17961804
: {}),
17971805
// exclude create operations for models that don't allow create
1798-
| (RelationModelAllowsCreate<Schema, Model, Field> extends true ? never : 'create' | 'connectOrCreate' | 'upsert')
1806+
RelationModelAllowsCreate<Schema, Model, Field> extends true ? never : 'create' | 'connectOrCreate' | 'upsert'
17991807
>;
18001808

18011809
// #endregion
@@ -2460,11 +2468,14 @@ export type ExtractExtResult<ExtResult extends ExtResultBase, Model extends stri
24602468
* Extracts extended result field names as optional boolean keys for use in select/omit inputs.
24612469
* When ExtResult is `{}`, this resolves to `{}` (no-op for intersection).
24622470
*/
2463-
export type ExtResultSelectOmitFields<ExtResult extends ExtResultBase, Model extends string> = keyof ExtResult extends never
2471+
export type ExtResultSelectOmitFields<
2472+
ExtResult extends ExtResultBase,
2473+
Model extends string,
2474+
> = keyof ExtResult extends never
24642475
? {}
24652476
: Uncapitalize<Model> extends keyof ExtResult
2466-
? { [K in keyof ExtResult[Uncapitalize<Model>]]?: boolean }
2467-
: {};
2477+
? { [K in keyof ExtResult[Uncapitalize<Model>]]?: boolean }
2478+
: {};
24682479

24692480
type TruthyKeys<S, Keys extends string> = {
24702481
[K in Keys]: K extends keyof S ? (S[K] extends false | undefined ? never : K) : never;
@@ -2476,23 +2487,26 @@ type TruthyKeys<S, Keys extends string> = {
24762487
* - If T has `omit`, excludes ext result fields that are explicitly omitted.
24772488
* - Otherwise, includes all ext result fields.
24782489
*/
2479-
export type SelectAwareExtResult<ExtResult extends ExtResultBase, Model extends string, T> =
2480-
keyof ExtResult extends never
2481-
? {}
2482-
: T extends { select: infer S }
2483-
? S extends null | undefined
2484-
? ExtractExtResult<ExtResult, Model>
2485-
: Pick<
2486-
ExtractExtResult<ExtResult, Model>,
2487-
TruthyKeys<S, Extract<keyof S & string, keyof ExtractExtResult<ExtResult, Model>>>
2488-
>
2489-
: T extends { omit: infer O }
2490-
? O extends null | undefined
2491-
? ExtractExtResult<ExtResult, Model>
2492-
: Omit<
2493-
ExtractExtResult<ExtResult, Model>,
2494-
TruthyKeys<O, Extract<keyof O & string, keyof ExtractExtResult<ExtResult, Model>>>
2495-
>
2496-
: ExtractExtResult<ExtResult, Model>;
2490+
export type SelectAwareExtResult<
2491+
ExtResult extends ExtResultBase,
2492+
Model extends string,
2493+
T,
2494+
> = keyof ExtResult extends never
2495+
? {}
2496+
: T extends { select: infer S }
2497+
? S extends null | undefined
2498+
? ExtractExtResult<ExtResult, Model>
2499+
: Pick<
2500+
ExtractExtResult<ExtResult, Model>,
2501+
TruthyKeys<S, Extract<keyof S & string, keyof ExtractExtResult<ExtResult, Model>>>
2502+
>
2503+
: T extends { omit: infer O }
2504+
? O extends null | undefined
2505+
? ExtractExtResult<ExtResult, Model>
2506+
: Omit<
2507+
ExtractExtResult<ExtResult, Model>,
2508+
TruthyKeys<O, Extract<keyof O & string, keyof ExtractExtResult<ExtResult, Model>>>
2509+
>
2510+
: ExtractExtResult<ExtResult, Model>;
24972511

24982512
// #endregion

0 commit comments

Comments
 (0)