Syntax error expected name found

I'm attempting to set up Apollo GraphQL support in a new React project, but when I try to compile a query using gql I keep receiving the error: Syntax Error: Expected Name, found } This is genera...

I’m attempting to set up Apollo GraphQL support in a new React project, but when I try to compile a query using gql I keep receiving the error:

Syntax Error: Expected Name, found }

This is generated by the following code:

import gql from 'graphql-tag'

const query = gql`
    {
      user(id: 5) {
        firstName
        lastName
      }
    }
  `

console.log(query)

I’m basing this code off the example code found here: https://github.com/apollographql/graphql-tag

What is the Name referred to in the error message? Does anyone know what I’m doing wrong here?

Soviut's user avatar

Soviut

86.8k48 gold badges187 silver badges254 bronze badges

asked Jan 18, 2018 at 22:06

Nathan's user avatar

2

This error occurs mostly when there are unclosed curly braces or when some fields are not properly defined while calling the query.

answered Apr 2, 2018 at 12:33

Razi Abdul Rasheed's user avatar

The accepted answer didn’t solve my issue. Instead, it worked if you remove the initial curly brackets.

The query should look like this instead:

const query=gql`
  user(id: 5) {
    firstName
    lastName
  }
`

Pang's user avatar

Pang

9,365146 gold badges85 silver badges121 bronze badges

answered Jul 17, 2018 at 20:34

Joseph Lin's user avatar

Joseph LinJoseph Lin

3213 silver badges2 bronze badges

1

The causes could be:

  • you are adding a «()» at the beginning for no reason
  • you need to add more ‘nested’ parameters.

Especially if you are using an online GraphiQL editor. Examples:

1- Wrong code (extra parenthesis)

{
  allFilms() {
    films {
      title
    }
  }
}

2- Wrong code (more parameters need it eg: title)

{
  allFilms {
    films {         
    }
  }
}

3- Correct code

{
  allFilms {
    films {
     title         
    }
  }
}

answered Oct 7, 2020 at 17:53

Juanma Menendez's user avatar

Juanma MenendezJuanma Menendez

15.6k7 gold badges54 silver badges52 bronze badges

GraphQLError: Syntax Error: Expected Name, found «$».

One more example of a similar error (For other users).

