google cloud function error when defining simple function - firebase

Hi there I'm trying to deploy a simple function using firebase hosting and the following error arises in my firebase log when I do:
TypeError: Cannot set property 'content-type' of undefined
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:365:22)
at ServerResponse.header (/user_code/node_modules/express/lib/response.js:767:10)
at ServerResponse.contentType (/user_code/node_modules/express/lib/response.js:595:15)
at ServerResponse.send (/user_code/node_modules/express/lib/response.js:145:14)
at app.get (/user_code/lib/index.js:10:22)
at Layer.handle [as handle_request] (/user_code/node_modules/express/lib/router/layer.js:95:5)
at next (/user_code/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/user_code/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/user_code/node_modules/express/lib/router/layer.js:95:5)
at /user_code/node_modules/express/lib/router/index.js:281:22
Seeing as I've just started with firebase hosting, I have no idea what could be causing this; here are my files:
src > index.ts:
import * as functions from 'firebase-functions';
import * as express from 'express';
// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
const app = express();
export const getTime = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
firebase.json:
{
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites":[{
"source": "/timestamp",
"function": "getTime"
}]
},
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint",
"npm --prefix \"$RESOURCE_DIR\" run build"
]
}
}
package.json:
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"main": "lib/index.js",
"dependencies": {
"express": "^4.16.4",
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.1.0"
},
"devDependencies": {
"tslint": "^5.12.0",
"typescript": "^3.2.2"
},
"private": true
}

As you could see here, your index.ts should be :
import * as functions from 'firebase-functions';
import * as express from 'express';
// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
const app = express();
app.get("*", (request, response) => {
response.send("Hello from Firebase!");
});
export const getTime = functions.https.onRequest(app);

Related

#google-cloud/logging causing Error: Could not load the default credential

I am getting this error when trying to use #google-cloud/logging with Firebase Functions. If I remove the logging stuff everything works fine. I also tried using #google-cloud/logging-winston however, causing the same error along with an additional error.
Here is my code:
const functions = require('firebase-functions')
const mongoose = require('mongoose')
const Tag = require('../../models/tag')
const { Logging } = require('#google-cloud/logging')
const logging = new Logging({projectId: 'circle-fc687'})
const log = logging.log('tags')
const METADATA = {
resource: {
type: 'cloud_function',
labels: {
function_name: 'tags-getTags',
region: 'us-central1'
}
}
}
const uri = 'mongoURL'
module.exports = functions.https.onRequest(async (req, res) => {
try {
console.log('getTags : start')
const logOne = log.entry(METADATA, { event: 'getTags:mongodb:started', value: 'started', message: 'tags-getTags:started' })
log.write(logOne) // I've also tried with an await here thinking maybe it was trying to do something after the function terminates but that didn't fix anything
console.log('getTags : after first logging statement') // doesn't work
await mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
const result = await Tag.find({})
res.send(result)
} catch (err) {
res.send(err)
}
})
Here is the error:
Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
Edit 1: adding package.json
{
"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"
},
"engines": {
"node": "10"
},
"dependencies": {
"#google-cloud/logging": "^6.0.0",
"#google-cloud/logging-winston": "^3.0.2",
"axios": "^0.19.0",
"cors": "^2.8.5",
"firebase-admin": "^8.9.0",
"firebase-functions": "^3.3.0",
"mongoose": "^5.8.3",
"mongoose-unique-validator": "^2.0.3",
"winston": "^3.2.1"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.1.7"
},
"private": true
}

Debug firebase functions locally in VSCode with latest version of firebase and node v10 [duplicate]

