JavaScript parsing error occurred

Encountering a parsing error in my JavaScript code when deploying Firebase functions. The error mentions an unexpected token, indicating there might be a character out of place. I've been stuck on this issue for weeks now. Any assistance would be greatly appreciated.

Code

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

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

admin.initializeApp();

exports.sendNotification = functions.database.ref(`/Notifications/${user_id}/${notification_id}/`).onWrite((change, context) => {
        const user_id = context.params.user_id;
        const notification_id = context.params.notification_id;

        console.log('We have a notification to send to ', user_id);

        if (!change.after.val()) {
            return console.log("A Notification has been deleted from the database", notification_id);
        }

        const fromUser = admin.database().ref('/Notifications/${user_id}/${notification_id}').once('value');
        return fromUser.then(fromUserResult => {
            const fromUserId = fromUserResult.val().from;
            console.log('You have a new notification from : ', from_user_id);

            const userQuery = admin.database().ref('UserData/${fromUserId}/name').once('value');
            return userQuery.then(userResult => {
                const userName = userResult.val();

                const deviceToken = admin.database().ref(`/UserData/${user_id}/TokenID`).once('value');
                return deviceToken.then(result => {

                    const token_id = result.val();

                    const payload = {
                        notification: {
                            title: '${userName}',
                            body: "You have recieved a new Message",
                            icon: "default",
                            click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
                        },
                        data: {
                            from_user_id: fromUserId,
                            from_user_name: userName
                        }
                    };
                    return admin.messaging().sendToDevice(token_id, payload).then(response => {
                        return console.log('This was the notofication Feature');
                    });
                });
            });
        });

https://i.stack.imgur.com/E0dzw.png

Answer №1

There are two missing pairs of }) at the end of your file. Here is the corrected code:

...
return admin.messaging().sendToDevice(token_id, payload).then(response =>{
    return console.log('This was the notification Feature');
});

It can be difficult to spot this issue in your current code.

The lack of indentation makes it challenging to read and understand. I recommend using a tool like to improve readability.

You may also want to consider utilizing a tool such as https://eslint.org/demo/ to help catch mistakes like this in the future.

Answer №2

There are still a few bugs in your code. In three places, you're using single quotes ' instead of back-ticks `

...
const fromUser = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');
...
const userQuery = admin.database().ref(`UserData/${fromUserId}/name`).once('value');
...
const payload = {
  notification: {
    title: `${userName}`,
    body: "You have received a new Message",
    icon: "default",
    click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
  },
  data: {
    from_user_id: fromUserId,
    from_user_name: userName
  }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you confirm if the user originated from JavaScript when Ajax is sent?

Illustration: Upon using "ajax.send", the file is displayed (for example, "post.php?q=...".) However, by copying the specific "url" and pasting it into the browser with the same parameters, access can also be gained. Hence, is there a way to prevent this ...

Selecting a value will cause other blocks to vanish

How do I hide other filter buttons when I select a value? Check out my code snippet below: const FilterBlock = props => { const { filterApi, filterState, filterFrontendInput, group, items, name, ...

Issue with VueJS components not functioning as expected with routes

I've encountered an issue when using the component tag with an id of #app within the template of my components/App.vue file. Whenever I include this setup, I receive the following errors: // components/App.vue <template> <div id="app"> ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...

Unable to retrieve component name using React.Children

While working with react in the nextjs framework, I attempted to create my own dropdown component structured as follows: <Dropdown> <DropdownToggle>Action</DropdownToggle> <DropdownMenu> <DropdownItem>Menu 1</Dr ...

enhanced labeling for checkboxes in Vuetify

Below is a snippet of my straightforward code: <v-checkbox v-model="rodo" label="I consent to Terms and Conditions (click for more info)" :rules="termsRules" required ></v-checkbox> I am looking to keep the label simple with an option ...

Can an image be scanned pixel by pixel to extract and store each pixel's color in an array mapped by its coordinates?

Currently, I am working on a browser game where I have created a pixel map as a coordinate system. Each color on the map represents a unique terrain type with specific values that impact different aspects of the game. I'm looking for a solution using ...

Unable to load files in Handlebars when using Node and Express

Currently, I am in the process of developing a Node/Express web application for basic CRUD operations. However, I am encountering difficulties incorporating Handlebars into my project. Whenever I attempt to utilize Handlebars, none of the stylesheets from ...

req.next does not exist as a function [END]

I am currently working on developing a website and I have encountered an issue in the dashboard stage. The error message TypeError: req.next is not a function keeps appearing, particularly when trying to create a subpage for the dashboard. I am utilizing t ...

How can I calculate the total sum of values in an array retrieved from an API call?

Within the array this.state.companiesIncome, I've got 50 objects each containing a {value and date}. However, when attempting to retrieve this.state.companiesIncome[2].value, I'm encountering an error stating: TypeError: Cannot read property &apo ...

Remove HTML element and launch in a separate browser tab while preserving styles

I am currently working on developing a single-page application with Polymer3 (Javascript ES6 with imports). One of the key functionalities of my application involves moving widgets to new browser windows, allowing users to spread them across multiple scree ...

Can anyone figure out why this code is not functioning properly? It seems to be targeting the body element and all of

Currently, I am utilizing jqtouch to create a mobile website. In addition to this, I am incorporating a gallery image slider into the website. However, I have encountered an issue where the images do not display when placed between <div id="project_name ...

The functionality of "Body Onload" for sending "ScrollHeight" is malfunctioning in Chrome and Safari

I came across an issue where the iframe_resize function in my code was not working as expected. After investigating further, I realized that the problem did not lie with the function itself. So, I decided to post a new question. Within my index.html file ...

What is the best way to incorporate a button in my code that automatically triggers changes at regular intervals?

Is there a way to automatically change the color of my working traffic light in JavaScript on a timed basis, rather than relying solely on button clicks? Here is the current code I am using: <!DOCTYPE html> <html> <head> <style> # ...

Leveraging Javascript to retrieve input values

Here is my HTML code snippet: <li id='category-10'> <label class="selectit"> <input value="10" type="checkbox" name="post_category[]" id="in-category-10" /> Developmental </label> </li> Below is my JavaScript funct ...

Top choice for removing items from a list array

Hey there, I'm working with an array of a custom type in Angular: List { task: string; id?: number; status?: boolean; } I'm trying to figure out how to delete elements where List.status == true. I've tried two methods for this. ...

Slider Volume with jQuery

Struggling to find a solution for this issue. Seeking some assistance. My goal is to create a basic volume slider. So, the orange section represents my volume slider. This is the jQuery code I am using: var mouseIsDown = false; $("#volSlider").on("mou ...

Activating scrolling through Javascript

A friend of mine created a web page to help me learn some JavaScript. He designed a feature where the content in each div becomes visible as soon as the user scrolls past it. However, I noticed that the content appears too late for my liking. I would like ...

How to Fetch a Singular Value from a Service in Angular 4 Using a Defined Pattern

I am currently working on developing a service in Angular 4 (supported by a C# RESTful API) that will facilitate the storage and retrieval of web-application wide settings. Essentially, it's like a system for key-value pair lookups for all common appl ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...