I have deployed the following firebase function:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
// other functions
exports.createProfileDocument = functions.auth.user().onCreate(async user => {
await admin.firestore().collection('profiles').doc(user.uid).set({
userName: user.displayName
})
});
This was working but recently stopped, when a new user account was created the function would simply not fire (nothing in the logs, no errors, no activity, etc.). I updated my dependencies to the following:
"dependencies": {
"firebase-admin": "^8.0.0",
"firebase-functions": "^2.3.1",
"firebase-tools": "^6.11.0"
},
The function is now firing when I would expect but fails with the following error:
/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/build/src/index.js:740
async initializeIfNeeded() {
^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at FirebaseNamespace.get [as firestore] (/user_code/node_modules/firebase-admin/lib/firebase-namespace.js:329:29)
Any ideas?
It looks as though this was failing due to the async keyword before initializeIfNeeded() as this is not available in node 6. I was able to resolve the issue by adding
"engines": { "node": "8" }
To my package.json
You need to update your node to version 8.x, which allows async hooks.
Upgrade: How to update nodejs from 6.x to 8.x?
Related
Yesterday Night I deployed my functions and the deployment was successfull without any errors.
But when i tried to execute/call the function it throwed following error and logged in firebase console :
{ Error: Failed to import the Cloud Storage client library for Node.js. Make sure to install the "#google-cloud/storage" npm package. Original error: SyntaxError: Unexpected token {
at new FirebaseError (/srv/node_modules/firebase-admin/lib/utils/error.js:43:28)
at new Storage (/srv/node_modules/firebase-admin/lib/storage/storage.js:65:19)
at /srv/node_modules/firebase-admin/lib/firebase-app.js:255:20
at FirebaseApp.ensureService_ (/srv/node_modules/firebase-admin/lib/firebase-app.js:376:23)
at FirebaseApp.storage (/srv/node_modules/firebase-admin/lib/firebase-app.js:253:21)
at FirebaseNamespace.fn (/srv/node_modules/firebase-admin/lib/firebase-namespace.js:292:45)
at Object.exports.processCard (/srv/Files/process.js:157:24)
at Busboy.bus.on (/srv/index.js:44:13)
at emitNone (events.js:106:13)
at Busboy.emit (events.js:208:7)
errorInfo:
{ code: 'storage/missing-dependencies',
message: 'Failed to import the Cloud Storage client library for Node.js. Make sure to install the "#google-cloud/storage" npm package. Original error: SyntaxError: Unexpected token {' } }
after that i tried on more time ,to check if the error has gone, but then it throwed following:
Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.
at FirebaseAppError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:43:28)
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:89:28)
at new FirebaseAppError (/srv/node_modules/firebase-admin/lib/utils/error.js:124:28)
at FirebaseNamespaceInternals.initializeApp (/srv/node_modules/firebase-admin/lib/firebase-namespace.js:68:23)
at FirebaseNamespace.initializeApp (/srv/node_modules/firebase-admin/lib/firebase-namespace.js:423:30)
at Object.exports.processCard (/srv/Files/process.js:140:15)
at Busboy.bus.on (/srv/index.js:44:13)
at emitNone (events.js:106:13)
at Busboy.emit (events.js:208:7)
at Busboy.emit (/srv/node_modules/busboy/lib/main.js:37:33)
errorInfo:
{ code: 'app/duplicate-app',
message: 'The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.' },
codePrefix: 'app' }
I executed the function locally and everything was good function executed without any errors.
The weired part is that i never actully used google-storage library i use firebase-admin sdk to generate a signedURL and this is the function of generation of singedURL:
admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "urlToDatabase"
});
function getSignedUrl(file) {
console.time('URLGenerated ');
let options = { action: 'read', expires: Date.now() + 5 * 60 * 1000 }; // 5min Expiration Time
let bucketFileName = path.basename(file);
return bucket.upload(file, { destination: `public/${bucketFileName}`})
.then(() => {
return bucket.file(`public/${bucketFileName}`).getSignedUrl(options)
.then((urls) => {
fs.unlinkSync(file);
console.timeEnd('URLGenerated ');
return urls[0];
})
.catch((e) => {
console.log('Link Generation Error' + e);
});
}).catch((e) => console.log(e));
}
In the second error it says that i've initialized admin twice but i don't think i've done that. I double checked evything and also tried emulator as i mentioned before.
and this is 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": "8"
},
"main": "index.js",
"dependencies": {
"#google-cloud/storage": "^5.3.0",
"busboy": "^0.3.1",
"docx": "^5.3.0",
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.11.0",
"gs4fb": "^1.1.0"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
It is 20 Hours now and my function is down. The functions is heart of my website.
Where is the problem ?
I've updated to latest version of firebase-admin, firebase-functions library and firebaseCLI not because i needed just because it was warning me everytime.
Latest version of firebase-Admin was causing the error. Rolled back to 8.13 and everything was on track.
Seriously Never Update to latest if NOT REQUIRED.
I am trying to use Realm imported with NPM but it fails.
I am using the Realm example for JavaScript:
const Realm = require('realm');
// Define your models and their properties
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
birthday: 'date',
cars: 'Car[]',
picture: 'data?' // optional property
}
};
Realm.open({schema: [CarSchema, PersonSchema]})
.then(realm => {
// Create Realm objects and write to local storage
realm.write(() => {
const myCar = realm.create('Car', {
make: 'Honda',
model: 'Civic',
miles: 1000,
});
myCar.miles += 20; // Update a property value
});
// Query Realm for all cars with a high mileage
const cars = realm.objects('Car').filtered('miles > 1000');
// Will return a Results object with our 1 car
cars.length // => 1
// Add another car
realm.write(() => {
const myCar = realm.create('Car', {
make: 'Ford',
model: 'Focus',
miles: 2000,
});
});
// Query results are updated in realtime
cars.length // => 2
})
.catch(error => {
console.log(error);
});
And this is the error it throws:
Uncaught Error: Cannot find module
'[path]/node_modules/realm/compiled/electron-v2.0_darwin_x64/realm.node'
at Module._resolveFilename (module.js:543:15)
at Function.Module._resolveFilename ([path]/node_modules/electron/dist/Electron.app/Contents/Resources/electron.asar/common/reset-search-paths.js:35:12)
at Function.Module._load (module.js:473:25)
at Module.require (module.js:586:17)
at require (internal/module.js:11:18)
at Object. ([path]/node_modules/realm/lib/index.js:102:28)
at Object. ([path]/node_modules/realm/lib/index.js:133:3)
at Module._compile (module.js:642:30)
at Object.Module._extensions..js (module.js:653:10)
at Module.load (module.js:561:32)
Thank you so much for help.
Welcome to SO!
What happens is that electron specifies its own environment, while realm runtime loads its binaries based on this currently running environment.
However, when installing realm with npm, we fetch the binaries corresponding to the environment at the time of install, i.e. our node engine.
Therefore when running electron in dev mode, realm does not find the binary corresponding to the electron environment.
The usual workaround is to use the electron-builder package and run its install-app-deps command, which will install the appropriate binaries for the electron target environment.
It is usually recommended to make it an automatic script in your package.json file:
To ensure your native dependencies are always matched electron version, simply add script :
"scripts": {
"postinstall": "electron-builder install-app-deps"
}
…so that it get run whenever you install a new package.
I have a function in Firebase Functions service that send any FCM.
I would to use admin.messaging().send() function, like this reference guide, but I got this error while function is triggered, not during deploy:
TypeError: admin.messaging(...).send is not a function
at exports.sendChatNotification.functions.database.ref.onCreate.event (/user_code/lib/index.js:113:30)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59: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:53:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
I can see this error in Functions->Log inside Firebase console.
That's my function code:
exports.sendChatNotification = functions.database.ref('/messages').onCreate(event => {
var message = {
data: {
title: 'title',
body: 'body',
},
apns: {
header: {
'apns-priority': '10',
'apns-expiration':'0'
},
payload: {
aps: {
sound: 'default',
'content-available':'1'
}
}
},
android: {
ttl: 60*1000,
priority: 'high'
},
topic: 'mytopic'
};
return admin.messaging().send(message);
});
If I use admin.messaging().sendToTopic() and (changing the message structure) it works fine. It seems Firebase doesn't support its own API.
I deploy this using Firebase tools, with command line "firebase deploy".
I have updated firebase-tools and firebase-functions and firebase-admin in my functions project.
The send() function was added in firebase-admin 5.9.0. If you want to use it, you should run npm install firebase-admin#latest in your functions folder to install the latest version. At the time of this writing, the latest version is 5.9.1.
I'm trying to use sendgrid npm package in Meteor (on the server):
const sendgridMail = require('#sendgrid/mail');
Keep getting this error:
(STDERR) packages\modules.js:961
(STDERR) const {
(STDERR) ^
(STDERR)
(STDERR) SyntaxError: Unexpected token {
(STDERR) at Object.exports.runInThisContext (vm.js:53:16)
(STDERR) at D:\myProject\.meteor\local\build\programs\server\boot.js:331:30
(STDERR) at Array.forEach (native)
(STDERR) at Function._.each._.forEach (C:\Users\user1\AppData\Local\.meteor\packages\meteor-tool\1.5.2\mt-os.windows.x86_32\dev_bundle\server-lib\node_modules\underscore\underscore.js:79:11)
Any ideas how to fix it?
Update: package.json includes the following dependencies:
"dependencies": {
"#sendgrid/client": "^6.1.4",
"#sendgrid/mail": "^6.1.4",
"babel-runtime": "^6.20.0",
"bcrypt": "^1.0.2",
"body-parser": "^1.17.2",
"card": "^2.3.0",
"google-auth-library": "^0.10.0",
"googleapis": "^21.3.0",
"meteor-node-stubs": "~0.2.4",
"moment": "^2.18.1",
"pnotify": "^3.2.0",
"shortid": "^2.2.8",
"simpl-schema": "^0.3.1",
"stripe": "^4.24.0"
}
I use it like this, and find it works fine.
import sendgridModule from 'sendgrid';
let SEND_GRID_API_KEY = '';
try {
SEND_GRID_API_KEY = Meteor.settings.env.SEND_GRID_API_KEY;
} catch (e) {
// no-op
}
const sendgrid = sendgridModule(SEND_GRID_API_KEY);
I think using import instead of require is preferred, and it now can be used for conditional imports
The problem is that SendGrid SDK v6 requires Node.js version 6 and higher, but the one bundled in Meteor is 4.8.4:
$ meteor node --version
v4.8.4
As stated in this issue, updating Node.js will help, but it's obviously can't be done with Meteor.
I suggest you to use sendgrid npm package, this one works fine with Node.js v4.
I'm trying bookshelf-modelbase and getting a SyntaxError while running the server:
//model.js
var knex = require('knex')(require('../knexfile').development);
var bookshelf = require('bookshelf')(knex);
var ModelBase = require('bookshelf-modelbase')(bookshelf);
//...
And the error:
/node_modules/bookshelf-modelbase/lib/index.js:77
return this.findOne({ [this.prototype.idAttribute]: id }, options)
^
SyntaxError: Unexpected token [
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
Has anyone ever had this error?
You should try Node.js v4 and higher.
try this:
var param = {}
param[this.prototype.idAttribute]=id
return this.findOne(param, options)