#How to import a Json in Nestjs?

6 messages · Page 1 of 1 (latest)

serene gyro
#

I have the following code:

auth.module:

import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'
import serviceAccount from './serviceAccountKey.json'

const FirebaseAppProvider = {
  provide: 'FIREBASE_APP',
  useFactory: () => {
    console.log({ serviceAccount })
  },
}

@Module({
  imports: [ConfigModule],
  providers: [FirebaseAppProvider],
  exports: [FirebaseAppProvider],
})
export class AuthModule {}

auth.middleware:

import { Inject, Injectable, NestMiddleware } from '@nestjs/common'

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  constructor(@Inject('FIREBASE_APP') private firebaseApp: any) {}

  use(req: any, res: any, next: () => void) {
    console.log({ firebaseApp: this.firebaseApp })
    console.log('Request...')

    next()
  }
}

My problem is that the console.log that shows the serviceAccountKey.json file shows undefined when I make a request. I attach evidence in the image.

Please 🙏, can you help me know what I'm doing wrong?

Regards thank you very much

vagrant wigeon
#

Try this instead:

const FirebaseAppProvider = {
  provide: 'FIREBASE_APP',
  useFactory: () => {
    return {
      serviceAccount
    };
  },
}
serene gyro
oblique parrot
#

your useFactory is returning nothing, so the injected "FIREBASE_APP" provider will be undefined

#

I'd suggest you to read about nestjs custom providers. It's pretty straightforward