Home > Blockchain >  How to go about using javascript variables inside a graphql-tag mutation
How to go about using javascript variables inside a graphql-tag mutation

Time:05-17

I'm using graphql-tag to setup queries and mutations to an apollo server and haven't been able to use javascript variables inside the tag consistently or successfully. Here's an example:

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

internalDeviceId and firebaseToken are just strings, but I keep getting the GraphQL syntax error "Expected Name, found...". What's the best way to go about using JS variables inside a graphql-tag query or mutation? For context, I'm setting this up in an older nativescript-angular app and here is the full function that is attempting to send 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));
  }

I can make the above mutation work by just swapping out gql with String.raw, but I was hoping to utilize graphql-tag for this. If I were to execute this mutation in Apollo directly, I would just pass the strings like so:

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

CodePudding user response:

why don't you pass the parameters into the mutation function itself, e.g

gql"mutation SetDeviceFirebaseToken($internalDeviceId: String!, $firebaseToken: String!) { SetDeviceFirebaseToken(internalDeviceId: $internalDeviceId, firebaseToken: $firebaseToken) .... .... } Then passing the variable from the client-side like this:

{
"internalDeviceId": "something",
"firebaseToken": "something"
}

CodePudding user response:

GraphQL probably expects a string like this:

`
internalDeviceId: "a-nice-uuid"
`

But you are instead giving it this:

`
internalDeviceId: a-nice-uuid
`

You missed out on the quotes around the template literal:

`
internalDeviceId: "${internalDeviceId}"
`
  • Related