This question already has answers here:
Functions debugging in VS Code
(6 answers)
Closed 2 years ago.
There seem to be many examples for #google-cloud/functions-emulator on the web but this has become deprecated now. I went through latest firebase docs Test functions interactively where we can test the functions locally using shell.
I tried debugging in VSCode but whenever I hit the debugger button, VSCode gives me this warning and then halt debugging immediately:
C:\Program Files\nodejs\node.exe --inspect-brk=46655 functions\lib\index.js
Debugger listening on ws://127.0.0.1:46655/c8545176-06c0-4b95-80ec-bcba4ca9d90e
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail
setup.js:53
I also initialized the admin object in ts/js code but debugger gave the same issue:
const admin = require("firebase-admin");
if (!admin.apps.length)
admin.initializeApp({
projectId: "...",
appId: "...",
databaseURL: "...",
storageBucket: "...",
apiKey: "...",
authDomain: "...",
messagingSenderId: "...",
measurementId: "..."
});
VSCode launch.json
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": ["<node_internals>/**"],
"program": "${file}",
"outFiles": ["${workspaceFolder}/**/*.js"]
}
]
firebase functions package.json
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "10"
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "^8.6.0",
"firebase-functions": "^3.3.0"
},
"devDependencies": {
"firebase-functions-test": "^0.1.6",
"tslint": "^5.20.1",
"typescript": "^3.7.2"
},
"private": true
}
firebase.json:
{
"hosting": {
"public": "_site",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint",
"npm --prefix \"$RESOURCE_DIR\" run build"
]
},
"rewrites": [
{
"source": "/bigben",
"function": "bigben"
},
{
"source": "**",
"destination": "/index.html"
}
],
"cleanUrls": true
}
}
Platform: Windows 10
Node: v10
Project: Firebase web app with Typescript functions
firebase: 7.8.1.
I wonder if it's all possible to put breakpoints and run the debugger in VSCode for latest firebase functions.
It's not currently supported by the emulators in the Firebase CLI, but the feature is being worked on. You can read about it here:
https://github.com/firebase/firebase-tools/issues/1360

firebase functions:shell onWrite property undefined

I am trying to test my cloud functions locally. I am using the command firebase functions:shell which starts the emulator successfully. I have the following cloud function in my index.ts:
export const stripeCharge = functions.region('europe-west1').database
.ref('/payments/{userId}/{paymentId}')
.onWrite(async (change, context) => {
someCode;
});
I read that you should invoke an onWrite firestore function the following way (https://firebase.google.com/docs/functions/local-shell):
stripeCharge({before: "oldData", after: "newData"})
However, this results in the following error:
'Successfully invoked function.'
firebase > ! TypeError: Cannot read property 'eventType' of undefined
at cloudFunction (C:\Users\Jesper\intergun\functions\node_modules\firebase-functions\lib\cloud-functions.js:80:40)
at Run (C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:458:20)
at C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:442:19
at Generator.next (<anonymous>)
at C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:7:71
at new Promise (<anonymous>)
at __awaiter (C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:3:12)
at Run (C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:435:12)
at C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:457:15
at Generator.next (<anonymous>)
! Your function was killed because it raised an unhandled error.
The error happens in some other file and I'm not sure why. What am I missing?
Edit: My package.json:
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"main": "lib/index.js",
"dependencies": {
"#google-cloud/storage": "^2.5.0",
"#types/fs-extra": "^7.0.0",
"firebase-admin": "^8.1.0",
"firebase-functions": "^3.0.1",
"fs-extra": "^8.0.1",
"mailgun-js": "^0.22.0",
"sharp": "^0.22.1",
"stripe": "^7.1.0"
},
"devDependencies": {
"#types/sharp": "^0.22.2",
"#types/stripe": "^6.30.0",
"firebase-functions-test": "^0.1.6",
"tslint": "^5.12.0",
"typescript": "^3.2.2"
},
"private": true
}
After replicating this I've found this thread it looks there is an open case for this issue.
The similar setup works fine for Firestore, but the issue seems to to be with the RTDB, I assume we have to wait until they solve it, sorry :(

Function execution took 60027 ms, finished with status: 'timeout'

I have looked at several other timeout posts but nothing seems to help. I have a very basic setup going on here using a brand new functions project. In my logs I constantly see 'timeout'
Any ideas??
Here is the code
import * as functions from 'firebase-functions';
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');
exports.app = functions.https.onRequest(app);
app.use(cors({ origin: true }));
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(cors);
app.get('/hello', (req, res) => {
res.status(200).send("Mateo");
});
Here is my package.json
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"main": "lib/index.js",
"dependencies": {
"body-parser": "^1.18.3",
"cors": "^2.8.5",
"express": "^4.16.4",
"firebase-admin": "^6.0.0",
"firebase-functions": "^2.1.0"
},
"devDependencies": {
"tslint": "~5.8.0",
"typescript": "~2.8.3"
},
"private": true
}
Here is how I execute my function
https://us-central1-anxietybox-6177e.cloudfunctions.net/app/hello
Heres a screenshot of logs
UPDATE
After making the changes suggested below I am still not having any luck. I'm not sure how much more bare bones it can get than this..
import * as functions from 'firebase-functions';
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const app = express();
app.get('/hello', (req, res) => {
res.status(200).send("Mateo");
});
exports.app = functions.https.onRequest(app);

