Extending `PrismaClient` in custom service in a Nest.js application yields wrong typings for `PrismaClient.$on`
See original GitHub issueBug description
The code example showing how to integrate Prisma with Nest.js on the Prisma homepage does not behave correctly when attempting to access Prisma.$on('query', fn)
within the service. Since the $on
method infers its own typing from the constructor using it to listen to query events works only as long as a client is created inline:
const client = new PrismaClient({
log: [
{ emit: 'event', level: 'query' },
{ emit: 'event', level: 'info' },
{ emit: 'event', level: 'warn' },
{ emit: 'event', level: 'error' }
],
});
client.$on('query', event => {}); // typings only work for as long as there is at least one `event` in the log options above.
Unfortunately when extending the client within a Nest.js application there is no way at all to nudge the typings into the right direction since they are not inferable.
@Injectable()
export class PrismaService extends PrismaClient {
public constructor() {
super({
log: [
{ emit: 'event', level: 'query' },
{ emit: 'event', level: 'info' },
{ emit: 'event', level: 'warn' },
{ emit: 'event', level: 'error' }
],
});
// TS2345: Argument of type '"query"' is not assignable to parameter of type '"beforeExit"'
this.$on('query', (e) => {});
}
}
This can only be silenced using @ts-ignore
and manually supplementing the type Prisma.QueryEvent
for event
but is prone to breaking changes and it looks suspicious. I’d like to understand how to work around this issue, since using the client within the application directly it not an option due to a lack of support for dependency injection and not being idiomatic in terms of working with the Repository pattern. Wrapping the client is also not an option breaking design patterns and paradigms.
How to reproduce
see above
Expected behavior
No response
Prisma information
not relevant
Environment & setup
not relevant
Prisma Version
not relevant
Issue Analytics
- State:
- Created a year ago
- Comments:5 (1 by maintainers)
Top GitHub Comments
I was able to reduce a bit of the redundancy, especially using
typeof options
as the argument for the generic as follows:I think this is a TypeScript limitation, take a look at this issue tracking this. I am therefore closing this issue, but do let me know if you need anything. @ChristianIvicevic’s solution looks like a good workaround in the meantime.