GithubHelp home page GithubHelp logo

aginix / nestjs-firebase-admin Goto Github PK

View Code? Open in Web Editor NEW
108.0 3.0 37.0 1.74 MB

Firebase Admin Module for Nest.js Framework

License: MIT License

TypeScript 100.00%
firebase nestjs typescript firebase-admin nest-framework

nestjs-firebase-admin's Introduction

NPM Version Package License NPM Downloads

Description

Firebase Admin Module for Nest.js Framework

Installation

$ yarn add @aginix/nestjs-firebase-admin

Import module

import { Module } from '@nestjs/common';
import { FirebaseAdminModule } from '@aginix/nestjs-firebase-admin'
import * as admin from 'firebase-admin'

@Module({
  imports: [
    FirebaseAdminModule.forRootAsync({
      useFactory: () => ({
        credential: admin.credential.applicationDefault()
      })
    }),
  ],
})
export class AppModule {}

Example

Inject Authentication Service

import { Injectable } from '@nestjs/common';
import { FirebaseAuthenticationService } from '@aginix/nestjs-firebase-admin';

@Injectable()
export class AppService {
  constructor(private firebaseAuth: FirebaseAuthenticationService) {}

  getUsers() {
    return this.firebaseAuth.listUsers()
  }
}

Compatibility Table

firebase-admin NestJS Library
9.xx master
8.xx 1.xx

License

MIT © Aginix Technologies Co., Ltd.

nestjs-firebase-admin's People

Contributors

arvinsingla avatar codingalecr avatar dependabot-preview[bot] avatar lynx39 avatar michaelmarner avatar n3n avatar notaduck avatar samuelsweet avatar sohail05 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nestjs-firebase-admin's Issues

has no exported member 'admin'

Im trying to build my app but I got this errors:

node_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-authentication.service.d.ts:5:51 - error TS2694: Namespace '"/src/node_modules/firebase-admin/lib/auth/index"' has no exported member 'admin'.

5     get auth(): import("firebase-admin/lib/auth").admin.auth.Auth;
                                                    ~~~~~

node_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-database.service.d.ts:4:14 - error TS2416: Property 'app' in type 'FirebaseDatabaseService' is not assignable to the same property in base type 'Database'.
  Property 'automaticDataCollectionEnabled' is missing in type 'App' but required in type 'FirebaseApp'.

4     readonly app: admin.app.App;
               ~~~

  node_modules/@firebase/app-types/index.d.ts:50:3
    50   automaticDataCollectionEnabled: boolean;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    'automaticDataCollectionEnabled' is declared here.

node_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-database.service.d.ts:6:59 - error TS2694: Namespace '"/src/node_modules/firebase-admin/lib/database/index"' has no exported member 'admin'.

6     get database(): import("firebase-admin/lib/database").admin.database.Database;
                                                            ~~~~~

node_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-firestore.service.d.ts:2:22 - error TS2720: Class 'FirebaseFirestoreService' incorrectly implements class 'Firestore'. Did you mean to extend 'Firestore' and inherit its members as a subclass?
  Property 'bundle' is missing in type 'FirebaseFirestoreService' but required in type 'Firestore'.

