Coder Social home page Coder Social logo

dalenguyen / firebase-functions-helper Goto Github PK

View Code? Open in Web Editor NEW
81.0 5.0 17.0 724 KB

A helper NPM package for Firebase Cloud Functions

Home Page: https://www.npmjs.com/package/firebase-functions-helper

License: MIT License

TypeScript 99.06% Shell 0.94%
npm-package firestore firebase firebase-functions firebase-helper hacktoberfest firebase-database

firebase-functions-helper's Introduction

firebase-functions-helper

GitHub version Build Status

A helper NPM package for Firebase Cloud Functions

Tables of Contents

Installation

Install using npm.

npm install firebase-functions-helper

Get Google Cloud Account Credentials from Firebase

You can Generate New Private Key from Project Settings from Firebase Console.

After that you need to copy the databaseURL for initiating the App.

Usage

Examples

This is the first step that you need to do before doing any other actions. You still can use the other methods from firebase helpers if you initialize the app by using other methods from Firebase docs.

const { firebaseHelper }  = require('firebase-functions-helper');
const serviceAccount = require('./serviceAccountKey.json');

// Initialize Firebase App
firebaseHelper.initializeApp(serviceAccount);

If you want to use this package in TypeScript. Please follow this instruction:

import { firebaseHelper } from 'firebase-functions-helper';
import * as serviceAccount from './serviceAccountKey.json';

// Initialize Firebase App
firebaseHelper.initializeApp(serviceAccount);

In order to import JSON, you need to create a typings.d.ts in your project

// typings.d.ts
declare module "*.json" {
    const value: any;
    export default value;
}

Contributions

This project is based on firebase-functions-snippets, feel free to report bugs and make feature requests in the Issue Tracker, fork and create pull requests!

firebase-functions-helper's People

Contributors

ansidev avatar dependabot[bot] avatar eamonwhiter73 avatar thirumurthy 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

Watchers

 avatar  avatar  avatar  avatar  avatar

firebase-functions-helper's Issues

Get specifict document with subcollections

In method:
firebaseHelper.firestore
.getDocument(db, 'collection-name', 'document-id')
.then(doc => console.log(doc));

the data return dosen't include subcollections.

request to add createSubcollectionWithDocument and deleteDocumentFromSubcollection (or is there already a way to do this?)

I am trying to create a document in a subcollection, and then delete a document in a subcollection - is there a way I can accomplish this with the functions available? Otherwise, I would like to add:

js:

createSubcollectionWithDocument(db, collectionName, docId, collectionNameTwo, docIdTwo, data) {
        db.collection(collectionName).doc(docId).collection(collectionNameTwo).doc(docIdTwo).set(data)
            .then(res => console.log(`${JSON.stringify(data)} is added to ${collectionNameTwo} collection`))
            .catch(err => console.log('Error: ', err));
    }

deleteDocumentFromSubcollection(db, collectionName, docId, collectionNameTwo, docIdTwo) {
        db.collection(collectionName).doc(docId).collection(collectionNameTwo).doc(docIdTwo).delete()
            .then(() => {
            console.log(`${docIdTwo} successfully deleted!`);
        }).catch(error => {
            console.error("Error removing document: ", error);
        });
    }

ts:

createSubcollectionWithDocument (db: any, collectionName: string, docId: string, , collectionNameTwo: string, docIdTwo: string, data: Object): void {
        db.collection(collectionName).doc(docId).collection(collectionNameTwo).doc(docIdTwo)).set(data)
            .then(res => console.log(`${JSON.stringify(data)} is added to ${collectionNameTwo} collection`))
            .catch(err => console.log('Error: ', err))
    }

deleteDocumentFromSubcollection (db: any, collectionName: string, docId: string, collectionNameTwo: string, docIdTwo: string) {
        db.collection(collectionName).doc(docId).collection(collectionNameTwo).doc(docIdTwo).delete()
            .then(() => {
                console.log(`${docIdTwo} successfully deleted!`);
            }).catch(error => {
                console.error("Error removing document: ", error);
            });
    }

I've actually never gone about editing a package. if you can provide the steps that would be helpful (i think maybe requesting a pull? and then commiting...to master?)

queryData() return only ONE RECORD

Hi @dalenguyen
I used queryData as your guide and its response only one record while FireStore has 2 records.

Can you help to check, Thank you!

app.get('/ielts-reading-level/:levelSlug', (req, res) => {
   const {levelSlug} = req.params
    const queryArray = [['levelSlug', '==',  levelSlug]];
    firebaseHelper.firestore
        .queryData(db, levelsCollection, queryArray)
        .then(data => res.status(200).send(data))
        .catch(error => {
            console.error('ERROR::: ', error)
            res.status(500).send(error.message)
        })
})

Response:

{
    "PfX9074Z1uvaMT18djas": {
        "name": "Children",
        "description": "For children",
        "levelSlug": "level1",
        "slug": "level1"
    }
}

Service account does not recognize project_id

Hey,

I wanted to use your library to upload a json with an auto-generated id to firestore.
As I was using firestore-import-export and it worked quite well, I wanted to switch over to this lib, as it has the auto-generated id.
Nevertheless, when I try to call initializeApp with the serviceAccount it says:

Error: Service account object must contain a string "project_id" property.

Even though it has this value in the serviceaccount.json file I have downloaded from firebase. It is also the same file that was working with the firestore-import-export lib.

