2021年4月28日星期三

TypeScript/GraphQL: Can you not string interpolate with a mutation?

I have a function that makes a GraphQL mutation like below that interpolates a value into it:

  runDataStreams(userId: number | string, subscription: string) {      const stream1 = StreamType['Audio']; // 'AUDIO'      const stream2 = StreamType['Video']; // 'VIDEO'        return gqlQuery<CreateWebPushMutation>({        query: gql`          mutation createStreamCurr($userId: Int, $subscription: String!) {            ${stream1}: editingVideo(              userId: $userId              instName: ${stream1}              subscription: $subscription            ) { ...... **rest omitted**  

When the build scripts run to create the GraphQL types, it shows this error in the console:

  ✖ Load GraphQL documents      → Syntax Error: Expected Name, found :  

I got around this in my local environment by commenting out the mutation, starting the build scripts and once they ran, uncommented the code out and the mutations work fine. I inspect them with a GraphQL browser extension and the correct mutation is made.
This obviously isn't a sufficient workaround because this will fail a deployment build since I can't comment it out and re-comment it in back in prod.

I found that just hardcoding the value in the mutation name works like this:

  runDataStreams(userId: number | string, subscription: string) {      const stream1 = StreamType['Audio']; // 'AUDIO'      const stream2 = StreamType['Video']; // 'VIDEO'        return gqlQuery<CreateWebPushMutation>({        query: gql`          mutation createStreamCurr($userId: Int, $subscription: String!) {            AUDIO: editingVideo(              userId: $userId              instName: AUDIO              subscription: $subscription            ) { ...... **rest omitted**  

I was trying to avoid this due to it being "hardcoded" but I don't know if I have any way around that. Is interpolating not allowed or am I messing something up?

https://stackoverflow.com/questions/67310493/typescript-graphql-can-you-not-string-interpolate-with-a-mutation April 29, 2021 at 11:08AM

没有评论:

发表评论