Optimize in a Constructor

I use prisma in a nest.js api and instantiate a globally used version in a constructor - I've been trying to get optimize to work, and while the console log says it is set up and good to go, no data ever flows through. It looks like this - any idea what I'm doing wrong, or how to do this correctly?
export class ApiCoreDataAccessService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
public queryCount: number

constructor() {
const config: any = {
datasources: {
db: { url: `${process.env.DATABASE_URL}?connection_limit=30` },
},
log: [
{
emit: 'event',
level: 'query',
},
],
}

console.log('process.env.DATABASE_URL', process.env.DATABASE_URL)

super(config)
this.queryCount = 0

console.log('Initializing Prisma Optimize...')

try {
this.$extends(
withOptimize({
apiKey: process.env.OPTIMIZE_API_KEY,
}),
)
console.log('Prisma Optimize extension initialized successfully')
} catch (error) {
console.error('Failed to initialize Prisma Optimize:', error)
}
}

public async onModuleDestroy(): Promise<void> {
await this.$disconnect()
}

public async onModuleInit(): Promise<void> {
await this.$connect()

if (process.env.LOG_PRISMA_QUERIES === 'true') {
this.$on('query' as never, async (e: Prisma.QueryEvent) => {
console.log(`QUERY: ${e.query} \n\nPARAMS: ${e.params}\n\n\n`)
})
}

if (process.env.COUNT_PRISMA_QUERIES === 'true') {
this.$on('query' as never, async () => {
this.queryCount++
})
}
}
}
export class ApiCoreDataAccessService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
public queryCount: number

constructor() {
const config: any = {
datasources: {
db: { url: `${process.env.DATABASE_URL}?connection_limit=30` },
},
log: [
{
emit: 'event',
level: 'query',
},
],
}

console.log('process.env.DATABASE_URL', process.env.DATABASE_URL)

super(config)
this.queryCount = 0

console.log('Initializing Prisma Optimize...')

try {
this.$extends(
withOptimize({
apiKey: process.env.OPTIMIZE_API_KEY,
}),
)
console.log('Prisma Optimize extension initialized successfully')
} catch (error) {
console.error('Failed to initialize Prisma Optimize:', error)
}
}

public async onModuleDestroy(): Promise<void> {
await this.$disconnect()
}

public async onModuleInit(): Promise<void> {
await this.$connect()

if (process.env.LOG_PRISMA_QUERIES === 'true') {
this.$on('query' as never, async (e: Prisma.QueryEvent) => {
console.log(`QUERY: ${e.query} \n\nPARAMS: ${e.params}\n\n\n`)
})
}

if (process.env.COUNT_PRISMA_QUERIES === 'true') {
this.$on('query' as never, async () => {
this.queryCount++
})
}
}
}
3 Replies
RaphaelEtim
RaphaelEtim2w ago
Hi @justinhandley Can you please use this example to see how to properly setup Optimize in a Nestjs project?
GitHub
GitHub - nurul3101/Optimize-NestJS
Contribute to nurul3101/Optimize-NestJS development by creating an account on GitHub.
justinhandley
justinhandleyOP2w ago
That is amazing, thanks @RaphaelEtim - but it still isn't working form me.. Here is my latest.
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'
import { Prisma, PrismaClient } from '@prisma/client'
import { withOptimize } from '@prisma/extension-optimize'

@Injectable()
export class ApiCoreDataAccessService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
public queryCount: number

constructor() {
const config: any = {
datasources: {
db: { url: `${process.env.DATABASE_URL}?connection_limit=30` },
},
log: [
{
emit: 'event',
level: 'query',
},
],
}

super(config)
this.queryCount = 0
}

public async onModuleDestroy(): Promise<void> {
await this.$disconnect()
}

public async onModuleInit(): Promise<void> {
const customPrismaClient = new PrismaClient().$extends(withOptimize({ apiKey: process.env.OPTIMIZE_API_KEY }))

Object.assign(this, customPrismaClient)

await this.$connect()

if (process.env.LOG_PRISMA_QUERIES === 'true') {
this.$on('query' as never, async (e: Prisma.QueryEvent) => {
console.log(`QUERY: ${e.query} \n\nPARAMS: ${e.params}\n\n\n`)
})
}

if (process.env.COUNT_PRISMA_QUERIES === 'true') {
this.$on('query' as never, async () => {
this.queryCount++
})
}
}

search(conditions: any[], searchQuery: string, searchFields: string[]): any[] {
const query = searchQuery.trim()
const terms: string[] = query?.includes(' ') ? query.split(' ') : [query].filter(Boolean)
const searchFilters = terms.map((term) => ({
OR: searchFields.map((field) => ({
[field]: { contains: term, mode: Prisma.QueryMode.insensitive },
})),
}))

conditions.push(...searchFilters)
return conditions
}
}
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'
import { Prisma, PrismaClient } from '@prisma/client'
import { withOptimize } from '@prisma/extension-optimize'

@Injectable()
export class ApiCoreDataAccessService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
public queryCount: number

constructor() {
const config: any = {
datasources: {
db: { url: `${process.env.DATABASE_URL}?connection_limit=30` },
},
log: [
{
emit: 'event',
level: 'query',
},
],
}

super(config)
this.queryCount = 0
}

public async onModuleDestroy(): Promise<void> {
await this.$disconnect()
}

public async onModuleInit(): Promise<void> {
const customPrismaClient = new PrismaClient().$extends(withOptimize({ apiKey: process.env.OPTIMIZE_API_KEY }))

Object.assign(this, customPrismaClient)

await this.$connect()

if (process.env.LOG_PRISMA_QUERIES === 'true') {
this.$on('query' as never, async (e: Prisma.QueryEvent) => {
console.log(`QUERY: ${e.query} \n\nPARAMS: ${e.params}\n\n\n`)
})
}

if (process.env.COUNT_PRISMA_QUERIES === 'true') {
this.$on('query' as never, async () => {
this.queryCount++
})
}
}

search(conditions: any[], searchQuery: string, searchFields: string[]): any[] {
const query = searchQuery.trim()
const terms: string[] = query?.includes(' ') ? query.split(' ') : [query].filter(Boolean)
const searchFilters = terms.map((term) => ({
OR: searchFields.map((field) => ({
[field]: { contains: term, mode: Prisma.QueryMode.insensitive },
})),
}))

conditions.push(...searchFilters)
return conditions
}
}
RaphaelEtim
RaphaelEtim2w ago
Hi @justinhandley Can you please take a look at this issue comment
GitHub
Ability to extend PrismaClient class w/ Client Extensions before ...
Problem Within NestJS, the common solution to implementing an injectable Prisma Client instance is to extend PrismaClient and add the onModuleInit and enableShutdownHooks functions required by Nest...
Want results from more Discord servers?
Add your server