From 907b907d383b24dffb45e01e23402428837761ef Mon Sep 17 00:00:00 2001 From: ymc9 <104139426+ymc9@users.noreply.github.com> Date: Wed, 18 Mar 2026 11:39:24 -0700 Subject: [PATCH 1/2] fix(orm): improve result field extension plugin's typing --- packages/orm/src/client/contract.ts | 89 +- packages/orm/src/client/crud-types.ts | 64 +- packages/orm/src/client/plugin.ts | 101 ++- tests/e2e/orm/plugin-infra/ext-result.test.ts | 765 +++++++++--------- 4 files changed, 579 insertions(+), 440 deletions(-) diff --git a/packages/orm/src/client/contract.ts b/packages/orm/src/client/contract.ts index 99f247d06..0ed8d0004 100644 --- a/packages/orm/src/client/contract.ts +++ b/packages/orm/src/client/contract.ts @@ -40,15 +40,16 @@ import type { } from './crud-types'; import type { Diagnostics } from './diagnostics'; import type { ClientOptions, QueryOptions } from './options'; -import type { ExtClientMembersBase, ExtQueryArgsBase, ExtResultBase, RuntimePlugin } from './plugin'; +import type { + ExtClientMembersBase, + ExtQueryArgsBase, + ExtResultBase, + ExtResultInferenceArgs, + RuntimePlugin, +} from './plugin'; import type { ZenStackPromise } from './promise'; import type { ToKysely } from './query-builder'; -import type { - GetSlicedModels, - GetSlicedOperations, - GetSlicedProcedures, - ModelAllowsCreate, -} from './type-utils'; +import type { GetSlicedModels, GetSlicedOperations, GetSlicedProcedures, ModelAllowsCreate } from './type-utils'; import type { ZodSchemaFactory } from './zod/factory'; type TransactionUnsupportedMethods = (typeof TRANSACTION_UNSUPPORTED_METHODS)[number]; @@ -128,12 +129,20 @@ export type ClientContract< get $auth(): AuthType | undefined; /** - * Sets the current user identity. + * Returns a new client bound to the specified user identity. The original client remains unchanged. + * + * @example + * ``` + * const userClient = db.$setAuth({ id: 'user-id' }); + * ``` */ - $setAuth(auth: AuthType | undefined): ClientContract; + $setAuth( + auth: AuthType | undefined, + ): ClientContract; /** - * Returns a new client with new options applied. + * Returns a new client with new options applied. The original client remains unchanged. + * * @example * ``` * const dbNoValidation = db.$setOptions({ ...db.$options, validateInput: false }); @@ -144,7 +153,7 @@ export type ClientContract< ): ClientContract; /** - * Returns a new client enabling/disabling query args validation. + * Returns a new client enabling/disabling query args validation. The original client remains unchanged. * * @deprecated Use {@link $setOptions} instead. */ @@ -152,6 +161,11 @@ export type ClientContract< /** * The Kysely query builder instance. + * + * @example + * ``` + * db.$qb.selectFrom('User').selectAll().where('id', '=', 1).execute(); + * ``` */ readonly $qb: ToKysely; @@ -162,14 +176,31 @@ export type ClientContract< /** * Starts an interactive transaction. + * + * @example + * ``` + * await db.$transaction(async (tx) => { + * const user = await tx.user.update({ where: { id: 1 }, data: { name: 'Alice' } }); + * const post = await tx.post.create({ data: { title: 'Hello World', authorId: user.id } }); + * return { user, posts: [post] }; + * ``` */ $transaction( - callback: (tx: TransactionClientContract) => Promise, + callback: ( + tx: TransactionClientContract, + ) => Promise, options?: { isolationLevel?: TransactionIsolationLevel }, ): Promise; /** - * Starts a sequential transaction. + * Starts a sequential transaction that runs the provided operations in order. + * + * @example + * ``` + * await db.$transaction([ + * db.user.update({ where: { id: 1 }, data: { name: 'Alice' } }), + * db.post.create({ data: { title: 'Hello World', authorId: 1 } }), + * ]); */ $transaction