connexion to infura fail with web3 in firebase cloud functions

I have an issue with Firebase cloud function. The connexion to infura fails when my function is called. I have upgraded to Blaze plan as mention here, but it didn't change.
Here is my code:
const Web3 = require('web3')
exports.getInstructorOnBlock = functions.database.ref('/services/{serviceId}').onUpdate((snapshot, context) => {
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/MyKey"));
}
var abi = [{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"instructorAccts","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"fName","type":"string"},{"indexed":false,"name":"lName","type":"string"},{"indexed":false,"name":"age","type":"uint256"}],"name":"instructorInfo","type":"event"},{"constant":false,"inputs":[{"name":"_address","type":"address"},{"name":"_age","type":"uint256"},{"name":"_fName","type":"string"},{"name":"_lName","type":"string"}],"name":"setInstructor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getInstructors","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_address","type":"address"}],"name":"getInstructor","outputs":[{"name":"","type":"uint256"},{"name":"","type":"string"},{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"countInstructors","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}];
var address = "address of the contract";
var MyContract = web3.eth.contract(abi);
var SmartContract = MyContract.at(address);
web3.eth.defaultAccount = web3.eth.accounts[0];
SmartContract.getInstructor(web3.eth.defaultAccount,"address", (err, res) => {
console.log("+++ res +++ " + res);
if (err) {
console.log("getInstructor fail" + err);
}
});
return 0
});
I've also tried to reinstall npm package. This is my package.json
{
"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": {
"ansicolor": "^1.1.72",
"axios": "^0.18.0",
"dotenv": "^6.0.0",
"eth": "^4.0.1",
"ethereumjs-tx": "^1.3.6",
"ethereumjs-util": "^5.2.0",
"express": "^4.16.3",
"firebase-admin": "^5.12.1",
"firebase-functions": "^1.0.4",
"npm": "^6.1.0",
"ololog": "^1.1.103",
"personal": "^1.0.1",
"web3": "github:ethereum/web3.js"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.8.0"
},
"private": true
}
and the error returned by firebase:
Error: CONNECTION ERROR: Couldn't connect to node https://rinkeby.infura.io/key.
at Object.InvalidConnection (/user_code/node_modules/web3/lib/web3/errors.js:31:16)
at HttpProvider.send (/user_code/node_modules/web3/lib/web3/httpprovider.js:93:18)
at RequestManager.send (/user_code/node_modules/web3/lib/web3/requestmanager.js:58:32)
at Eth.get [as accounts] (/user_code/node_modules/web3/lib/web3/property.js:107:62)
at exports.getInstructorOnBlock.functions.database.ref.onUpdate (/user_code/index.js:112:39)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36
Does anyone have an idea of my problem?
Note that I can access to my smart contract "getInstructor" function through the same infura/rinkeby on a html page
Thanks

Resources