I've been trying to send push notification via Cloud Functions.
This is the guide on how to do it from Firebase:
https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js
This is the payload I have
const payload = {
"notification": {
title: 'Title!',
body: 'Body!',
sound: 'default'
},
"data":{"score":"3x1"},
"content_available": true,
};
Now, this throwing an error, and when I check the log, here's the error:
Error: Messaging payload contains an invalid "content_available" property. Valid properties are "data" and "notification".
at FirebaseMessagingError.Error (native)
at FirebaseMessagingError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:25:28)
at new FirebaseMessagingError (/user_code/node_modules/firebase-admin/lib/utils/error.js:130:23)
at /user_code/node_modules/firebase-admin/lib/messaging/messaging.js:465:23
at Array.forEach (native)
at Messaging.validateMessagingPayload (/user_code/node_modules/firebase-admin/lib/messaging/messaging.js:462:21)
at /user_code/node_modules/firebase-admin/lib/messaging/messaging.js:204:37
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
If I removing the content_available: true, it works fine, so I know the code works.
I also tried to send this manually with CURL/POST request WITH content_available: true, and it also works.
Thanks!
contentAvailable is passed in the options parameter of sendToDevice(regToken, payload, options). Example code is in this documentation. The documentation for MessagingOptions is here.
Related
I am trying to create a cloud function for creating an user profile when a new user user is created(gosh a lot of "create).
I implemented this function:
exports.createProfile = functions.auth.user()
.onCreate( (userRecord, context) => {
return admin.database().ref(`/userProfile/${userRecord.data.uid}`).set({
email: userRecord.data.email
});
});
but when I create a new user, I got this error:
Error: Cloud function needs to be called with an event parameter.If you are writing unit tests, please use the Node module firebase-functions-fake.
at Object.<anonymous> (/srv/node_modules/firebase-functions/lib/cloud-functions.js:84:19)
at Generator.next (<anonymous>)
at /srv/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at new Promise (<anonymous>)
at __awaiter (/srv/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /worker/worker.js:731:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
is anyone facing something like that?
any solution so far?
Kind Regards
According to the docs the onCreate takes only an event as the parameter and there's no need for context (in this case userRecord): https://firebase.google.com/docs/functions/auth-events
You should then be able to simply access the uid via userRecord.uid :)
I upgraded to the latest firebase-functions, which solved the problem on my system. Run
npm outdated
to see if your firebase-functions is really up to date. NPM by itself won't update past semvers.
My guess is that firebase-functions defines an event class, and it is their internals which pass this event object to the user-defined callback. So if you are using an older version of firebase-functions, the callback is not receiving an "event parameter"
Don't have enough points to comment on Alchemist Shahed's answer, but the docs actually seem to be a bit conflicting on how to call onCreate().
https://firebase.google.com/docs/functions/auth-events#trigger_a_function_on_user_creation
says:
exports.sendWelcomeEmail =
functions.auth.user().onCreate((user) => {
// ...
});
But the upgrade guide
https://firebase.google.com/docs/functions/beta-v1-diff#authentication
shows
exports.authAction =
functions.auth.user().onCreate((userRecord, context) => {
const creationTime = userRecord.metadata.creationTime; //
// 2016-12-15T19:37:37.059Z
const lastSignInTime = userRecord.metadata.lastSignInTime;
// 2018-01-03T16:23:12.051Z
}
and https://firebase.google.com/docs/reference/functions/providers_auth_.userbuilder#on-create
also shows the (user: UserRecord, context: EventContext): PromiseLike<any> | any handler
So it is not clear if the context argument is needed or not.
Am getting this error after following the steps mentioned in the nativescript-plugin-firebase readme file.
JS: firebase.init error: TypeError: Cannot read property 'database' of
undefined
https://github.com/EddyVerbruggen/nativescript-plugin-firebase
but i dont really understand nor do i know how to solve that.
the version of the plugin am using is : 6.4.0
with tns 4.1.2
EDIT: init code, from app.js
var firebase = require("nativescript-plugin-firebase");
firebase.init({ persist: true
// Optionally pass in properties for database, authentication and cloud messaging,
// see their respective docs.
}).then(
function (instance) {
console.log("firebase.init done");
},
function (error) {
console.log("firebase.init error: " + error);
}
);
I finally solved it by installing the plugin manually via the CLI (i initially installed it through NativeScript sidekick) apparently they didnt take in count the fact that some plugins may require some user inputs, to do write specific config file (which nativescript-plugin-firebase), so by installing it manually i got to provide the user input needed, it got configured and it worked!
I would like to test some firebase database and auth triggers locally and have found this documentation https://firebase.google.com/docs/functions/local-emulator#invoke_realtime_database_functions.
Following along the instructions I typed
firebase functions:shell
and then invoked my custom firebase trigger with
createNewUser({user: {email: 'some#email.com'}},{auth: {uid: '123'}})
However, this gives me the error
firebase > createNewUser({user: {email: 'some#email.com'}},{auth: {uid: '123'}})
'Successfully invoked function.'
firebase > info: User function triggered, starting execution
info: Function crashed
TypeError: Cannot read property 'toLowerCase' of null
This is the function I try to run:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.createNewUser = functions.auth.user().onCreate((user) => {
let lowerCaseEmail = user.email.toLowerCase();
return admin.database().ref(`/users/${user.uid}/lowerCaseEmail`).set(lowerCaseEmail);
});
I believe I don't invoke my custom function correctly in firebase functions:shell.
Would someone like to point me in the right direction?
As per the documentation you have to pass a UserRecord (see doc) when invoking an Auth function, see at the bottom of the doc you point to in your Question (i.e. https://firebase.google.com/docs/functions/local-emulator#invoke_realtime_database_functions)
Doing the following works:
createNewUser({ disabled: false,
displayName: 'Renaud',
email: 'Mail#Gmail.com',
emailVerified: false,
metadata: {creationTime: null, lastSignInTime: null},
photoURL: null,
providerData: ['google.com'],
uid: '123' })
You do find the new record in the database, with the email in lower case.
Actually, since the documentation says: "Specify only the fields that your code depends on, or none at all if you only want to run the function.", I've tried with the following UserRecord object, and it also works.
createNewUser({email: 'Mail#Gmail.com', uid: '123'})
After updating to the lastest Firebase functions "firebase-admin": "^5.12.0",
,"firebase-functions": "^1.0.1 and Firebase tools 3.18.4, I have the following error message with the database trigger complaining of the property 'key' as undefined, how to fix this code
// this is the cloud function
exports.OnBalanceChange = functions.database.ref('/balance/{userID}')
.onUpdate(event => {
var userid = event.data.key;
var eventSnapshot = event.data;
console.log("user ID is", userid);
return 0;
});
TypeError: Cannot read property 'key' of undefined
at exports.OnBalanceChange.functions.database.ref.onUpdate.event (/user_code/index.js:760:28)
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)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Please study the migration guide for the 1.0 version of Cloud Functions for Firebase: https://firebase.google.com/docs/functions/beta-v1-diff
Specifically, see this. You'll see that the single argument to onUpdate was converted to two arguments, and the types of the arguments have changed. You can now use change.before.key (assuming that the first arg is now change to get the id of the document that changed.
I have successfully uploaded an image to amazon s3 with this meteor package
https://github.com/Lepozepo/S3 Now I am trying to delete the file, which I am getting a error on.
This is the documentation for the s3.delete code
S3.delete(path,callback)
This function permanently destroys a file located in your S3 bucket.
Parameters:
path: Must be in this format ("/folder/other_folder/file.extension").
So basically always start with "/" and never end with "/". This is
required.
callback: A function that is run after the delete operation
is complete returning an Error as the first parameter (if there is
one), and a Result as the second.
This is my upload and delete code
Template.postSubmit.events({
"click button.upload": function(){
var files = $("input.file_bag")[0].files
S3.upload({
files:files,
path:"uploads"
},function(e,r){
console.log(r);
delete_url = r.relative_url;
console.log(delete_url);
});
},
"click button.delete": function(){
S3.delete({
path:delete_url
},function(e,r){
console.log(e);
console.log(r);
});
}
});
The error I get when hitting the delete button.
errorClass {isClientSafe: true, error: 400, reason: "Match failed", details: undefined, message: "Match failed [400]", …}
details
:
undefined
error
:
400
errorType
:
"Meteor.Error"
isClientSafe
:
true
message
:
"Match failed [400]"
reason
:
"Match failed"
stack
:
"Error↵ at Connection._livedata_result (http://localhost:3000/packages/ddp-client.js?hash=14d966b7972bd95a1f7015fec9ac340f10508a44:4823:23)↵ at onMessage (http://localhost:3000/packages/ddp-client.js?hash=14d966b7972bd95a1f7015fec9ac340f10508a44:3528:206)↵ at http://localhost:3000/packages/ddp-client.js?hash=14d966b7972bd95a1f7015fec9ac340f10508a44:2908:9↵ at Array.forEach (<anonymous>)↵ at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?hash=cde485f60699ff9aced3305f70189e39c665183c:149:11)↵ at SockJS.self.socket.onmessage (http://localhost:3000/packages/ddp-client.js?hash=14d966b7972bd95a1f7015fec9ac340f10508a44:2907:43)↵ at SockJS.REventTarget.dispatchEvent (http://localhost:3000/packages/ddp-client.js?hash=14d966b7972bd95a1f7015fec9ac340f10508a44:142:28)↵ at SockJS._dispatchMessage (http://localhost:3000/packages/ddp-client.js?hash=14d966b7972bd95a1f7015fec9ac340f10508a44:1309:14)↵ at SockJS._didMessage (http://localhost:3000/packages/ddp-client.js?hash=14d966b7972bd95a1f7015fec9ac340f10508a44:1375:26)↵ at WebSocket.that.ws.onmessage (http://localhost:3000/packages/ddp-client.js?hash=14d966b7972bd95a1f7015fec9ac340f10508a44:1531:21)"
__proto__
:
Error
Update
This is the error I got on the server in terminal side
Exception while invoking method '_s3_delete' Error: Match error: Expected string, got object
You should call it like this:
S3.delete(delete_url, function() { ... });
First parameter should be url itself, not the object like in your example.