[]>( arg: [...P], @@ -177,24 +208,36 @@ export type ClientContract< ): Promise>; /** - * Returns a new client with the specified plugin installed. + * Returns a new client with the specified plugin installed. The original client remains unchanged. + * + * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation} */ $use< PluginSchema extends SchemaDef = Schema, PluginExtQueryArgs extends ExtQueryArgsBase = {}, PluginExtClientMembers extends ExtClientMembersBase = {}, PluginExtResult extends ExtResultBase = {}, + _R = {}, // auxiliary type for inferring precise typing for `PluginExtResult` >( - plugin: RuntimePlugin, - ): ClientContract; + plugin: RuntimePlugin & { + // intersect with the `result` extension field for precise typing + result?: ExtResultInferenceArgs; + }, + ): ClientContract< + Schema, + Options, + ExtQueryArgs & PluginExtQueryArgs, + ExtClientMembers & PluginExtClientMembers, + ExtResult & PluginExtResult + >; /** - * Returns a new client with the specified plugin removed. + * Returns a new client with the specified plugin removed. The original client remains unchanged. */ $unuse(pluginId: string): ClientContract; /** - * Returns a new client with all plugins removed. + * Returns a new client with all plugins removed. The original client remains unchanged. */ $unuseAll(): ClientContract; @@ -224,7 +267,13 @@ export type ClientContract< */ get $diagnostics(): Promise; } & { - [Key in GetSlicedModels as Uncapitalize]: ModelOperations; + [Key in GetSlicedModels as Uncapitalize]: ModelOperations< + Schema, + Key, + Options, + ExtQueryArgs, + ExtResult + >; } & ProcedureOperations & ExtClientMembers; @@ -297,7 +346,7 @@ type SliceOperations< [Key in keyof T as Key extends GetSlicedOperations ? Key : never]: T[Key]; }, // exclude create operations for models that don't allow create (delegate models, required Unsupported fields) - | (ModelAllowsCreate extends true ? never : OperationsRequiringCreate) + ModelAllowsCreate extends true ? never : OperationsRequiringCreate >; export type AllModelOperations< diff --git a/packages/orm/src/client/crud-types.ts b/packages/orm/src/client/crud-types.ts index 18bdd7183..e7aba1f68 100644 --- a/packages/orm/src/client/crud-types.ts +++ b/packages/orm/src/client/crud-types.ts @@ -238,6 +238,7 @@ export type ModelResult< : Args extends { omit: infer O } & Record ? DefaultModelResult : DefaultModelResult) & + // intersect with fields contributed by result extension plugins SelectAwareExtResult, Optional, Array @@ -960,7 +961,10 @@ export type SelectIncludeOmit< /** * Explicitly select fields and relations to be returned by the query. */ - select?: (SelectInput & ExtResultSelectOmitFields) | null; + select?: + | (SelectInput & + ExtResultSelectOmitFields) + | null; /** * Explicitly omit fields from the query result. @@ -1389,7 +1393,9 @@ type CreateRelationFieldPayload< // no "createMany" for non-array fields | (FieldIsArray extends true ? never : 'createMany') // exclude create operations for models that don't allow create - | (RelationModelAllowsCreate extends true ? never : 'create' | 'createMany' | 'connectOrCreate') + | (RelationModelAllowsCreate extends true + ? never + : 'create' | 'createMany' | 'connectOrCreate') >; type CreateRelationPayload< @@ -1747,7 +1753,9 @@ type ToManyRelationUpdateInput< set?: SetRelationInput; }, // exclude create operations for models that don't allow create - | (RelationModelAllowsCreate extends true ? never : 'create' | 'createMany' | 'connectOrCreate' | 'upsert') + RelationModelAllowsCreate extends true + ? never + : 'create' | 'createMany' | 'connectOrCreate' | 'upsert' >; type ToOneRelationUpdateInput< @@ -1795,7 +1803,7 @@ type ToOneRelationUpdateInput< } : {}), // exclude create operations for models that don't allow create - | (RelationModelAllowsCreate extends true ? never : 'create' | 'connectOrCreate' | 'upsert') + RelationModelAllowsCreate extends true ? never : 'create' | 'connectOrCreate' | 'upsert' >; // #endregion @@ -2460,11 +2468,14 @@ export type ExtractExtResult = keyof ExtResult extends never +export type ExtResultSelectOmitFields< + ExtResult extends ExtResultBase, + Model extends string, +> = keyof ExtResult extends never ? {} : Uncapitalize extends keyof ExtResult - ? { [K in keyof ExtResult[Uncapitalize]]?: boolean } - : {}; + ? { [K in keyof ExtResult[Uncapitalize]]?: boolean } + : {}; type TruthyKeys = { [K in Keys]: K extends keyof S ? (S[K] extends false | undefined ? never : K) : never; @@ -2476,23 +2487,26 @@ type TruthyKeys = { * - If T has `omit`, excludes ext result fields that are explicitly omitted. * - Otherwise, includes all ext result fields. */ -export type SelectAwareExtResult = - keyof ExtResult extends never - ? {} - : T extends { select: infer S } - ? S extends null | undefined - ? ExtractExtResult - : Pick< - ExtractExtResult, - TruthyKeys>> - > - : T extends { omit: infer O } - ? O extends null | undefined - ? ExtractExtResult - : Omit< - ExtractExtResult, - TruthyKeys>> - > - : ExtractExtResult; +export type SelectAwareExtResult< + ExtResult extends ExtResultBase, + Model extends string, + T, +> = keyof ExtResult extends never + ? {} + : T extends { select: infer S } + ? S extends null | undefined + ? ExtractExtResult + : Pick< + ExtractExtResult, + TruthyKeys>> + > + : T extends { omit: infer O } + ? O extends null | undefined + ? ExtractExtResult + : Omit< + ExtractExtResult, + TruthyKeys>> + > + : ExtractExtResult; // #endregion diff --git a/packages/orm/src/client/plugin.ts b/packages/orm/src/client/plugin.ts index 42a34b5f6..bd3fc555b 100644 --- a/packages/orm/src/client/plugin.ts +++ b/packages/orm/src/client/plugin.ts @@ -1,8 +1,9 @@ import type { OperationNode, QueryId, QueryResult, RootOperationNode, UnknownRow } from 'kysely'; import type { ZodType } from 'zod'; import type { ClientContract, ZModelFunction } from '.'; -import type { GetModels, NonRelationFields, SchemaDef } from '../schema'; +import type { GetModelFields, GetModels, NonRelationFields, SchemaDef } from '../schema'; import type { MaybePromise } from '../utils/type-utils'; +import type { MapModelFieldType } from './crud-types'; import type { AllCrudOperations, CoreCrudOperations } from './crud/operations/base'; type AllowedExtQueryArgKeys = CoreCrudOperations | '$create' | '$read' | '$update' | '$delete' | '$all'; @@ -35,6 +36,44 @@ export type ExtResultBase = { >; }; +/** + * Mapped type that provides per-field contextual typing for `compute` callbacks + * based on the `needs` declaration. Uses a separate type parameter `R_` that captures + * the needs shape (model → field → { neededField: true }), then links each field's + * `compute` parameter to exactly the keys declared in its `needs`. + */ +export type ExtResultInferenceArgs = { + [K in keyof R_ & string]: { + [P in keyof R_[K]]?: { + needs?: { + // constraint for `needs` keys + [F in keyof R_[K][P]]: F extends NonRelationFields> ? true : never; + } & Partial>, true>>; // further intersects with all possible keys for intellisense + + // refine `computes`'s parameter type based on the inferred type of `needs` + compute: (data: ExtResultComputeData, R_[K][P]>) => unknown; + }; + }; +}; + +/** + * Reverse-maps an uncapitalized key back to the original model name in the schema. + * E.g., for a schema with model `myModel`, the key `myModel` maps back to `myModel` + * (not `MyModel` as `Capitalize` would produce). + */ +type ModelNameFromKey = { + [M in GetModels]: Uncapitalize extends K ? M : never; +}[GetModels]; + +/** + * Maps the needs shape `S` to an object with actual schema field types. + * For each key in `S` that is a valid non-relation field of model `M`, + * resolves the TypeScript type from the schema field definition. + */ +type ExtResultComputeData, S> = { + [F in keyof S & GetModelFields]: MapModelFieldType; +}; + /** * ZenStack runtime plugin. */ @@ -42,7 +81,7 @@ export interface RuntimePlugin< Schema extends SchemaDef, ExtQueryArgs extends ExtQueryArgsBase, ExtClientMembers extends Record, - ExtResult extends ExtResultBase = {}, + ExtResult extends ExtResultBase, > { /** * Plugin ID. @@ -108,8 +147,58 @@ export interface RuntimePlugin< export type AnyPlugin = RuntimePlugin; /** - * Defines a ZenStack runtime plugin. + * Defines a ZenStack runtime plugin based on type of the given schema. + * + * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation} + * + * @example + * ```typescript + * definePlugin(schema, { + * id: 'my-plugin', + * result: { + * user: { + * fullName: { + * needs: { firstName: true, lastName: true }, + * compute: (user) => `${user.firstName} ${user.lastName}`, + * }, + * }, + * }, + * }); + * ``` */ +export function definePlugin< + Schema extends SchemaDef, + const ExtQueryArgs extends ExtQueryArgsBase = {}, + const ExtClientMembers extends Record = {}, + const ExtResult extends ExtResultBase = {}, + R_ = {}, +>( + schema: Schema, + plugin: RuntimePlugin & { + result?: ExtResultInferenceArgs; + }, +): RuntimePlugin; + +/** + * Defines a ZenStack runtime plugin. + * + * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation} + * + * @example + * ```typescript + * definePlugin(schema, { + * id: 'my-plugin', + * result: { + * user: { + * fullName: { + * needs: { firstName: true, lastName: true }, + * compute: (user) => `${user.firstName} ${user.lastName}`, + * }, + * }, + * }, + * }); + * ``` + * */ export function definePlugin< Schema extends SchemaDef, const ExtQueryArgs extends ExtQueryArgsBase = {}, @@ -117,8 +206,10 @@ export function definePlugin< const ExtResult extends ExtResultBase = {}, >( plugin: RuntimePlugin, -): RuntimePlugin { - return plugin; +): RuntimePlugin; + +export function definePlugin(...args: unknown[]) { + return args.length === 2 ? args[1] : args[0]; } /** diff --git a/tests/e2e/orm/plugin-infra/ext-result.test.ts b/tests/e2e/orm/plugin-infra/ext-result.test.ts index 56ed288cd..141eabea2 100644 --- a/tests/e2e/orm/plugin-infra/ext-result.test.ts +++ b/tests/e2e/orm/plugin-infra/ext-result.test.ts @@ -16,19 +16,41 @@ describe('Plugin extended result fields', () => { }); it('should compute virtual fields on findMany results', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - greeting: { - needs: { name: true }, - compute: (user) => `Hello, ${user.name}!`, - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + greeting: { + needs: { name: true }, + compute: (user) => `Hello, ${user.name}!`, }, }, - }), - ); + }, + }); + + await extDb.user.create({ data: { name: 'Alice' } }); + await extDb.user.create({ data: { name: 'Bob' } }); + + const users = await extDb.user.findMany({ orderBy: { id: 'asc' } }); + expect(users).toHaveLength(2); + expect(users[0]!.greeting).toBe('Hello, Alice!'); + expect(users[1]!.greeting).toBe('Hello, Bob!'); + }); + + it('should compute virtual fields with definePlugin on findMany results', async () => { + const plugin = definePlugin(schema, { + id: 'greeting', + result: { + user: { + greeting: { + needs: { name: true }, + compute: (user) => `Hello, ${user.name}!`, + }, + }, + }, + }); + + const extDb = db.$use(plugin); await extDb.user.create({ data: { name: 'Alice' } }); await extDb.user.create({ data: { name: 'Bob' } }); @@ -40,39 +62,36 @@ describe('Plugin extended result fields', () => { }); it('should compute virtual fields on findUnique', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - greeting: { - needs: { name: true }, - compute: (user) => `Hello, ${user.name}!`, - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + greeting: { + needs: { name: true }, + compute: (user) => `Hello, ${user.name}!`, }, }, - }), - ); + }, + }); const created = await extDb.user.create({ data: { name: 'Alice' } }); + expect(created.greeting).toBe('Hello, Alice!'); const user = await extDb.user.findUnique({ where: { id: created.id } }); expect(user?.greeting).toBe('Hello, Alice!'); }); it('should compute virtual fields on findFirst', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); const user = await extDb.user.findFirst(); @@ -80,19 +99,17 @@ describe('Plugin extended result fields', () => { }); it('should compute virtual fields on findUniqueOrThrow and findFirstOrThrow', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); const created = await extDb.user.create({ data: { name: 'Alice' } }); const user1 = await extDb.user.findUniqueOrThrow({ where: { id: created.id } }); @@ -103,19 +120,17 @@ describe('Plugin extended result fields', () => { }); it('should compute virtual fields on create, update, upsert, delete', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); // create const created = await extDb.user.create({ data: { name: 'Alice' } }); @@ -147,19 +162,17 @@ describe('Plugin extended result fields', () => { return; } - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); const users = await extDb.user.createManyAndReturn({ data: [{ name: 'Alice' }, { name: 'Bob' }], @@ -170,19 +183,17 @@ describe('Plugin extended result fields', () => { }); it('should NOT compute virtual fields on count, exists, createMany, updateMany, deleteMany', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -210,23 +221,21 @@ describe('Plugin extended result fields', () => { }); it('should compute only selected virtual fields when using select', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, - idDoubled: { - needs: { id: true }, - compute: (user) => user.id * 2, - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), + }, + idDoubled: { + needs: { id: true }, + compute: (user) => user.id * 2, }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -241,19 +250,17 @@ describe('Plugin extended result fields', () => { }); it('should not compute virtual fields when not selected explicitly', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -264,19 +271,17 @@ describe('Plugin extended result fields', () => { }); it('should exclude virtual fields when using omit', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -286,19 +291,17 @@ describe('Plugin extended result fields', () => { }); it('should still compute virtual fields when their needs dependency is omitted', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -344,19 +347,17 @@ describe('Plugin extended result fields', () => { }); it('should remove virtual fields when plugin is removed via $unuse', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -370,32 +371,28 @@ describe('Plugin extended result fields', () => { it('should remove all virtual fields when $unuseAll is called', async () => { const extDb = db - .$use( - definePlugin({ - id: 'p1', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + .$use({ + id: 'p1', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ) - .$use( - definePlugin({ - id: 'p2', - result: { - user: { - idDoubled: { - needs: { id: true }, - compute: (user) => user.id * 2, - }, + }, + }) + .$use({ + id: 'p2', + result: { + user: { + idDoubled: { + needs: { id: true }, + compute: (user) => user.id * 2, }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -410,19 +407,17 @@ describe('Plugin extended result fields', () => { }); it('should compute virtual fields inside $transaction', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.$transaction(async (tx) => { const created = await tx.user.create({ data: { name: 'Alice' } }); @@ -434,19 +429,17 @@ describe('Plugin extended result fields', () => { }); it('should accept virtual fields in select/omit via Zod validation', async () => { - const extDb = db.$use( - definePlugin({ - id: 'greeting', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'greeting', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -458,19 +451,17 @@ describe('Plugin extended result fields', () => { }); it('should handle virtual fields that depend on multiple needs', async () => { - const extDb = db.$use( - definePlugin({ - id: 'full-info', - result: { - user: { - fullInfo: { - needs: { id: true, name: true }, - compute: (user) => `${user.id}:${user.name}`, - }, + const extDb = db.$use({ + id: 'full-info', + result: { + user: { + fullInfo: { + needs: { id: true, name: true }, + compute: (user) => `${user.id}:${user.name}`, }, }, - }), - ); + }, + }); const created = await extDb.user.create({ data: { name: 'Alice' } }); const users = await extDb.user.findMany(); @@ -478,19 +469,17 @@ describe('Plugin extended result fields', () => { }); it('should inject needs and strip them when using select with virtual field', async () => { - const extDb = db.$use( - definePlugin({ - id: 'full-info', - result: { - user: { - fullInfo: { - needs: { id: true, name: true }, - compute: (user) => `${user.id}:${user.name}`, - }, + const extDb = db.$use({ + id: 'full-info', + result: { + user: { + fullInfo: { + needs: { id: true, name: true }, + compute: (user) => `${user.id}:${user.name}`, }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -504,19 +493,17 @@ describe('Plugin extended result fields', () => { }); it('should not strip needs fields that were explicitly selected', async () => { - const extDb = db.$use( - definePlugin({ - id: 'full-info', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'full-info', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -529,23 +516,21 @@ describe('Plugin extended result fields', () => { }); it('should have correct types when select includes ext result fields', async () => { - const extDb = db.$use( - definePlugin({ - id: 'typing-test', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, - idDoubled: { - needs: { id: true }, - compute: (user) => user.id * 2, - }, + const extDb = db.$use({ + id: 'typing-test', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), + }, + idDoubled: { + needs: { id: true }, + compute: (user) => user.id * 2, }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); @@ -582,19 +567,17 @@ describe('Plugin extended result fields', () => { }); it('should compute ext result fields on included relations', async () => { - const extDb = db.$use( - definePlugin({ - id: 'post-ext', - result: { - post: { - upperTitle: { - needs: { title: true }, - compute: (post) => post.title.toUpperCase(), - }, + const extDb = db.$use({ + id: 'post-ext', + result: { + post: { + upperTitle: { + needs: { title: true }, + compute: (post) => post.title.toUpperCase(), }, }, - }), - ); + }, + }); const user = await extDb.user.create({ data: { name: 'Alice' } }); await extDb.post.create({ data: { title: 'Hello World', authorId: user.id } }); @@ -608,25 +591,23 @@ describe('Plugin extended result fields', () => { }); it('should compute ext result fields on both parent and nested relations', async () => { - const extDb = db.$use( - definePlugin({ - id: 'both-ext', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'both-ext', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, - post: { - upperTitle: { - needs: { title: true }, - compute: (post) => post.title.toUpperCase(), - }, + }, + post: { + upperTitle: { + needs: { title: true }, + compute: (post) => post.title.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); await extDb.post.create({ data: { title: 'Hello', authorId: 1 } }); @@ -637,19 +618,17 @@ describe('Plugin extended result fields', () => { }); it('should handle ext result fields on nested relations with select', async () => { - const extDb = db.$use( - definePlugin({ - id: 'post-ext', - result: { - post: { - upperTitle: { - needs: { title: true }, - compute: (post) => post.title.toUpperCase(), - }, + const extDb = db.$use({ + id: 'post-ext', + result: { + post: { + upperTitle: { + needs: { title: true }, + compute: (post) => post.title.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); await extDb.post.create({ data: { title: 'Hello', authorId: 1 } }); @@ -666,19 +645,17 @@ describe('Plugin extended result fields', () => { }); it('should NOT compute ext result fields on nested relations when omitted', async () => { - const extDb = db.$use( - definePlugin({ - id: 'post-ext', - result: { - post: { - upperTitle: { - needs: { title: true }, - compute: (post) => post.title.toUpperCase(), - }, + const extDb = db.$use({ + id: 'post-ext', + result: { + post: { + upperTitle: { + needs: { title: true }, + compute: (post) => post.title.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); await extDb.post.create({ data: { title: 'Hello', authorId: 1 } }); @@ -691,19 +668,17 @@ describe('Plugin extended result fields', () => { }); it('should compute ext result fields on relations fetched via select', async () => { - const extDb = db.$use( - definePlugin({ - id: 'post-ext', - result: { - post: { - upperTitle: { - needs: { title: true }, - compute: (post) => post.title.toUpperCase(), - }, + const extDb = db.$use({ + id: 'post-ext', + result: { + post: { + upperTitle: { + needs: { title: true }, + compute: (post) => post.title.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); await extDb.post.create({ data: { title: 'Hello', authorId: 1 } }); @@ -716,19 +691,17 @@ describe('Plugin extended result fields', () => { }); it('should compute ext result fields on to-one nested relations', async () => { - const extDb = db.$use( - definePlugin({ - id: 'user-ext', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'user-ext', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); await extDb.post.create({ data: { title: 'Hello', authorId: 1 } }); @@ -739,25 +712,23 @@ describe('Plugin extended result fields', () => { }); it('should have correct types for ext result fields on nested relations', async () => { - const extDb = db.$use( - definePlugin({ - id: 'nested-types', - result: { - user: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'nested-types', + result: { + user: { + upperName: { + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), }, - post: { - upperTitle: { - needs: { title: true }, - compute: (post) => post.title.toUpperCase(), - }, + }, + post: { + upperTitle: { + needs: { title: true }, + compute: (post) => post.title.toUpperCase(), }, }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); await extDb.post.create({ data: { title: 'Hello', authorId: 1 } }); @@ -784,25 +755,23 @@ describe('Plugin extended result fields', () => { }); it('should support resultField helper for typed compute', async () => { - const extDb = db.$use( - definePlugin({ - id: 'typed-compute', - result: { - user: { - upperName: resultField({ - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }), - }, - post: { - titleAndContent: resultField({ - needs: { title: true, content: true }, - compute: (post) => `${post.title}: ${post.content ?? 'no content'}`, - }), - }, + const extDb = db.$use({ + id: 'typed-compute', + result: { + user: { + upperName: resultField({ + needs: { name: true }, + compute: (user) => user.name.toUpperCase(), + }), + }, + post: { + titleAndContent: resultField({ + needs: { title: true, content: true }, + compute: (post) => `${post.title}: ${post.content ?? 'no content'}`, + }), }, - }), - ); + }, + }); await extDb.user.create({ data: { name: 'Alice' } }); await extDb.post.create({ data: { title: 'Hello', content: 'World', authorId: 1 } }); @@ -815,19 +784,17 @@ describe('Plugin extended result fields', () => { }); it('should ignore invalid model names in result config at runtime', async () => { - const extDb = db.$use( - definePlugin({ - id: 'bad-model', - result: { - userr: { - upperName: { - needs: { name: true }, - compute: (user) => user.name.toUpperCase(), - }, + const extDb = db.$use({ + id: 'bad-model', + result: { + userr: { + upperName: { + needs: { name: true }, + compute: (user: any) => user.name.toUpperCase(), }, - } as any, - }), - ); + }, + } as any, + }); await extDb.user.create({ data: { name: 'Alice' } }); // "userr" doesn't match any model, so no ext result fields are applied @@ -838,62 +805,80 @@ describe('Plugin extended result fields', () => { it('should reject ext result fields that shadow real model fields', async () => { await db.user.create({ data: { name: 'Alice' } }); - const extDb = db.$use( - definePlugin({ - id: 'shadow', - result: { - user: { - name: { - needs: { id: true }, - compute: (user) => `name-${user.id}`, - }, + const extDb = db.$use({ + id: 'shadow', + result: { + user: { + name: { + needs: { id: true }, + compute: (user: any) => `name-${user.id}`, }, - } as any, - }), - ); + }, + } as any, + }); - await expect(extDb.user.findMany()).rejects.toThrow( - /conflicts with an existing model field/, - ); + await expect(extDb.user.findMany()).rejects.toThrow(/conflicts with an existing model field/); }); it('should reject ext result fields with invalid needs field names', async () => { - const extDb = db.$use( - definePlugin({ - id: 'bad-needs', - result: { - user: { - upperName: { - needs: { nonExistentField: true }, - compute: (user) => String(user.nonExistentField), - }, + const extDb = db.$use({ + id: 'bad-needs', + result: { + user: { + upperName: { + needs: { nonExistentField: true }, + compute: (user: any) => String(user.nonExistentField), + }, + }, + } as any, + }); + + await expect(extDb.user.findMany()).rejects.toThrow(/invalid need "nonExistentField"/); + }); + + it('should type-error when compute accesses a field not in needs (inline plugin)', () => { + db.$use({ + id: 'type-check-inline', + result: { + user: { + wrongField: { + needs: { id: true }, + // @ts-expect-error - name is not in needs + compute: (user) => `Hello, ${user.name}!`, }, - } as any, - }), - ); + }, + }, + }); + }); - await expect(extDb.user.findMany()).rejects.toThrow( - /invalid need "nonExistentField"/, - ); + it('should type-error when compute accesses a field not in needs (definePlugin)', () => { + definePlugin(schema, { + id: 'type-check-define', + result: { + user: { + wrongField: { + needs: { id: true }, + // @ts-expect-error - name is not in needs + compute: (user) => `Hello, ${user.name}!`, + }, + }, + }, + }); }); it('should reject ext result fields with relation fields in needs', async () => { - const extDb = db.$use( - definePlugin({ - id: 'bad-needs-relation', - result: { - user: { - postCount: { - needs: { posts: true }, - compute: (user) => String(user.posts), - }, + const extDb = db.$use({ + id: 'bad-needs-relation', + result: { + user: { + postCount: { + needs: { posts: true }, + compute: (user: any) => String(user.posts), }, - } as any, - }), - ); + }, + } as any, + }); - await expect(extDb.user.findMany()).rejects.toThrow( - /invalid need "posts"/, - ); + await expect(extDb.user.findMany()).rejects.toThrow(/invalid need "posts"/); }); }); From b155cef84e682d0f3c2dce272908798741ae3e19 Mon Sep 17 00:00:00 2001 From: ymc9 <104139426+ymc9@users.noreply.github.com> Date: Wed, 18 Mar 2026 12:08:32 -0700 Subject: [PATCH 2/2] fix: address PR comments --- packages/orm/src/client/plugin.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/orm/src/client/plugin.ts b/packages/orm/src/client/plugin.ts index 1affe92ae..7535b6872 100644 --- a/packages/orm/src/client/plugin.ts +++ b/packages/orm/src/client/plugin.ts @@ -206,7 +206,7 @@ export function definePlugin< const ExtResult extends ExtResultBase = {}, >( plugin: RuntimePlugin, -): RuntimePlugin; +): RuntimePlugin; export function definePlugin(...args: unknown[]) { return args.length === 2 ? args[1] : args[0];