2 export declare class FirebaseFirestoreService implements FirebaseFirestore.Firestore {
                       ~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@google-cloud/firestore/types/firestore.d.ts:319:5
    319     bundle(bundleId?: string): BundleBuilder;
            ~~~~~~
    'bundle' is declared here.

node_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-messaging.service.d.ts:5:61 - error TS2694: Namespace '"/src/node_modules/firebase-admin/lib/messaging/index"' has no exported member 'admin'.

5     get messaging(): import("firebase-admin/lib/messaging").admin.messaging.Messaging;
                                                              ~~~~~

node_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-remote-config.service.d.ts:5:68 - error TS2694: Namespace '"/src/node_modules/firebase-admin/lib/remote-config/index"' has no exported member 'admin'.

5     get remoteConfig(): import("firebase-admin/lib/remote-config").admin.remoteConfig.RemoteConfig;
                                                                     ~~~~~

node_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-storage.service.d.ts:6:57 - error TS2694: Namespace '"/src/node_modules/firebase-admin/lib/storage/index"' has no exported member 'admin'.

6     get storage(): import("firebase-admin/lib/storage").admin.storage.Storage;
                                                          ~~~~~

[4:28:50 PM] Found 7 errors. Watching for file changes.

Nest 8 question

Hi there! Was looking at this issue #447, just wondering if there will be a versioned release containing the update to Nest 8? Thanks very much!

error while nest build

�[91m�[96mnode_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-firestore.service.d.ts�[0m:�[93m9�[0m:�[93m5�[0m - �[91merror�[0m�[90m TS2416: �[0mProperty 'collectionGroup' in type 'FirebaseFirestoreService' is not assignable to the same property in base type 'Firestore'.
Type '(collectionId: string) => Query' is not assignable to type '(collectionId: string) => CollectionGroup'.
Property 'getPartitions' is missing in type 'Query' but required in type 'CollectionGroup'.

�[7m9�[0m collectionGroup(collectionId: string): FirebaseFirestore.Query;
�[7m �[0m �[91m ~~~~~~~~~~~~~~~�[0m

�[96mnode_modules/@google-cloud/firestore/types/firestore.d.ts�[0m:�[93m1552�[0m:�[93m5�[0m
�[7m1552�[0m getPartitions(
�[7m �[0m �[96m ~~~~~~~~~~~~~�[0m
'getPartitions' is declared here.

�[0mFound 1 error(s).

Able to fix this when changed from
collectionGroup(collectionId: string): FirebaseFirestore.Query;
to
collectionGroup(collectionId: string): FirebaseFirestore.CollectionGroup;
in node_modules@aginix\nestjs-firebase-admin\dist\services\firebase-admin-firestore.service.d.ts

Has this project been abandoned?

Lots of open PRs and issues that are very old. No support for Nest 9 and 10. Seems like there would probably be others who would be willing to put in basic maintenance to keep the project alive if you wanted to add maintaners.

peer deps conflict with nest ^9 and @aginix/[email protected]

When trying to run a docker with nest ^9 and @aginix/[email protected] you get the next error
Could not resolve dependency:
#8 3.775 npm ERR! peer @nestjs/common@"^7.1.2" from @aginix/[email protected]
#8 3.776 npm ERR! node_modules/@aginix/nestjs-firebase-admin
#8 3.776 npm ERR! @aginix/nestjs-firebase-admin@"^2.2.0" from the root project

my package json is this

{
"name": "my-org",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"start": "nx serve",
"build": "nx build",
"test": "nx test"
},
"private": true,
"dependencies": {
"@aginix/nestjs-firebase-admin": "^2.2.0",
"@log4js-node/gelf": "^1.0.2",
"@nestjs/class-validator": "^0.13.4",
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.0.0",
"tslib": "^2.3.0"
},
"devDependencies": {
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@nrwl/cli": "14.8.3",
"@nrwl/eslint-plugin-nx": "14.8.3",
"@nrwl/jest": "14.8.3",
"@nrwl/linter": "14.8.3",
"@nrwl/nest": "14.8.3",
"@nrwl/node": "14.8.3",
"@nrwl/nx-cloud": "latest",
"@nrwl/workspace": "14.8.3",
"@types/jest": "28.1.1",
"@types/node": "16.11.7",
"@typescript-eslint/eslint-plugin": "^5.36.1",
"@typescript-eslint/parser": "^5.36.1",
"eslint": "~8.15.0",
"eslint-config-prettier": "8.1.0",
"jest": "28.1.1",
"jest-environment-jsdom": "28.1.1",
"nx": "14.8.3",
"prettier": "^2.6.2",
"ts-jest": "28.0.5",
"ts-node": "10.9.1",
"typescript": "~4.8.2"
}
}

and my docker file is this

FROM node:16-alpine
ENV APP_NAME=api
COPY --chown=node:node ./ ./app
WORKDIR ./app
RUN npm install
RUN echo "DONE!!!!"

its an NX workspace
my docker command is

docker build --progress=plain -f ./apps/api/Dockerfile . -t api-test

BTW - on node 14 it seems to be working fine

Not working with firebase 10

When updating to firebase 10, I receive errors that initializing is not working anymore.

import { FirebaseAdminModule } from '@aginix/nestjs-firebase-admin';
import { Module } from '@nestjs/common';
import { join } from 'path';
import { cert } from 'firebase-admin/app';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const serviceAccount = require(join(
  __dirname,
  `config/firebase-admin-${process.env.FIREBASE_ENV}.json`,
));

console.log(serviceAccount);

@Module({
  imports: [
    FirebaseAdminModule.forRootAsync({
      useFactory: () => ({
        credential: cert(serviceAccount),
      }),
    }),
  ],
})
export class FirebaseModule {}

ERROR
Failed to determine project ID for Auth. Initialize the SDK with service account credentials or set project ID as an app option.

Class 'FirebaseFirestoreService' incorrectly implements class 'Firestore' [error TS2720:]

I have an issue when trying to run nest build:

node_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-firestore.service.d.ts:2:22 - error TS2720: 
Class 'FirebaseFirestoreService' incorrectly implements class 'Firestore'. Did you mean to extend 'Firestore' and 
inherit its members as a subclass?
  Property 'recursiveDelete' is missing in type 'FirebaseFirestoreService' but required in type 'Firestore'.

2 export declare class FirebaseFirestoreService implements FirebaseFirestore.Firestore {
                       ~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@google-cloud/firestore/types/firestore.d.ts:278:5
    278     recursiveDelete(
            ~~~~~~~~~~~~~~~
    'recursiveDelete' is declared here.

Found 1 error(s).

And i have this config for nestjs-firebase-admin , nest core and nest CLI:

"@aginix/nestjs-firebase-admin": "^2.1.0",
"@nestjs/common": "^7.5.1",
"@nestjs/core": "^7.5.1",
"@nestjs/cli": "^7.5.1",

And I tested this on node v12.17.0, v12.18.1, and on the latest but with no success. Thank you for your feedback.

gitlab build fail

�[91m�[96mnode_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-authentication.service.d.ts�[0m:�[93m5�[0m:�[93m51�[0m - �[91merror�[0m�[90m TS2694: �[0mNamespace '"/app/node_modules/firebase-admin/lib/auth/index"' has no exported member 'admin'.

�[7m5�[0m get auth(): import("firebase-admin/lib/auth").admin.auth.Auth;

please look into it
getting failed build from gitlab ci/cd

Class 'FirebaseAuthenticationService' incorrectly implements interface 'Auth'.

Using npm package the Auth interface is incorrectly implements:

ERROR in /Users/michaelmusso/Workspace/NestJS/klasse-uno-core/node_modules/@aginix/nestjs-firebase-admin/dist/services/firebase-admin-authentication.service.d.ts(2,22):
TS2420: Class 'FirebaseAuthenticationService' incorrectly implements interface 'Auth'.
  Type 'FirebaseAuthenticationService' is missing the following properties from type 'Auth': deleteUsers, getUsers

Add two methods implements deleteUsers and getUsers.
If I have a time resolve in a PR.
Assign to @LynX39 please.

node_modules/@google-cloud/firestore/types/firestore.d.ts:23:1

`[11:44:13] Starting compilation in watch mode...

node_modules/@google-cloud/firestore/types/firestore.d.ts:23:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: DocumentData, UpdateData, Firestore, GeoPoint, Transaction, WriteBatch, WriteResult, DocumentReference, DocumentSnapshot, QueryDocumentSnapshot, OrderByDirection, WhereFilterOp, Query, QuerySnapshot, DocumentChangeType, CollectionReference, FieldValue, FieldPath, Timestamp, v1beta1, v1, OK, CANCELLED, UNKNOWN, INVALID_ARGUMENT, DEADLINE_EXCEEDED, NOT_FOUND, ALREADY_EXISTS, PERMISSION_DENIED, RESOURCE_EXHAUSTED, FAILED_PRECONDITION, ABORTED, OUT_OF_RANGE, UNIMPLEMENTED, INTERNAL, UNAVAILABLE, DATA_LOSS, UNAUTHENTICATED, FirebaseFirestore

23 declare namespace FirebaseFirestore {


node_modules/firebase-admin/node_modules/@google-cloud/firestore/types/firestore.d.ts:25:1
 25 declare namespace FirebaseFirestore {
    ~~~~~~~
 Conflicts are in this file.

node_modules/firebase-admin/node_modules/@google-cloud/firestore/types/firestore.d.ts:25:1 - error TS6200: 
Definitions of the following identifiers conflict with those in another file: DocumentData, UpdateData, Firestore, GeoPoint, Transaction, WriteBatch, WriteResult, DocumentReference, DocumentSnapshot, QueryDocumentSnapshot, OrderByDirection, WhereFilterOp, Query, QuerySnapshot, DocumentChangeType, CollectionReference, FieldValue, FieldPath, Timestamp, v1beta1, v1, OK, CANCELLED, UNKNOWN, INVALID_ARGUMENT, DEADLINE_EXCEEDED, NOT_FOUND, ALREADY_EXISTS, PERMISSION_DENIED, RESOURCE_EXHAUSTED, FAILED_PRECONDITION, ABORTED, OUT_OF_RANGE, UNIMPLEMENTED, INTERNAL, UNAVAILABLE, DATA_LOSS, UNAUTHENTICATED, FirebaseFirestore

25 declare namespace FirebaseFirestore {

node_modules/@google-cloud/firestore/types/firestore.d.ts:23:1
23 declare namespace FirebaseFirestore {
~~~~~~~
Conflicts are in this file.

node_modules/firebase-admin/node_modules/@google-cloud/firestore/types/firestore.d.ts:168:5 - error TS2374: Duplicate string index signature.

168 [key: string]: any; // Accept other properties, such as GRPC settings.
~~~~~~~~~~~~~~~~~~~

[11:44:19] Found 3 errors. Watching for file changes.
`

Allow query parameter for firestore.collection

Hello,

Firstly, thanks for the great NestJS package, really handy.

One thing I've run into is that the FirebaseFirestoreService::collection method doesn't accept the second optional query argument here:

I can't seem to find the part of the official docs where I first came across this, but as an example @angular/fire allow it here:

It's handy if you want to do things like build dynamic queries by looping through objects.

Is this something that can be added?

Cheers,

NestJS8 version bump for NPMJS

I'm seeing the latest source has been updated to NestJS 8, is there any chance where a release can be made to NPMJS so I can run NPM install?
Currently I have to force install the package and manually patch the package from NPMJS

Curious about how this compares to my current implementation

I've incorporated Firebase Auth into my NestJS product. It requires firebase-admin and I include like such:

main.ts

import { NestFactory } from "@nestjs/core";
import { AppModule } from "app.module";
import * as admin from "firebase-admin";

/**
 * If there comes a time that we want to exclude "api" prefix
 * from certain controllers, then refernce this answer:
 *
 * https://github.com/nestjs/nest/issues/255#issuecomment-360749246
 *
 * Otherwise, this functionality doesn't exist atm.
 * I think it is actively being discussed/worked on though
 */
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix("api");

  // Redacted the URL and credential for our purposes here
  admin.initializeApp({
    credential: <CREDENTIAL_CERT>,
    databaseURL: <DATEBASE_URL>
  });

  await app.listen(5000);
}
bootstrap();

Everything works fine, but then I came across this npm library.

Is there a benefit to using your method over what I did above? Is your method explicitly for baking firebase-admin into the dependency injection flow?

Injected services are undefined

Hey there,
I've tried to implement the basic example provided in the README file, but wherever I inject a service in my code, it's resolved as undefined. No error messages nor warnings are displayed.

Here is my app.module.ts:

@Module({
  imports: [
    GraphQLFederationModule.forRoot({
      context: ({ req }) => ({
        uid: req.headers.uid,
        role: req.headers.role,
      }),
      typePaths: ['./**/*.graphql'],
      resolvers: { Upload: GraphQLUpload },
      definitions: {
        path: join(process.cwd(), 'src/graphql.ts'),
      },
    }),
    DevicesModule,
    FirebaseAdminModule.forRootAsync({
      useFactory: () => ({
        credential: admin.credential.applicationDefault()
      })
    }),
    SecretsModule.forRoot({
      keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS,
      projectId: process.env.GCP_PROJECT_ID,
      env: process.env.ENVIRONMENT === 'DEV' ? 'DEV' : 'PROD',
    }),
    SetupModule,
  ],
  providers: [],
})
export class AppModule {}

This is the service where I try to inject the Firebase Services:

export class SetupService {
  constructor(
    private database: FirebaseDatabaseService,
    private storage: FirebaseStorageService,
  ) {}

  async foo(bar: string): Promise<boolean> {
    console.log(this.database) // prints undefined
    // ...
  }
}

This is the module where my service is contained:

@Module({
    providers: [SetupResolver, SetupService]
})
export class SetupModule {}

Is there anything wrong with my code that I'm not able to see?

Version 1.1.1 fails in firebase verify token

Using the 1.1.1 version get this issue when try to verify a user token:

errorInfo: {
code: 'auth/invalid-credential',
message: 'Must initialize app with a cert credential or set your Firebase project ID as the GOOGLE_CLOUD_PROJECT environment variable to call verifyIdToken().'
},

I do the validation this way:

FirebaseAdminModule.forRootAsync({
  useFactory: () => ({
    credential: admin.credential.applicationDefault()
  })
}),

and

imagen

downgrading to 1.0.9 solves the problem

Firebase versions
"firebase": "^7.17.2",
"firebase-admin": "^8.13.0",
"firebase-functions": "^3.9.0",
"firebase-tools": "^8.7.0",

verifyIdToken is not a function

I'm getting this error:

TypeError: this.firebaseAuth.verifyIdToken is not a function

I'm only injecting this:

private firebaseAuth: FirebaseAuthenticationService,

Module:

imports: [
        FirebaseAdminModule.forRootAsync({
          imports: [ConfigModule],
          inject: [ConfigService],
          useFactory: async (
            configService: ConfigService
          ): Promise<FirebaseAdminAppOptions> => ({
            credential: credential.cert({
              projectId: configService.get('FIREBASE_PROJECT_ID'),
              clientEmail: configService.get('FIREBASE_CLIENT_EMAIL'),
              privateKey: configService
                .get('FIREBASE_PRIVATE_KEY')
                .replace(/\\n/g, '\n'),
            }),
          }),
        }),
      ],

Logging this.firebaseAuth.toString() gets this:

(...params) => callback(...params)

What am I doing wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.