Search code examples
nestjsprisma

Nest could not find PrismaService element (this provider does not exist in the current context)


I'm trying to get PrismaService on my main.ts, but it's keep crashing. I'm new on this, can anyone help me to solve it? My prisma.service.ts:

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

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }
}

My main.ts:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { PrismaService } from './prisma.service';
import { ValidationPipe } from '@nestjs/common';
import helmet from 'helmet';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.enableCors({
    allowedHeaders: '*',
    origin: '*',
  });
  app.use(helmet());
  app.use(helmet.hidePoweredBy());
  app.use(helmet.contentSecurityPolicy());

  const prismaService = app.get(PrismaService);
  await prismaService.enableShutdownHooks(app);

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true,
    }),
  );

  await app.listen(process.env.PORT, () => console.log('runing...'));
}
bootstrap();

The error message:

Error: Nest could not find PrismaService element (this provider does not exist in the current context)
    at InstanceLinksHost.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/instance-links-host.js:15:19)
    at NestApplication.find (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/abstract-instance-resolver.js:8:60)
    at NestApplication.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-application-context.js:64:20)
    at /home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:133:40
    at Function.run (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/errors/exceptions-zone.js:10:13)
    at Proxy.<anonymous> (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:132:46)
    at Proxy.<anonymous> (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:181:54)
    at bootstrap (/home/rafittu/wophi/alma/back/src/main.ts:18:29)

When I delete PrismaService from main.ts, server start normaly


Solution

  • Use app.get(PrismaService, { strict: false }). The strict: false is to say that AppModule doesn't directly provider the provider and to traverse the DI container to find it