Error occurred while parsing your function triggers firebase - firebase

I am trying to implement an image upload in react using firebase storgae and I run into err 'Error occurred while parsing your function triggers firebase' when I run firebase deploy in cmd. I can't seem to figure out where the error is coming from.
The error can be seen at the bottom of the code.
const functions = require("firebase-functions");
const cors = require("cors")({origin: true});
const Busboy = require("busboy");
const fs = require("fs");
const gcconfig = {
projectId: "abcdefgh-13ff0",
keyFilename: "abcdefgh-13ff0-firebase-adminsdk-abcdefgh.json"
}
const gcs = require("#google-cloud/storage")(gcconfig);
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
exports.uploadFile = functions.https.onRequest((req, res) => {
cors(req, res, () => {
if (req.method !== "POST"){
return res.status(500).json({
message: "Not Allowed"
});
}
const busboy = new Busboy({headers: req.headers});
let uploadData = null;
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
const filepath = path.join(os.tmpdir(), filename);
uploadData = {file: filepath, type: mimetype};
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish", () => {
const bucket = gcs.bucket("gs://abcdefgh-13ff0.appspot.com");
bucket.upload(uploadData.file, {
uploadType: "media",
metadata: {
metadata: {
contentType: uploadData.type
}
}
})
.then(() => {
return res.status(200).json({
message: "It worked"
});
})
.catch(err => {
return res.status(500).json({
error: err
});
});
return;
});
busboy.end(req.rawBody);
return null;
});
});
This is the error
Error: Error occurred while parsing your function triggers.
C:\Users\Joseph\node_modules\streamsearch\lib\sbmh.js:1
(function (exports, require, module, __filename, __dirname) {
SyntaxError: Invalid or unexpected token
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:670:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Module.require (internal/modules/cjs/loader.js:650:17)
at require (internal/modules/cjs/helpers.js:20:18)

the error you're experiencing might be 1 of 2 things, but probably both combined...
The keyFileName file (abcdefgh-13ff0-firebase-adminsdk-abcdefgh.json) should be in your src folder so it can be directly accessed.
You should edit these lines of code:
const gcconfig = {
projectId: "abcdefgh-13ff0",
keyFilename: "abcdefgh-13ff0-firebase-adminsdk-abcdefgh.json"
}
const gcs = require("#google-cloud/storage")(gcconfig);
TO INSTEAD READ:
const gcs = require('#google-cloud/storage')
gcs.projectId ='abcdefgh-13ff0'
gcs.keyFilename = 'abcdefgh-13ff0-firebase-adminsdk-abcdefgh.json'
// As far as I'm concerned this should fix the issue you're experiencing!

Related

Why is firebase cloud function invoked in react-native not logging output?

I have a firebase cloud function:
exports.copyImage = functions.region('us-central1').https.onCall(async (data, context) => {
const { auth } = context || {}
const { uid } = auth || {}
if (!uid) throw 'Unauthenticated'
const srcBucketName = <bucket-name>'
const destinationBucketName = '<bucket-name'
const { imageFile, archiveId, sessionId } = data
const srcFileName = `message-attachments/${imageFile}`
const destinationFileName = `archived-attachments/${uid}/${imageFile}`
console.log(`source path: ${srcFileName}\ndestination path: ${destinationFileName}`)
const storage = new Storage()
storage
.bucket(srcBucketName)
.file(srcFileName)
.copy(storage.bucket(destinationBucketName).file(destinationFileName))
.then(() => {
console.log(`COPY SUCCESS: gs://${destinationBucketName}/${destinationFileName}`)
})
.catch(err => console.error('COPY ERROR: ' + err))
})
and I have a react-native project (v61.5) using react-native-firebase (v5) which calls this function:
firebase.functions().httpsCallable('copyFile')({
imageFile: fileName,
archiveId: uid,
sessionId
})
.then(() => {
// copied file
const ref = firebase.storage()
.ref('archived-attachments')
.child(uid)
.child(fileName)
ref.getDownloadURL()
.then(url => {
// do more
})
.catch(err => alert(err.message))
})
.catch(err => {
// copy error
})
the problem is im not getting any log output in the functions console when executing this function. the functions been successfully deployed as well. Any advice?
Updating my comment in this answer as it solves the issue.
The issue occurred because Jim has been triggering a different function copyFile
instead of copyImage.
mismatch between the function name exports.copyImage vs httpsCallable('copyFile').
Updating the function name solved the issue!

FormData using BusBoy for firebase works in serve but not in deploy

Situation
I have a firebase function that updates the user image.
Problem
When I run locally my function using firebase serve, I successfully upload the image to firestore using Postman. However, when I run firebase deploy and I try to upload the image using Postman, I get a 500 Internal Server Error. The other functions (not dealing with FormData, just json) work perfectly when I deploy them.
I don't understand why it works locally, but not on deploy when I am doing the exact same thing. Not sure if this is something in the config I am missing, or if I am doing something wrong. Any help would be appreciated!
Code
users.js
const { admin, db, firebase } = require('../util/admin');
const config = require('../util/config');
exports.postUserImage = (req, res) => {
const BusBoy = require('busboy');
const path = require('path');
const os = require('os');
const fs = require('fs');
let imgFileName;
let imgToBeUploaded = {};
const busboy = new BusBoy({ headers: req.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Invalid file type
if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
return res.status(400).json({ error: 'Invalid file type' });
}
// Extract img extension
const imgDotLength = filename.split('.').length;
const imgExtension = filename.split('.')[imgDotLength - 1];
// Create img file name
imgFileName = `${Math.round(Math.random() * 1000000)}.${imgExtension}`;
// Create img path
const filepath = path.join(os.tmpdir(), imgFileName);
// Create img object to be uploaded
imgToBeUploaded = { filepath, mimetype };
// Use file system to create the file
file.pipe(fs.createWriteStream(filepath));
});
busboy.on('finish', () => {
admin
.storage()
.bucket()
.upload(imgToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imgToBeUploaded.mimetype
}
}
})
.then(() => {
// Create img url to add to our user
const imgUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imgFileName}?alt=media`;
// Add img url to user document
return db.doc(`/users/${req.user.handle}`).update({ imgUrl });
})
.then(() => {
return res.json({ message: 'Image uploaded succesfully' });
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error });
});
});
busboy.end(req.rawBody);
};
index.js
const { app, functions } = require('./util/admin');
const FirebaseAuth = require('./util/firebaseAuth');
const {
postUserImage,
} = require('./handlers/users');
app.post('/user/image', FirebaseAuth, postUserImage);

Unable to upload image to firebase storage with firebase functions

here is my code:-
exports.uploadImage = (req, res) => {
const BusBoy = require('busboy');
const path = require('path');
const os = require('os');
const fs = require('fs');
const busboy = new BusBoy({ headers: req.headers });
let imageFileName;
let imageToBeUploaded = {};
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
const imageExtension = filename.split('.')[filename.split('.').length - 1];
imageFileName = `${Math.round(Math.random() * 100000000000)}.${imageExtension}`;
const filepath = path.join(os.tmpdir(), imageFileName);
imageToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on('finish', () => {
console.log('Busboy on started');
//code breaks here
admin.storage().bucket().upload(imageToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imageToBeUploaded.mimetype
}
}
})
.then(() => {
const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
console.log('logging image url' + imageUrl);
return db.doc(`/users/${req.user.handle}`).update({ imageUrl })
})
.then(() => {
return res.json({ message: 'Image uploaded successfully' });
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: err.code });
})
});
busboy.end(req.rawBody);
}
I have mentioned where my code is breaking in a comment and the error I am getting is Error: Cannot parse response as JSON: Not Found
message: 'Cannot parse response as JSON: Not Found'
The error message says cannot parse response as JSON. Does that mean the response from firebase is not JSON? I have a token in the header of the request and an image in the body as form-data. I really have not clue what wrong, please help
I unfortunately can't identify the JSON parsing error, so I've instead rewritten the code to be more streamlined as #robsiemb eluded to.
Your uploadImage function appears to be configured as some middleware, so I have done the same below. This code will stream the uploaded data straight to Cloud Storage under a unique file name as generated from Reference.push().key to prevent conflicts.
In the code below,
The uploaded file will be stored at a location similar to: userData/someUserId/images/-JhLeOlGIEjaIOFHR0xd.png
The image's raw URL is not stored in the database because unless the file object or containing bucket is made public it will require a signed URL which can only last up to 7 days (see below).
More than one file can be accepted and uploaded. If this is undesired, configure the limits for the BusBoy instance.
Basic error handling for non-POST requests and missing file entries was added.
// import Firebase libraries & initialize
const admin = require('firebase-admin');
admin.initializeApp(); // initializes from environment variables
// import required modules
const BusBoy = require('busboy');
exports.uploadImage = (req, res) => {
if (req.method !== 'POST') {
res.sendStatus(405); // 405 METHOD_NOT_ALLOWED
return;
}
let busboy = new BusBoy({headers: req.headers}); // add {limits: {files: 1}} to limit to only a single file upload
let bucket = admin.storage().bucket();
let db = admin.firestore();
let storageFilepath;
let storageFile;
// Note: Currently only the last file is saved to `/users/${req.user.handle}`
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
let fileext = filename.match(/\.[0-9a-z]+$/i)[0];
storageFilepath = `userData/${req.user.handle}/images/` + getUniqueName() + fileext;
storageFile = bucket.file(storageFilepath);
file.pipe(storageFile.createWriteStream({ gzip: true }));
})
.on('finish', () => {
if (!storageFile) {
res.status(400).json({error: 'expected file'}); // 400 BAD_REQUEST
return;
}
db.doc(`/users/${req.user.handle}`).update({ imagePath: storageFilepath })
.then(() => {
res.status(201).json({ message: 'Image uploaded successfully' }); // 201 CREATED
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: err.code }); // 500 INTERNAL_SERVER_ERROR
});
})
.on('error', (err) => {
console.error(err);
res.status(500).json({ error: err.code });
});
req.pipe(busboy);
});
function getUniqueName() {
// push() without arguments returns a ThennableReference, which we'll abuse for it's key generation
return admin.database().ref().push().key;
}
If you did want the uploaded image to be publicly accessible, you could use the following .on('finish', ...) handler that adds in the File.makePublic() function:
.on('finish', () => {
if (!storageFile) {
res.status(400).json({error: 'expected file'}); // 400 BAD_REQUEST
return;
}
storageFile.makePublic()
.then(() => {
return db.doc(`/users/${req.user.handle}`).update({
imagePath: storageFilepath,
imageUrl: `https://storage.googleapis.com/${config.storageBucket}/${storageFilepath}`
});
})
.then(() => {
res.status(201).json({ message: 'Image uploaded successfully' }); // 201 CREATED
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: err.code }); // 500 INTERNAL_SERVER_ERROR
});
})
Found a solution to the issue!
Essentially - you need to set up your Google Application Credentials. Go into firebase and look into your settings. You need to set up the environment variable GOOGLE_APPLICATION_CREDENTIALS so that firebase has your credentials when you access these files.
https://firebase.google.com/docs/admin/setup?authuser=1 for more information.
After you've done that, check the security settings in firebase, in every area you're dealing with. This should solve the problem (it's definitely a security issue and not your code).
This was the tutorial in question as well for those looking on . https://www.youtube.com/watch?v=m_u6P5k0vP0&t=7661s .
In my case it was wrong bucket Id configured - after correcting that i was able to upload file

Firebase function featuring val undefined

I am trying to do a push notification function whenever the database update sends a notification but the function gets an error at first
Error:
TypeError: Cannot read property 'val' of undefined
at exports.fcmSend.functions.database.ref.onCreate.event (/srv/index.js:9:31)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
at /worker/worker.js:825:24
at
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
my function
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();
exports.fcmSend = functions.database.ref('/messages/{userId}/{messageId}').onCreate(event => {
console.log('event', event)
const message = event.after.val()
const userId = event.params.userId
const payload = {
notification: {
title: message.title,
body: message.body,
icon: "https://placeimg.com/250/250/people"
}
};
admin.database()
.ref(`/fcmTokens/${userId}`)
.once('value')
.then(token => token.val() )
.then(userFcmToken => {
return admin.messaging().sendToDevice(userFcmToken, payload)
})
.then(res => {
console.log("Sent Successfully", res);
})
.catch(err => {
console.log('err', err);
});
});
The onCreate() listener doesn't have an "after". Only onUpdate() and onWrite() have before and after. It should work just to do:
event.val();

TypeError: Cannot read property 'file' of null busboy in firebase cloud function

I'm trying to write a simple function which takes a request containing multipart/form data and uploads the image to the firebase cloud storage using busboy, but in the cloud functions console it throw the following error "TypeError: Cannot read property 'file' of null". I have checked if the postman sends the correct header 'Content-type: multipart/form-data' and everything seems to be ok. Any help will be much appreciated.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
const os = require('os');
const path = require('path');
const fs = require('fs');
const Busboy = require('busboy');
var { Storage } = require('#google-cloud/storage');
var gcs = new Storage({
projectId: 'xxxxxxxxxxxxxxx',
keyFilename: 'xxxxxxxxk-y7fqf-38xxx5121.json'
});
exports.uploadFile = functions.https.onRequest((req, res) => {
cors(req, res, () => {
if (req.method !== "POST") {
res.status(500).json({
message: "Not allowed"
});
}
console.log(req.body)
const busboy = new Busboy({ headers: req.headers });
let uploadData = null;
busboy.on('file', function (fieldname, file, filename, encoding,
mimetype) {
const filepath = path.join(os.tmpdir(), filename);
uploadData = { file: filepath, type: mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish", () => {
const bucket = gcs.bucket("xxxxxxxxxxx.appspot.com");
// const bucket = admin.storage().bucket();
bucket
.upload(uploadData.file, {
uploadType: "media",
metadata: {
metadata: {
contentType: uploadData.type
}
}
})
.then(() => {
res.status(200).json({
message: "It worked!"
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
req.pipe(busboy)
});
});`

Resources