theErrorIsHere (Could be extra ( or { before the $varName) added before $speakerId

Error code:

const FEATURED_SPEAKER = gql`
  mutation markFeatured($speakerId: ID!, $featured: Boolean!){
    markFeatured(speaker_id: theErrorIsHere$speakerId , featured: $featured){
      id
      featured
    }
  }
`;

Error output

Correct code:

const FEATURED_SPEAKER = gql`
  mutation markFeatured($speakerId: ID!, $featured: Boolean!){
    markFeatured(speaker_id: $speakerId , featured: $featured){
      id
      featured
    }
  }
`;

answered Oct 13, 2020 at 15:51

Ezra Siton's user avatar

Ezra SitonEzra Siton

6,3292 gold badges21 silver badges34 bronze badges

1

I’m not 100% sure what the root of my problem was, but moving all the query code into a separate es6 module fixed the issue. There must have been some kind of contamination from the surrounding code. For reference my query was embedded within a React component.

This works:

import gql from 'graphql-tag'

const query = gql`
{
  user(id: 5) {
    firstName
    lastName
  }
}
`

export default query

answered Jan 23, 2018 at 15:48

Nathan's user avatar

NathanNathan

1,8272 gold badges14 silver badges16 bronze badges

Another cause for this error: you are referencing a type that is defined further down. Move the type you are referencing up.

For example:

    type Launch {
        rocket: Rocket
    }

    type Rocket {
        name: String
    }

will throw an error, as Launch references Rocket before Rocket is defined.

The corrected code:

    type Rocket {
        name: String
    }

    type Launch {
        rocket: Rocket
    }

answered May 7, 2019 at 23:43

ginna's user avatar

ginnaginna

1,6851 gold badge16 silver badges16 bronze badges

In my case, I got the error simply because I’m adding : which I shouldn’t have done.

e.g:

const query = `
   query($id: String!) {
      getUser(id: $id) {
        user: {
          id
          name
          email
          createdAt
        }
      }
   }
`

If you pay close attention to line 4 of the code above you’ll realize that I added : after the user before the curly brace, then I began to list the user’s data I wanna query and THAT WAS EXACTLY WHERE THE ERROR WAS!
Removing the : solve the issue!

It should be:

user {
   id
   name
   ...
}

answered Nov 2, 2021 at 21:48

Shamxeed's user avatar

ShamxeedShamxeed

3324 silver badges7 bronze badges

In NestJS framework, this error happened to me because I defiled GraphQL field in my schema.graphql file as:

  lastUpdated(): Date

Instead it should be just

  lastUpdated: Date

(it doesn’t take any argument)

answered Apr 1, 2022 at 5:34

justdvl's user avatar

justdvljustdvl

5353 silver badges11 bronze badges

1

I was receiving a similar error server side:

GraphQLError: Syntax Error: Expected Name, found ]

I realized the cause in my case was a type definition with an empty array.

This breaks:

  type Settings {
    requires: []
  }

But this works:

  type Settings {
    requires: [String]
  }

answered Jun 11, 2020 at 20:04

Jiert's user avatar

JiertJiert

5551 gold badge4 silver badges11 bronze badges

I had this problem and the cause was a string value with double-quotes inside double-quotes, like so: "this "is" bad".

answered Mar 25, 2021 at 22:15

SlothFriend's user avatar

SlothFriendSlothFriend

5911 gold badge6 silver badges14 bronze badges

In my case I got the error because of the following:

const GET_POSTS_OF_AUTHOR = gql`
  query GetPostsOfAuthor($authorId: Int!) {
    postsOf($authorId: Int!) {
      id
      title
    }
  }
`;

When it should have been:

const GET_POSTS_OF_AUTHOR = gql`
  query GetPostsOfAuthor($authorId: Int!) {
    postsOf(authorId: $authorId) {
      id
      title
    }
  }
`;

erroneously thought $authorId passed through identically to the function call instead of setting a property inside the function call.

answered Jun 20, 2021 at 6:52

Wild Bill's user avatar

Wild BillWild Bill

411 silver badge3 bronze badges

This can happen if you use gql from @clinet/apollo and in the backticks you try to inject dynamic js value. Remove it and replace with normal scalar and it will fix your issue.
example:

${SOME_MAX_VALUE} -> 20

answered Nov 23, 2022 at 8:58

Tigran Petrosyan's user avatar

On ny side the error was caused by extra {} Curly braces. Solved by just removing them.

answered Jun 2, 2021 at 2:35

Gesy Darati's user avatar

I was getting the same error. In my case putting the id inside double quote solved the issue as the type of id required string value.

{
        product(id: "${id}") {
            name
        }
}

answered Jun 3, 2022 at 8:49

Md Roknuzzaman's user avatar

Posting here in case anyone else had this problem but you also get this error if you accidentally make your query look like json with colons (:).

ex:

data {
  property {
    key: {
      deepKey
    }
  }
}

will give the same error from GQL compile

answered Nov 2, 2022 at 16:05

Zack Biernat's user avatar

@timbergus

I have the following code:

import gql from 'graphql-tag';

export const USER_QUERY = gql `{
    query User($id: ID!) {
        getUser(id: id) {
            name
            surname
        }
    }
}`;

Here is the connection point:

export default graphql(USER_QUERY, {
    name: 'User',
    options: ({ id }) => ({
        variables: { id }
    }),
})(User);

And the error in the title.

I am not sure if this error goes here, but I have been searching the web for this problem, and I cannot find anything. All the answers say that my code is OK, but I cannot make it work. Could you please halp me? Thanks.

@jnwng

Apologies for brevity, I’m on my phone.

When using variables for arguments in GraphQL they must be prefixed with an
“$”. In this case, the variable you’re passing to the getUser field (“id”)
should reference the $id variable declared at the query level.

getUser(id: $id)

On Thu, May 3, 2018 at 8:46 AM Gustavo Muñoz ***@***.***> wrote:
I have the following code:

import gql from ‘graphql-tag’;
export const USER_QUERY = gql `{ query User($id: ID!) { getUser(id: id) { name surname } }}`;

Here is the connection point:

export default graphql(USER_QUERY, {
name: ‘User’,
options: ({ id }) => ({
variables: { id }
}),
})(User);

And the error in the title.

I am not sure if this error goes here, but I have been searching the web
for this problem, and I cannot find anything. All the answers say that my
code is OK, but I cannot make it work. Could you please halp me? Thanks.


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#180>, or mute the
thread
<https://github.com/notifications/unsubscribe-auth/ABERRjMD3g-QQXKjAeGW0-hK1dWE6Uqbks5tuyZEgaJpZM4TxVVV>
.

@jnwng

On Thu, May 3, 2018 at 8:48 AM Jon Wong ***@***.***> wrote:
Apologies for brevity, I’m on my phone.

When using variables for arguments in GraphQL they must be prefixed with
an “$”. In this case, the variable you’re passing to the getUser field
(“id”) should reference the $id variable declared at the query level.

getUser(id: $id)
On Thu, May 3, 2018 at 8:46 AM Gustavo Muñoz ***@***.***>
wrote:

> I have the following code:
>
> import gql from ‘graphql-tag’;
> export const USER_QUERY = gql `{ query User($id: ID!) { getUser(id: id) { name surname } }}`;
>
> Here is the connection point:
>
> export default graphql(USER_QUERY, {
> name: ‘User’,
> options: ({ id }) => ({
> variables: { id }
> }),
> })(User);
>
> And the error in the title.
>
> I am not sure if this error goes here, but I have been searching the web
> for this problem, and I cannot find anything. All the answers say that my
> code is OK, but I cannot make it work. Could you please halp me? Thanks.
>
> —
> You are receiving this because you are subscribed to this thread.
> Reply to this email directly, view it on GitHub
> <#180>, or mute the
> thread
> <https://github.com/notifications/unsubscribe-auth/ABERRjMD3g-QQXKjAeGW0-hK1dWE6Uqbks5tuyZEgaJpZM4TxVVV>
> .
>

@timbergus

I’m pretty sorry about that. That is a typo. I get the same error with the right code. I have tested it using GraphiQL and it worked. The error is in the first line query User($id: ID!). If I remove the $, it throws the same error in the !, and if I remove the !, it works, but the app fails because there is no getUser result in the props. However, I will double check this as soon as I get a computer.

@timbergus

Doublechecked. With this code still failing:

import gql from 'graphql-tag';

export const USER_QUERY = gql `{
    query User($id: ID!) {
        getUser(id: $id) {
            name
            surname
        }
    }
}`;

The browser shows me this query in the error, and the same error as before:

body: "{↵    query User($id: ID!) {↵        getUser(id: $id) {↵            name↵            surname↵        }↵    }↵}"

Seems to be OK. Could be graphqlthe one having the problem using it?

@detrohutt

@timbergus Make sure you are using the same type for id in your backend schema typedefs. It seems like maybe you have it defined as type ID in one place and ID! in the other?

@timbergus

OK. I got it. The problem is that I’m passing extra curly braces. I have test this code, and it works perfectly:

import gql from 'graphql-tag';

export const USER_QUERY = gql `query User($id: ID!) {
    getUser(id: $id) {
        name
        surname
    }
}`;

I have discovered it using the importer of webpack and a code highligther for GraphQL. When creating the .graphql files, the sintax was highligted different with the curly braces and without them, so I tried.

The library is perfect. Thank you very much for your work, and sorry for the inconveniences.

Regards.

theoutlander, danielocampo2, tim-phillips, codenamezjames, Frogglet, coniel, wederribas, bhunjadi, a70537952, ismanf, and 76 more reacted with thumbs up emoji
detrohutt, RickBorst, hicoldcat, theoutlander, tim-phillips, jure, coniel, antoniofreyr, Chris-Maina, 404sand808s, and 14 more reacted with hooray emoji
pietro909, pavinduLakshan, oneezy, tinaszheng, LionelBeato, fuadnafiz98, polmabri, SamoriR, benwinding, TobioDev, and 6 more reacted with heart emoji
victorgois, lukasriha, LoesterFranco, israelsaraiva, asbjornenge, brillante06, and ayumitamai97 reacted with rocket emoji

@vinayvatsa007

i also made the same mistake, it helped Thanks for sharing.

timbergus, DingGGu, lirael, MarkMekhaiel, ashishnitinpatil, HeeL, jacqui, carchrae, cedrtang, LoesterFranco, and 2 more reacted with thumbs up emoji

@Tsudhishnair

I also made the same sort of mistake thanks for helping.

@MrSunshyne

@detrohutt I’m using gql statements with template literals as such :

return gql` query {
      ${entityTypes} {
        id
      }
    }`;

I get the error «Expected Name…. «

Any suggestions on how to deal with the above?

Thanks !

@detrohutt

@MrSunshyne it looks like you’re trying to use string interpolation syntax ${} in your query. I don’t believe that is supported by the gql template function. You’ll probably need to hard-code your field name. Hope that helps, good luck!

@MrSunshyne

@detrohutt That’s correct. I’m using native javascript string interpolation.
I’m not sure what you mean by «it’s not supported», as it definitely works.

I’m having issues with the syntax highlighting.

You’ll probably need to hard-code your field name
That’s not an option because my application only knows the name of the mutation at runtime.

Here’s another working example :

Screenshot 2019-07-29 at 17 58 11

The above would translate to article_delete in this case, which works fine. I can also have author_delete or whatever_delete.
I have no idea if gql statements was built to be used this way, but so far this is the only way I found to create my queries at runtime. Apologies if there’s something I missed. This is my first graphql project.

Any other hints? Much appreciated

@mgjules

it looks like you’re trying to use string interpolation syntax ${} in your query

I do confirm that using interpolation syntax ${} in a query works just fine but the syntax highlighting is all over the place like @MrSunshyne showed and described.

@detrohutt is that an unintended feature?
image

oneezy, MrSunshyne, kriscodes2, kevinbluer, timclifford, finkegabriel, krthr, JacksonMalloy, xai1983kbu, FrankDev-327, and 4 more reacted with laugh emoji

@digeomel

Same here. String interpolation in GraphQL queries seems to cause this error. Any updates?

@jtich

If it’s a query without any arguments, be sure to omit the empty () in typeDefs.

Содержание

  1. Syntax Error: Expected Name, found $ #180
  2. Comments
  3. GraphQL gql Syntax Error: Expected Name, found >
  4. 15 Answers 15
  5. GraphQLError: Syntax Error: Expected Name, found «$».
  6. GraphQLError: Syntax Error GraphQL #520
  7. Comments
  8. Unclear Error Output on Language/Parser.js #743
  9. Comments
  10. Syntax Error: Expected Name, found > #9
  11. Comments

Syntax Error: Expected Name, found $ #180

I have the following code:

Here is the connection point:

And the error in the title.

I am not sure if this error goes here, but I have been searching the web for this problem, and I cannot find anything. All the answers say that my code is OK, but I cannot make it work. Could you please halp me? Thanks.

The text was updated successfully, but these errors were encountered:

I’m pretty sorry about that. That is a typo. I get the same error with the right code. I have tested it using GraphiQL and it worked. The error is in the first line query User($id: ID!) . If I remove the $, it throws the same error in the !, and if I remove the !, it works, but the app fails because there is no getUser result in the props. However, I will double check this as soon as I get a computer.

Doublechecked. With this code still failing:

The browser shows me this query in the error, and the same error as before:

Seems to be OK. Could be graphql the one having the problem using it?

@timbergus Make sure you are using the same type for id in your backend schema typedefs. It seems like maybe you have it defined as type ID in one place and ID! in the other?

OK. I got it. The problem is that I’m passing extra curly braces. I have test this code, and it works perfectly:

I have discovered it using the importer of webpack and a code highligther for GraphQL. When creating the .graphql files, the sintax was highligted different with the curly braces and without them, so I tried.

The library is perfect. Thank you very much for your work, and sorry for the inconveniences.

i also made the same mistake, it helped Thanks for sharing.

I also made the same sort of mistake thanks for helping.

@detrohutt I’m using gql statements with template literals as such :

I get the error «Expected Name. «

Any suggestions on how to deal with the above?

@MrSunshyne it looks like you’re trying to use string interpolation syntax $<> in your query. I don’t believe that is supported by the gql template function. You’ll probably need to hard-code your field name. Hope that helps, good luck!

@detrohutt That’s correct. I’m using native javascript string interpolation.
I’m not sure what you mean by «it’s not supported», as it definitely works.

I’m having issues with the syntax highlighting.

You’ll probably need to hard-code your field name
That’s not an option because my application only knows the name of the mutation at runtime.

Here’s another working example :

The above would translate to article_delete in this case, which works fine. I can also have author_delete or whatever_delete .
I have no idea if gql statements was built to be used this way, but so far this is the only way I found to create my queries at runtime. Apologies if there’s something I missed. This is my first graphql project.

Источник

GraphQL gql Syntax Error: Expected Name, found >

I’m attempting to set up Apollo GraphQL support in a new React project, but when I try to compile a query using gql I keep receiving the error:

Syntax Error: Expected Name, found >

This is generated by the following code:

I’m basing this code off the example code found here: https://github.com/apollographql/graphql-tag

What is the Name referred to in the error message? Does anyone know what I’m doing wrong here?

15 Answers 15

This error occurs mostly when there are unclosed curly braces or when some fields are not properly defined while calling the query.

The accepted answer didn’t solve my issue. Instead, it worked if you remove the initial curly brackets.

The query should look like this instead:

The causes could be:

  • you are adding a «()» at the beginning for no reason
  • you need to add more ‘nested’ parameters.

Especially if you are using an online GraphiQL editor. Examples:

1- Wrong code (extra parenthesis)

2- Wrong code (more parameters need it eg: title)

GraphQLError: Syntax Error: Expected Name, found «$».

One more example of a similar error (For other users).

Error code:

Correct code:

I’m not 100% sure what the root of my problem was, but moving all the query code into a separate es6 module fixed the issue. There must have been some kind of contamination from the surrounding code. For reference my query was embedded within a React component.

Another cause for this error: you are referencing a type that is defined further down. Move the type you are referencing up.

will throw an error, as Launch references Rocket before Rocket is defined.

The corrected code:

In my case, I got the error simply because I’m adding : which I shouldn’t have done.

If you pay close attention to line 4 of the code above you’ll realize that I added : after the user before the curly brace, then I began to list the user’s data I wanna query and THAT WAS EXACTLY WHERE THE ERROR WAS! Removing the : solve the issue!

Источник

GraphQLError: Syntax Error GraphQL #520

I am trying to follow the graphql tutorial using react + apollo and I cannot pass through «Exploring the server» step. When the playground webpage is loaded, the database model works but app model does not work.

In the server console log I receive this error:

37: type BatchPayload <
38: «»»
^
39: The number of nodes that have been affected by the Batch operation.
at syntaxError (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/error/syntaxError.js:30:15)
at expect (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/language/parser.js:972:32)
at parseName (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/language/parser.js:90:15)
at parseFieldDefinition (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/language/parser.js:715:14)
at any (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/language/parser.js:1008:16)
at parseObjectTypeDefinition (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/language/parser.js:685:16)
at parseTypeSystemDefinition (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/language/parser.js:609:16)
at parseDefinition (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/language/parser.js:150:16)
at parseDocument (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/language/parser.js:108:22)
at parse (/Users/carlos.gusmao/workspace/playground/hackernews-react-apollo/server/node_modules/prisma-binding/node_modules/graphql-tools/node_modules/graphql/language/parser.js:45:10)
message: ‘Syntax Error GraphQL request (38:3) Expected Name, found Stringnn37: type BatchPayload <n38: «»»n ^n39: The number of nodes that have been affected by the Batch operation.n’,
locations: [ < line: 38, column: 3 >],
path: undefined >**

Could you help me to understand what is happening and how can I solve this issue? It seems some error in prisma.graphql file, but this file is auto generated, I dont’t know how can I solve this.

I am using node 8.9.4, the last stable version.

Thanks for help.

The text was updated successfully, but these errors were encountered:

Источник

Unclear Error Output on Language/Parser.js #743

I’m assuming I introduced the following error, but it seems to originate deep within the module and is not clear on exactly what it is that’s failing

/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/language/parser.js:966 throw (0, _error.syntaxError)(lexer.source, token.start, ‘Expected ‘ + kind + ‘, found ‘ + (0, _lexer.getTokenDesc)(token)); ^ GraphQLError at syntaxError (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/error/syntaxError.js:28:15) at expect (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/language/parser.js:966:32) at parseFieldDefinition (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/language/parser.js:715:3) at any (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/language/parser.js:1002:16) at parseObjectTypeDefinition (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/language/parser.js:683:16) at parseTypeSystemDefinition (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/language/parser.js:607:16) at parseDefinition (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/language/parser.js:148:16) at parseDocument (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/language/parser.js:106:22) at parse (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/language/parser.js:43:10) at buildSchema (/home/zmg/Thinkful/Goalzapp/server/node_modules/graphql/utilities/buildASTSchema.js:461:43) at Object. (/home/zmg/Thinkful/Goalzapp/server/index.js:15:16) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3)

