Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: preserve prisma client extensions's typing #1148

Merged
merged 2 commits into from
Mar 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 22 additions & 14 deletions packages/schema/src/plugins/enhancer/enhance/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,31 +92,39 @@ export class EnhancerGenerator {
`import { createEnhancement, type EnhancementContext, type EnhancementOptions, type ZodSchemas, type AuthUser } from '@zenstackhq/runtime';
import modelMeta from './model-meta';
import policy from './policy';
import { Prisma } from '${prismaImport}';
import { Prisma as _Prisma, PrismaClient as _PrismaClient } from '${prismaImport}';
import type { InternalArgs, TypeMapDef, TypeMapCbDef, DynamicClientExtensionThis } from '${prismaImport}/runtime/library';
${
withLogicalClient
? `import type * as _P from '${logicalPrismaClientDir}/index-fixed';
import type { PrismaClient } from '${logicalPrismaClientDir}/index-fixed';
import type { Prisma, PrismaClient } from '${logicalPrismaClientDir}/index-fixed';
`
: `import type * as _P from '${prismaImport}';
import type { PrismaClient } from '${prismaImport}';
import type { Prisma, PrismaClient } from '${prismaImport}';
`
}
${this.options.withZodSchemas ? "import * as zodSchemas from './zod';" : 'const zodSchemas = undefined;'}

${authTypes}
// overload for plain PrismaClient
export function enhance<ExtArgs extends Record<string, any> & InternalArgs>(
prisma: _PrismaClient<any, any, ExtArgs>,
context?: EnhancementContext<${authTypeParam}>, options?: EnhancementOptions): PrismaClient;

export function enhance<DbClient extends object>(prisma: DbClient, context?: EnhancementContext<${authTypeParam}>, options?: EnhancementOptions)${
withLogicalClient ? ': PrismaClient' : ''
} {
return createEnhancement(prisma, {
modelMeta,
policy,
zodSchemas: zodSchemas as unknown as (ZodSchemas | undefined),
prismaModule: Prisma,
...options
}, context)${withLogicalClient ? ' as PrismaClient' : ''};
}
// overload for extended PrismaClient
export function enhance<TypeMap extends TypeMapDef, TypeMapCb extends TypeMapCbDef, ExtArgs extends Record<string, any> & InternalArgs>(
prisma: DynamicClientExtensionThis<TypeMap, TypeMapCb, ExtArgs>,
context?: EnhancementContext<${authTypeParam}>, options?: EnhancementOptions): DynamicClientExtensionThis<Prisma.TypeMap, Prisma.TypeMapCb, ExtArgs>;

export function enhance(prisma: any, context?: EnhancementContext<${authTypeParam}>, options?: EnhancementOptions): any {
return createEnhancement(prisma, {
modelMeta,
policy,
zodSchemas: zodSchemas as unknown as (ZodSchemas | undefined),
prismaModule: _Prisma,
...options
}, context);
}
`,
{ overwrite: true }
);
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/tests/cli/plugins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ describe('CLI Plugins Tests', () => {
'swr',
'@tanstack/react-query@^5.0.0',
'@trpc/server',
'@prisma/client@^4.0.0',
'@prisma/client@^5.0.0',
`${path.join(__dirname, '../../../../.build/zenstackhq-language-' + ver + '.tgz')}`,
`${path.join(__dirname, '../../../../.build/zenstackhq-sdk-' + ver + '.tgz')}`,
`${path.join(__dirname, '../../../../.build/zenstackhq-runtime-' + ver + '.tgz')}`,
Expand All @@ -83,7 +83,7 @@ describe('CLI Plugins Tests', () => {
const devDepPkgs = [
'typescript',
'@types/react',
'prisma@^4.0.0',
'prisma@^5.0.0',
`${path.join(__dirname, '../../../../.build/zenstack-' + ver + '.tgz')}`,
`${path.join(__dirname, '../../../../.build/zenstackhq-tanstack-query-' + ver + '.tgz')}`,
`${path.join(__dirname, '../../../../.build/zenstackhq-swr-' + ver + '.tgz')}`,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { PrismaErrorCode } from '@zenstackhq/runtime';
import { loadSchema, run } from '@zenstackhq/testtools';
import fs from 'fs';
import path from 'path';
import { loadSchema } from '@zenstackhq/testtools';
import { POLYMORPHIC_MANY_TO_MANY_SCHEMA, POLYMORPHIC_SCHEMA } from './utils';

describe('Polymorphism Test', () => {
Expand Down Expand Up @@ -1039,16 +1037,14 @@ describe('Polymorphism Test', () => {
);
});

it('typescript compilation', async () => {
const { projectDir } = await loadSchema(schema, { enhancements: ['delegate'] });
it('typescript compilation plain prisma', async () => {
const src = `
import { PrismaClient } from '@prisma/client';
import { enhance } from '.zenstack/enhance';

const prisma = new PrismaClient();

async function main() {
await prisma.user.deleteMany();
const db = enhance(prisma);

const user1 = await db.user.create({ data: { } });
Expand Down Expand Up @@ -1084,31 +1080,82 @@ describe('Polymorphism Test', () => {
}
}

main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
main();
`;

fs.writeFileSync(path.join(projectDir, 'script.ts'), src);
fs.writeFileSync(
path.join(projectDir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
outDir: 'dist',
strict: true,
lib: ['esnext'],
esModuleInterop: true,
await loadSchema(schema, {
compile: true,
enhancements: ['delegate'],
extraSourceFiles: [
{
name: 'main.ts',
content: src,
},
})
);
],
});
});

run('npm i -D @types/node', undefined, projectDir);
run('npx tsc --noEmit --skipLibCheck script.ts', undefined, projectDir);
it('typescript compilation extended prisma', async () => {
const src = `
import { PrismaClient } from '@prisma/client';
import { enhance } from '.zenstack/enhance';

const prisma = new PrismaClient().$extends({
model: {
user: {
async signUp() {
return prisma.user.create({ data: {} });
},
},
},
});

async function main() {
const db = enhance(prisma);

const user1 = await db.user.signUp();

await db.ratedVideo.create({
data: {
owner: { connect: { id: user1.id } },
duration: 100,
url: 'abc',
rating: 10,
},
});

await db.image.create({
data: {
owner: { connect: { id: user1.id } },
format: 'webp',
},
});

const video = await db.video.findFirst({ include: { owner: true } });
console.log(video?.duration);
console.log(video?.viewCount);

const asset = await db.asset.findFirstOrThrow();
console.log(asset.assetType);
console.log(asset.viewCount);

if (asset.assetType === 'Video') {
console.log('Video: duration', asset.duration);
} else {
console.log('Image: format', asset.format);
}
}

main();
`;
await loadSchema(schema, {
compile: true,
enhancements: ['delegate'],
extraSourceFiles: [
{
name: 'main.ts',
content: src,
},
],
});
});
});
Loading