A guide on incorporating JavaScript variables within a GraphQL-tag mutation

I'm having trouble consistently using javascript variables inside graphql-tag queries and mutations when setting up an apollo server. Here's a specific issue I've encountered:

gql`
  mutation SetDeviceFirebaseToken {
    SetDeviceFirebaseToken(
      internalDeviceId: ${internalDeviceId},
      firebaseToken: ${firebaseToken}
      )
    }
`

The variables internalDeviceId and firebaseToken are both strings, but I keep receiving the GraphQL syntax error "Expected Name, found...". What is the most effective approach for incorporating JS variables within a graphql-tag query or mutation? For additional context, I am implementing this in an older nativescript-angular application, and below is the complete function where I am attempting to execute the mutation:

/**
   * Call SetDeviceFirebaseToken mutation
   *
   * @param {string} internalDeviceId
   * @param {string} firebaseToken
   */
  public setDeviceFirebaseToken(internalDeviceId: string, firebaseToken: string, jwt: string): Observable<Object> {
    return this.http.post(this._carebearApiUrl, {
      query: gql`
        mutation SetDeviceFirebaseToken {
          SetDeviceFirebaseToken(
            internalDeviceId: ${internalDeviceId},
            firebaseToken: ${firebaseToken}
            )
          }
      `
    }, this.graphqlRequestHeaders(jwt));
  }

To make the above mutation work, I ended up replacing gql with String.raw. However, my initial hope was to utilize graphql-tag for this purpose. If I were to directly execute this mutation in Apollo, I would simply pass the strings as follows:

mutation SetDeviceFirebaseToken {
  SetDeviceFirebaseToken(
    internalDeviceId: "asfas9easefja9sefasef",
    firebaseToken: "asefa9sefaefafe"
    )
  }

Answer №1

Have you considered including the parameters directly in the mutation function itself?

gql"

mutation SetDeviceFirebaseToken($internalDeviceId: String!, $firebaseToken: String!) { SetDeviceFirebaseToken(internalDeviceId: $internalDeviceId, firebaseToken: $firebaseToken) .... .... }
Then send the variables from the client-side in this manner:

{
"internalDeviceId": "example",
"firebaseToken": "example"
}

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

What is the functionality of the keydown event?

Whenever the input text value is not empty, I want my .removetext div to be displayed, but it's not working correctly. When I type something after the second character, my .removetext gets hidden, but it shouldn't be hidden when the input is not ...

Can dates in the form of a String array be transmitted from the server to the client?

Struggling to send a String array from the server side to the client using Nodejs and Pug. Encounter errors like "SyntaxError: expected expression, got '&'" or "SyntaxError: identifier starts immediately after numeric literal". Server runs o ...

The local types package cannot be built by react-scripts even though tsc has successfully completed the process

I have developed an application with a TypeScript frontend and backend. To streamline the process, I decided to create a shared types module that contains all the necessary types for both components in one centralized location. Rather than going through th ...

Transform the IO type to an array of Either in functional programming with the fp-ts

Looking for assistance with implementing this in fp-ts. Can someone provide guidance? const $ = cheerio.load('some text'); const tests = $('table tr').get() .map(row => $(row).find('a')) .map(link => link.attr(&apos ...

Error: Client was unable to process JSON data

My server setup looks like this: var http = require('http'); //Defining the port to listen to const PORT=8092; //Function that handles requests and sends responses function handleRequest(request, response){ response.statusCode = 200; ...

Methods used on a server and methods used on a client-side application

In my ASP.NET application using C# 2.0, I have created objects for a database with properties that can be called natively or through a RESTful JSON API. These objects are used to convert data into HTML for display on the website. On the site, there are se ...

Creating void functions in TypeScript

I encountered a section of code within a custom component that is proving to be quite puzzling for me to comprehend. public onTouch: () => void = () => {} The function onTouch is being assigned by the private method registerOnTouch(fn: any) { ...

The method this.$el.querySelector does not exist

The data retrieved from the database is inserted into the input fields and submitted as a form. This data is an object that passes the value to the database. However, when I trigger this form, an error occurs. See example of the error <input id=" ...

Styling Form validation with Ant Design

Can a className prop be included in the Form.Item validation? <Form.Item name="username" rules={[ { required: true, message: '...' }, className="customValidation" //<- attempting to add a className but it is not fu ...

press a cURL PHP ajax button to trigger an action

Hello everyone, I could really use some help here. I've been looking at similar questions but none of the answers seem to apply to my situation. I extracted a page using curl, however, there's a button on that page that I am unable to interact w ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

Ways to incorporate a php file based on the user's selection

I have numerous div elements, possibly a dozen or two, such as... <div class="mydivs" id="firstdiv"></div> <div class="mydivs" id="seconddiv"></div> <div class="mydivs" id="thirddiv"></div> <div class="mydivs" id="fo ...

The autocomplete feature in Atom is not functioning as expected

Autocomplete+ is included with the installation of Atom and is activated by default. I have noticed that when I am coding, no suggestions are appearing. What could be causing this issue? Do I need to adjust any files in order for Autocomplete+ to functio ...

Creating a dynamic image gallery in Handlebars using Express

I have successfully implemented handlebars with puppeteer to generate a PDF server-side and save it in my database. However, I am facing an issue with loading images stored in an assets directory through the img tag. In my index.js file, I have a helper c ...

The breeze is puzzled by the altered being, unable to identify it

I am currently working on a breeze implementation that involves displaying properties from a location object on the UI. However, when I make changes to some properties and attempt to save them, breeze does not recognize the entity as being changed. Here is ...

Tips for incorporating the "define" function into your Mocha testing

Starting my journey with JavaScript testing, I made the decision to use Mocha. The specific modules I am looking to test are AMD/RequireJS. However, it appears that Mocha only works with CommonJS modules. Consequently, when trying to run it, I encounter t ...

Dynamically loading pages into a div with the power of AngularJS

I am attempting to dynamically load pages into a div using a select Here is my HTML code : <div ng-app="App" ng-controller="ProjectCtrl"> <div> <select ng-model="selectedType" class="form-control" ng-change="showContent()" ng-opt ...

Eliminate specific elements from an array while retaining others

Here is a simple page setup: https://i.sstatic.net/z9MF9.png The page consists of an input field at the top, followed by a list (<ul>), and a button for saving changes. The <ul> is connected to an array called items. When the user clicks on "S ...

In express.js, cookies automatically expire upon the browser being closed

When working with express.js, I typically set cookies using the command: res.cookie("name", "value"); However, upon closing and reopening the browser, I noticed that the cookie is no longer there. Could someone advise me on how to mak ...

Removing a CSS Class Using Tampermonkey: A Step-by-Step Guide

I'm completely new to CSS and javascript, so please bear with me. My goal is to remove the class disable-stream from each of the div elements located under the div with the class "stream-notifications". Below is an image for reference: Even though I ...