The text was updated successfully, but these errors were encountered:

Источник

Syntax Error: Expected Name, found > #9

Hello jexp, first thanks for the project, it looks very useful.

I’m having a problem when running the grapqhl load that maybe you would know what it would mean.

I’m running the database API with prisma, and I have uploaded my whole minimum viable test project to get this functionality working in this repository: https://github.com/daquintero/testGraphqlCLILoad/tree/master

I’m not sure if this is enough information for the question, but please tell me if you need anything else. I appreciate very much the help!

The text was updated successfully, but these errors were encountered:

I’ve found prisma/prisma#1981 but I’m not sure its relationship given that in the graphql playground localhost:4000 the mutation works correctly, but through the graphql-cli-load I get this error.

Solved it, the mappings inside the const column=(rMapping[key]||key).toString(); were not giving me the correct column headers for the values generation that is used in the mappings, so I changed it to const column = mapping[key].toString() which gave me the correct mappings when using this output:

I will send a pull request for this correction and if you want we can use my repository as the minimum viable graphql-cli-load example code that currently does not exist in a «plug in -and — run» sort of thing.

I also removed the original example repository since I have now copied the working version of the minimum example code as a separate branch of my own fork here

Sounds great, thanks so much !
sorry was away over the weekend so I didn’t see your initial issue immediately.

