Error parsing triggers Cannot find module when deploying firebase function - firebase

I am implementing a firebase function endpoint that requires I authenticate with two different projects. Information found on SO and other sources suggest this
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
const serviceAccountSource = require('./source.json');
const serviceAccountTarget = require('./target.json');
const sourceAdmin = admin.initializeApp({
credential: admin.credential.cert(serviceAccountSource)
})
const targetAdmin = admin.initializeApp({
credential: admin.credential.cert(serviceAccountTarget)
s}, "destination")
Where source.json and target.json are files storing the serviceAccount credentials (JSON) obtained from the Project Settings => Generate New Private Key.
My folder structure is as follows
functions/
index.ts
source.json
target.json
Running the following
npm run-script lint
produces no errors, however when I run
firebase deploy --only functions
I get
Error: Error parsing triggers: Cannot find module './source.json'
Firebase admin / functions versions as follows
"firebase-admin": "7.0.0",
"firebase-functions": "^2.2.0"
Typescript
"typescript": "^3.2.2"
Any ideas as what is causing the error.

If you are using Typescript try moving your source.json to the lib folder.

I found a solution to this. Although documentation on the firebase admin functions (parameters etc) seems to be very scarce I did notice that the credential.cert member takes a ServiceAccountPathOrObject.
I tried
const sourceAdmin = admin.initializeApp({
credential: admin.credential.cert('./source.json')
})
This failed with a path not found but this time it gave the path. From this I was able to see that there was a missing element in the Path
const sourceAdmin = admin.initializeApp({
credential: admin.credential.cert('./src/source.json')
})
The function deployed. I then tried to go back to the original code and added the 'src' folder to the path - however that resulted in the same error.
I prefer the above solution but I am still interested to know what caused the original error - given that much of the documentation out there seems to recommend this including this https://gist.github.com/brunobraga95/82bef0672ce451767107e62df1d8b28f - which is the code I am trying to implement.
The function has deployed and is working - so I can confirm the recommendation above works.

Related

Emulator Storage running but ignored

I have a firebase function that is successfully uploading a file when run in the emulator, but the file ends up on production even though I'm running the Storage Emulator
I'm running with the following package.json snippets in the functions directory
"dependencies": {
"firebase-admin": "^8.13.0",
"firebase-functions": "^3.16.0",
...
}
"engines": {
"node": "14"
}
I'm initializing everything with defaults (which has worked fine in emulation and production until recently).
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const storage = admin.storage();
const bucket = storage.bucket();
...
const myFunction = async () => {
const savedFile = await bucket.file(`99999999.html`).save(fileContents);
}
The code above works, although the file ends up on production, not in the emulator storage. The logs show that a production google api is being accessed.
This would be fine (not ideal, but workable) if I could also read the file. But when I try to run the .exits() or .download() function for the same file with bucket.file('99999999.html').download();, I get the following log entries:
I need to either:
Get emulation for storage working to resolve this (ideal)
Figure out why downloading isn't working in this case
If anyone can help me with either, I'd greatly appreciate it.
I have updated firebase-admin and firebase-tools packages accordingly:
"dependencies": {
"firebase-admin": "^10.0.0",
"firebase-tools": "^9.23.1",
...
}
This resulted in a more clear error saying that the file downloaded did not match the file on the server (a hash mismatch from what I understand). I know that this is not the case, so I changed .download() to .download({validation: false}). This resolved my issue with accessing the file. It is still not storing on local emulation, but maybe that's not the intent.
UPDATE: I figured out you have to change the bucket to see your files in emulated storage.

Error while initializing Service Account key

When I try to initialize my service account key like so:
const admin = require('firebase-admin');
const serviceAccount = require("./serviceAccountKey.json");
// Initialize the Firebase Storage admin constant
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: "<DATABASE-NAME>.appspot.com",
databaseURL: "https://<DATABASE-NAME>.firebaseio.com"
});
I get the following error Error parsing triggers: Cannot find module './serviceAccountKey.json'
My serviceAccountKey.json file is inside my project name folder.
Also my dependencies from Firebase are the following:
"dependencies": {
"firebase": "^6.5.0",
"firebase-admin": "8.4.0",
"firebase-functions": "^3.2.0"
},
My directory structure is the following:
-server
-idea
-bin
-functions
-node_modules
-public
-routes
-views
-.firebaserc
-.gitignore
- app.js
- firebase.json
- master
- package.json
- package-lock.json
- serviceAccountKey.json ===> ***
- server.iml
Why am I getting this error?
Note: I've done some research on this and my file path does conform with the node.js documentation on using the require method.
Put your serverAccountKey.json file in your "functions" folder. The entire contents of that gets packaged up and sent to Cloud Functions (unless you changed that default in firebase.json). Files that are outside that folder will not be available. Right now, it looks like the file is in "server".

Deploying Function Error on Cloud Function with error code 13 and Message "INTERNAL"

