0
votes

I'm trying to deploy a cloud function for my react native app that sends a notification to users when a new node appears in the database. To do so, I'm using Expo's Push API as shown here: https://docs.expo.io/versions/v32.0.0/guides/push-notifications and following a tutorial available here: https://www.youtube.com/watch?v=R2D6J10fhA4

I've been able to acquire device tokens and save them to my database just fine. However, I'm unable to deploy the function to my database because of an error that says:

31:27 Parsing error: Unexpected token, expected ,

It's throwing a fatal error at the line 'body: JSON.stringify(messages)' as if it expects a comma right after 'stringify'. I'm very unsure of how to proceed from here and can't seem to find any posts tackling this specific issue.

Any help and/or advice is appreciated! Thank you.

const functions = require('firebase-functions');

let fetch = require('node-fetch');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendPushNotification = functions.database.ref('Omicron-Pi')
.onCreate(event => {
  const root = event.data.ref.root;
  let messages = [];

  root.child('Omicron-Pi/profiles').once('value').then((snapshot) => {
    snapshot.forEach((childSnapshot) => {
      let pushToken = childSnapshot.val().pushToken;
        if (pushToken) {
          messages.push({
            to: pushToken,
            body: 'New Node added'
          });
        }
    });
    return Promise.all(messages);
  }).then(messages => {
    fetch('https://exp.host/--/api/v2/push/send', [
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(messages)
    ]);
  });
});
1

1 Answers

0
votes

The second argument to fetch() is an object with initialization properties, but you are passing an array.

To fix it, use {} instead of []:

fetch('https://exp.host/--/api/v2/push/send', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(messages)
});

To learn more, read the documentation on how to use fetch on MDN.