Your original issue looked like a missing/incorrect mutation name?

Hey jexp, thanks for the reply. Apologies for the unclean code, I will be more careful with presenting it better next time. Would I suggest continuing to discuss this issue here before continuing at the pull request? I will also make it better as soon as I can.

So I was trying to run this command:

And I had defined this resolver in src/resolvers/Mutations.js from my most minimum example:

Also running this mutation in the graphql playground, it worked:

Источник

Discussion on: Direct Lambda Resolvers with AWS Amplify and AppSync


Collapse

Expand


swyx profile image

swyx

Infinite Builder 👷🏽‍♂️ I help people Learn in Public • Author, the Coding Career Handbook (https://www.learninpublic.org)

  • Location

    NYC

  • Work

    head of dx at temporal.io

  • Joined

    Dec 2, 2017

Aug 17 ’20

  • Copy link
Syntax Error: Expected Name, found @

GraphQL request:4:9
3 |   id: ID
4 |   task: @function(name: "DirectLambdaResolver-${env}")
  |         ^
5 | }

Enter fullscreen mode

Exit fullscreen mode


Collapse

Expand


andthensumm profile image

Matt Marks 🐣

Heyooo, I’m a full stack React | Native | Servereless developer out here trying to bring his apps to life. Find me on twitter @andthensumm

  • Location

    Chicago

  • Work

    Software Dev / Founder at Shindy

  • Joined

    Mar 3, 2020

