I'm following the example from the github repository to short a link url
https://github.com/firebase/functions-samples/tree/Node-8/url-shortener
The error is giving is the following
12:49:56.472 a. m. shortenUrl Function execution took 509 ms, finished
with status: 'error' 12:49:56.464 a. m. shortenUrl RequestError:
Error: getaddrinfo EAI_AGAIN api-ssl.bitly.com:443
at new RequestError (/srv/node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (/srv/node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (/srv/node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (/srv/node_modules/request/request.js:185:22)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at Request.onRequestError (/srv/node_modules/request/request.js:881:8)
at emitOne (events.js:116:13)
at ClientRequest.emit (events.js:211:7)
at TLSSocket.socketErrorListener (_http_client.js:387:9)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
I'm really new at functions but I did follow all the steps from the documentation there.
here is my index.js inside my functions folder
const functions = require('firebase-functions');
const BitlyClient = require('bitly');
// TODO: Make sure to set the bitly.access_token cloud functions config using the CLI.
const bitly = BitlyClient(functions.config().bitly.access_token);
// Shorten URL written to /links/{linkID}.
exports.shortenUrl = functions.database.ref('/links/{linkID}').onCreate(async (snap) => {
const originalUrl = snap.val();
const response = await bitly.shorten(originalUrl);
return snap.ref.set({
original: originalUrl,
short: response.data.url,
})
});
and my package.json in order to compile the the neccesary for bitly
{
"name": "url-shortener-functions",
"description": "URL Shortener Firebase Functions sample",
"dependencies": {
"bitly": "^5.1.7",
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.0.5"
},
"devDependencies": {
"eslint": "^4.13.1",
"eslint-plugin-promise": "^3.6.0"
},
"scripts": {
"lint": "./node_modules/.bin/eslint --max-warnings=0 .",
"serve": "firebase serve --only functions",
"shell": "firebase experimental:functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"private": true
}
I also did npm -install bitly inside my functions folder but still throwing that error
Also I added my link inside my database as the documentation states
/functions-project-12345
/links
link-123456: "https://my.super.long-link.com/api/user/profile/-jEHitne10395-k3593085"
Any clue ? thanks
it complains, that it cannot resolve for the remote host:
RequestError: Error: getaddrinfo EAI_AGAIN api-ssl.bitly.com:443
therefore I'd assume, that a paid plan is required, in order to perform this external API call.
Related
This question already has answers here:
Error Deploying Firestore Function with a space in the name of a collection
(2 answers)
Closed 2 years ago.
I have been trying to deploy my firebase function called onFollowUser however, it has been constantly failing to launch. I have the Blaze plan currently and this is the error message:
⚠ functions[onFollowUser(us-central1)]: Deployment error.
Failed to configure trigger providers/cloud.firestore/eventTypes/document.create#firestore.googleapis.com (__gcf__.us-central1.onFollowUser)
Functions deploy had errors with the following functions:
onFollowUser
To try redeploying those functions, run:
firebase deploy --only functions:onFollowUser
To continue deploying other features (such as database), run:
firebase deploy --except functions
Error: Functions did not deploy properly.
Here is my complete index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.onFollowUser =
functions
.firestore
.document('/Followers/{userID}/User Follower/{followerID}')
.onCreate(async (snapshot, context) => {
console.log(snapshot.data());
});
I have spotted the error... My database is located in Europe-central, however, for some reason, it is deploying to US-central... How can I change this? The ID of my project which it says it is deploying to is correct.
Here is my 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": "10"
},
"dependencies": {
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
Edit: Even though I get this failing message, I can see the function on my console :
This is a know issue, see: Error Deploying Firestore Function with a space in the name of a collection
Rename the a collections so that they do not includes spaces, rather use camel case, dashes or underscores.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
admin.firestore().settings({ timestampsInSnapshots: true });
exports.onFollowUser =
functions
.firestore
.document('/Followers/{userID}/User-Follower/{followerID}')
.onCreate(async (snapshot, context) => {
console.log(snapshot.data());
return;
});
I've got a problem with the firebase functions. I need to call an external API and because of that I am using the request package. Which was never a problem with other projects. I am now running into a case where I am able to deploy my function if I only call
request(options).
But I am not able to deploy the function if I add a callback like:
request(options, function (err, res, body) {})
I do not get a very helpfull log. All I see in the debug log is this:
10 silly lifecycle functions#~lint: Args: [ '/d /s /c', 'tslint --project tsconfig.json' ]
11 silly lifecycle functions#~lint: Returned: code: 2 signal: null
12 info lifecycle functions#~lint: Failed to exec lint script
13 verbose stack Error: functions# lint: `tslint --project tsconfig.json`
13 verbose stack Exit status 2
13 verbose stack at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack at EventEmitter.emit (events.js:189:13)
13 verbose stack at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:189:13)
13 verbose stack at maybeClose (internal/child_process.js:970:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid functions#
If its interesting my package.json is this:
{
"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": {
"#google-cloud/firestore": "^3.5.0",
"buffer": "^5.6.0",
"cors": "^2.8.5",
"dateformat": "^3.0.3",
"firebase-admin": "^8.12.1",
"firebase-functions": "^3.6.1",
"request": "^2.83.0"
},
"devDependencies": {
"tslint": "^5.12.0",
"typescript": "^3.2.2"
},
"private": true
}
I really can't find a reason why the callback would prevent the deployment.
I would greatly appreciate any form of help. Thanks!
Update:
My function does not really do much
exports.testApi = functions.https.onRequest((req, res) => {
var body = {
'key': 'val'
}
var options = {
uri: 'https://google.com',
method: 'POST',
body: body
}
// This works:
request(options);
//This can not be deployed
request(options, function(err, res, body) {
console.log(body);
});
});
Im currently working with Google Cloud Functions and Firestore. But i run into problems when trying to get data from a parent document. I have searched the issue on the internet, but it seems that no of the fixes suggested works for me.
The following is what i get in the terminal when i try to deploy.
/Users/macmini1/Documents/resould-firebase/functions/index.js
24:1 error Parsing error: 'import' and 'export' may appear only with 'sourceType: module'
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/macmini1/.npm/_logs/2019-11-22T12_20_27_403Z-debug.log
So far i have concluded that it has something to do with "firebase-admin" i have required.
I have tried to update everything, and different ways to execute the same objective.
But nothing seems to works.
Here is my code.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
exports.createBid = functions.firestore.document('auctions/{auctionId}/bids/{bidId}').onCreate(async (snap, context) => {
const bid = snap.ref;
const auction = await getAuction(auctionId);
return bid.set({
test: auction.end_date
}, {merge: true}).then(() => {
console.log("Count is created! " + bidId);
return null;
}).catch((error) => {
console.error("Counter Error writing document: ", error);
return null;
});
});
export async getAuction(auctionId) {
if (!auctionId) return Promise.reject('no userId');
const auctionSnap = await db.collection('auctions').doc(auctionId).get();
return auctionSnap.data();
}
And here 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"
},
"engines": {
"node": "8"
},
"dependencies": {
"firebase-admin": "^8.8.0",
"firebase-functions": "^3.3.0"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.1.6"
},
"private": true
}
And my .eslintrc.json has ecmaVersion 2017
Hope there is somebody out there who can point out what i am doing wrong :-)
I have face the same issue
I have tried this and it worked for me.
parserOptions: {
ecmaVersion: 11,
sourceType: "module",
},
Check spaces properly Between {} and key value
.
Try adding this to your .eslintrc.js or .eslintrc.cjs file:
parserOptions: {
ecmaVersion: "latest",
ecmaVersion: 11,
sourceType: "module"
},
I have defined the following function in my index.ts file:
export const stripeCharge = functions.region('europe-west1').database
.ref('/payments/{userId}/{paymentId}')
.onWrite(async (change, context) => {
...
});
I want to debug this function, so I am trying to use the Google Cloud Functions Emulator (npm install -g #google-cloud/functions-emulator).
First i run:
functions start
to start the emulator.
Then I want to deploy the function:
functions deploy --trigger-http --timeout 600s stripeCharge
This results in the following errors:
ERROR: Function load error: Code could not be loaded.
ERROR: Does the file exists? Is there a syntax error in your code?
ERROR: Detailed stack trace: Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail
C:\Users\Jesper\intergun\functions\lib\index.js:14
const stripe = new Stripe(functions.config().stripe.testkey);
^
TypeError: Cannot read property 'testkey' of undefined
at Object.<anonymous> (C:\Users\Jesper\intergun\functions\lib\index.js:14:52)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at [eval]:1:40
at ContextifyScript.Script.runInThisContext (vm.js:50:33)
ERROR: Error: Failed to deploy function.
at exec (C:\Users\Jesper\AppData\Roaming\nvm\v8.16.0\node_modules\#google-cloud\functions-emulator\src\cli\controller.js:126:22)
at ChildProcess.exithandler (child_process.js:288:5)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at maybeClose (internal/child_process.js:915:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
So i think the problem is that it cannot find FIREBASE_CONFIG and GCLOUD_PROJECT, which I don't understand since they should be automatically populated according to this: https://firebase.google.com/docs/functions/config-env
This is at the top of my index.ts file:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import 'firebase-functions';
import * as Stripe from 'stripe';
admin.initializeApp();
const stripe = new Stripe(functions.config().stripe.testkey);
I also have a .runtimeconfig.json file which contains the following:
{
"stripe": {
"testkey": "..."
}
}
Finally, 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"
},
"engines": {
"node": "8"
},
"main": "lib/index.js",
"dependencies": {
"#google-cloud/storage": "^2.5.0",
"firebase-admin": "^8.1.0",
"firebase-functions": "^3.0.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
}
How can I fix this?
You use the emulators provided by the Firebase CLI in order to test functions written using the Firebase SDKs. The Cloud emulator (#google-cloud/functions-emulator) will not work.
Unfortunately, you're writing a Realtime Database function, which is currently not supported by the emulator.
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 :(