Firebase Cloud Function - Parsing error: Unexpected token => - node.js

I have a problem during deploy the functions into Cloud Function. I do believe before I put the const admin = require('firebase-admin') and admin.initializeApp() there will be a problem after I place these two, but before I place the two-line there is no problem occurred.
This is my full code for index.js
const functions = require("firebase-functions");
const express = require('express');
const cors = require('cors');
const admin = require('firebase-admin');
admin.initializeApp();
const app = express();
app.get('/', (req, res) => {
});
app.post("/", async (req, res) => {
const user = req.body;
await admin.firestore().collection("users").add(user);
res.status(201).send();
});
exports.user = functions.https.onRequest(app)
package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "12"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.11.0"
},
"devDependencies": {
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
.eslintrc.js
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
quotes: ["error", "double"],
},
};

Try adding the second part to your package.json:
{
"parserOptions": {
"ecmaVersion": 2017
}
}

"parser": "babel-eslint" - add this to your.eslintrc.js and run npm install babel-eslint --save this will resolve the issue.

Related

Firebase Deployment error, it seems facing problem when it run creating Node.js 16 function app (us-central1)

I am deploying express application to firebase Functions. But receiving error when it's doing functions: creating Node.js 16 function app (us-central1)...
Here are my ExpressJS sample under "Functions" folder. I not quite sure what is happening
const express = require('express')
const firebasefunctions = require('firebase-functions')
const cors = require('cors')
const dotenv = require('dotenv');
const fs = require('fs');
dotenv.config();
const app = express()
const port = process.env.DB_PORT
app.use(cors())
app.use(express.json())
app.use(express.urlencoded())
const knex = require('knex')({
client: 'pg',
connection: {
host : process.env.DB_HOST,
port : process.env.DB_DO_PORT,
user : process.env.DB_USERNAME,
password : process.env.DB_PASSWORD,
database : process.env.DB_DO,
ssl: {
ca: fs.readFileSync('./ca-certificate.crt').toString()
}
}
});
app.get('/data', (req, res) => {
knex.select().table('tablename')
.then(response => res.json(response))
.catch(console.log)
})
app.post('/update', (req, res) => {
console.log(req.body)
req.body.forEach(item => {
knex('tablename')
.where('number', '=', item)
.increment({
occurence: 1
})
.catch(console.log)
})
res.json("Success")
})
exports.app = firebasefunctions.https.onRequest(app)
And also the package.json under "Functions"
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"firebase-admin": "^10.0.2",
"firebase-functions": "^3.18.0"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
The error debug looks like this

Google cloud function with puppeteer does not work, even though it works in firebase functions emulator

So I made this function. It works correctly in firebase functions emulator, but when i use firebase deploy --only functions, I am getting errors like the ones on the picture. Any idea what I am doing wrong?
Here is my package.json
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions -P default",
"serve-dev": "npm run build && firebase serve --only functions -P staging",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions -P default",
"deploy-dev": "firebase deploy --only functions -P staging",
"logs": "firebase functions:log"
},
"main": "lib/index.js",
"dependencies": {
"#google-cloud/functions-framework": "^1.7.1",
"#types/node-fetch": "^2.3.3",
"firebase-admin": "^9.4.1",
"firebase-functions": "^3.11.0",
"golang": "^0.1.5-stable",
"node-fetch": "^2.5.0",
"puppeteer": "5.4.1",
"xml2js": "^0.4.19"
},
"devDependencies": {
"tslint": "^5.20.1",
"typescript": "^3.9.2"
},
"private": true,
"engines": {
"node": "10"
}
}
Here is the code of the function, it is in TypeScript, which after building becomes js ofc:
export const RecurringTradingUpdate = functions.https.onRequest(async (request, response) => {
const browser = await puppeteer.launch({
headless: true
});
const page = await browser.newPage();
await page.goto('website');
await page.waitFor(2000);
//await page.click('input[type=password]');
await page.click('#inputPassword');
await page.keyboard.sendCharacter('password')
//await page.click('button[type=submit]');
await page.click('#clickPassword');
await page.waitFor(2000);
//await page.click('button[type=submit]');
await page.click('#submit');
await page.waitFor(120000)
response.send("All done.")
});

TypeError: Cannot read property 'from' of undefined