Aug 17 ’20

  • Copy link

Thank you Shawn for catching this, it’s a treat just to have you actually use this code!


Collapse

Expand


swyx profile image

swyx

Infinite Builder 👷🏽‍♂️ I help people Learn in Public • Author, the Coding Career Handbook (https://www.learninpublic.org)

  • Location

    NYC

  • Work

    head of dx at temporal.io

  • Joined

    Dec 2, 2017

Aug 17 ’20

  • Copy link

not at all lol, i barely know what i’m doing and was following along just to try to learn about this new feature 😅

i think the struggle i had was how to use direct lambda resolvers in mutations not just queries. i couldnt figure out how to do it. maybe worth a followup post?

andthensumm profile image

Matt Marks 🐣

Heyooo, I’m a full stack React | Native | Servereless developer out here trying to bring his apps to life. Find me on twitter @andthensumm

  • Location

    Chicago

  • Work

    Software Dev / Founder at Shindy

  • Joined

    Mar 3, 2020

Aug 17 ’20

  • Copy link

Pfffh, you got it. I’ll whip something up for this week.

nxtra profile image

Nxtra

Cloud && Serverless evangelist ✨丨always curious and caffeinated丨
🛰 #AWSCommunity Builder • ServerlessDays Belgium Organizer • runner && cyclist

  • Location

    Belgium

  • Joined

    Sep 24, 2020

Nov 20 ’20

  • Copy link

Did you guys manage to figure this out?

andthensumm profile image

Matt Marks 🐣

Heyooo, I’m a full stack React | Native | Servereless developer out here trying to bring his apps to life. Find me on twitter @andthensumm

  • Location

    Chicago

  • Work

    Software Dev / Founder at Shindy

  • Joined

    Mar 3, 2020

Nov 20 ’20

• Edited on Nov 20

  • Copy link

@nxtra
, in order to do this for a mutation, you’d set the typeName: Mutation and fieldName: yourMutationName. Query, Mutation and Subscription are really just a Type like Todo.

The one gotcha is that you can’t create a resolver on a mutation that already has one. Example being createToDo. Amplify has already created a resolver for it inside CloudFormation. You’ll need to either to add @model(mutations: null) so you can override it or create a custom mutation. I prefer the custom mutation because then I still have access to the autogenerated vtl from Amplify. There are times where the authorization rules that are generated in the response.vtl can still be useful.

  "MutationyourMutationNameLambdaResolver": {
  "Type": "AWS::AppSync::Resolver",
  "Properties": {
    "ApiId": {
        "Ref": "AppSyncApiId"
    },
    "DataSourceName": "DirectLambdaResolverLambdaDataSource",
    "TypeName": "Mutation",
    "FieldName": "yourMutationName"
  },

  "DependsOn": "DirectLambdaResolverLambdaDataSource"
}

Enter fullscreen mode

Exit fullscreen mode

nxtra profile image

Nxtra

Cloud && Serverless evangelist ✨丨always curious and caffeinated丨
🛰 #AWSCommunity Builder • ServerlessDays Belgium Organizer • runner && cyclist

  • Location

    Belgium

  • Joined

    Sep 24, 2020

Nov 23 ’20

  • Copy link

Thanks for the info! I didn’t realize yet that indeed a resolver with that name already exists if you name it like that.
Until now I’ve been making custom Resolvers with lambda functions as pipeline resolvers. I’ll try to convert one to a «no-more-vtl» version using your guide.

Возможно, вам потребуется отправить переменные в компонент мутации, например:

<Mutation mutation  = {CREATE_AUTHOR} variables = {{"firstName": firstName, "lastName": lastName}}>

ОБНОВИТЬ

Хотя это не совсем то, что вы ищете, вот как я сейчас делаю мутации Аполлона.

Функция, принадлежащая к классу компонентов React:

sendInstantMsg(createIM) {
    const textToSendElem = document.getElementById("textToSend");
    const textToSend = textToSendElem.value;

    const {toID} = this.props;
    const fromID = Meteor.userId();
    const msgText = trimInput(textToSend);

    createIM({
        variables: {
            "fromID": fromID,
            "toID": toID,
            "msgText": msgText
        },
        optimisticResponse: {
            __typename: 'Mutation',
            createIM: {
                __typename: 'instant_message',
                id: -1, 
                fromID: fromID,
                toID: toID,
                msgText: msgText,
                createdAt: +new Date
            },
        },
        update: (cache, {data: {createIM}}) => {
            let cacheData = cache.readQuery({query: GETIMS_QUERY, variables: {"fromID": fromID, "toID": toID}});
            let instant_message = cacheData.instant_message;
            if (!isDuplicateObject(createIM, instant_message)) {
                instant_message.push(createIM);

                cache.writeQuery({
                    query: GETIMS_QUERY,
                    data: {instant_message},
                    variables: {"fromID": fromID, "toID": toID}
                });
            }
            textToSendElem.value = "";
            scrollToBottomOfTextMsgs();
        }
    })
}

В функции рендеринга:

<Mutation
    mutation = {CREATE_IM_MUTATION}
>
    {(createIM, {data}) => (
        <RaisedButton
            id = "sendMsgButton"
            label = "SEND"
            style = {styles.makeApptButton}
            secondary = {true}
            onClick = {() => this.sendInstantMsg(createIM)}
        />
    )}
</Mutation>

Понравилась статья? Поделить с друзьями:
  • Syntax error expected gthtdjl
  • Syntax error expected but identifier readln found
  • Syntax error expected but found перевод
  • Syntax error expected but found паскаль
  • Syntax error expected but found pascal