I am trying to send notification from Node.js server to an ios application. It seems working if I send notification from Firebase console, but isn't working if try from my node.js server using firebase-admin sdk.
I followed tutorial from https://firebase.google.com/docs/cloud-messaging/admin/send-messages.
One thing I do not understand is the response after sending notification seems working. I get below response.
{
"results": [
{
"messageId": "0:1511109840587284%a63b4c28f9fd7ecd"
}
],
"canonicalRegistrationTokenCount": 0,
"failureCount": 0,
"successCount": 1,
"multicastId": 7436388871122493000
}
Does anyone know what I am doing wrong?
-- Edit
Here is the code that sends the notification. admin is the firebase-admin instance.
router.post('/notify', (req, res) => {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "<database>.firebaseio.com"
});
var registrationTokens = [
'tokenFromIosApp'
];
var payload = {
data : {
body : 'TEST'
}
};
admin.messaging().sendToDevice(registrationTokens, payload)
.then((response) => {
console.log('Sent successfully.\n');
console.log(response);
res.status(statusCodes.Ok);
res.json(response);
})
.catch((error) => {
console.log('Sent failed.\n');
console.log(error);
res.status(statusCodes.InternalServerError);
res.json(error);
});
});
To send a notification, the payload must use the notification key:
var payload = {
notification: {
title: 'My Title',
body : 'TEST'
}
};
Related
I am sending data only messages from a Firebase Function to a React Native app.
It works on Android, but it not works on iOS.
As specified here https://rnfirebase.io/messaging/usage#data-only-messages
my code for sending a message is the following:
var payload = {
data: {
//my app data
},
apns: {
payload: {
aps: {
contentAvailable: true,
priority: 'high',
},
},
headers: {
'apns-push-type': 'background',
'apns-priority': '5',
'apns-topic': 'com.xxxx.xxxx', //my app bundle id
},
},
tokens: tokens
};
const response = await admin.messaging().sendMulticast(payload);
The response has success=true, so the code is working.
In my iOS app I have this handler:
const setMessages = useCallback(async (remoteMessage: any) => {
console.log('A new FCM message arrived!', JSON.stringify(remoteMessage));
});
useEffect(() => {
const unsubscribe = messaging().onMessage(setMessages);
return unsubscribe;
}, []);
As I said before, it works on Android. In iOS the callback is never triggered.
I am pretty sure I setup the iOS app correctly:
- I can receive notification-only messages in iOS
- I can generate the fcm token
Is it possible to test graphql subscriptions using k6 framework?
I tried to do it, but did not have much success. Also tried to do it with k6 websockets, but did not help.
Thanks
Grapqhql Subscription is based on Websockets so this is theoretically possible to implement using k6 WebSocket.
You can also refer to the documentation for subscriptions here.
You can also use the playground and Networks tab in developer tools to figure out the messages/requests that are sent to the server.
Here is how I was able to achieve it:
import ws from "k6/ws";
export default function(){
const url = "ws://localhost:4000/graphql" // replace with your url
const token = null; // replace with your auth token
const operation = `
subscription PostFeed {
postCreated {
author
comment
}
}` // replace with your subscription
const headers = {
"Sec-WebSocket-Protocol": "graphql-ws",
};
if (token != null) Object.assign(headers,{ Authorization: `Bearer ${token}`});
ws.connect(
url,
{
headers,
},
(socket) => {
socket.on("message", (msg) => {
const message = JSON.parse(msg);
if (message.type == "connection_ack")
console.log("Connection Established with WebSocket");
if (message.type == "data") console.log(`Message Received: ${message}`)
});
socket.on("open", () => {
socket.send(
JSON.stringify({
type: "connection_init",
payload: headers,
})
);
socket.send(
JSON.stringify({
type: "start",
payload: {
query: operation,
},
})
);
});
}
);
}
Hope this helps! 🍻
To send a silent remote notification to my iOS app from Google Firebase Functions, this is my index.js file:
const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp();
const messaging = admin.messaging();
exports.sendPushNotification = functions.https.onRequest((req, res) => {
var payload = {
"notification": {
title: 'test title 2',
body: 'test body 2.1',
icon: 'https://i.pinimg.com/236x/2f/b9/bd/2fb9bd91b530d20410744249a418240b.jpg'
}
"data": {
"aps" = {
"content-available" : 1,
};
}
}
messaging.sendToTopic("backgroundUpdate", payload).then(function (response) {
console.log(response);
res.send(response);
}).catch(e => {
console.log(e)
res.send(e)
})
});
But Google keeps giving me this error message:
Deployment failure:
Build failed: /workspace/index.js:13
"data": { ^^^^^^ SyntaxError: Unexpected string at new Script (vm.js:83:7) at checkScriptSyntax (internal/bootstrap/node.js:620:5) at startup (internal/bootstrap/node.js:280:11) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3); Error ID: d984e68f
Can anyone point me to my error? I have not been able to find a solution.
I'm trying to send e-mails with MS Graph 1.0 and I have not any get any result or response. E-Mails haven't been sent and sendMail method don't return any error o message... it only says "null".
My code is based on this example https://github.com/microsoftgraph/msgraph-sdk-javascript#post-and-patch and looks like this:
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
try {
// construct the email object
var mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [{
emailAddress: {
address: "mail#domain.com"
}
}],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html"
}
};
client
.api('/me/sendMail')
.post({message: mail}, (err, res) => {
console.log("---> " + res);
});
console.log("Try ends");
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = { status: `${err.code}: ${err.message}` };
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
I guess mail var needs a header, but anyway, API should return me something, right? And, obviously, which is the problem with the email sending?
I finally added rawResponse to .post call and look at err log...
client
.api('/me/sendMail')
.header("Content-type", "application/json")
.post({message: mail}, (err, res, rawResponse) => {
console.log(rawResponse);
console.log(err);
});
... and I could see that I had problem with my authentication token. So, I was using the api correctly and code from the question is ok.
I have an SNS triggered by a lambda on AWS that generates an iOS push notification, is working fine, but the problem is that the sound is not happening...
const sns = new AWS.SNS();
var payload = {
default: ' World23',
APNS: {
aps: {
alert: 'tkt',
sound: 'default',
badge: 1
}
}
};
// first have to stringify the inner APNS object...
payload.APNS = JSON.stringify(payload.APNS);
// then have to stringify the entire message payload
payload = JSON.stringify(payload);
var params = {
Message:payload,
MessageStructure: 'json',
Subject: event.body.subject,
TargetArn:TargetArn
};
sns.publish(params, function(err,data){
if(err) {
console.error('error publishing to SNS',err);
context.fail(err);
} else {
console.info('message published to SNS',data);
done(null, data);
}
});
What is wrong with my payload?, the sound and badge are not getting set.
Cheers...
The formatting for the body needed some tweaks, also the environment was the "sandbox", will have to change for prod push notifications "APNS"...
const sns = new AWS.SNS();
var payload = {
default: notifMessage,
'APNS_SANDBOX': {
'aps': {
'alert': notifMessage,
'sound': 'default',
'badge': 1
}
},
// first have to stringify the inner APNS object...
payload.APNS_SANDBOX = JSON.stringify(payload.APNS_SANDBOX);
// then have to stringify the entire message payload
payload = JSON.stringify(payload);
var params = {
// Message: event.body.message,
Message:payload,
MessageStructure: 'json',
Subject: event.body.subject,
TargetArn:TargetArn
};
console.log('params:: ', payload);
sns.publish(params, function(err,data){
if(err) {
console.error('error publishing to SNS',err);
context.fail(err);
} else {
console.info('message published to SNS',data);
done(null, data);
}
});