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
}
Related
I have a google cloud function that will send me an email when a document is added to the Cloud firestore.
Runtime envirment is: Nodejs 14
The function does work but in the logs I get a warning "Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail" I don't really understand this warning.
Do you know of any solution? I don't want to see this warning. What do I have to do(solution).
I saw some people used nodejs 8 and it worked but I don't want to use nodejs 8.
I am very new to the cloud stuff. I am talking weeks. Please don't make you answer complicated.
here is the code:
"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const nodemailer = require("nodemailer");
const FireStoreParser = require ("firestore-parser");
const { google } = require("googleapis");
admin.initializeApp();
exports.sendMail = functions.handler.firestore.document.onCreate(async(change,context) => {
const OAuth2 = google.auth.OAuth2;
const clientID = "you-dont-need-this";
const clientSecret = "you-dont-need-this";
const refreshToken = "you-dont-need-this"
const oauth2Client = new OAuth2(
clientID, //client Id
clientSecret, // Client Secret
"https://developers.google.com/oauthplayground" // Redirect URL
);
oauth2Client.setCredentials({
refresh_token: refreshToken
});
const accessToken = await oauth2Client.getAccessToken()
const smtpTransport = nodemailer.createTransport({
service: "gmail",
auth: {
type: "OAuth2",
user: "you-dont-need-this",
clientId: clientID,
clientSecret: clientSecret,
refreshToken: refreshToken,
accessToken: accessToken
}
});
const _fieldsProtoInJSON = FireStoreParser(change._fieldsProto);
const textToMail = JSON.stringify(_fieldsProtoInJSON);
var attachment = [
{ // binary buffer as an attachment
filename: 'dataContainer.json',
content: textToMail
}
];
const mailOptions = {
from: `<you-dont-need-this>`,
to: 'you-dont-need-this,
subject: `New message container ${_fieldsProtoInJSON.ContainerNumber} from ${_fieldsProtoInJSON.Tag}`,
text: `See attachment for data.`,
attachments: attachment
};
smtpTransport.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error.message);
smtpTransport.close();
}
return "mail sent";
});
});
this is the 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": "14"
},
"dependencies": {
"firebase-admin": "^8.12.1",
"firebase-functions": "^3.6.2",
"firestore-parser": "0.9.0",
"#google-cloud/storage": "^5.1.1",
"googleapis": "^51.0.0",
"nodemailer": "^6.4.8"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1"
},
"private": true
}
I fixed the issue by deploying the function using firebase cli. That way the variables are populated automatically.
check this link for an example: Firebase CLI reference
While trying to redeploy a function I now get this error message: Error parsing triggers: Cannot find module 'core-js / fn / reflect'.
Here's my package.json:
{
"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": "14"
},
"main": "index.js",
"dependencies": {
"#google-cloud/logging": "^9.1.0",
"#woocommerce/woocommerce-rest-api": "^1.0.1",
"algoliasearch": "^4.8.5",
"cors": "^2.8.5",
"csvtojson": "^2.0.10",
"express": "^4.17.1",
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.14.1",
"mkdirp": "^1.0.4",
"stripe": "^8.137.0"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
In index.js i use
const cors = require('cors')({origin: true});
....
exports.StripeEvents = functions.https.onRequest((req, res) => {
cors(req, res, () => {
//// some code that worked great
}
}
I do not use cors-js package at all...
Where does the problem comes from?
Thank you
depending the browser that you are using and the Javascript that you are using in some cases they do not support all the features required by Firebase so you need to at the Polyfills, in this documentation they show you the way to add the Polyfills to your app, the no recommended way to do it is with the core-js library, feel free to do it what you want.
I quick way to solve the error could be go to the directory where your functions live and execute:
solution install core-js#2.6.5
I've been trying callable functions to avoid handling cors manually but so far nothing is working
i've read similar issue Firebase Callable Function + CORS
the difference is the that dude has 'no access control allow origin' issue. Mine is response to preflight ... issue
I'd like to request for a guidance people. It's frustrating argh..
I'm on Blaze plan
So far i've been trying only to run the functions Locally. i have not deployed the function at all.
this is my function code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.createOrder = functions.https.onCall((data, context) => {
return new Promise((resolve, reject) => {
resolve(data)
.then(result => {
return result;
})
.catch(err => {
console.error(err.code);
throw new functions.https.HttpsError('unknown', err.message);
});
});
});
this is my client code
export const createOrder = order => {
functions
.httpsCallable('createOrder')({ data: order })
.then(result => {
console.log('result create order is', result);
return result;
});
};
functions package.json
{
"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": {
"#sendgrid/mail": "^6.4.0",
"axios": "^0.19.0",
"cors": "^2.8.5",
"firebase": "^6.3.1",
"firebase-admin": "^8.2.0",
"firebase-functions": "^3.1.0",
"firebase-functions-test": "^0.1.6"
},
"engines": {
"node": "8"
},
"private": true
}
firebase config.json
"firebase": {
"apiKey": "AIzaSy*****",
"authDomain": "jokii-test.firebaseapp.com",
"databaseURL": "https://jokii-test.firebaseio.com",
"projectId": "jokii-test",
"storageBucket": "jokii-test.appspot.com",
"messagingSenderId": "104544.....",
"appId": "1:10454485....."
}
Firebase SDK = "firebase": "^6.3.1",
The client SDK doesn't know how to access a function that hasn't been deployed. Notice in the error output that the URL it's trying to access is the one for your fully deployed function. It's currently not possible to have it override the URL to access one you're running locally on localhost.
If you want to invoke your callable function locally, you'll need to implement a client that follows the protocol specification for callable functions. And, as you can see, that's going to be a fair amount of work, because the client SDK is managing a lot of the HTTP protocol work for you.
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);
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