I'm trying to code a function that triggers when a user gets a new comment and sends a notification.Comments are stored in /Users/{user_id}/Notifications/{notification_id}. Users save their device notification tokens to /users/{userID}
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotif = functions.firestore.document('Users/{user_id}/Notifications/{notification_id}')
.onWrite((change,context) =>
{
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
return admin.firestore().collection('Users').document(user_id).collection('Notifications').document(notification_id).get().then(queryResult=>{
const from_user_id = queryResult.data().From;
const from_data = admin.firestore().collection('Users').document(from_user_id).get();
const to_data = admin.firestore().collection('Users').document(user_id).get();
return Promise.all([from_data, to_data]).then(result => {
const from_name = result[0].data().From;
const to_name = result[1].data().From;
console.log("FROM: " + from_name + "TO: " + to_name);
});
});
});
And here's the package.json file. Everything is up-to-date
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"firebase-admin": "^6.4.0",
"firebase-functions": "^2.1.0"
},
"private": true
}
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"firebase-admin": "^6.4.0",
"firebase-functions": "^2.1.0"
},
"private": true
}
Firebase gives the following error:
TypeError: Cannot read property 'from' of undefined
at Promise.all.then.result (/user_code/index.js:21:47)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Please check the length of your array (result). You should log result.
return Promise.all([from_data, to_data]).then(result => {
console.log(result);
const from_name = result[0].data().From;
const to_name = result[1].data().From;
console.log("FROM: " + from_name + "TO: " + to_name);
});

Using a Firestore Cloud Functions

I have this problem. In my code depends of choosen project name I want to retrieve a document from another collection. I am use
exports.updateUser = functions.firestore
.document('Users/{userId}')
.onUpdate((change, context) => {
const newValue = change.after.data().currentProject;
console.log("Project changed to - " + newValue);
const previousValue = change.before.data().currentProject;
console.log("from - " + previousValue);
// ### FROM HERE DOES NOT WORK ###
const projectId = firestore.collection('Projects')
.where('name', '==', newValue).get()
.then(doc => {
console.log(doc.data().id);
return doc.data().id;
});
});
And I get an error
ReferenceError: firestore is not defined
at exports.updateUser.functions.firestore.document.onUpdate (/user_code/index.js:25:14)
So maybe I need another dependencies ?
My package.json is
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"firebase-admin": "~5.12.0",
"firebase-functions": "^1.0.1"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.6.0"
},
"private": true
}
What I am missing? Please give a hint
You will need to use the Firebase Admin SDK to access Firestore collections that are outside of the scope that your function was triggered on. Typically this will look something like:
admin.firestore().collection('Projects')...

Firebase functions cannot deploy : SyntaxError: Unexpected token function

I am trying to deploy a function to firebase and I get an error during deployment
Error: Functions did not deploy properly.
Could it be linked with the async function ?
Actual behavior
Functions get deployed with errors, the cli shows me the following message:
================ console log ================
> eslint .
✔ functions: Finished running predeploy script.
i functions: ensuring necessary APIs are enabled...
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (56.39 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating function sendContactEmailOAuth...
⚠ functions[sendContactEmailOAuth]: Deployment error.
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:13
async function getJwt() {
^^^^^^^^
================ functions index.js file ================
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const { JWT } = require('google-auth-library/build/src/index');
exports.sendContactEmailOAuth = functions.https.onRequest((req, res) => {
const sender_msg = 'just a test'
const email = 'contact#lechorodescharentes.org'
async function getJwt() {
const client = new JWT(
functions.config().service_key.client_email,
null,
functions.config().service_key.private_key,
['https://www.googleapis.com/auth/cloud-platform', 'https://mail.google.com'],
);
await client.authorize();
const url = `https://www.googleapis.com/dns/v1/projects/${functions.config().service_key.project_id}`;
const res = await client.request({ url });
console.log(res.data);
}
getJwt();
/* send email with nodemailer to be inserted here */
});
================ package.json file ================
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"firebase-admin": "~5.12.0",
"firebase-functions": "^1.0.2",
"firebase-tools": "^3.18.4",
"google-auth-library": "^1.4.0",
"nodemailer": "^4.6.4"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.6.0"
},
"private": true
}
As of September 2019:
Update firebase-admin : npm install --save firebase-admin
Update firebase-functions : npm install --save firebase-functions
Add "engines": { "node": "10" } to your /functions/package.json
...
"dependencies": {
"firebase-admin": "^8.5.0",
"firebase-functions": "^3.2.0"
},
"devDependencies": {
"tslint": "~5.19.0",
"typescript": "~3.6.2"
},
"engines": {
"node": "10"
}
...
As of August 2018:
Cloud Functions now support Node 8 (8.11.1). Check out this blog post.
Upgrade to Node 8
As suggested in this blog post, follow these steps to upgrade to Node 8:
Upgrade your firebase-functions version via npm install --save firebase-functions#latest
Upgrade firebase-tools via npm update -g firebase-tools
Add "engines": { "node": "8" } to your /functions/package.json
If you are still having the issue on a recent version (such as node 12), use the ecmaVersion parser option in your .eslintrc.js file.
Here's a sample:
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
parserOptions: {
ecmaVersion: 8,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
quotes: ["error", "double"],
},
};
h/t to Dean for the original suggestion.

Resources