any help :) ?

Update document

Hi @dalenguyen,

I have seen the breaking change in function queryData between 0.6.3 and 0.6.4. You should notice about it in README.md on git repository homepage.

Thank you!

Object.entries is not a function un backup

Hi, when i call this line:

firebaseHelper.firestore.backup(firestoreInstance, 'Categories', 'Subcollection')

appear this error:

TypeError: Object.entries is not a function
    at FirestoreHelper.<anonymous> (/user_code/node_modules/firebase-functions-helper/dist/firestore.js:268:47)
    at next (native)
    at /user_code/node_modules/firebase-functions-helper/dist/firestore.js:7:71
    at __awaiter (/user_code/node_modules/firebase-functions-helper/dist/firestore.js:3:12)
    at FirestoreHelper.getSubCollection (/user_code/node_modules/firebase-functions-helper/dist/firestore.js:267:16)
    at results.then.dt (/user_code/node_modules/firebase-functions-helper/dist/firestore.js:244:26)
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

Create multiple users in Aaray

I saw the documentation of being able to create a
Single user but I would like to pass an array of data
To create multiple users. Is this possible?

*I am using firebase real-time database and storage

How to write our own implementations

Hello.Thanks for this amazing package. This sound like stupid question.But I really like to add my own implementations to this package.How to do it ? For example instead of updating a document is it possible to write code segment to append items into a firestore document? I tired to do it by reading firestore documentation. But didn't work. My question If can add something that to which file should I add those custom code parts ?Thank you

Could not find a declaration file for module 'firebase-functions-helper'

Good morning,
Im getting:

[ts]
Could not find a declaration file for module 'firebase-functions-helper'. 'c:/Projects/firebase-typescript-express-functions/node_modules/firebase-functions-helper/dist/index.js' implicitly has an 'any' type.
Try npm install @types/firebase-functions-helper if it exists or add a new declaration (.d.ts) file containing declare module 'firebase-functions-helper'; [7016]

When I attempt to npm install firebase-functions-helper

Any ideas?

Can't find declaration file

Receiving this error

src/index.ts:4:33 - error TS7016: Could not find a declaration file for module 'firebase-functions-helper'. '/Users/asdf/Developer/git/Personal/my-api/functions/node_modules/firebase-functions-helper/dist/index.js' implicitly has an 'any' type.
Try npm install @types/firebase-functions-helper if it exists or add a new declaration (.d.ts) file containing declare module 'firebase-functions-helper';

Error: firebase-admin/lib/database/index"' has no exported member 'admin'

Hi,

I'm using the latest firebase-functions-helper, and all works well on the local emulator, but when i try to do firebase deploy, i get the following error:

node_modules/firebase-functions-helper/dist/firebase.d.ts:15:57 - error TS2694: Namespace '"/Users/xx/code/xxx/xxx/functions/node_modules/firebase-admin/lib/database/index"' has no exported member 'admin'.

15         realtime: import("firebase-admin/lib/database").admin.database.Database;
                                                           ~~~~~

This is my full code of functions/index.ts:

import * as functions from "firebase-functions";
import * as firebaseHelper from "firebase-functions-helper";
import * as express from "express";
import * as serviceAccount from "../../XXXX.json";
import * as bodyParser from "body-parser";

const databaseURL = "https://XXXXXXX";
// Initialize Firebase App
const fire = firebaseHelper.firebase.initializeApp(serviceAccount, databaseURL);

const db = fire.firestore;
const app = express();
const main = express();

main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));
main.use("/api/v1", app);

const bookingsCollection = "bookings";

export const webApi = functions.https.onRequest(main);

app.get("/bookings", (req, res) => {
  firebaseHelper.firestore
    .backup(db, bookingsCollection)
    .then((data) => res.status(200).send(data))
    .catch((error) => res.status(400).send(`Cannot get bookings: ${error}`));
});

export { app };

i'm not sure if its an issue with the firebase-functions-helper or firebase-admin. i have another project with the exact same code and it works fine there...

any help is greatly appreciated!

Query two parameters

Is possible to query two parameters?

Something like:

const queryArray = [['website', '==', 'dalenguyen.me'],['status', '==', '200']];

Regards

Victor

FirebaseHelper backup undefined error

While using v0.11.0, I noticed that calls to firebaseHelper.firestore.backup() resulted in a cannot read property 'backup; of undefined error. I had to switch to v0.7.5. The implementation of the backup function in the two versions is different.

[email protected] - has no exported member 'admin' error

Hey,
I'm getting an error:

node_modules/firebase-functions-helper/dist/firebase.d.ts:15:57 - error TS2694: Namespace '".../functions/node_modules/firebase-admin/lib/database/index"' has no exported member 'admin'.

15         realtime: import("firebase-admin/lib/database").admin.database.Database;
                                                           ~~~~~

could you please update the package to support [email protected]
Thanks

Support multiple query

this.afStore.collection('listings', ref => {
				let query: firebase.firestore.Query = ref;
				
				if (filter.listing_type) { query = query.where('listing_type', '==', filter.listing_type) };
				if (filter.province) { query = query.where('province', '==', filter.province) };
				query = query.where('status', '==', 1);
				query = query.orderBy('created_date', 'desc').limit(10);
				
				

				return query;
			}).valueChanges().subscribe(callback);

would you mind if I PR?

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.