How import firebase cloud function config dynamically in NodeJS 14 with `type: module`? [ closed ] - node.js

I would like to achieve importing cloud function config dynamically but it won't working as expected.
import config from "firebase-functions";
It works ✔️
const {config} = await import('firebase-functions');
It won't work ❌
also tried the following but won't works.
import * as functions from "firebase-functions"; // function is already using as static import
or
const functions = await import('firebase-functions');
functions.config ❌// => undefined
functions.auth ✔️
functions.firestore ✔️
//and analytics, app, auth, database, firestore, handler, https, pubsub, remoteConfig, storage, testLab, logger ✔️
Am not getting a way to dynamically import the config import along with function.

Oh finaly it works.
const { default: functions} = await import('firebase-functions');
and
import functions from "firebase-functions";
giving functions.config

Related

Firebase import cannot be done outside modules

I'm going crazy over "writing stuff exactly what the documentation wants but came back with different outcome."
I'm trying to import firebase to my express.js API so the app can GET directly from the database.
// Initialize Firebase
const functions = require('firebase-functions');
import { initializeApp } from 'firebase/app';
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
... //some other code
I've looked for the solution at
https://firebase.google.com/docs/web/setup
and
SyntaxError: Cannot use import statement outside a module Firebase Functions
but seems like the problem is pretty different. The outcome still 'SyntaxError: Cannot use import statement outside a module.'
Can anyone explain what happened? Did I miss something?
The latest Firebase version is now using the ES6/modular syntax which in return will result in SyntaxError: Cannot use import statement outside a module. You have to add the "type": "module" on your package.json. This enables ES6 modules discovery. Also, When using "module" you also have to change all your require syntax to import syntax. Here's your sample code for reference:
import * as functions from "firebase-functions";
import { initializeApp } from 'firebase/app';
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"type": "module",
...
}
For more information, you may check out this documentations:
ECMAScript Modules
Upgrade from version 8 to the modular Web SDK

Initializing multiple connections to firebase are failing in Nodejs for firebase-admin NPM

I have the following code trying to connect to Firebase Realtime Database in NodeJS using the latest firebase-admin package (10.x):
import { database } from 'firebase-admin';
import { applicationDefault, initializeApp } from 'firebase-admin/app';
const app = initializeApp({
credential: applicationDefault(),
databaseURL: 'https://DATABASE_NAME.firebaseio.com'
}, 'xx');
const db = database(app);
The issue is that the database(app) call fails with following error:
TypeError: _this.ensureApp(...).database is not a function
I believe that my code is correct since I need the ability to connect to multiple databases...
Anybody knows what am I doing wrong?
The following import is incorrect:
import { database } from 'firebase-admin';
The correct modular import is:
import { getDatabase } from 'firebase-admin/database';
getDatabase()
Or, if using the old namespaced API:
import * as admin from 'firebase-admin'
admin.database()

Firebase getAuth() throws error getProvider of undefined but can access database

I have the following code running on a Node server.
import admin from 'firebase-admin';
import {getAuth} from 'firebase/auth';
class MyFirebase {
constructor() {
console.log("MyFirebase Constructor");
this.firebaseApp = admin.initializeApp({
credential: admin.credential.cert("PATH_TO_CERT/cert.json"),
databaseURL: "https://DATABASE_URL",
});
console.log("App name="+firebaseApp.name);
this.defaultAuth = getAuth(firebaseApp);
this.database = this.firebaseApp.database();
// database ref code here...
}
}
and it throws the following error:
return app.container.getProvider(name);
TypeError: Cannot read property 'getProvider' of undefined
If I remove "firebaseApp" from the getAuth(..) call I get this error:
No Firebase app '[DEFAULT'] has been created - call Firebase
App.initializeApp() (app/no-app)
However the "console.log("App Name...")" line produces:
App name=[DEFAULT]
So clearly a DEFAULT app has been created. Additionally if I remove the "getAuth..." call the database calls pulling data from the realtime database below it work just fine, which seem to imply the authentication worked properly because I can access data from the database.
What the heck is going on?
You are confusing Firebase Admin SDK (Node.js) with Firebase Javascript SDK. The former is for the back-end, while the latter is for the front-end. I understand your confusion because the front-end package/s are installable via NPM, although they are meant to be bundled with front-end code.
You can't do this:
import admin from 'firebase-admin' // back-end code
import { getAuth } from 'firebase/auth' // front-end code !!!
const adminApp = admin.initializeApp(...)
getAuth(adminApp) // TypeScript actually catches this error
/*
Argument of type 'App' is not assignable to parameter of type 'FirebaseApp'.
Property 'automaticDataCollectionEnabled' is missing in type 'App' but required in type 'FirebaseApp'.ts(2345)
app-public.d.ts(92, 5): 'automaticDataCollectionEnabled' is declared here.
const adminApp: admin.app.App
*/
If you are on the back-end, just use adminApp.auth() to get the Auth instance. If on the front-end, you need to call getAuth with the front-end Firebase App instance:
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
const app = initializeApp(...)
const auth = getAuth(app)
The new modular apis have a slightly different syntax. The following should still work if you wrap it in a class, but as long as you only do this once at the top of your express? server you shouldn't need to use a class.
Also, I'm using the require syntax but imports should work too depending on your setup.
//Import each function from the correct module.
const { initializeApp, applicationDefault } = require("firebase-admin/app");
const { getAuth } = require("firebase-admin/auth");
const { getDatabase } = require("firebase-admin/database");
const app = initializeApp({
credential: applicationDefault(), //Don't forget to export your configuration json https://firebase.google.com/docs/admin/setup
databaseURL: "https://DATABASE_URL",
});
const auth = getAuth(app)
const database = getDatabase(app)
It's not super well documented but you can find hints in the Admin SDK reference: https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth
One tip: In VSCode you should see the a description of each function when you hover over them, if you have the import path formatted correctly.

