DEV Community

Denys
Denys

Posted on

NestJs Prisma Logs

Problematic

The main reason for this post is types in prisma client for logs.

Issue preview

Default prisma service to use in nestjs

import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'
import { PrismaClient } from '@prisma/client'

@Injectable()
export class PrismaService
    extends PrismaClient implements OnModuleInit, OnModuleDestroy
{
    async onModuleDestroy() {
        await this.$disconnect()
    }

    async onModuleInit() {
        await this.$connect()
    }
}

Enter fullscreen mode Exit fullscreen mode

But what about logs...

Control logs

We can add a constructor with super call and control logs like:

constructor() {
        super({
            log: [
                { emit: 'event', level: 'query' },
                { emit: 'stdout', level: 'info' },
                { emit: 'stdout', level: 'warn' },
                { emit: 'stdout', level: 'error' },
            ],
            errorFormat: 'pretty',
        })
    }
Enter fullscreen mode Exit fullscreen mode

And we are faced with emit: event, so what does it mean in this case?
The default stdout just brings the message to the console and we no need to control it, but what with event?

Event

Event property is used for an event-based message approach. So in our case, we use an event to send an event and use a listener to catch the event and provide some log or even middleware.

Solution

We provide emit: event in the constructor to send events instead of sending them directly to the console.

And now we can catch our events like:

this.$on('query', (event) => {
            this.logger.log(`[Duration]: ${event.duration} ms`)
            this.logger.log(`[Timestamp]: ${event.timestamp}`)
            this.logger.log(`[Query]: ${event.query}`)
        })
Enter fullscreen mode Exit fullscreen mode

And also we faced another error regarding types....

The argument of type '"query"' is not assignable to parameter of type 'never'.ts(2345)
Enter fullscreen mode Exit fullscreen mode

Remember extends:

... PrismaService extends PrismaClient ...
Enter fullscreen mode Exit fullscreen mode

there is no default generic for logs, so we need to add it:

PrismaClient<Prisma.PrismaClientOptions, Prisma.LogLevel>
Enter fullscreen mode Exit fullscreen mode

and it's DONE!

Full code example: https://gist.github.com/lgtome/e05973fe289bef32ca5ccaa0247fe7ee

Top comments (0)