P
Prisma21h ago
PingZing

Declaring a PrismaClient with conditional logging

Hi folks! I'm trying to instantiate a PrismaClient in a TypeScript project. I'm using v6.0.1, and have the following code:
export class DatabaseClient {
private _prismaClient;

constructor(databaseUrl: string, appInsightsClient?: appInsights.TelemetryClient) {
const logDefinitions: Prisma.LogDefinition[] = [
{
level: "error",
emit: "event",
},
{
level: "warn",
emit: "event",
},
];

this._prismaClient = new PrismaClient({
datasourceUrl: databaseUrl,
log: logDefinitions,
});

if (someCondition) {
this._prismaClient.$on("error", (evt: Prisma.LogEvent) => {
// Do som error logging stuff
});
}
}
export class DatabaseClient {
private _prismaClient;

constructor(databaseUrl: string, appInsightsClient?: appInsights.TelemetryClient) {
const logDefinitions: Prisma.LogDefinition[] = [
{
level: "error",
emit: "event",
},
{
level: "warn",
emit: "event",
},
];

this._prismaClient = new PrismaClient({
datasourceUrl: databaseUrl,
log: logDefinitions,
});

if (someCondition) {
this._prismaClient.$on("error", (evt: Prisma.LogEvent) => {
// Do som error logging stuff
});
}
}
Unfortunately, on the line where I set up the error logging, I get the following error: Argument of type '"error"' is not assignable to parameter of type 'never'. I can fix that if I declare my array of LogDefinitions inline with the PrismaClient but I'd like to conditionally set up my log levels, which means I can't do everything inline. Is there a way around this?
4 Replies
PingZing
PingZingOP21h ago
Asking the AI gave me a kind of a workaround: if I adjust my declaration to
private _prismaClient: PrismaClient<Prisma.PrismaClientOptions, "error" | "warn">;
private _prismaClient: PrismaClient<Prisma.PrismaClientOptions, "error" | "warn">;
...then that works, but it still requires me to know ahead of time what error levels I'll be logging. I'd like to allow logging levels to be actually dynamic, if possible. oh, hey, digging into the GitHub issue mentioned by the AI led me to https://github.com/prisma/prisma/issues/11986#issuecomment-1119739964:
in that case, I think, you should be able to specify all events during compile time and then just subscribe to the ones you need in run time:
...which works well enough, I suppose!
Nurul
Nurul21h ago
I am glad to see that AI was able to help in this case 🙂 I agree, you can specify all the possible logging events: 'query' | 'info' | 'warn' | 'error' and then can select which you would like to subscribe to at run time
PingZing
PingZingOP21h ago
👍 In that case, I think this can be marked as "Solved". Do I do that myself, somehow? (Also, hooray for rubber ducking with AI assistance 😅)
Nurul
Nurul20h ago
I marked it as solved 😄
Want results from more Discord servers?
Add your server