cloud functions - export from .TS to .JS index

My project cloud functions are built-in javascript and I've decided to slowly migrate it to typescript file by file.
I'm trying to export my onCall function from a TypeScript file on my index.js to firebase cloud functions but I keep receiving the following error into the terminal
"Error: Error parsing triggers: Cannot find module './business'" when trying to deploy and not being able to properly import the Typescript function into my index.js
index.js
const business = require('./business');
exports.business.processBusinessSignUp;
business.ts:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as api from "./api";
import { BusinessFirestoreModel } from "./ts models/business_firestore_model";
module.exports.processBusinessSignUp = functions.https.onCall((data, context) => {
const business_model = new BusinessFirestoreModel(data.fullName, data.businessName, data.email, data.address, data.phone, Date.now());
return signBusinessUp(business_model);
});
const signBusinessUp = async (business: BusinessFirestoreModel) => {
const firestoreRef = admin.firestore().collection('pending_business').doc();
return await api.callFirestoreSet(firestoreRef, business.toJSON());
}
Any ideas?
Thank you!
As Brian Burton said You need to transpile your TypeScript into regular JavaScript before deploying if you want to run Typescript natively On Firebase Cloud Function, if you want more information here is the official documentation

React Redux - Error passing several store enhancers to createStore()

I have a react app running redux and thunk which has all been working fine. I need to persist the store state on page reload so that data is not lost, so have created a function which is storing data in the localstorage and then returning the data ready for adding to createStore (https://stackoverflow.com/a/45857898/801861). The data storage is working fine and returning the object ready for setting the sate. When adding the data object at createStore react fails to compile with this error:
Error: It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function
Here is CURRENT CODE RETURNING ERROR:
const store = createStore(reducers, LoadState, applyMiddleware(thunk) );
//Error: It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function
My original code which was running:
const store = createStore(reducers, applyMiddleware(thunk) );
I attempted to fix this following some similar issues I found online, compiles but breaks site code which was originally working fine:
const composeEnhancers = LoadState || compose;
const store = createStore(reducers, composeEnhancers( applyMiddleware(thunk) ) );
//Error: Actions must be plain objects. Use custom middleware for async actions.
Not sure what I need to change to get this to work, any help is appreciated.
I think you are following a tutorial which is performing tasks in a previous version of redux.
You need to create a composeEnhancer which will take in your Redux Dev Tools extension as shown
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
after importing compose from 'redux' obviously as shown -
import {createStore, compose, applyMiddleware} from 'redux';
and then, you can create the store as shown -
const Store = createStore(rootReducer, composeEnhancer(applyMiddleware(thunk)))
The error is self-explanatory. It tells you what to do exactly!!
Namely it tell you that you should compose your enhancers instead.
Here is how to it:
Step #1: Import 'compose' from redux library
import { createStore, applyMiddleware, compose } from 'redux';
Step #2: Compose your list of enhancers since you have more than one
const enhancers = [LoadState, applyMiddleware(thunk)];
const store = createStore(
reducers,
compose(...enhancers)
);
Refer to this page for more details.
I suspect your issue is within your LoadState. What ever is it? Here is a working createStore:
const store = createStore(
reducers,
{ counter: { count: 5 } },
applyMiddleware(() => dispatch => {
console.log('Yoyoyo')
return dispatch;
}));
Hope it solves your issue. Make sure to put actual initial state values and not some function or what ever it is LoadState is :)
You can use a package to persist the redux store into the local storage and you don't need to make your own function:
https://github.com/rt2zz/redux-persist
In the first example of the package you can see how to use the persistReducer() and persistStore() to save your state and then auto rehydrates on refresh page.
plz check this advanced store setup that may help you
enter link description here
https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup
import { createStore, applyMiddleware, compose } from 'redux';
+ const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
+ const store = createStore(reducer, /* preloadedState, */ composeEnhancers(
- const store = createStore(reducer, /* preloadedState, */ compose(
applyMiddleware(...middleware)
));
Am starting out with it React-Redux and faced the same issue. am not sure if it is the right approach but here we go.
the one issue you only need to fix in your code is to call the function,
store = createStore(reducers, LoadState(), applyMiddleware(thunk) );
this solution worked for me.
For redux saga users,
import createSagaMiddleware from "redux-saga";
const sagaMiddleware = createSagaMiddleware();
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, composeEnhancer(applyMiddleware(sagaMiddleware)))
import { applyMiddleware, compose, createStore } from "redux";
import { devToolsEnhancer } from "redux-devtools-extension";
import { logger } from "./middlewares/logger";
import reducers from "./reducers";
import { todoReducer } from "./todoReducer";
const store = createStore(
reducers,
compose(applyMiddleware(logger), devToolsEnhancer({ trace: true }))
);
export default store;

Resources