I'm deploying a Firestore trigger onCreate for my App, but everytime I want to deploy, it always Error
the console always showing Code 13 and Message "INTERNAL"
this is what comes up on Console
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog",
"status":{"code":13,"message":"INTERNAL"},
"authenticationInfo":{"principalEmail":"[My_EMAIL]"},
"requestMetadata":{"requestAttributes":{},"destinationAttributes":{}},
"serviceName":"cloudfunctions.googleapis.com",
"methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction",
"resourceName":"projects/etalase/locations/us-central1/functions/onNewMessage"}
this is my code on index.js
exports.onNewMessage = functions.firestore
.document('/messages/{groupChatId}/{groupChatId}/{messageFeedItem}')
.onCreate(async (snapshot, context) => {
const doc = snapshot.data();
console.log('------Message Created-----');
console.log(doc);
const idForm = doc.userID;
const idTo = doc.sellerID;
console.log('Message from : ', idForm);
console.log('Message to : ', idTo);
});
I expect this will deploy and every time a new message created on {messageFeedItem}, it will trigger the console, but even I can't deploy it
Thank you
So right now I can deploy the function by changing the directory
'messages/{groupChatId}/{groupChatId}/{messageFeedItem}'
into
'messages/{groupChatId}/{groupChatId2}/{messageFeedItem}'
my speculation is you can't have same name to the wildcard
You have to import firebase functions
import functions = require('firebase-functions');
or
const functions = require('firebase-functions');
If you did, then check your package.json
For anyone who got this far and still does not have a solution - here is what was wrong in my case
exports.fnName = functions.firestore
.document('Collection/{collId}/SubCollection/{subCollId')
.onUpdate((change, context) => {
...
});
Note the missing '} at the end of the document reference.
This caused the deploy to fail with the following on the client
Failed to configure trigger provider
And with the following in the function logs
"status":{
"code":13,
"message":"INTERNAL"
},
Set up Node.js and the Firebase CLI
In many cases, new features and bug fixes are available only with the
latest version of the Firebase CLI and the firebase-functions SDK.
It's a good practice to frequently update both the Firebase CLI and
the SDK with these commands inside the functions folder of your
Firebase project:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
my issue is because I use - character in my wild card
'chat/{abc-efg}'
I change - to _ and it works

Deploying firebase cloud function in typescript

I'm trying to deploy the very first cloud function.
It works perfectly fine, but when I try to deploy it in terminal, it sets out warning saying that "functions is declared but it's value is never read".
Is this some common starting mistake, as I am new to this subject? Thank you.
I tried both imports , deploy erros remains same
// const functions = require('firebase-functions');
import * as functions from 'firebase-functions'
Errors message
index.ts file code here
Your code doesn't declare any Cloud Functions yet, so eslint warns you that you're importing functions but not using it.
The message will disappear when you declare a Cloud Function in your index.js/index.ts. For example, the documentation on getting started contains this example:
exports.addMessage = functions.https.onRequest((req, res) => {
const original = req.query.text;
return admin.database().ref('/messages').push({original: original}).then((snapshot) => {
return res.redirect(303, snapshot.ref.toString());
});
});
As you can see, this code uses functions in its first line. So if you add this (or any other Cloud Functions declaration) to your code, you're using functions and eslint will no longer warn you about it not being used.
The error will disappear when you finally use "functions" in a cloud function.
nevermind, you are better off using
const functions = require('firebase-functions');
when importing firebase-functions in your index.js
========
EDIT : ======
Make sure that you have correctly installed those dependencies, by running those npm commands in the right folder:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
Probably solved, but for me I was expecting ~/functions/index.ts to be the file building but the firebase cli added ~/functions/src/index.ts and THAT was the file.

Error with Firebase on Electron app: Failed to load gRPC

I'm building an Electron app, and in the renderer.js file, I'm using Firebase Admin to get Firestore data. However, whenever I run it, it returns this error in the logs..
Error: Failed to load gRPC binary module because it was not installed for the current system
Expected directory: electron-v2.0-darwin-x64-unknown
Found: [node-v48-darwin-x64-unknown]
This problem can often be fixed by running "npm rebuild" on the current system
I tried to run "npm rebuild", but it still didn't fix it.
I also tried updating Firebase Admin and gRPC.
Here is the code from the renderer.js file...
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const admin = require('firebase-admin');
var serviceAccount = require('./credentials.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://mytestapp.firebaseio.com"
});
var db = admin.firestore();
const settings = {
timestampsInSnapshots: true
};
db.settings(settings);
function LoadList() {
db.collection("Orders").get().then(function(Collection){
Collection.forEach(function(OrderDoc){
console.log(OrderDoc.id)
})
}).catch(function(err){
console.error(err);
});
}
document.querySelector('#ListSec').addEventListener('click', LoadOrderList)
Any ideas? I've been trying to solve this for hours, but can't seem to figure it out.
That error message indicates that gRPC was installed for Node, not for Electron. Electron has a different binary interface, so binary modules like gRPC need to be installed specifically for Electron. You can generally do this just by running npm rebuild --runtime=electron --target=2.0.0 (modified to match the version of Electron you want to use).
The original answer by #murgatroid99 was helpful at the time, and a postinstall command worked great up until electron v7, where the issue returned.
For anyone else who comes across this issue, I've found a better solution:
the electron-rebuild package
npm install electron-rebuild --save-dev
Run it using
npx electron-rebuild
Or, add it as a postinstall command
{
...
"scripts": {
"postinstall": "electron-rebuild"
},
...
}
Further information is in the official Electron Documentation

Resources