enigmare/v2-crawler
1904
1{"id":"stack-41743253","source":"stackoverflow","questionId":41743253,"title":"What's the point of input type in GraphQL?","tags":["graphql"],"text":"Title: What's the point of input type in GraphQL?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nCould you please explain why if input argument of mutation is object it should be **input type**? I think much simpler just reuse **type** without providing id.\n\nFor example:\n\n```\ntype Sample {\n id: String\n name: String\n}\n\ninput SampleInput {\n name: String\n}\n\ntype RootMutation {\n addSample(sample: Sample): Sample # It's okay for small object, but when you have plenty of objects with 10+ properties in schema that'll become a burden.\n\n========================================\n\nTop Answer:\nJesse's comment is correct. For more formal answer, here is the excerpt from GraphQL documentation on input types:\n\n The Object type defined above is inappropriate for reβuse here,\n because Objects can contain fields that express circular references or\n references to interfaces and unions, neither of which is appropriate\n for use as an input argument. For this reason, input objects have a\n separate type in the system.\n\n### UPDATE\n\nSince posting it, I found that circular references actually are acceptable, so long as those are nilable (or else it would declare an infinite chain). But, still there are other limitations (e.g. interfaces) that seem to necessitate a separate type system for inputs.\n\n========================================\n\nCode:\n```text\ntype Sample {\n id: String\n name: String\n}\n\ninput SampleInput {\n name: String\n}\n\ntype RootMutation {\n addSample(sample: Sample): Sample # <-- instead of it should be\n addSample(sample: SampleInput): Sample\n}\n```\n\n```text\ntype Student {\n name: String\n grade: Grade\n}\n\ninput StudentInput {\n name: String\n grade: Grade\n}\n```\n\n```text\ntype Student {\n name(preferred: Boolean): String\n grade: Grade\n}\n\ninput StudentInput {\n name: String\n grade: Grade = F\n}\n```\n\n```text\ntype Student {\n firstName: String\n lastName: String\n grade: Grade\n}\n\ninput StudentInput {\n firstName: String\n lastName: String\n grade: Grade\n}\n```\n\n```text\ntype Student {\n fullName: String!\n classes: [Class!]!\n address: Address!\n emergencyContact: Contact\n # etc\n}\n```\n\n```text\ntype Student {\n firstName: String!\n lastName: String!\n}\n\ninput StudentInput {\n firstName: String\n lastName: String\n}\n```\n\n```text\ninput CreateUserInput {\n firstName: String!\n lastName: String!\n email: String!\n password: String!\n}\n\ninput UpdateUserInput {\n email: String\n password: String\n}\n```\n\n```text\npassword\n```\n\n```text\n@ObjectType\nclass Location {\n @Field()\n lat: number\n @Field()\n lon: number\n}\n```\n\n```text\n@ObjectType\nclass MyPlace {\n @Field(type => Location)\n location: Location\n}\n```\n\n```text\n@ObjectType\n@InputType('LocationInput')\nclass Location {\n @Field()\n lat: number\n @Field()\n lon: number\n}\n```\n\n```text\nLocation\n```\n\n```text\nMyPlace\n```\n\n```text\nlocation\n```\n\n```text\nLocation\n```\n\n========================================\n\nComments:\n- Input objects must be serializable. Because output objects can contain cycles, they can't be reused for input.\n- Jesse, it looks like enough answer! You can answer and I mark it so.\n- Wondering if it is possible to combine interfaces with it\n- There's a bit more discussion here on why this restriction exists: github.com/graphql/graphql-js/issues/599\n- Checkout the article here on the basics of GraphQL medium.com/@harshitpant_85243/graphql-made-easy-3112c6a62840\n- Correct me if I'm wrong but in your example, the type `Grade` cannot be reused in the input `StudentInput`, right? You'll need to either inline fields in the input object or have a `GradeInput` input object.\n- @Matt Good question! In the above example, `Grade` is an enum type. Unlike with objects, scalar types (like String, Int, etc.) and enums types can be used as *both* input types *and* output types.\n- This is so much clearer now -- if I'm understanding things correctly, in GraphQL there are both `Input Types` *and* \"output types\", that each deal separately with incoming requests or outgoing responses. But, the GraphQL \"output types\" are actually never referred to as such, output types are simply called `Type`. Perhaps in a later version instead of using `type` and `input` it would be clearer to use `output` and `input`. Thanks for the explanation\n- @DanielRearden thank you for a great explanation. I have the same issue, but in my case the output type just extends the input type. I understand why the coupling between them can be an issue, but for my use case it will be good enough. Is there a way to define that the output type will extend the input type?\n- @RoyLeibovitz as outlined in the \"Functionality\" section above, fields on output types and input types each have different properties, so having an output type extend an input type (or vice versa) would be problematic and is not supported by the spec. Depending on the language, libraries and frameworks you're using, it may be *possible* using some hacky method, but I would highly discourage doing so.\n- We don't want to use any hacky methods, we are just wondering why is this not supported at all, I prefer to decide by myself if the usage of it is making sense or not. In my scenario, the output and input fields are almost identical, the output can extend the input with other fields and we could avoid this duplication.\n- Why not just use scalar types for input instead of an input type?","metadata":{"transformedAt":"2026-08-18T18:32:36.017Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":194,"estimatedTokens":1338}}2{"id":"stack-42622912","source":"stackoverflow","questionId":42622912,"title":"In GraphQL what's the meaning of \"edges\" and \"node\"?","tags":["json","graphql"],"text":"Title: In GraphQL what's the meaning of \"edges\" and \"node\"?\nTags: json, graphql\nSource: Stack Overflow\n\nQuestion:\nI am consuming a GraphQL endpoint and I get results that contain `edges` and `node` tags. I am supplying a clean JSON structure for my query, so this doesn't make sense to me.\n\nIt seems as if the GraphQL server is polluting my data with no obvious benefit. Why are these terms included in the GraphQL endpoint's response and is it possible to get rid of those for faster/simpler parsing of data?\n\n========================================\n\nTop Answer:\nGraphQL stands for Graph Query Language, and has two parts: **the server and client**. The server effectively puts a graph structure in front of your database and your queries are traversing that **graph**.\n\nIn computer science:\n\n- a **graph** is a network\n\n- a **node** is one of the vertices in that network\n\n- an **edge** is one of the links between the nodes\n\nTake all of this together, a GraphQL query effectively asks the GraphQL server instance to traverse its graph of data and find some representation of that data. You'll see `edges` and `node` in your queries because you're literally looking at those entries in the graph.\n\nTypical query for `allXYZ` records will look like this:\n\n```\n{\n _allXYZ {\n edges {\n node {\n // your data shape will be in here\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nedges\n```\n\n```text\nnode\n```\n\n```text\nedges\n```\n\n```text\npageInfo\n```\n\n```text\nhasNextPage\n```\n\n```text\nhasPreviousPage\n```\n\n```text\nstartCursor\n```\n\n```text\nendCursor\n```\n\n```text\nhasNextPage\n```\n\n```text\nGraphQLList\n```\n\n```text\nnode\n```\n\n```text\ncursor\n```\n\n```text\nconnectionArgs(first, last, after, before)\n```\n\n```text\nfirst/last\n```\n\n```text\nafter/before\n```\n\n```text\nnodeDefinitions\n```\n\n```text\nglobalFieldId\n```\n\n```text\nnodeInterfaces\n```\n\n```text\n{\n _allXYZ {\n edges {\n node {\n // your data shape will be in here\n }\n }\n }\n}\n```\n\n```text\nedges\n```\n\n```text\nnode\n```\n\n```text\nallXYZ\n```\n\n========================================\n\nComments:\n- Connections, edges and nodes is terminology mainly used in the context of Relay, the GraphQL client. More information can be found in this FAQ.\n- Just to clarify: connections are not a Relay-specific thing. For an in-depth look, see this article: medium.com/p/explaining-graphql-connections-c48b7c3d6976\n- Its somewhat of a standard way of providing paging for long lists of results. Not tied to any implementation.\n- graphql.org/learn/pagination\n- I think this answer has the gist right, but it contains many misconceptions. This article explains the reasoning behind GraphQL connections pretty well: medium.com/p/explaining-graphql-connections-c48b7c3d6976\n- where do you find the misconceptions, it's just the brief information, if you found any misconceptions, you can always improve it to make it better\n- Can I work with these constructs through *graphql* UI? For example *hasNextPage*, or are they available only through JS with Relay?\n- yes, you can work on these from graphiql UI using graphql-relay\n- not `each node will have a cursor`, rather `each edge will have a cursor`, refer that blog.apollographql.com/…\n- This answer leans too much on an existing understanding of GraphQL terminology. It's more a list of the terms rather than an explanation.\n- This is the answer you would tell to an alien. Why wouldn't you explain what an edge actually is, and why we even have them?","metadata":{"transformedAt":"2026-08-18T18:32:36.017Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":151,"estimatedTokens":868}}3{"id":"stack-50684231","source":"stackoverflow","questionId":50684231,"title":"What is an exclamation point in GraphQL?","tags":["graphql"],"text":"Title: What is an exclamation point in GraphQL?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nIn a schema file that I have I noticed there are exclamation marks after some types, like\n\n```\n# Information on an account relationship\ntype AccountEdge {\n cursor: String!\n node: Account!\n}\n```\n\nWhat do these mean? I can't find anything about it in the documentation or through googling π
\n\n========================================\n\nTop Answer:\nFrom the spec:\n\n By default, all types in GraphQL are nullable; the null value is a valid response for all of the above types. To declare a type that disallows null, the GraphQL NonβNull type can be used. This type wraps an underlying type, and this type acts identically to that wrapped type, with the exception that null is not a valid response for the wrapping type. A trailing exclamation mark is used to denote a field that uses a NonβNull type like this: name: String!.\n\nIn other words, types in GraphQL are nullable by default. An exclamation point after a type specifically designates that type as non-nullable.\n\nThis has different implications depending on where the type is used.\n\n### Output\n\nWhen non-null is applied to the type of a **field**, it means that if the server resolves that field to `null`, the response will fail validation. You may still receive a partial response, as long as the error does not propagate all the way up to the root.\n\nFor example, given a schema like:\n\n```\ntype Query {\n user: User\n}\n\ntype User {\n id: ID!\n}\n```\n\nHere the `id` field is non-null. By marking the field as non-null, we are effectively *guaranteeing* we will never return null for this field. If the server does return null, then it's an indication that something went terribly wrong and we want to throw a validation error.\n\n### Input\n\nWhen non-null is applied to the type of an **input**, like an argument, input object field or a variable, it makes that input required. For example:\n\n```\ntype Query {\n getUser(id: ID!, status: Status): User\n}\n```\n\nHere, the `id` argument is non-null. If we request the `getUser` field, we will always have to provide the `id` argument for it. On the other hand, because the `status` argument is nullable, it's optional and can be omitted. This applies to variables as well:\n\n```\nquery MyQuery ($foo: ID!) {\n getUser(id: $foo)\n}\n```\n\nBecause the `$foo` variable is non-null, when you send the query, it cannot be omitted and it's value cannot equal `null`.\n\n### A special note on variable types\n\nBecause the `id` field is a non-null `ID` (i.e. `ID!`) type in our example, any variable we pass it must **also** be a non-null `ID`. If our `$foo` variable was a nullable `ID`, we could not pass it to the `id` argument. The opposite, however, is not true. If an argument is nullable, you **can** pass it a non-null variable.\n\nIn other words:\n\n```\n+----------+----------+--------+\n| Argument | Variable | Valid? |\n+----------+----------+--------+\n| String | String | β
|\n| String | String! | β
|\n| String! | String | β |\n| String! | String! | β
|\n+----------+----------+--------+\n```\n\n========================================\n\nCode:\n```text\n# Information on an account relationship\ntype AccountEdge {\n cursor: String!\n node: Account!\n}\n```\n\n```text\ntype Query {\n user: User\n}\n\ntype User {\n id: ID!\n}\n```\n\n```text\ntype Query {\n getUser(id: ID!, status: Status): User\n}\n```\n\n```text\nquery MyQuery ($foo: ID!) {\n getUser(id: $foo)\n}\n```\n\n```text\n+----------+----------+--------+\n| Argument | Variable | Valid? |\n+----------+----------+--------+\n| String | String | β
|\n| String | String! | β
|\n| String! | String | β |\n| String! | String! | β
|\n+----------+----------+--------+\n```\n\n```text\nnull\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\ngetUser\n```\n\n```text\nid\n```\n\n```text\nstatus\n```\n\n```text\n$foo\n```\n\n```text\nnull\n```\n\n```text\nid\n```\n\n```text\nID\n```\n\n```text\nID!\n```\n\n```text\nID\n```\n\n```text\n$foo\n```\n\n```text\nID\n```\n\n```text\nid\n```\n\n```text\ntype Query\n{\n data(input: InputType!): ResponseType!\n}\n\ninput InputType\n{\n inputField: String!\n}\n\ntype ResponseType\n{\n field: String!\n}\n```\n\n```json\n{\n input: {\n inputField: \"sample text\"\n }\n}\n```\n\n```json\n// error: inputField is null\n{\n input: {\n inputField: null\n }\n}\n\n// error: inputField is null (because it's missing)\n{\n input: {\n }\n}\n\n// error: input is null\n{\n input: null \n}\n\n// error: input is null (because it's missing)\n{\n}\n```\n\n```json\n{\n data: {\n field: \"sample text\"\n }\n}\n```\n\n```json\n// error: field is null\n{\n data: {\n field: null\n }\n}\n\n// error: field is null (because it's missing)\n{\n data: {\n }\n}\n\n// error: data is null\n{\n data: null\n}\n```\n\n```text\nnull\n```\n\n```text\n!\n```\n\n```text\nnull\n```\n\n```text\n!\n```\n\n```text\n!\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- I wrote quite long post on GraphQL, in general :) blog.ditectrev.com/blog/software-development/web-services/… enjoy\n- This took longer to find out than I expected. Even the GraphQL cheatsheets and the Prisma and Apollo docs didn't seem to mention that explicitly.\n- Documentation link with nifty highlighting (works in Chrome): graphql.org/learn/schema/….\n- makes sense right? if `?` often means nullable, then `!` would mean non-nullable","metadata":{"transformedAt":"2026-08-18T18:32:36.017Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":299,"estimatedTokens":1331}}4{"id":"stack-53930305","source":"stackoverflow","questionId":53930305,"title":"Nodemon Error: \"System limit for number of file watchers reached\"","tags":["node.js","graphql","nodemon"],"text":"Title: Nodemon Error: \"System limit for number of file watchers reached\"\nTags: node.js, graphql, nodemon\nSource: Stack Overflow\n\nQuestion:\nI'm learning GraphQL and am using `prisma-binding` for GraphQL operations. I'm facing this `nodemon` error while I'm starting my Node.js server and its giving me the path of schema file which is auto generated by a `graphql-cli`. What is this error all about?\n\nError:\n\nInternal watch failed: ENOSPC: System limit for number of file watchers reached, watch '/media/rehan-sattar/Development/All projects/GrpahQl/graph-ql-course/graphql-prisma/src/generated\n\n========================================\n\nTop Answer:\nYou need to increase the inotify watchers limit for users of your system. You can do this from the command line with:\n\n```\nsudo sysctl -w fs.inotify.max_user_watches=100000\n```\n\nThat will persist only until you reboot, though. To make this permanent, add a file named `/etc/sysctl.d/10-user-watches.conf` with the following contents:\n\n```\nfs.inotify.max_user_watches = 100000\n```\n\nAfter making the above (or any other) change, you can reload the settings from all sysctl configuration files in `/etc` with `sudo sysctl --system`. (On older systems you may need to use `sudo sysctl -p` instead.)\n\n========================================\n\nCode:\n```text\nprisma-binding\n```\n\n```text\nnodemon\n```\n\n```text\ngraphql-cli\n```\n\n```bash\n$ cat /proc/sys/fs/inotify/max_user_watches\n```\n\n```bash\n$ sudo sysctl fs.inotify.max_user_watches=131070\n$ sudo sysctl -p\n```\n\n```bash\necho fs.inotify.max_user_watches= 131070 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p\n```\n\n```bash\necho fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p\n```\n\n```text\nsudo npm start\n```\n\n```none\nsudo sysctl -w fs.inotify.max_user_watches=100000\n```\n\n```none\nfs.inotify.max_user_watches = 100000\n```\n\n```text\n/etc/sysctl.d/10-user-watches.conf\n```\n\n```text\n/etc\n```\n\n```text\nsudo sysctl --system\n```\n\n```text\nsudo sysctl -p\n```\n\n```none\nsysctl -w fs.inotify.max_user_watches=524288\n```\n\n```none\nnpm run serve\n```\n\n```none\ncat /etc/sysctl.conf | tail -n 2\nfs.inotify.max_user_watches=524288\n\nsudo systemctl restart systemd-sysctl.service\n```\n\n```sh\nfunction get_inode_watcher_count() {\n find /proc/*/fd -user \"$USER\" -lname anon_inode:inotify -printf '%hinfo/%f\\n' 2>/dev/null | \n xargs cat | \n grep -c '^inotify'\n}\n\nfunction set_inode_watchers() {\n sudo sysctl -w fs.inotify.max_user_watches=\"$1\"\n}\n\nfunction double_inode_watchers() {\n watcher_count=\"$(get_inode_watcher_count)\"\n set_inode_watchers \"$((watcher_count * 2))\"\n\n if test \"$1\" = \"-p\" || test \"$1\" = \"--persist\"; then\n echo \"fs.inotify.max_user_watches = $((watcher_count * 2))\" > /etc/sysctl.d/10-user-watches.conf\n fi\n}\n\n# Usage\ndouble_inode_watchers\n# to make the change persistent\ndouble_inode_watchers --persist\n```\n\n```text\nmodule.exports = {\n watchOptions: {\n ignored: /node_modules/\n }\n};\n```\n\n```text\nnodemon server.js\n```\n\n```none\nsudo sysctl -w fs.inotify.max_user_watches=100000\n```\n\n```none\nfs.inotify.max_user_watches = 10000\n```\n\n```text\nsudo sysctl -p\n```\n\n```text\nsudo systemctl restart systemd-sysctl.service\n```\n\n```none\n/etc/sysctl.d/10-user-watches.conf\n/usr/lib/sysctl.d/30-tracker.conf <<< Older file, with lower limit\n```\n\n```text\nsudo sysctl --system\n```\n\n```text\nman sysctl.d\n```\n\n```text\n/etc/sysctl.d/*.conf\n```\n\n```text\n/run/sysctl.d/*.conf\n```\n\n```text\n/usr/lib/sysctl.d/*.conf\n```\n\n```text\nexport default defineConfig({\n server: {\n watch: {\n ignored: ['**/venv/**'],\n }\n },\n})\n```\n\n========================================\n\nComments:\n- This is the linux ulimit error see here stackoverflow.com/questions/34588/…\n- Tried this! Getting the same error again!\n- You are probably watching too many files. Maybe it's including the nod_modules directory as well?\n- `node_modules` are essential because all the packages are there. I've tried to kill the previous processes running on the port of my server, it worked for me but I don't know how long it will take now :D\n- That's right! Because of VSCode. It should be autosave mode.\n- this worked for me; developing with ember-cli\n- As w/my focal box this happens intermittently and the VSCode restart is the fix w/out fiddling w/max-_user_watches. (note: When it is working, I typically see watchers in use well below 7k)\n- I think I have the same problem but with my Nextcloud client. How do I stop and restart the watcher? I couldn't search for the right term to get a proper answer.\n- Same situation (Ubuntu/VS Code). It might help to close any folders in the folder tree that you're not currently working on, maybe even hiding the explorer altogether (not sure if VS Code has watchers for currently visible files and folders in Explorer).\n- Same here with web storm in JetBrains (Ubuntu), restart/invalidating cache did the trick.\n- This will often work because root usually has a much higher inotify watch limit than regular users, but it's a *very* bad idea to be running things as root when they don't need to be. See my answer to this question for how to change the user limit.\n- Thank you so much! Worked for me!! But where i have to add this file?\n- @RehanSattar Create a file `/etc/sysctl.d/10-user-watches.conf` and in it put `fs.inotify.max_user_watches = 100000`.\n- Putting this here for completeness `echo fs.inotify.max_user_watches=100000 | sudo tee /etc/sysctl.d/10-user-watches.conf && sudo sysctl -p`.\n- use `sysctl --system` to reload for more recent systems\n- Is there a way to see the current value before updating it (eg to double the current value instead of using an arbitrary 100000)? Edit: it is `sudo sysctl fs.inotify.max_user_watches`, on my machine default is 65536\n- Also this answer seems to not work for Linux (either outdated or Mac-only?), see answer below using `/etc/sysctl.conf` file instead\n- @EricBurel It's a Linux-only answer; I've never tried this on Mac. However, the option to reload all sysctl files was incorrect; I've fixed it.\n- use `sysctl --system` to reload for more recent systems\n- is there any other implications that we must know when we do this? I knew this helps solve the issue, I tried it myself. But I am a bit skeptic what possible side effects this fix can cause.\n- @Aldee about the technical implications of this change I recommend checking this wiki: github.com/guard/listen/wiki/…\n- This also worked out a lot of issues with npm plugins. thx\n- Thank you! I had the same error on a React project I have just created and that has fixed it.\n- I wouldn't recommend increasing it so much if you're not sure how many are in use. Check the number in use with the following `find /proc/*/fd -user \"$USER\" -lname anon_inode:inotify -printf '%hinfo/%f\\n' 2>/dev/null | xargs cat | grep -c '^inotify'`\n- I actually have `max_user_watches` 4288 and excluded in `nodemonconfig` in `package.json` `.git` and `node_modules`. I wonder why there are so many files still which lead to the error.\n- Default value (on Ubuntu 21) was 65535 and setting it to just twice that value (131070) fixed the Node JS issues for me. So according to the principle of minimizing side effects, it is worth trying smaller increments before going all the way to 500k.\n- Note that changing `/etc/sysctl.conf` may result in your change conflicting with or being overwritten by an OS upgrade, depending on your distribution. Better is to use a separate file in `/etc/sysctl.d/`, as described in this answer.\n- Doesn't work for me sadly!\n- This helped me out in a situation where I was upgrading `Laravel 8` > `Laravel 9` and swapping out `Laravel Mix` for `vite` & `Laravel Vite`. The `vite build` command worked fine, but `vite` caused the `ENOSPC: System limit for number of file watchers reached`. Running the above command fixed `vite`, and I didn't have to reboot my machine, or my hosts!\n- On Ubuntu 22.04, I had to name the file `50-user-watches.conf` to make sure it got priority. To confirm the priority of what setting is being applied, run `sudo sysctl --system | grep max_user_watches -B2` and you'll see what setting is applied last and by which file.\n- The \"technical implications\" link above from @IsacMoura can now be found here: github.com/guard/listen/blob/…\n- Folks, thanks for the comments. I updated this question following the suggestions. 500K of limit is a huge limit (even though the documentation suggest that size) and I updated following the suggestion of @Dmitriy\n- To \"twice\" a number, you double it and add 1. `twice(x): 2x + 1`\n- This works for me, without restarting my ubuntu system.\n- running this command more than once appends the file repeatedly /etc/sysctl.conf file repeatedly, and additionally, the comment from @mofojed was important to make sure the change is persisted\n- This hint for test temporarily is priceless. Thank you\n- Worked for me as well. I had basically two VSCode open. Closing the previous one solved the issue.\n- this surprisingly worked!\n- Missing a zero in item 2\n- Ya, if anyone's reading this, the suggested limit of 10000 is ~1/6 of Ubuntu's default limit (65536). You'll likely want it to be much higher.\n- There is nothing in the question about the platform. Can you add the Linux distribution, version, etc. to the answer (but ********************* ***without*** ********************* \"Edit:\", \"Update:\", or similar - the answer should appear as if it was written today)?","metadata":{"transformedAt":"2026-08-18T18:32:36.017Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":236,"estimatedTokens":2370}}5{"id":"stack-34199982","source":"stackoverflow","questionId":34199982,"title":"How can I query all the GraphQL type fields without writing a long query?","tags":["php","laravel","graphql","graphql-php"],"text":"Title: How can I query all the GraphQL type fields without writing a long query?\nTags: php, laravel, graphql, graphql-php\nSource: Stack Overflow\n\nQuestion:\nAssume you have a GraphQL type and it includes many fields.\nHow can I query all the fields without writing down a long query that includes the names of all the fields?\n\nFor example, if I have these fields:\n\n```\npublic function fields()\n {\n return [\n 'id' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The id of the user'\n ],\n 'username' => [\n 'type' => Type::string(),\n 'description' => 'The email of user'\n ],\n 'count' => [\n 'type' => Type::int(),\n 'description' => 'login count for the user'\n ]\n\n ];\n }\n```\n\nTo query all the fields, usually the query is something like this:\n\n```\nFetchUsers{users(id:\"2\"){id,username,count}}\n```\n\nBut I want a way to have the same results without writing all the fields. Something like this:\n\n```\nFetchUsers{users(id:\"2\"){*}}\n\n// Or\nFetchUsers{users(id:\"2\")}\n```\n\nIs there a way to do this in GraphQL?\n\nI'm using the *Folkloreatelier/laravel-graphql* library.\n\n========================================\n\nTop Answer:\nYes, you **can** do this using introspection. Make a GraphQL query like (for type **UserType**)\n\n```\n{\n __type(name:\"UserType\") {\n fields {\n name\n description\n } \n }\n}\n```\n\nand you'll get a response like (actual field names will depend on your actual schema/type definition)\n\n```\n{\n \"data\": {\n \"__type\": {\n \"fields\": [\n {\n \"name\": \"id\",\n \"description\": \"\"\n },\n {\n \"name\": \"username\",\n \"description\": \"Required. 150 characters or fewer. Letters, digits, and @/./+/-/_ only.\"\n },\n {\n \"name\": \"firstName\",\n \"description\": \"\"\n },\n {\n \"name\": \"lastName\",\n \"description\": \"\"\n },\n {\n \"name\": \"email\",\n \"description\": \"\"\n },\n ( etc. etc. ...)\n ]\n }\n }\n}\n```\n\nYou can then read this list of fields in your client and dynamically build a second GraphQL query to get the values of these fields.\n\nThis relies on you knowing the name of the type that you want to get the fields for -- if you don't know the type, you could get all the types and fields together using introspection like\n\n```\n{\n __schema {\n types {\n name\n fields {\n name\n description\n }\n }\n }\n}\n```\n\nNOTE: This is the over-the-wire GraphQL data -- you're on your own to figure out how to read and write with your actual client. Your GraphQL javascript library may already employ introspection in some capacity. For example, the apollo codegen command uses introspection to generate types.\n\n**2022 Update**\n\nSince this answer was originally written, it is now a recommended security practice to *TURN OFF* introspection in production. References: Why you should disable GraphQL introspection in production and OWASP | Testing GraphQL. I recommend that you consider if these risks pertain to you.\n\nFor an environment where introspection is off in production, you could use it in development as a way to assist in creating a static query that was used in production; you wouldn't actually be able to create a query dynamically in production.\n\n========================================\n\nCode:\n```text\npublic function fields()\n {\n return [\n 'id' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The id of the user'\n ],\n 'username' => [\n 'type' => Type::string(),\n 'description' => 'The email of user'\n ],\n 'count' => [\n 'type' => Type::int(),\n 'description' => 'login count for the user'\n ]\n\n ];\n }\n```\n\n```text\nFetchUsers{users(id:\"2\"){id,username,count}}\n```\n\n```text\nFetchUsers{users(id:\"2\"){*}}\n\n// Or\nFetchUsers{users(id:\"2\")}\n```\n\n```text\nfragment UserFragment on Users {\n id\n username\n count\n} \n\nFetchUsers {\n users(id: \"2\") {\n ...UserFragment\n }\n}\n```\n\n```text\nmodule Graph\n module Types\n JsonType = GraphQL::ScalarType.define do\n name \"JSON\"\n coerce_input -> (x) { x }\n coerce_result -> (x) { x }\n end\n end\nend\n```\n\n```text\nfield :location, Types::JsonType\n```\n\n```text\n{\n __type(name:\"UserType\") {\n fields {\n name\n description\n } \n }\n}\n```\n\n```text\n{\n \"data\": {\n \"__type\": {\n \"fields\": [\n {\n \"name\": \"id\",\n \"description\": \"\"\n },\n {\n \"name\": \"username\",\n \"description\": \"Required. 150 characters or fewer. Letters, digits, and @/./+/-/_ only.\"\n },\n {\n \"name\": \"firstName\",\n \"description\": \"\"\n },\n {\n \"name\": \"lastName\",\n \"description\": \"\"\n },\n {\n \"name\": \"email\",\n \"description\": \"\"\n },\n ( etc. etc. ...)\n ]\n }\n }\n}\n```\n\n```text\n{\n __schema {\n types {\n name\n fields {\n name\n description\n }\n }\n }\n}\n```\n\n```text\n# Only most used selection properties\n\nfragment UserDetails on User {\n id,\n username\n}\n```\n\n```text\nFetchUsers {\n users() {\n ...UserDetails\n }\n}\n```\n\n```text\nFetchUserById($id: ID!) {\n users(id: $id) {\n ...UserDetails\n count\n }\n}\n```\n\n```text\nconst ExampleUser = {\n id: \"u_01\",\n firstName: \"Seph\",\n}\n\nconst ExamplePermission = {\n id: \"p_01\",\n userId: \"u_01\",\n type: \"admin\"\n}\n\ntype User = typeof ExampleUser;\ntype Perm = typeof ExamplePermission;\n\nconst UserFields = Array.from(Object.keys(ExampleUser))\nconst PermFields = Array.from(Object.keys(ExamplePermission))\n\n// an overview of all gql possibilities, could be generated\nconst gqlMapOverview = {\n Users: {\n fields: UserFields,\n Perms: {\n fields: PermFields,\n }\n },\n Perms: {\n fields: PermFields,\n }\n}\n\nfunction createGqlString(map, queryObj){ /*real work goes here*/ }\n\nconst queryString = createGqlString(gqlMapOverview, {\n Users: {\n _filter: { where: { firstName: \"Seph\" }, limit: 2 },\n Perms: {}\n }\n})\n\nqueryString == `Users(firstName: \"Seph\", _limit: 2) {\n id,\n firstname,\n Perms { id, userId, type }\n}`\n```\n\n========================================\n\nComments:\n- You're asking how to do something that GraphQL, by design, does not support.\n- It makes sense that it isnt supported, imagine you have Student and Class objects, student have field \"classes\" that lists all the classes he attends, class has field \"students\" that lists all students that attends that class. Thats a cyclical structure. Now if you request for all students with all fields, would that also include all fields of classes returned? And those classes has students, would their fields be included too? And students have classes, ...\n- I had this question and it was so that I could see what was even available to pull. Lots of GraphQL clients (e.g. GraphiQL, see gatsbyjs.org/docs/running-queries-with-graphiql) have a schema explorer that uses the introspection to present you with what you can pull, if that's the reason behind wanting to get \"everything\".\n- Here is the discussion: github.com/graphql/graphql-spec/issues/127\n- I'm sorry, can I just say GraphQL sucks? I can get all the data in 1 request instead of 2... yay...! Give me the equivalent of `SELECT *` and I'll reconsider... I'm not interested in saving 20 bytes by leaving out an email address field either.\n- Exactly @aross, if they wanted to have validation they could let as query for some really required fields, and let the rest of them be, for example {user, email, ...}\n- @aross its more than just leaving out the email address in the response. its the ability to completely omit retrieving it if you don't need it. Imagine that one client needs the e-mail address and another doesn't but fetching the e-mail address adds significant latency to the response. You don't have unnecessary latency on a client that doesn't require the field that causes the latency.\n- We had to to write long reusable arrays of fields on the client so we could use select * .., so buggy.. there is no requirement GraphQL needed. Switch to tRPC, enjoy life, go outside, see some sun.\n- For fields that may change or be dynamic, make them type Json and then you can sneak in any substructure you need and bypass GQL fussiness.\n- You can get the demo results here to match things. It gives all deep insights. allfiletools.com/graphql-tester\n- If I did that, then still I have to write each field name \"at least in the fragment\", witch what I was trying to avoid, it seems that GraphQL force us to be explicit.\n- how to add this in a POSTMan query? or jquery/UI framwork to make a stringified JSON . This graphiQL seems useless for actual development purpose.\n- This is solely for reuse purpose.\n- @BlackSigma Considering GraphQL documentation, this should be the accepted as best answer\n- @JPVentura: No my friend, there is a difference between reusability and wildcard both in concept and application. The fragment purpose is clear in the documentation \" GraphQL includes reusable units called fragments.\" Using fragment is useful, but is not the answer for the question.\n- It depends on if you have control over the API or not. If you do, you could create an fragment for all fields. Yes, you have to know the top-level type you are requesting, but that is reasonable, especially given the other features of GraphQL listed, like introspection.\n- Ok, and if I request some object of an unknown form from backend which I'm supposed to proxy or send back?\n- @meandre, the whole idea of graphql is that there is no such thing as an \"unkown form\".\n- Isn't it the whole idea of most API query languages and protocols?, @meandre\n- Though accurate, this is not a very useful answer. It would at least be helpful to have links and excerpts to official documentation on this topic.\n- @s.meijer That's all very nice on paper. Except that in the real world, devs just request the entire thing and looking at the keys and values quickly get an idea of what's possible and what isn't. GraphQL requires much more careful consideration of the documentation in this way, sometimes for things that are relatively benign. Also very annoying is that if you need all or most properties, you still have to enumerate them *all* just to retrieve the info. It seems like inspiration taken from SQL but important parts left out. Consider `SELECT *`\n- It's a bad and buggy 'mindset' for clients that use typed classes (95% of them). If they can give use the ability to query an object that would be great.\n- another reason to not use graphql\n- For those of you who think this is a bad thing, think about how often you've typed \"SELECT * FROM...\" when you really only needed a few or even one field and assured yourself that you'd fix it later.\n- This is exactly what I needed, thank you. My use case is I have user-translatable strings throughout the system, and they are stored as json in the db like `{\"en\": \"Hello\", \"es\": \"Hola\"}`. And since each user can implement their own subset of languages for their use case, it doesn't make sense for the UI to query every possible subset. Your example works perfectly.\n- `Otherwise it is defeating the object of GraphQL more generally speaking.` Who cares?\n- I don't understand enough Ruby to understand what exactly you did, but I assume you wrote code to represent the foreign object, and then just send an enumeration of its properties over the line? In any case, +1\n- @aross basically this is a straight pass through of a hashmap. in Typescript it would be `any` or `unknown`, in golang it would be `map[string]interface{}` regardless, you are defining a custom type which just passes through whatever it receives. WRT your previous comment. Anyone who is trying to use GraphQL to shape and limit data over the wire, provide security for certain attributes or provide a Typesafe API. That's who.\n- This is a global change, right? It seems like a more local change (i.e. specific to one model's schema) could be to add a field (perhaps fields, columns, or whatever name would be more meaningful) and write a resolver that returns a json representation of all of the schema's fields. Then, the query only has to return fields. And, other developers on your team will be clued in to the unique need for that model's schema to have that representation.\n- type Json is they key and it will save you from going insane with GQL\n- Seems like one should express care about recursive types. If you went down the tree and bumped on to a type which contains itself, in some form (list, single or other..), you could be in for an infinite recursion.\n- That doesn't actually happen in my experience with this particular query -- the query itself defines the resolution depth.\n- The above answer only allows you the query the types of fields available in a query. It doesn't return all the object fields \"values\", which is what the original question is about.\n- As per the answer, you have to dynamically build a second query based on the results of the first query -- I left that as an exercise for the reader.\n- And the user that will do the exercise will discover the type **UserType** has a property *fields* which is an array of objects containing *name* and *description* properties - which he already knew since that's exactly what he asked in his former query.\n- @GinQueen I've tweaked my answer to be more clear -- the second query is to get the values of those fields from the first query, not the names of the fields.\n- Can introspection be disabled in production, causing this to break?\n- This is a great question -- some quick research indicates that not only is the answer yes ( see apollographql.com/blog/graphql/security/… ) but is actually a recommended practice. I will add a caveat to my answer.\n- @MarkChackerian great, that's makes this wonderful answer useless IRL.\n- Just because one commercial company (that is selling a schema registry service) writes a blog post saying introspection may be a security risk in production, does not make it an industry standard or a recommended practice. It is just scare tactics by Apollo to get more $$$. Unless you are doing something really dumb like putting your trade secrets in your field descriptions, there is very little actual risk.\n- @Phil we can hope its low risk for most, but it would be unethical not to mention any security risks, especially since googling GraphQL introspection exploit has plenty of results.\n- Tip: If you want to know the types of the fields, then add `type {\\n name\\n kind\\n}` to the `fields` object.\n- This question is about `php` and not `node.js`\n- Can you explain further how to do this?","metadata":{"transformedAt":"2026-08-18T18:32:36.018Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":368,"estimatedTokens":3636}}6{"id":"stack-49835264","source":"stackoverflow","questionId":49835264,"title":"How to properly make mock throw an error in Jest?","tags":["javascript","meteor","graphql","jestjs"],"text":"Title: How to properly make mock throw an error in Jest?\nTags: javascript, meteor, graphql, jestjs\nSource: Stack Overflow\n\nQuestion:\nI'm testing my GraphQL api using Jest.\n\nI'm using a separate test suit for each query/mutation\n\nI have 2 tests (each one in a separate test suit) where I mock one function (namely, Meteor's `callMethod`) that is used in mutations.\n\n```\nit('should throw error if email not found', async () => {\n callMethod\n .mockReturnValue(new Error('User not found [403]'))\n .mockName('callMethod');\n\n const query = FORGOT_PASSWORD_MUTATION;\n const params = { email: 'user@example.com' };\n\n const result = await simulateQuery({ query, params });\n\n console.log(result);\n\n // test logic\n expect(callMethod).toBeCalledWith({}, 'forgotPassword', {\n email: 'user@example.com',\n });\n\n // test resolvers\n });\n```\n\nWhen I `console.log(result)` I get \n\n```\n{ data: { forgotPassword: true } }\n```\n\nThis behaviour is not what I want because in `.mockReturnValue` I throw an Error and therefore expect `result` to have an error object\n\nBefore this test, however, another is ran\n\n```\nit('should throw an error if wrong credentials were provided', async () => {\n callMethod\n .mockReturnValue(new Error('cannot login'))\n .mockName('callMethod');\n```\n\nAnd it works fine, the error is thrown\n\nI guess the problem is that mock doesn't get reset after the test finishes.\nIn my `jest.conf.js` I have `clearMocks: true`\n\nEach test suit is in a separate file, and I mock functions before tests like this:\n\n```\nimport simulateQuery from '../../../helpers/simulate-query';\n\nimport callMethod from '../../../../imports/api/users/functions/auth/helpers/call-accounts-method';\n\nimport LOGIN_WITH_PASSWORD_MUTATION from './mutations/login-with-password';\n\njest.mock(\n '../../../../imports/api/users/functions/auth/helpers/call-accounts-method'\n);\n\ndescribe('loginWithPassword mutation', function() {\n...\n```\n\n**UPDATE**\n\nWhen I substituted `.mockReturnValue` with `.mockImplementation` everything worked out as expected:\n\n```\ncallMethod.mockImplementation(() => {\n throw new Error('User not found');\n});\n```\n\nBut that doesn't explain why in another test `.mockReturnValue` works fine...\n\n========================================\n\nTop Answer:\nFor promises, can use https://jestjs.io/docs/mock-function-api#mockfnmockrejectedvaluevalue\n\n```\ntest('async test', async () => {\n const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));\n\n await asyncMock(); // throws \"Async error\"\n});\n```\n\nFor testing that error was thrown or not, can use https://eloquentcode.com/expect-a-function-to-throw-an-exception-in-jest\n\n```\nconst func = () => {\n throw new Error('my error')\n}\nit('should throw an error', () => {\n expect(func).toThrow()\n})\n```\n\n========================================\n\nCode:\n```text\nit('should throw error if email not found', async () => {\n callMethod\n .mockReturnValue(new Error('User not found [403]'))\n .mockName('callMethod');\n\n const query = FORGOT_PASSWORD_MUTATION;\n const params = { email: 'user@example.com' };\n\n const result = await simulateQuery({ query, params });\n\n console.log(result);\n\n // test logic\n expect(callMethod).toBeCalledWith({}, 'forgotPassword', {\n email: 'user@example.com',\n });\n\n // test resolvers\n });\n```\n\n```text\n{ data: { forgotPassword: true } }\n```\n\n```text\nit('should throw an error if wrong credentials were provided', async () => {\n callMethod\n .mockReturnValue(new Error('cannot login'))\n .mockName('callMethod');\n```\n\n```text\nimport simulateQuery from '../../../helpers/simulate-query';\n\nimport callMethod from '../../../../imports/api/users/functions/auth/helpers/call-accounts-method';\n\nimport LOGIN_WITH_PASSWORD_MUTATION from './mutations/login-with-password';\n\njest.mock(\n '../../../../imports/api/users/functions/auth/helpers/call-accounts-method'\n);\n\ndescribe('loginWithPassword mutation', function() {\n...\n```\n\n```text\ncallMethod.mockImplementation(() => {\n throw new Error('User not found');\n});\n```\n\n```text\ncallMethod\n```\n\n```text\nconsole.log(result)\n```\n\n```text\n.mockReturnValue\n```\n\n```text\nresult\n```\n\n```text\njest.conf.js\n```\n\n```text\nclearMocks: true\n```\n\n```text\n.mockReturnValue\n```\n\n```text\n.mockImplementation\n```\n\n```text\n.mockReturnValue\n```\n\n```text\nyourMockInstance.mockImplementation(() => {\n throw new Error();\n });\n```\n\n```text\ntest('the fetch fails with an error', () => {\n return expect(fetchData()).rejects.toMatch('error');\n });\n```\n\n```text\n.mockReturnValue\n```\n\n```text\n.mockImplementation\n```\n\n```text\nimport { throwError } from 'rxjs';\n\nyourMockInstance.mockImplementation(() => {\n return throwError(new Error('my error message'));\n});\n```\n\n```text\ntest('async test', async () => {\n const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));\n\n await asyncMock(); // throws \"Async error\"\n});\n```\n\n```text\nconst func = () => {\n throw new Error('my error')\n}\nit('should throw an error', () => {\n expect(func).toThrow()\n})\n```\n\n```text\nimport fetchApi from '../src'\n\nit(\"should throw error\", async () => {\n const errorMessage: string = \"Network Error\";\n \n (axios.post as jest.Mock).mockRejectedValueOnce(new Error(errorMessage));\n \n expect(async () => await fetchApi()).rejects.toThrow(\n errorMessage\n );\n});\n```\n\n```text\nthrow new Error('Network error or something')\n```\n\n```text\ncatch\n```\n\n========================================\n\nComments:\n- It looks like your mock is *returning* an error object, not *throwing* it. Without seeing your code that you are testing, I can only the experience I had. I forgot to mock a function called in my mutation, which caused an error to be thrown unintentionally. Perhaps there is something similar happening for you?\n- Do you manage to make this test not log an error to the console? All my mocks which throws causes an error of \"Unexpected error\" to appear in the console, even with the test passing.\n- cool. How to handle it and make and assert?\n- it throws the error but then the test fails because it has thrown an error. how do we assert?\n- @schlingel wrap the function call in a try/catch, put your expect()... in the catch\n- @theman0123 Instead of `try`/`catch` in the test, use `await expect(fnThatThrows()).rejects.toThrow(\"some error message or type\")` so it's first-class Jest with a clear error and proper logging, cleaner syntax. Basically what this answer and many others suggest.\n- Technically this isn't a `throw` in the pure JS sense. You are configuring the mock to return a RXJS observable object which immediately emits an error notification. Still, maybe handy for folks to see here. The accepted answer certainly *will* make a mock throw an error. In all cases.\n- Only returning `throw Error` should be enough: `yourMockInstance.mockImplementation(() => throwError('my error message'));`\n- Actually using `mockReturnValue` is enough: `mockInstance.mockReturnValue(throwError(() => new Error('my error message')))`\n- You would also need a try and catch in your expect otherwise it would not assert correctly. Can you please improve your answer or reply if I am missing something.\n- @MGDeveloper we dont need try-catch while unit testing and using toThrow() (jestjs.io/docs/expect#tothrowerror). If you try that in your tests, it should work. Can also test in here : codesandbox.io/s/jest-playground-forked-euewe?file=/src/… (sandbox content is transient though). I did edit the terminology from \"handling\" to \"testing\" if that was confusing\n- I found the mockRejectedValue helpful in the case that the asynchronous unit I was testing handled the exception thrown in a specific way that I wanted to test, therefore in that case a catch or toThrow() would not be needed.","metadata":{"transformedAt":"2026-08-18T18:32:36.018Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":283,"estimatedTokens":1936}}7{"id":"stack-37397886","source":"stackoverflow","questionId":37397886,"title":"Get GraphQL whole schema query","tags":["schema","graphql"],"text":"Title: Get GraphQL whole schema query\nTags: schema, graphql\nSource: Stack Overflow\n\nQuestion:\nI want to get the schema from the server.\nI can get all entities with the types but I'm unable to get the properties.\n\nGetting all types:\n\n```\nquery {\n __schema {\n queryType {\n fields {\n name\n type {\n kind\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n}\n```\n\nHow to get the properties for type:\n\n```\n__type(name: \"Person\") {\n kind\n name\n fields {\n name\n type {\n kind\n name\n description\n }\n }\n }\n```\n\nHow can I get all types with the properties in only 1 request? Or ever better: How can I get the whole schema with the mutators, enums, types ...\n\n========================================\n\nTop Answer:\nThis is the query that GraphiQL uses (network capture):\n\n```\nquery IntrospectionQuery {\n __schema {\n queryType {\n name\n }\n mutationType {\n name\n }\n subscriptionType {\n name\n }\n types {\n ...FullType\n }\n directives {\n name\n description\n locations\n args {\n ...InputValue\n }\n }\n }\n}\n\nfragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n}\n\nfragment InputValue on __InputValue {\n name\n description\n type {\n ...TypeRef\n }\n defaultValue\n}\n\nfragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n __schema {\n queryType {\n fields {\n name\n type {\n kind\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n}\n```\n\n```text\n__type(name: \"Person\") {\n kind\n name\n fields {\n name\n type {\n kind\n name\n description\n }\n }\n }\n```\n\n```text\n# install via NPM\nnpm install -g graphql-cli\n\n# Setup your .graphqlconfig file (configure endpoints + schema path)\ngraphql init\n\n# Download the schema from the server\ngraphql get-schema\n```\n\n```text\ngraphql get-schema --watch\n```\n\n```text\nnpm install -g get-graphql-schema\n```\n\n```text\nget-graphql-schema ENDPOINT_URL > schema.graphql\n```\n\n```text\nget-graphql-schema ENDPOINT_URL --json > schema.json\n```\n\n```text\nget-graphql-schema ENDPOINT_URL -j > schema.json\n```\n\n```text\ngraphql-cli\n```\n\n```text\nimport { introspectionQuery } from 'graphql';\n```\n\n```text\n{\n __schema: {\n types: {\n ...fullType\n }\n }\n}\n```\n\n```text\nfragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n fragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n }\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n`;\n```\n\n```html\nquery IntrospectionQuery {\n __schema {\n queryType {\n name\n }\n mutationType {\n name\n }\n subscriptionType {\n name\n }\n types {\n ...FullType\n }\n directives {\n name\n description\n locations\n args {\n ...InputValue\n }\n }\n }\n}\n\nfragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n}\n\nfragment InputValue on __InputValue {\n name\n description\n type {\n ...TypeRef\n }\n defaultValue\n}\n\nfragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nschema.json\n```\n\n```text\n~$ npx apollo-cli download-schema $GRAPHQL_URL --output schema.json\n```\n\n```text\n\"schema\": {\n\"README_request\" : \"To request the schema from a url instead, remove the 'file' JSON property above (and optionally delete the default graphql.schema.json file).\",\n\"request\": {\n \"url\" : \"http://localhost:4000\",\n \"method\" : \"POST\",\n \"README_postIntrospectionQuery\" : \"Whether to POST an introspectionQuery to the url. If the url always returns the schema JSON, set to false and consider using GET\",\n \"postIntrospectionQuery\" : true,\n \"README_options\" : \"See the 'Options' section at https://github.com/then/then-request\",\n \"options\" : {\n \"headers\": {\n \"user-agent\" : \"JS GraphQL\"\n }\n }\n}\n```\n\n```text\nLoaded schema from 'http://localhost:4000': {\"data\":{\"__schema\":{\"queryType\":{\"name\":\"Query\"},\"mutationType\":{\"name\":\"Mutation\"},\"subscriptionType\":null,\"types\":[{\"kind\":\"OBJECT\",\"name\":\"Query\",\"description\":\"\",\"fields\":[{\"name\":\"launche\n```\n\n```text\nJS GraphQL\n```\n\n```text\napollo codegen:client\n```\n\n```text\nnpx apollo schema:download --endpoint=http://localhost:4000/graphql schema.json\n```\n\n```text\n{\n \"projects\": {\n \"graphqlProjectTestingGraphql\": {\n \"schemaPath\": \"schema.graphql\",\n \"extensions\": {\n \"endpoints\": {\n \"dev\": {\n \"url\": \"https://api.github.com/graphql\",\n \"headers\": {\n \"Authorization\": \"Bearer <Your token here>\"\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\ngraphql init\n```\n\n```sh\nnpm install -g graphqurl\n\ngq <endpoint> --introspect > schema.graphql\n\n# or if you want it in json\ngq <endpoint> --introspect --format json > schema.json\n```\n\n```text\ngraphqurl\n```\n\n```sh\nnpm install --save graphql\nnpm install --save-dev @graphql-codegen/cli\nnpx graphql-codegen init\n```\n\n```yaml\nschema:\n - 'http://localhost:3000/graphql'\ngenerates:\n path/to/file.graphql:\n plugins:\n - schema-ast\n config:\n includeDirectives: true\n```\n\n```text\ncodegen.yml\n```\n\n```text\nnpm install --save-dev @graphql-codegen/schema-ast\n```\n\n```text\ncodegen.yml\n```\n\n```bash\n$ gql-sdl https://api.github.com/graphql -H \"Authorization: Bearer ghp_[redacted]\"\ndirective @requiredCapabilities(requiredCapabilities: [String!]) on OBJECT | SCALAR | ARGUMENT_DEFINITION | INTERFACE | INPUT_OBJECT | FIELD_DEFINITION | ENUM | ENUM_VALUE | UNION | INPUT_FIELD_DEFINITION\n\n\"\"\"Autogenerated input type of AbortQueuedMigrations\"\"\"\ninput AbortQueuedMigrationsInput {\n \"\"\"The ID of the organization that is running the migrations.\"\"\"\n ownerId: ID!\n\n \"\"\"A unique identifier for the client performing the mutation.\"\"\"\n clientMutationId: String\n}\n...\n```\n\n```js\nconst fs = require(\"fs\");\nconst { buildClientSchema, getIntrospectionQuery, printSchema } = require(\"graphql\");\nconst fetch = require(\"node-fetch\");\n\nasync function saveSchema(endpoint, filename) {\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ query: getIntrospectionQuery() })\n });\n const graphqlSchemaObj = buildClientSchema((await response.json()).data);\n const sdlString = printSchema(graphqlSchemaObj);\n fs.writeFileSync(filename, sdlString);\n}\n\nsaveSchema(\"https://example.com/graphql\", \"schema.graphql\");\n```\n\n```text\n-H\n```\n\n```text\n--json\n```\n\n```text\ngetIntrospectionQuery()\n```\n\n```text\nbuildClientSchema()\n```\n\n```text\nprintSchema()\n```\n\n```text\nfragment FullType on __Type {\n kind\n name\n fields(includeDeprecated: true) {\n name\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n}\nfragment InputValue on __InputValue {\n name\n type {\n ...TypeRef\n }\n defaultValue\n}\nfragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n}\nquery IntrospectionQuery {\n __schema {\n queryType {\n name\n }\n mutationType {\n name\n }\n types {\n ...FullType\n }\n directives {\n name\n locations\n args {\n ...InputValue\n }\n }\n }\n}\n```\n\n```text\nquery IntrospectionQuery {\n __schema {\n queryType {\n name\n }\n mutationType {\n name\n }\n subscriptionType {\n name\n }\n types {\n ...FullType\n }\n directives {\n name\n description\n\n locations\n args {\n ...InputValue\n }\n }\n }\n}\n\nfragment FullType on __Type {\n kind\n name\n description\n\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n}\n\nfragment InputValue on __InputValue {\n name\n description\n type {\n ...TypeRef\n }\n defaultValue\n}\n\nfragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nIntrospectionQuery\n```\n\n```text\nquery {\n _service {\n sdl\n }\n}\n```\n\n========================================\n\nComments:\n- I ended using the introspectionQuery from 'graphql'; as described at the bottom. It's fine.\n- This should be at the top!\n- In newer versions of `graphql` this is now a function called `getIntrospectionQuery()`\n- The answer that was marked the solution was not implementable with the GraphQL server I was trying to use but this library did exactly what was required to generate a full schema. It probably should be marked the solution.\n- The --json should go before the >\n- @Catharz: Nowhere does the question state that the OP does not want to use Node or JavaScript. Furthermore, this answer does not require using JavaScript *libraries*; it presents a command-line tool that happens to be *written* in JavaScript.\n- I followed the step and `graphql get-schema` doesn't write to the schema.graphql file. It output to the screen, however. I don't know why.\n- how to pass authentication header to the `graphql get-schema`\n- This answer is actually out of date - see github.com/Urigo/graphql-cli/blob/master/docs/… Re headers, you in your gql config you can do `schema: { YOUR/ENDPOINT: { headers: {Authorization: \"Token your_token\"}}}`\n- `graphql get-schema` does not do anything for me - prints nothing, does not throw an error. `get-graphql-schema` says Authorization is not a correct header. `Insomnia` uses this header just fine.\n- It seems `get-schema` was removed from graphql-cli, or at the very least moved to an optional module\n- I coouldn't get `graphql-cli` to work (and it seems to be a somewhat abandoned project). This works though: graphql-code-generator.com/plugins/schema-ast\n- github.com/graphcool/get-graphql-schema github.com/gabrielf/graphql-schema-from-introspection . Two separated packages FYI.\n- The same query is used by Postwoman, but the UI only shows the relevant types when you click on the \"Get schema\" button.\n- Version 2 of this plugin will be soon available (now it's beta: github.com/jimkyndemeyer/js-graphql-intellij-plugin/releases‌​/… ). Instead of `graphql.config.json` file, there is `.graphqlconfig` file. You have to set field `schemaPath` to non-existing file (it will be auto created after downloading schema) and `url` to GraphQL remote server. Next, in tab \"Schemas and project structure\" (in \"GraphQL\" tab), double click on selected \"Endpoint\" and click \"Get GraphQL Schema from Endpoint (introspection)\". In previously mentioned file will be downloaded schema.\n- use npx apollo client:download-schema --endpoint=localhost:4000/graphql schema.json\n- link returns 404\n- @Raj just fixed\n- This library is now unmaintained with outdated and vulnerable dependencies.\n- `gql-sdl` does the job really well with no upfront configuration, thanks! Usage example: `gql-sdl http://localhost:4000/graphql -o schema-autogenerated.graphql -H \\\"Authorization: Bearer \"`","metadata":{"transformedAt":"2026-08-18T18:32:36.018Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":40,"totalLines":808,"estimatedTokens":3657}}8{"id":"stack-38071714","source":"stackoverflow","questionId":38071714,"title":"When and How to use GraphQL with microservice architecture","tags":["architecture","microservices","graphql"],"text":"Title: When and How to use GraphQL with microservice architecture\nTags: architecture, microservices, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to understand where GraphQL is most suitable to use within a microservice architecture.\n\nThere is some debate about having only 1 GraphQL schema that works as API Gateway proxying the request to the targeted microservices and coercing their response. Microservices still would use REST / Thrift protocol for communication though.\n\nAnother approach is instead to have multiple GraphQL schemas one per microservice. Having a smaller API Gateway server that route the request to the targeted microservice with all the information of the request + the GraphQL query.\n\n**1st Approach**\n\nHaving 1 GraphQL Schema as an API Gateway will have a downside where every time you change your microservice contract input/output, we have to change the GraphQL Schema accordingly on the API Gateway Side.\n\n**2nd Approach**\n\nIf using Multiple GraphQL Schema per microservices, make sense in a way because GraphQL enforces a schema definition, and the consumer will need to respect input/output given from the microservice.\n\n**Questions**\n\nWhere do you find GraphQL the right fit for designing microservice architecture?\n\nHow would you design an API Gateway with a possible GraphQL implementation?\n\n========================================\n\nTop Answer:\nThis article recommends approach #1. See the below image too, taken from the mentioned article:\nhttps://i.sstatic.net/BrnFy.png\n\nOne of the main benefits of having everything behind a single endpoint is that data can be routed more effectively than if each request had its own service. While this is the often touted value of GraphQL, a reduction in complexity and service creep, the resultant data structure also allows data ownership to be extremely well defined, and clearly delineated.\n\nAnother benefit of adopting GraphQL is the fact that you can fundamentally assert greater control over the data loading process. Because the process for data loaders goes into its own endpoint, you can either honor the request partially, fully, or with caveats, and thereby control in an extremely granular way how data is transferred.\n\nThe following article explains these two benefits along with others very well: https://nordicapis.com/7-unique-benefits-of-using-graphql-in-microservices/\n\n========================================\n\nCode:\n```text\ngraphql-weaver\n```\n\n```text\n@apollo/federation\n```\n\n```text\n@apollo/gateway\n```\n\n```text\nversion: '3'\n\nservices:\n service1:\n build: service1\n service2:\n build: service2\n gateway:\n ports:\n - 80:80\n image: xmorse/apollo-federation-gateway\n environment: \n - CACHE_MAX_AGE=5\n - \"FORWARD_HEADERS=Authorization, X-Custom-Header\" # default is Authorization, pass '' to reset\n - URL_0=http://service1\n - URL_1=http://service2\n```\n\n```text\nOne Platform\n```\n\n========================================\n\nComments:\n- Checkout this video\n- For a demo example, you can see the results here. allfiletools.com/graphql-tester to help other for live testing.\n- @helfer: This really make sense :) thanks. I have few questions on top of this gorgeous answer. - You are saying that GraphQL has to be used as API gateway? - Let's say i have an **Order** Microservice which expose Either a REST or GraphQL end point. Once i finished with it I have to update the main GraphQL schema to reflect the exactly the same data that the microservice will expose? Does it not sound duplication or moving away from microservice culture which should be independenty deployed? Any changes to a microservice has to be reflected / duplicated to the Main GraphQL Schema?\n- @Fabrizio the nice thing with GraphQL is that even if the backend REST API changes, the GraphQL schema can still stay the same, as long as there's a way to get the data that the REST service previously exposed. If it exposes more data, then the canonical way to deal with this is to just add new fields/types to the existing schema. The folks at Facebook who created GraphQL told me they've never made a breaking change to their schema in four years. All the changes they made were additive, which means that new clients could use the new functionality, while old clients would continue to work.\n- Right! :) Thanks to write this up! I'm following you on Medium and on github through apollo repos! Your articles and posts are very valuable! :) Keep up the good work! I also think that a medium article with topic GraphQL + Microservices will be very enjoyable to read!\n- Thanks, I'll keep that in mind. Definitely planning to write about about GraphQL and Microservices at some point, but probably not in the next couple of weeks.\n- How about the combination of option #2 and github.com/AEB-labs/graphql-weaver ?\n- (I agree with solution #1) You may have a look at the BFF pattern (\"Backend For Frontend\"), for which GraphQL seems a perfect fit. This would mean a GraphQL endpoint by client.\n- I am learning GraphQL, have one query. In the first approach, if GraphQL is down then all the micro-services will go down. In other approach at least other services will be up.\n- Using GraphQL in Android is imperative that I create a .graphql file with all the queries? Or can I just create them in the code without this file?\n- @MauroAlexandro I'm not an android guy, but you can have the queries in different files. It's more a design problem. IMHO, I prefer the first one :)\n- HI, sorry for the noob questions, but isn't your graphQL gateway a new retention point? Eg if I have a basket service that is suddenly over sollicited, would'nt my graphQL gateway break too? Basically I am not sure of its role, this gateway is supposed to contain a lot of resolvers for each service?\n- @EricBurel Thanks for the question. Actually, as far as I understood from the article, all the schema from different services are unified under one GraphQL schema, so as you mentioned, other services are still resides on their own datasets. Regarding possibility of single source of failure for graphQL gateway, there are always other options like providing a backup plan. Please read this article (labs.getninjas.com.br/…) for more information. Hope this helps.\n- How do you test the central API gateway and the individual services? Are you doing integration or mocking http response?\n- @JaimeSangcap, in my experience integration tests are written against both: direct to the back-end to test complex workflows & edge cases as well as integration tests that hit the proxy to test common \"API user journeys\".\n- it's also valid to know that this solution demands Apollo Server which is slightly limited in free version (max 25 millions queries per month)","metadata":{"transformedAt":"2026-08-18T18:32:36.018Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":94,"estimatedTokens":1699}}9{"id":"stack-44737043","source":"stackoverflow","questionId":44737043,"title":"Is it possible to not return any data when using a GraphQL mutation?","tags":["java","graphql"],"text":"Title: Is it possible to not return any data when using a GraphQL mutation?\nTags: java, graphql\nSource: Stack Overflow\n\nQuestion:\nI have several GraphQL queries and mutations, now I'm trying to implement a *delete* mutation without returning any data:\n\n```\ntype Mutation{\n addElement(element: ElementData): ID\n removeElement(id: ID): ΒΏ?\n }\n```\n\nHowever, it seems to be required to have a return value for the delete operation. Is there a way to perform an \"empty\" response in GraphQL? I would like to avoid things like returning a boolean or status flag if possible. \n\nI'm not sure on what are the best practices for GraphQL delete operations.\n\n========================================\n\nTop Answer:\nAccording to this Github issue you cannot return nothing.\n\nYou can define a return type which is nullable e.g.\n\n\r\n\r\n\n```\ntype Mutation {\r\n addElement(element: ElementData): ID\r\n removeElement(id: ID): Boolean\r\n}\n```\n\n\r\n\r\n\r\n\nBut I suggest you return the id of the deleted element, because if you want to work with a cached store you have to update the store when the delete mutation has ran successfully.\n\n========================================\n\nCode:\n```text\ntype Mutation{\n addElement(element: ElementData): ID\n removeElement(id: ID): ΒΏ?\n }\n```\n\n```text\n# file: ./schema.gql\n\nscalar Void\n```\n\n```js\n// file ./scalar-void.js\n\nimport { GraphQLScalarType } from 'graphql'\n\nconst Void = new GraphQLScalarType({\n name: 'Void',\n\n description: 'Represents NULL values',\n\n serialize() {\n return null\n },\n\n parseValue() {\n return null\n },\n\n parseLiteral() {\n return null\n }\n})\nexport Void\n```\n\n```js\n# file: ./server.js\n\nimport { ApolloServer } from 'apollo-server-express'\nimport { Void } from './scalar-void'\n\nconst server = new ApolloServer({\n typeDefs, // use your schema\n resolvers: {\n Void: Void,\n // ... your resolvers\n },\n \n})\n```\n\n```text\n# file: ./schema.gql\n\ntype Mutation{\n addElement(element: ElementData): ID\n removeElement(id: ID): Void\n}\n```\n\n```text\ngraphql-scalars\n```\n\n```text\ngraphql-scalars\n```\n\n```text\nnpm install graphql-scalars\n```\n\n```text\nVoid\n```\n\n```text\nscalar\n```\n\n```text\nvoid\n```\n\n```text\ngraphql-void\n```\n\n```text\nVoid\n```\n\n```text\nVoid\n```\n\n```text\nVoid\n```\n\n```text\nscalar\n```\n\n```js\ntype Mutation {\n addElement(element: ElementData): ID\n removeElement(id: ID): Boolean\n}\n```\n\n```text\nscalar Void\n\ntype Mutation {\n removeElement(id: ID): Void\n}\n```\n\n```yaml\nconfig:\n scalars:\n Void: \"void\"\n```\n\n```text\ngraphql-codegen\n```\n\n```text\nremoveElement\n```\n\n```text\nnull\n```\n\n```text\nnpm i graphql-scalars\n```\n\n```text\ntype Mutation {\n\n invokeNullMutation: Void\n\n}\n```\n\n```java\n@Internal\npublic class GraphQLVoidScalar {\n\n static final Coercing<Void, Void> COERCING = new Coercing<>() {\n\n @Override\n public Void serialize(Object dataFetcherResult, GraphQLContext graphQLContext, Locale locale) {\n return null;\n }\n\n @Override\n public Void parseValue(Object input, GraphQLContext graphQLContext, Locale locale) {\n return null;\n }\n\n @Override\n public Void parseLiteral(Value<?> input, CoercedVariables variables, GraphQLContext graphQLContext, Locale locale) {\n return null;\n }\n\n @Override\n public Value<?> valueToLiteral(Object input, GraphQLContext graphQLContext, Locale locale) {\n return Coercing.super.valueToLiteral(input, graphQLContext, locale);\n }\n };\n\n public static final GraphQLScalarType INSTANCE = GraphQLScalarType\n .newScalar()\n .name(\"Void\")\n .description(\"Void scalar wrapper\")\n .coercing(COERCING)\n .build();\n\n}\n```\n\n```java\npublic class GraphQLConfiguration {\n\n @Bean\n public RuntimeWiringConfigurer runtimeWiringConfigurer() {\n\n return wiringBuilder -> wiringBuilder\n .scalar(GraphQLCustomScalars.VOID);\n\n }\n\n}\n```\n\n========================================\n\nComments:\n- You could go out of your way to introduce a `Void` type as shown below, but **the return value is how the client tells whether an operation succeeded.** It's possible for the request to succeed (e.g., status 200) and yet one or more mutations fail (e.g., because of a database error).\n- In case of deletion you are better off returning the product ID, as suggested (since it's graphql, perhaps even the whole product). However, some operations truly require no data. For those cases one could define `type Void` and then do `someOperation(input: InputObject!): Void` to indicate the intent clearly.\n- An example of a mutation that needs to return value is a logout, which would just destroy the session.\n- @Sandy, even with a logout mutation, a client may still want to know whether the operation succeeded (in which case a return value is necessary). A mutation that truly needs no return value would be one in which the API developer wants *no* client to know whether it succeeded or not. I'm sure there are examples, but they are likely uncommon.\n- @Arel, that is what Exceptions are for\n- What part of the linked \"GQL best practices\" do you suggest is saying that a void-returning mutation is bad practise? I was unable to find any such recommendation.\n- @MEMark graphql-rules.com/rules/mutation-payload : *\"Every mutation should have a unique payload type\"* . and I'm going to update the link in the answer\n- graphql-rules.com seems dead.","metadata":{"transformedAt":"2026-08-18T18:32:36.018Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":258,"estimatedTokens":1365}}10{"id":"stack-50189364","source":"stackoverflow","questionId":50189364,"title":"Shouldn't the login be a Query in GraphQL?","tags":["graphql"],"text":"Title: Shouldn't the login be a Query in GraphQL?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nIn the tutorial on GraphQL authentication, the `login` is a **Mutation**:\n\n```\ntype Mutation {\n post(url: String!, description: String!): Link!\n signup(email: String!, password: String!, name: String!): AuthPayload\n login(email: String!, password: String!): AuthPayload\n}\n```\n\nShouldn't the login be a ***Query*** since:\n\n- The operation has no side-effects on the server.\n\n- The goal is to *query* a token.\n\nAm I missing something here ?\n\n========================================\n\nTop Answer:\nNo, login should be a mutation.\n\nThe 2 assumptions are generally incorrect for a login process.\n\n- The operation has no side-effects on the server.\n\n- The goal is to query a token.\n\nBefore login, the token does not exist on both the server and client side.\n\nDuring login, the token was created by the server and sent to the client side.\n\nAfter login, the server side accepts one more token that was just created.\n\nSo login DO create something. It definitely mutates the system state (by allowing 1 more token in the system).\n\nThe illusion that you may think that the login has no side effects it's just because the token is not stored on the server side. Just think the client side is a special database for storing the login tokens.\n\nSo\n\n- The login operation has side effects on the server side, which will accept 1 more token\n\n- The goal of the login operation is to create a token.\n\nThus, the login is definitely a mutation, it mutates the whole system.\n\n========================================\n\nCode:\n```text\ntype Mutation {\n post(url: String!, description: String!): Link!\n signup(email: String!, password: String!, name: String!): AuthPayload\n login(email: String!, password: String!): AuthPayload\n}\n```\n\n```text\nlogin\n```\n\n```text\nlogin\n```\n\n```text\nreact-apollo\n```\n\n```text\nuseQuery\n```\n\n```text\nuseMutation\n```\n\n```text\nlogin\n```\n\n========================================\n\nComments:\n- Sorry for the late reply, From my understanding, A mutation is what modifying your data and query is just retrieving so Login should be Query. π\n- `Mutations are ran sequentially, while queries are ran simultaneously` this was some good observation. I had no idea about. Thank you. Helps in some decision making on whether to resolve as a mutation or query.\n- Note Apollo now have a hook \"useLazyQuery\" which won't query the data until you trigger manually the load, quite similar to useMutation. But currently it does not return a promise (see github.com/apollographql/react-apollo/issues/3499)\n- This x 100. If `mutation` was instead called (the admittedly less catchy) \"imperative, non-cached query\" it would be more apparent that it's exactly what you want in this scenario. If debating semantics is your thing, I highly recommend switching to a REST API where you can drink your fill.\n- My colleague throws this answer in my face when we are discussing if a login should be a query or mutation. I can not believe that no one stands out to point out the issue here. See my answer to this question.","metadata":{"transformedAt":"2026-08-18T18:32:36.018Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":95,"estimatedTokens":774}}11{"id":"stack-41510880","source":"stackoverflow","questionId":41510880,"title":"what's the difference between parseValue and parseLiteral in GraphQLScalarType","tags":["graphql","graphql-js"],"text":"Title: what's the difference between parseValue and parseLiteral in GraphQLScalarType\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nLooking through the GraphQL documentation for custom scalar types (I'm trying to create my own date type) I'm not sure what the difference between `parseValue` and `parseLiteral` are. \n\nhttp://graphql.org/graphql-js/type/#graphqlscalartype\n\nThe documentation doesn't seem to include any descriptions of what the functions are supposed to do.\n\nCan someone let me know what the requirements are? I'm assuming that `serialize` must serialize the scalar to a string. Is that correct? I'm assuming that parseLiteral is a deserialization of that string to the type? In my case a Date type. However, in the examples - serialize and parseValue are the same function - which suggests it's not a simple deserialization method.\n\n========================================\n\nCode:\n```text\nparseValue\n```\n\n```text\nparseLiteral\n```\n\n```text\nserialize\n```\n\n```text\nquery {\n allUsers(first:10) {\n id\n }\n}\n```\n\n```text\nquery ($howMany: YourCustomType) {\n users(first: $howMany) {\n id\n }\n}\n```\n\n```text\n{\n \"howMany\": {\n \"thisMany\": 10\n }\n}\n```\n\n```text\nfunction parseValue(value) {\n let first = value.thisMany;\n return first;\n}\n```\n\n```text\nserialize\n```\n\n```text\nserialize\n```\n\n```text\nparseValue\n```\n\n```text\nparseLiteral\n```\n\n```text\n10\n```\n\n```text\nfirst\n```\n\n```text\n10\n```\n\n```text\nparseLiteral\n```\n\n```text\nparseLiteral\n```\n\n```text\nparseValue\n```\n\n========================================\n\nComments:\n- would you where did you get that information?\n- @thisdotvoid to be honest i don't remember, i think i read the source code since i was interested! you can find some good stuff here: graphql.org/graphql-js/type\n- Hey @Aα΄ΙͺΚ any idea why `PaseLiteral` gets called twice?\n- @Hannan I don't know, maybe it's related to your code? or perhaps there's a good reason for that. You're welcome to create a new stackoverflow question, someone might beable to help! :)\n- Excellent explanation I've ever read! Really appreciate your findings\n- This explanation must be uploaded to the official article :)","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":108,"estimatedTokens":539}}12{"id":"stack-39962867","source":"stackoverflow","questionId":39962867,"title":"How do I add a description to a field in \"GraphQL schema language\"","tags":["javascript","graphql","apollo-server"],"text":"Title: How do I add a description to a field in \"GraphQL schema language\"\nTags: javascript, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI have a graphql schema, a fragment of which looks like this:\n\n```\ntype User {\n username: String!\n password: String!\n}\n```\n\nIn graphiql, there is a description field, but it always says \"self-descriptive\". How do I add descriptions to the schema?\n\n========================================\n\nTop Answer:\nThis is a great question! And actually has a great history in `graphql` world.\n\nThere were multiple issues, discussions, and Pull Requests on the `graphql-js` repo that tried to discuss possible syntax for this, as it was something that a lot of members of the community felt were needed. Thanks to Lee Byron and this Pull Request, we can actually add descriptions to a schema language by using traditional comments.\n\nFor example,\n\n```\n// Grab some helpers from the `graphql` project\nconst { buildSchema, graphql } = require('graphql');\n\n// Build up our initial schema\nconst schema = buildSchema(`\nschema {\n query: Query\n}\n\n# The Root Query type\ntype Query {\n user: User\n}\n\n# This is a User in our project\ntype User {\n # This is a user's name\n name: String!\n\n # This is a user's password\n password: String!\n}\n`);\n```\n\nAnd, if we're using `graphql` that's newer than `0.7.0`, the comments are actually turned into the description for the fields or types. We can verify this by running an introspection query on our schema:\n\n```\nconst query = `\n{\n __schema {\n types {\n name\n description,\n fields {\n name\n description\n }\n }\n }\n}\n`;\n\ngraphql(schema, query)\n .then((result) => console.log(result));\n```\n\nWhich would give us a result that looks like:\n\n```\n{\n \"data\": {\n \"__schema\": {\n \"types\": [\n {\n \"name\": \"User\",\n \"description\": \"This is a User in our project\",\n \"fields\": [\n {\n \"name\": \"name\",\n \"description\": \"This is a user's name\"\n },\n {\n \"name\": \"password\",\n \"description\": \"This is a user's password\"\n }\n ]\n },\n ]\n }\n }\n}\n```\n\nAnd shows us that the `#` comments were incorporated as the descriptions for the fields/comments that we put them on.\n\nHope that helps!\n\n========================================\n\nCode:\n```text\ntype User {\n username: String!\n password: String!\n}\n```\n\n```text\n# A type that describes the user\ntype User {\n # The user's username, should be typed in the login field.\n username: String!\n # The user's password.\n password: String!\n}\n```\n\n```text\n\"\"\"\nA type that describes the user. Its description might not \nfit within the bounds of 80 width and so you want MULTILINE\n\"\"\"\ntype User {\n \"The user's username, should be typed in the login field.\"\n username: String!\n \"The user's password.\"\n password: String!\n\n}\n```\n\n```text\n// Grab some helpers from the `graphql` project\nconst { buildSchema, graphql } = require('graphql');\n\n// Build up our initial schema\nconst schema = buildSchema(`\nschema {\n query: Query\n}\n\n# The Root Query type\ntype Query {\n user: User\n}\n\n# This is a User in our project\ntype User {\n # This is a user's name\n name: String!\n\n # This is a user's password\n password: String!\n}\n`);\n```\n\n```text\nconst query = `\n{\n __schema {\n types {\n name\n description,\n fields {\n name\n description\n }\n }\n }\n}\n`;\n\ngraphql(schema, query)\n .then((result) => console.log(result));\n```\n\n```text\n{\n \"data\": {\n \"__schema\": {\n \"types\": [\n {\n \"name\": \"User\",\n \"description\": \"This is a User in our project\",\n \"fields\": [\n {\n \"name\": \"name\",\n \"description\": \"This is a user's name\"\n },\n {\n \"name\": \"password\",\n \"description\": \"This is a user's password\"\n }\n ]\n },\n ]\n }\n }\n}\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql-js\n```\n\n```text\ngraphql\n```\n\n```text\n0.7.0\n```\n\n```text\n#\n```\n\n```text\ngraphql-java\n```\n\n========================================\n\nComments:\n- PS hash your passwords kids!\n- This is no longer the default, see: github.com/graphql/graphql-js/blob/master/src/utilities/… -- should be a string literal like `\"My description\"`\n- So string literals are the current default as of February 2018.\n- Relevant part of spec: graphql.github.io/graphql-spec/June2018/#sec-Descriptions\n- If anybody is looking for how to do it in TypeGraphQL, just use the `description` property in decorator options. eg. `@ObjectType({description:'Here'})`. Same for `@Field({description:...}, @Arg and @Query`\n- Very helpful thanks - I did search for a long time for an answer, and was struggling through lots of old issues - when the answer was so simple! :)\n- Yes, took me a while to find as well. TYVM!\n- I'm using graphql 0.12.3 and this isn't working for me. Description is always null using the code above.","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":244,"estimatedTokens":1211}}13{"id":"stack-46111514","source":"stackoverflow","questionId":46111514,"title":"Field \\\"me\\\" of type \\\"User\\\" must have a selection of subfields","tags":["javascript","graphql","graphql-js"],"text":"Title: Field \\\"me\\\" of type \\\"User\\\" must have a selection of subfields\nTags: javascript, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nHi I am trying to learn `GraphQL` language. I have below snippet of code.\n\n```\n// Welcome to Launchpad!\n// Log in to edit and save pads, run queries in GraphiQL on the right.\n// Click \"Download\" above to get a zip with a standalone Node.js server.\n// See docs and examples at https://github.com/apollographql/awesome-launchpad\n\n// graphql-tools combines a schema string with resolvers.\nimport { makeExecutableSchema } from 'graphql-tools';\n\n// Construct a schema, using GraphQL schema language\nconst typeDefs = `\n type User {\n name: String!\n age: Int!\n }\n\n type Query {\n me: User\n }\n`;\n\nconst user = { name: 'Williams', age: 26};\n\n// Provide resolver functions for your schema fields\nconst resolvers = {\n Query: {\n me: (root, args, context) => {\n return user;\n },\n },\n};\n\n// Required: Export the GraphQL.js schema object as \"schema\"\nexport const schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n});\n\n// Optional: Export a function to get context from the request. It accepts two\n// parameters - headers (lowercased http headers) and secrets (secrets defined\n// in secrets section). It must return an object (or a promise resolving to it).\nexport function context(headers, secrets) {\n return {\n headers,\n secrets,\n };\n};\n\n// Optional: Export a root value to be passed during execution\n// export const rootValue = {};\n\n// Optional: Export a root function, that returns root to be passed\n// during execution, accepting headers and secrets. It can return a\n// promise. rootFunction takes precedence over rootValue.\n// export function rootFunction(headers, secrets) {\n// return {\n// headers,\n// secrets,\n// };\n// };\n```\n\nRequest:\n\n```\n{\n me\n}\n```\n\nResponse:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Field \\\"me\\\" of type \\\"User\\\" must have a selection of subfields. Did you mean \\\"me { ... }\\\"?\",\n \"locations\": [\n {\n \"line\": 4,\n \"column\": 3\n }\n ]\n }\n ]\n}\n```\n\nDoes anyone know what I am doing wrong ? How to fix it ?\n\n========================================\n\nCode:\n```text\n// Welcome to Launchpad!\n// Log in to edit and save pads, run queries in GraphiQL on the right.\n// Click \"Download\" above to get a zip with a standalone Node.js server.\n// See docs and examples at https://github.com/apollographql/awesome-launchpad\n\n// graphql-tools combines a schema string with resolvers.\nimport { makeExecutableSchema } from 'graphql-tools';\n\n// Construct a schema, using GraphQL schema language\nconst typeDefs = `\n type User {\n name: String!\n age: Int!\n }\n\n type Query {\n me: User\n }\n`;\n\nconst user = { name: 'Williams', age: 26};\n\n// Provide resolver functions for your schema fields\nconst resolvers = {\n Query: {\n me: (root, args, context) => {\n return user;\n },\n },\n};\n\n// Required: Export the GraphQL.js schema object as \"schema\"\nexport const schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n});\n\n// Optional: Export a function to get context from the request. It accepts two\n// parameters - headers (lowercased http headers) and secrets (secrets defined\n// in secrets section). It must return an object (or a promise resolving to it).\nexport function context(headers, secrets) {\n return {\n headers,\n secrets,\n };\n};\n\n// Optional: Export a root value to be passed during execution\n// export const rootValue = {};\n\n// Optional: Export a root function, that returns root to be passed\n// during execution, accepting headers and secrets. It can return a\n// promise. rootFunction takes precedence over rootValue.\n// export function rootFunction(headers, secrets) {\n// return {\n// headers,\n// secrets,\n// };\n// };\n```\n\n```text\n{\n me\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Field \\\"me\\\" of type \\\"User\\\" must have a selection of subfields. Did you mean \\\"me { ... }\\\"?\",\n \"locations\": [\n {\n \"line\": 4,\n \"column\": 3\n }\n ]\n }\n ]\n}\n```\n\n```text\nGraphQL\n```\n\n```text\n{\n me {\n name\n }\n}\n```\n\n```text\nUser\n```\n\n```text\nname\n```\n\n```text\nage\n```\n\n========================================\n\nComments:\n- Is there a way to do this dynamically? For example: there is a object of language keys that have translated string values. But only return the key/value pair that matches the current language key? eg ``` title: { en: \"English Title\", de: \"German Title\", ... } ```\n- You can do that using a combination of variables and the `@skip` or `@include` directive. graphql.org/learn/queries/#directives","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":213,"estimatedTokens":1140}}14{"id":"stack-34011964","source":"stackoverflow","questionId":34011964,"title":"What is the point of naming queries and mutations in GraphQL?","tags":["graphql"],"text":"Title: What is the point of naming queries and mutations in GraphQL?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nPardon the naive question, but I've looked all over for the answer and all I've found is either vague or makes no sense to me. Take this example from the GraphQL spec:\n\n```\nquery getZuckProfile($devicePicSize: Int) {\n user(id: 4) {\n id\n name\n profilePic(size: $devicePicSize)\n }\n}\n```\n\nWhat is the point of naming this query `getZuckProfile`? I've seen something about GraphQL documents containing multiple operations. Does naming queries affect the returned data somehow? I'd test this out myself, but I don't have a server and dataset I can easily play with to experiment. But it would be good if something in some document somewhere could clarify this--thus far all of the examples are super simple single queries, or are queries that are named but that don't explain why they are (other than \"here's a cool thing you can do.\") What benefits do I get from naming queries that I don't have when I send a single, anonymous query per request?\n\nAlso, regarding mutations, I see in the spec:\n\n```\nmutation setName {\n setName(name: \"Zuck\") {\n newName\n }\n}\n```\n\nIn this case, you're specifying `setName` twice. Why? I get that one of these is the field name of the mutation and is needed to match it to the back-end schema, but why not:\n\n```\nmutation {\n setName(name: \"Zuck\") {\n...\n```\n\nWhat benefit do I get specifying the same name twice? I get that the first is likely arbitrary, but why isn't it noise? I have to be missing something obvious, but nothing I've found thus far has cleared it up for me.\n\n========================================\n\nTop Answer:\nWe use named queries so that they can be monitored consistently, and so that we can do persistent storage of a query. The duplication is there for query variables to fill the gaps.\n\nAs an example:\n\n```\nquery getArtwork($id: String!) {\n artwork(id: $id) {\n title\n }\n}\n```\n\nYou can run it against the Artsy GraphQL API here\n\nThe advantage is that the same query each time, not a different string because the *query variables* are the bit that differs. This means you can build tools on top of those queries because you can treat them as immutable.\n\n========================================\n\nCode:\n```text\nquery getZuckProfile($devicePicSize: Int) {\n user(id: 4) {\n id\n name\n profilePic(size: $devicePicSize)\n }\n}\n```\n\n```text\nmutation setName {\n setName(name: \"Zuck\") {\n newName\n }\n}\n```\n\n```text\nmutation {\n setName(name: \"Zuck\") {\n...\n```\n\n```text\ngetZuckProfile\n```\n\n```text\nsetName\n```\n\n```text\n{\n user(id: 4) {\n id\n name\n profilePic(size: 200)\n }\n}\n```\n\n```text\nquery getArtwork($id: String!) {\n artwork(id: $id) {\n title\n }\n}\n```\n\n========================================\n\nComments:\n- Do you have a reference for this sentence: `Once you use the query keyword you need to provide a name`? I am faced this problem and I didn't found an official documentation about it\n- The official specification is at spec.graphql.org. Don't take my word for it (read the full spec if you're implementing a server or a library and need a reference) but I think it's actually possible to specify a `query` with the keyword but without a name. I think `mutation` fields still need a name though.\n- The unnamed versions: `query { myName }` and `mutation { setName(name: \"Zuck\") { newName } }` are **both** valid according to the spec: spec.graphql.org/draft/#sec-Root-Operation-Types. Edited the incorrect information out of the answer.\n- Any source with feedback in terms of consequences at scale? Removing query name and injecting values in the query rather than using variables seems fine when the variables are known ahead of time (not using user input), but maybe there are consequences I do not foresee ?","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":118,"estimatedTokens":951}}15{"id":"stack-48331103","source":"stackoverflow","questionId":48331103,"title":"GraphQL gql Syntax Error: Expected Name, found }","tags":["syntax-error","graphql","apollo","react-apollo","graphql-tag"],"text":"Title: GraphQL gql Syntax Error: Expected Name, found }\nTags: syntax-error, graphql, apollo, react-apollo, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nI'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:\n\nSyntax Error: Expected Name, found }\n\nThis is generated by the following code:\n\n```\nimport gql from 'graphql-tag'\n\nconst query = gql`\n {\n user(id: 5) {\n firstName\n lastName\n }\n }\n `\n\nconsole.log(query)\n```\n\nI'm basing this code off the example code found here: https://github.com/apollographql/graphql-tag\n\nWhat is the `Name` referred to in the error message? Does anyone know what I'm doing wrong here?\n\n========================================\n\nTop Answer:\nThis error occurs mostly when there are unclosed curly braces or when some fields are not properly defined while calling the query.\n\n========================================\n\nCode:\n```text\nimport gql from 'graphql-tag'\n\nconst query = gql`\n {\n user(id: 5) {\n firstName\n lastName\n }\n }\n `\n\nconsole.log(query)\n```\n\n```text\ngql\n```\n\n```text\nName\n```\n\n```text\nimport gql from 'graphql-tag'\n\nconst query = gql`\n{\n user(id: 5) {\n firstName\n lastName\n }\n}\n`\n\nexport default query\n```\n\n```text\nconst query=gql`\n user(id: 5) {\n firstName\n lastName\n }\n`\n```\n\n```text\ntype Launch {\n rocket: Rocket\n }\n\n type Rocket {\n name: String\n }\n```\n\n```text\ntype Rocket {\n name: String\n }\n\n type Launch {\n rocket: Rocket\n }\n```\n\n```text\nLaunch\n```\n\n```text\nRocket\n```\n\n```text\nRocket\n```\n\n```text\ntype Settings {\n requires: []\n }\n```\n\n```text\ntype Settings {\n requires: [String]\n }\n```\n\n```text\nGraphQLError: Syntax Error: Expected Name, found ]\n```\n\n```text\n{\n allFilms() {\n films {\n title\n }\n }\n}\n```\n\n```text\n{\n allFilms {\n films { \n }\n }\n}\n```\n\n```text\n{\n allFilms {\n films {\n title \n }\n }\n}\n```\n\n```text\nconst FEATURED_SPEAKER = gql`\n mutation markFeatured($speakerId: ID!, $featured: Boolean!){\n markFeatured(speaker_id: theErrorIsHere$speakerId , featured: $featured){\n id\n featured\n }\n }\n`;\n```\n\n```text\nconst FEATURED_SPEAKER = gql`\n mutation markFeatured($speakerId: ID!, $featured: Boolean!){\n markFeatured(speaker_id: $speakerId , featured: $featured){\n id\n featured\n }\n }\n`;\n```\n\n```text\ntheErrorIsHere\n```\n\n```text\n(\n```\n\n```text\n{\n```\n\n```text\n$varName\n```\n\n```text\n$speakerId\n```\n\n```text\n\"this \"is\" bad\"\n```\n\n```text\nconst GET_POSTS_OF_AUTHOR = gql`\n query GetPostsOfAuthor($authorId: Int!) {\n postsOf($authorId: Int!) {\n id\n title\n }\n }\n`;\n```\n\n```text\nconst GET_POSTS_OF_AUTHOR = gql`\n query GetPostsOfAuthor($authorId: Int!) {\n postsOf(authorId: $authorId) {\n id\n title\n }\n }\n`;\n```\n\n```js\nconst query = `\n query($id: String!) {\n getUser(id: $id) {\n user: {\n id\n name\n email\n createdAt\n }\n }\n }\n`\n```\n\n```js\nuser {\n id\n name\n ...\n}\n```\n\n```text\n:\n```\n\n```text\n:\n```\n\n```text\n:\n```\n\n```text\nlastUpdated(): Date\n```\n\n```text\nlastUpdated: Date\n```\n\n```js\n{\n product(id: \"${id}\") {\n name\n }\n}\n```\n\n```text\ndata {\n property {\n key: {\n deepKey\n }\n }\n}\n```\n\n```text\n:\n```\n\n```text\n${SOME_MAX_VALUE} -> 20\n```\n\n```text\ntype Query{\n oppurtunities():[Oppurtunity!] # in this line i had `()` \n }\n```\n\n```text\ntype Query{\n oppurtunities:[Oppurtunity!] # in this line i had `()` \n }\n```\n\n```text\ntype Query\n```\n\n========================================\n\nComments:\n- It should work. Do you use graphql-tag version 2.6.x?\n- @Win Yes, I am using graphql-tag version 2.6.1\n- Is this relevant? github.com/apollographql/graphql-tag/issues/180\n- Thanks this was my issue as well. Was doing a mutation and could not figure out that it didn't need the exterior curlies.\n- I had the \"Expected Name, found $\" too. What I had done wrong was something like: markfeatured($speaker_id: $speaker_id ... So you can see I did a sloppy copy and paste meaning to get rid or the extra $ but I did not.\n- Thanks buddy. I'm not using NestJS but your suggestion works for me too.\n- It worked for my expressJs code as well. Thanks\n- joke is i re-visited my own answer 2nd time today. (haha)..,\n- thanks for this. i was scratching my head trying to find the problem\n- :) ur welcome .,","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":40,"totalLines":328,"estimatedTokens":1114}}16{"id":"stack-41921137","source":"stackoverflow","questionId":41921137,"title":"Can a GraphQL input type inherit from another type or interface?","tags":["graphql"],"text":"Title: Can a GraphQL input type inherit from another type or interface?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nIs it possible to use inheritance with GraphQL input types?\n\nSomething like that (this, of course, doesn't work with input types):\n\n```\ninterface UserInputInterface {\n firstName: String\n lastName: String\n}\n\ninput UserInput implements UserInputInterface {\n password: String!\n}\n\ninput UserChangesInput implements UserInputInterface {\n id: ID!\n password: String\n}\n```\n\n========================================\n\nTop Answer:\nStarting with the June2018 stable version of the GraphQL spec, an Input Object type can *extend* another Input Object type:\n\n Input object type extensions are used to represent an input object type which has been extended from some original input object type.\n\nThis isn't inheritance per se; you can only extend the base type, not create new types based on it:\n\n```\nextend input MyInput {\n NewField: String\n}\n```\n\nNote there is no name for the new type; the existing `MyInput` type is extended.\n\nThe JavaScript reference implementation has implemented Input Object extensions in GraphQL.js v14 (June 2018), though it's unclear how to actually pass the extended input fields to a query without getting an error.\n\nFor actual type inheritance, see the graphql-s2s library.\n\n========================================\n\nCode:\n```text\ninterface UserInputInterface {\n firstName: String\n lastName: String\n}\n\ninput UserInput implements UserInputInterface {\n password: String!\n}\n\ninput UserChangesInput implements UserInputInterface {\n id: ID!\n password: String\n}\n```\n\n```text\ninput Name {\n firstName: String\n lastName: String\n}\n\ninput UserInput {\n name: Name\n password: String!\n}\n\ninput UserChangesInput {\n name: Name\n id: ID!\n password: String\n}\n```\n\n```text\nextends\n```\n\n```text\nextend input MyInput {\n NewField: String\n}\n```\n\n```text\nMyInput\n```\n\n```text\ninterface Foo {\n id: ID!\n foo: Int!\n}\n\ntype Bar implements Foo @entity {\n id: ID!;\n foo: Int!;\n bar: Int!;\n}\n```\n\n```text\nBar\n```\n\n```text\nFoo\n```\n\n```js\nconst typeDefs = gql`\n directive @inherits(type: String!) on OBJECT\n\n type Car {\n manufacturer: String\n color: String\n }\n \n type Tesla @inherits(type: \"Car\") {\n manufacturer: String\n papa: String\n model: String\n }\n \n type Query {\n tesla: Tesla\n }\n`;\n\nconst resolvers = {\n Query: {\n tesla: () => ({ model: 'S' }),\n },\n Car: {\n manufacturer: () => 'Ford',\n color: () => 'Orange',\n },\n Tesla: {\n manufacturer: () => 'Tesla, Inc',\n papa: () => 'Elon',\n },\n};\n\nclass InheritsDirective extends SchemaDirectiveVisitor {\n visitObject(type) {\n const fields = type.getFields();\n const baseType = this.schema.getTypeMap()[this.args.type];\n Object.entries(baseType.getFields()).forEach(([name, field]) => {\n if (fields[name] === undefined) {\n fields[name] = { ...field };\n }\n });\n }\n}\n\nconst schemaDirectives = {\n inherits: InheritsDirective,\n};\n```\n\n```text\nquery {\n tesla {\n manufacturer\n papa\n color\n model\n }\n}\n```\n\n```json\n{\n \"data\": {\n \"tesla\": {\n \"manufacturer\": \"Tesla, Inc\",\n \"papa\": \"Elon\",\n \"color\": \"Orange\",\n \"model\": \"S\",\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Have you ever figured out answer to your question? I'm facing the exact same one!\n- @LB2 unfortunately not, I'm keeping 2 separate types at the moment repeating properties.\n- Thanks! I'm trying to represent a boolean expression (much like SQL's WHERE clause), and without inheritance, it seems impossible to express an arbitrary boolean expression without possibility of syntax-matching nonsense. Bummer that it's not part of the language.\n- Could your example be \"extended\" further by using the second type in the third one? `input userChangesInput { userInput: UserInput, id: ID! }` ?\n- @WhatWouldBeCool Of course, you can compose the types freely.\n- @kaqqao ok, I would now say that both answers are valuable choices, so have upvoted both. I do like your composition approach, but for cases of adding a few fields, the new extends keyword seems like a simpler approach.\n- As stated by the question, the \"implements\" keyword will only work with `types` and not with `inputs`","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":203,"estimatedTokens":1081}}17{"id":"stack-47523384","source":"stackoverflow","questionId":47523384,"title":"How to Inherit or Extend typeDefs in GraphQL","tags":["inheritance","schema","graphql","extend","extends"],"text":"Title: How to Inherit or Extend typeDefs in GraphQL\nTags: inheritance, schema, graphql, extend, extends\nSource: Stack Overflow\n\nQuestion:\nI have a `type User`. Users can also be a `type TeamMember`. The only difference between a `User` and `TeamMember` is an added field `teamRole: String`. So, Iβd love to do something like the following to avoid having to redundantly define all the user's fieldsβ¦\n\n```\ntype User {\n id: ID!,\n name: String,\n (many other field defs)\n }\n\n type TeamMember extends User {\n teamRole: String,\n }\n```\n\nAnyone aware of a syntax for this? I thought `extend` would be the answer, but it seems more like javascriptβs `prototype`\n\n========================================\n\nTop Answer:\nUsing a schema transpiler like graphql-s2s to achieve inheritance is probably overkill, and graphql-s2s is outdated as of 2021.\n\nHave a look at this Apollo Server directive: https://github.com/jeanbmar/graphql-inherits\n\n```\nconst typeDefs = gql`\n directive @inherits(type: String!) on OBJECT\n\n type Car {\n manufacturer: String\n color: String\n }\n \n type Tesla @inherits(type: \"Car\") {\n manufacturer: String\n papa: String\n model: String\n }\n`;\n\nclass InheritsDirective extends SchemaDirectiveVisitor {\n visitObject(type) {\n const fields = type.getFields();\n const baseType = this.schema.getTypeMap()[this.args.type];\n Object.entries(baseType.getFields()).forEach(([name, field]) => {\n if (fields[name] === undefined) {\n fields[name] = field;\n }\n });\n }\n}\n```\n\n========================================\n\nCode:\n```text\ntype User {\n id: ID!,\n name: String,\n (many other field defs)\n }\n\n type TeamMember extends User {\n teamRole: String,\n }\n```\n\n```text\ntype User\n```\n\n```text\ntype TeamMember\n```\n\n```text\nUser\n```\n\n```text\nTeamMember\n```\n\n```text\nteamRole: String\n```\n\n```text\nextend\n```\n\n```text\nprototype\n```\n\n```text\nconst sharedFields = `\n foo: String\n bar: String\n`\nconst typeDefs = `\n type A {\n ${sharedFields}\n }\n\n type B {\n ${sharedFields}\n }\n`\n```\n\n```text\ntype A {\n a: Int\n foo: String\n bar: String\n}\n\ntype B {\n b: Int\n foo: String\n bar: String\n}\n```\n\n```text\ntype X {\n foo: String\n bar: String\n aOrB: AOrB\n}\n\nunion AOrB = A | B\n\ntype A {\n a: Int\n}\n\ntype B {\n b: Int\n}\n```\n\n```text\nextend\n```\n\n```text\nQuery\n```\n\n```text\ngraphql-s2s\n```\n\n```js\nconst typeDefs = gql`\n directive @inherits(type: String!) on OBJECT\n\n type Car {\n manufacturer: String\n color: String\n }\n \n type Tesla @inherits(type: \"Car\") {\n manufacturer: String\n papa: String\n model: String\n }\n`;\n\nclass InheritsDirective extends SchemaDirectiveVisitor {\n visitObject(type) {\n const fields = type.getFields();\n const baseType = this.schema.getTypeMap()[this.args.type];\n Object.entries(baseType.getFields()).forEach(([name, field]) => {\n if (fields[name] === undefined) {\n fields[name] = field;\n }\n });\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks! This is exactly what I was looking for. Well, not exactly, since ideally I wouldn't have needed another package, but `graphql-s2s` gives me what I needed. I'm using `graphql-yoga` as my server, so I had to `monkey patch their typeDefs` declaration, which is also less than idea. If you know of a better way, I'm all ears. Thanks!\n- Is it true this is still not available as of mid-2019?\n- @A.com Yes. You can see the latest specification here.\n- but wouldn't you as of early 2020 use `@inherit from` instead?\n- @Alexander that is not a standard directive -- what library is that used by?\n- When I use google to search the exact phrase \"@inherit from\", this stack overflow question is the only page that shows up. You've invented a brand new sentence.","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":198,"estimatedTokens":933}}18{"id":"stack-64436979","source":"stackoverflow","questionId":64436979,"title":"GraphQL optional Query Arguments","tags":["javascript","graphql"],"text":"Title: GraphQL optional Query Arguments\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI know you can set arguments in a schema to default values but is it possible to make the argument `limit` argument completely optional in my GraphQL Schema?\n\nRight now it seems like when I hit this without specifying a limit I think that's why I get `Int cannot represent non-integer value: undefined`\n\n```\nconst schema = buildSchema(`\n companies(limit: Int): [Company]\n...)\n```\n\nhttps://i.sstatic.net/yLF7x.jpg\n\nI want to be able to skip the limit so that it gets all companies.\n\nIn JS, I call it like this:\n\n```\nquery: `query { \n companies(limit: ${limit}) {\n ...\n```\n\nbut sometimes I don't want to specify a limit. So what is happening is the client is sending `crafters(limit: undefined)` and it's probably trying to convert that to Int. I'm not sure how to not send `limit` in and how to make that entire param optional.\n\n(I also read that from the **client** I should be instead specifying the arguments as **variables** like `query($limit: Int) { companies(limit: $limit) {` I guess from my **client**, from **JS**? If so how would I send in my limit **JS variable** into that?\n\n========================================\n\nTop Answer:\nBelow is an example of how you could define a query on client and pass non-required argument. Not sure about your client-side config, but you may want to use a lib like graphql-tag to convert string to AST.\n\n```\nconst GET_COMPANIES = gql`\n query Companies($limit: Int) {\n companies(limit: $limit) {\n ... // return fields\n }\n }\n`;\n```\n\n========================================\n\nCode:\n```text\nconst schema = buildSchema(`\n companies(limit: Int): [Company]\n...)\n```\n\n```text\nquery: `query { \n companies(limit: ${limit}) {\n ...\n```\n\n```text\nlimit\n```\n\n```text\nInt cannot represent non-integer value: undefined\n```\n\n```text\ncrafters(limit: undefined)\n```\n\n```text\nlimit\n```\n\n```text\nquery($limit: Int) { companies(limit: $limit) {\n```\n\n```text\ncompanies(limit: Int): [Company]\n```\n\n```text\ncompanies(limit: Int!): [Company]\n```\n\n```text\nquery ($limit: Int){\n companies (limit: undefined) {\n # ...\n }\n}\n```\n\n```text\nquery ($limit: Int){\n companies (limit: $limit) {\n # ...\n }\n}\n```\n\n```text\nlimit\n```\n\n```text\nlimit\n```\n\n```text\n!\n```\n\n```text\nlimit\n```\n\n```text\nundefined\n```\n\n```text\nInt\n```\n\n```text\nInt!\n```\n\n```text\nconst GET_COMPANIES = gql`\n query Companies($limit: Int) {\n companies(limit: $limit) {\n ... // return fields\n }\n }\n`;\n```\n\n========================================\n\nComments:\n- specify a default value like so - graphql.org/learn/schema/#arguments\n- but if it's optional why do I want a default. I just said I know you can set defaults, bht that I don't want to specify a default. If there is no `limit` specified there's no default I want there. This is for my DB query, if they don't specify a limit, then I don't want that limit in my DB query either. So specifying an integer there is not what I want. I'd have to specify like 0 if that's the case for limit and then check that at the DB JS code level that if it's 0 don't include limit which feels hacky compared to just checking if that limit is undefined lower down\n- I apologize, I simply spammed a link without deeply understanding your question. In my experience I've had too much data not to pass at least some sort of ceiling limit and have always to specify a default as a safety net. GL w/ your implementation\n- I'm doing fine without a third party. I prefer not to use Apollo and stuff like that. I just use JS constants and a query object with string inside. Example: `const query = { query: `query { companies(limit: ${companyLimit}) { ${fields} } }`, };` But it's working without specifying variables so why is it necessary? LOL I just broke stack comments\n- Not completely clear on how your client implementation is working, but based on what I see above, you're literally passing `undefined` with your use of the template literal. If you pass an argument, it needs to be of type Int by your schema def. With what I recommended, you can invoke the query with no variables and should work fine.\n- thanks, makes sense. It was already optional then, I just needed to handle the client query better by taking the limit out.","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":152,"estimatedTokens":1070}}19{"id":"stack-65950407","source":"stackoverflow","questionId":65950407,"title":"Prisma many-to-many relations: create and connect","tags":["typescript","graphql","prisma","prisma-graphql","prisma2"],"text":"Title: Prisma many-to-many relations: create and connect\nTags: typescript, graphql, prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nIn my Prisma schema, I have a many-to-many relationship between posts and categories. I've added `@map` options to match the Postgres snake_case naming convention:\n\n```\nmodel Post {\n id Int @id @default(autoincrement())\n title String\n body String?\n categories PostCategory[]\n\n @@map(\"post\")\n}\n\nmodel Category {\n id Int @id @default(autoincrement())\n name String\n posts PostCategory[]\n\n @@map(\"category\")\n}\n\nmodel PostCategory {\n categoryId Int @map(\"category_id\")\n postId Int @map(\"post_id\")\n category Category @relation(fields: [categoryId], references: [id])\n post Post @relation(fields: [postId], references: [id])\n\n @@id([categoryId, postId])\n @@map(\"post_category\")\n}\n```\n\nI'm trying to create a post with multiple categories at the same time. If a category exists, I'd like to `connect` the category to the post. If the category doesn't exist, I'd like to create it. The creation part is working well, but the connection part is problematic:\n\n```\nawait prisma.post.create({\n data: {\n title: 'Hello',\n categories: {\n create: [{ category: { create: { name: 'News' } } }],\n connect: {\n categoryId_postId: { categoryId: 1, postId: ? }, // This doesn't work, even if I had the postId\n },\n },\n },\n });\n```\n\nHow can I connect an existing category to a new post with the schema that I have?\n\n========================================\n\nTop Answer:\nAfter hours of trying I finally came up with the following solution for my use case.\n\n```\npark[] exercise[]\n```\n\n```\n// create parks\nconst parks = await prisma.park.createMany({data: [...]});\n\n// create and connect exercises\nconst exercises = [...];\nawait Promise.all(\n exercises.map(async (exercise) => {\n await prisma.exercise.create({\n data: {\n ...exercise,\n parks: {\n connect: parks.map((park) => ({ id: park.id })),\n },\n },\n });\n }),\n);\n```\n\n========================================\n\nCode:\n```text\nmodel Post {\n id Int @id @default(autoincrement())\n title String\n body String?\n categories PostCategory[]\n\n @@map(\"post\")\n}\n\nmodel Category {\n id Int @id @default(autoincrement())\n name String\n posts PostCategory[]\n\n @@map(\"category\")\n}\n\nmodel PostCategory {\n categoryId Int @map(\"category_id\")\n postId Int @map(\"post_id\")\n category Category @relation(fields: [categoryId], references: [id])\n post Post @relation(fields: [postId], references: [id])\n\n @@id([categoryId, postId])\n @@map(\"post_category\")\n}\n```\n\n```text\nawait prisma.post.create({\n data: {\n title: 'Hello',\n categories: {\n create: [{ category: { create: { name: 'News' } } }],\n connect: {\n categoryId_postId: { categoryId: 1, postId: ? }, // This doesn't work, even if I had the postId\n },\n },\n },\n });\n```\n\n```text\n@map\n```\n\n```text\nconnect\n```\n\n```text\nawait prisma.post.create({\n data: {\n title: 'Hello',\n categories: {\n create: [\n {\n category: {\n create: {\n name: 'category-1',\n },\n },\n },\n { category: { connect: { id: 10 } } },\n ],\n },\n },\n });\n```\n\n```text\nconnectOrCreate\n```\n\n```text\nawait Promise.all(DEFAULT_FILES[2].map(file => prisma.file.create({\n data: {\n ...file,\n user_id: userId,\n parent_id: homeFolder.id,\n tags: {\n create: file.tags?.map(name => ({\n tag: {\n connect: {\n id: tags.find(t => t.name === name)?.id\n }\n }\n }))\n },\n }\n })))\n```\n\n```text\nawait prisma.postCategory.create({\n data: {\n category: {\n connectOrCreate: {\n id: categoryId\n }\n },\n posts: {\n create: [\n {\n title: 'g3xxxxxxx',\n body: 'body g3xxxxx'\n }\n ],\n },\n },\n})\n```\n\n```js\nlet args =[1,2,3,4]\ntags: {\n create: args.tags?.map(tagId=>({\n tag:{\n connect:{\n id:tagId\n }\n }\n }))\n },\n }\n```\n\n```text\npark[] <-> exercise[]\n```\n\n```text\n// create parks\nconst parks = await prisma.park.createMany({data: [...]});\n\n// create and connect exercises\nconst exercises = [...];\nawait Promise.all(\n exercises.map(async (exercise) => {\n await prisma.exercise.create({\n data: <any>{\n ...exercise,\n parks: {\n connect: parks.map((park) => ({ id: park.id })),\n },\n },\n });\n }),\n);\n```\n\n========================================\n\nComments:\n- This exhibits strange behavior. If the `{ categoryId: 1, postId: 1 }` bridge record exists in the `post_category` table, then it replaces the bridge record with `{ categoryId: 1, postId: new_id }`. In other words, it re-assigns another post's category to this new post. I don't want any other post to be impacted when I create a new post. I'd like to create a new category if the category doesn't exist, or add a new bridge record if it does. There's a good example using `create` and `set` on implicit relations here: (url to ), but it doesn't work b/c I'm using explicit relation.\n- Here's the URL that I was referring to in my previous comment: prisma.io/docs/support/help-articles/… The example there uses `tags: { set: [{ id: 1 }, { id: 2 }], create: { name: 'typescript' } }`, which is what I'd like to do, but can't seem to get it to work with my explicit relationship.\n- Based on the docs you linked to, I think I want something like this, but this throws an exception because I can't link from `categoryId_postId` to `category` (sorry about the formatting): `connectOrCreate: { create: { category: { create: { name: 'category-1' } }, }, where: { categoryId_postId: { category: { name: 'category-1' }, }, }`\n- In that case, this should work: `await prisma.post.create({ data: { title: 'title', categories: { create: { category: { connect: { id: 1 } } } }, }, })` This should connect the post to an existing category and will create the relation in the join table as well.\n- Could you tell me the type of file in your solution? I got it to work, but don't know the type of the input. I thought it's Prisma.FileCreateInput but tags has no map property.\n- It's a `seed.ts` that I execute with `\"seed\": \"ts-node ./prisma/seed.ts\"`\n- Nice one! This is what I needed, although I opted for a little different expression: connect: parks.map(({ id }) => ({ id })),","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":248,"estimatedTokens":1642}}20{"id":"stack-69629051","source":"stackoverflow","questionId":69629051,"title":"Using multiple endpoints in Apollo Client","tags":["javascript","graphql","next.js","apollo","apollo-client"],"text":"Title: Using multiple endpoints in Apollo Client\nTags: javascript, graphql, next.js, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have learned `Apollo` + `GraphQL` through **Odyssey**. Currently, I am building my own project using **Next.js** which required fetching data from 2 **GraphQL endpoints**.\n\nMy problem: How can I fetch data from **multiple GraphQL endpoints** with `ApolloClient`?\n\nBelow is my code for my first endpoint:\n\n```\nimport { ApolloClient, InMemoryCache, createHttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n ssrMode: true,\n link: createHttpLink({\n uri: \"https://api.hashnode.com/\",\n credentials: \"same-origin\",\n headers: {\n Authorization: process.env.HASHNODE_AUTH,\n },\n }),\n cache: new InMemoryCache(),\n});\n\nexport default client;\n```\n\n========================================\n\nTop Answer:\nEncountered the same problem today. I wanted to have it dynamic so this is what I came out with:\n\n```\nexport type DynamicLinkClientName = \"aApp\" | \"bApp\" | \"graphqlApp\";\ntype Link = RestLink | HttpLink;\ntype DynamicLink = { link: Link; name: DynamicLinkClientName };\nconst LINK_MAP: DynamicLink[] = [\n { link: aRestLink, name: \"aApp\" },\n { link: bAppRestLink, name: \"bApp\" },\n { link: graphqlAppLink, name: \"graphqlApp\" },\n];\n\nconst isClientFromContext = (client: string) => (op: Operation) =>\n op.getContext().client === client;\n\nconst DynamicApolloLink = LINK_MAP.reduce(\n (prevLink, nextLink) => {\n // When no name is specified, fallback to defaultLink.\n if (!prevLink) {\n return ApolloLink.split(\n isClientFromContext(nextLink.name),\n nextLink.link,\n defaultLink\n );\n }\n return ApolloLink.split(\n isClientFromContext(nextLink.name),\n nextLink.link,\n prevLink\n );\n },\n undefined\n) as ApolloLink;\n```\n\n========================================\n\nCode:\n```text\nimport { ApolloClient, InMemoryCache, createHttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n ssrMode: true,\n link: createHttpLink({\n uri: \"https://api.hashnode.com/\",\n credentials: \"same-origin\",\n headers: {\n Authorization: process.env.HASHNODE_AUTH,\n },\n }),\n cache: new InMemoryCache(),\n});\n\nexport default client;\n```\n\n```text\nApollo\n```\n\n```text\nGraphQL\n```\n\n```text\nApolloClient\n```\n\n```text\n//Declare your endpoints\nconst endpoint1 = new HttpLink({\n uri: 'https://api.hashnode.com/graphql',\n ...\n})\nconst endpoint2 = new HttpLink({\n uri: 'endpoint2/graphql',\n ...\n})\n\n//pass them to apollo-client config\nconst client = new ApolloClient({\n link: ApolloLink.split(\n operation => operation.getContext().clientName === 'endpoint2',\n endpoint2, //if above \n endpoint1\n )\n ...\n})\n\n//pass client name in query/mutation\nuseQuery(QUERY, {variables, context: {clientName: 'endpoint2'}})\n```\n\n```text\nexport type DynamicLinkClientName = \"aApp\" | \"bApp\" | \"graphqlApp\";\ntype Link = RestLink | HttpLink;\ntype DynamicLink = { link: Link; name: DynamicLinkClientName };\nconst LINK_MAP: DynamicLink[] = [\n { link: aRestLink, name: \"aApp\" },\n { link: bAppRestLink, name: \"bApp\" },\n { link: graphqlAppLink, name: \"graphqlApp\" },\n];\n\nconst isClientFromContext = (client: string) => (op: Operation) =>\n op.getContext().client === client;\n\nconst DynamicApolloLink = LINK_MAP.reduce<ApolloLink | undefined>(\n (prevLink, nextLink) => {\n // When no name is specified, fallback to defaultLink.\n if (!prevLink) {\n return ApolloLink.split(\n isClientFromContext(nextLink.name),\n nextLink.link,\n defaultLink\n );\n }\n return ApolloLink.split(\n isClientFromContext(nextLink.name),\n nextLink.link,\n prevLink\n );\n },\n undefined\n) as ApolloLink;\n```\n\n```text\nconst defaultClient: keyof typeof clients = \"heroku\";\n\nconst clients = {\n \"heroku\": new HttpLink({ uri: \"https://endpointURLForHeroku\" }),\n \"lists\": new HttpLink({uri: \"https://endpointURLForLists\" })\n}\n\nconst isRequestedClient = (clientName: string) => (op: Operation) =>\n op.getContext().clientName === clientName;\n\nconst ClientResolverLink = Object.entries(clients)\n .map(([clientName, Link]) => ([clientName, ApolloLink.from([Link])] as const))\n .reduce(([_, PreviousLink], [clientName, NextLink]) => {\n\n const ChainedLink = ApolloLink.split(\n isRequestedClient(clientName),\n NextLink,\n PreviousLink\n )\n\n return [clientName, ChainedLink];\n }, [\"_default\", clients[defaultClient]])[1]\n\ndeclare module \"@apollo/client\" {\n interface DefaultContext {\n clientName: keyof typeof clients\n }\n}\n```\n\n```text\nconst defaultClient = \"heroku\";\n\nconst clients = {\n \"heroku\": new HttpLink({ uri: \"https://endpointURLForHeroku\" }),\n \"lists\": new HttpLink({uri: \"https://endpointURLForLists\" })\n}\n\nconst isRequestedClient = (clientName) => (op) =>\n op.getContext().clientName === clientName;\n\nconst ClientResolverLink = Object.entries(clients)\n .reduce(([_, PreviousLink], [clientName, NextLink]) => {\n\n const ChainedLink = ApolloLink.split(\n isRequestedClient(clientName),\n NextLink,\n PreviousLink\n )\n\n return [clientName, ChainedLink];\n}, [\"_default\", clients[defaultClient]])[1]\n```\n\n```text\nimport { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client'\n\n// Declare your endpoints\nconst animeEndpoint = new HttpLink({\n uri: 'https://graphql.anilist.co',\n})\nconst countriesEndpoint = new HttpLink({\n uri: 'https://countries.trevorblades.com/',\n})\n\n// Not necessary. Just helps with type safety.\nexport enum Endpoint {\n anime = 'anime',\n country = 'country',\n}\n\n//pass them to apollo-client config\nconst client = new ApolloClient({\n // Version here is just a custom property that we can use to determine which endpoint to use\n // Truthy = animeEndpoint (second) parameter, falsy = countriesEndpoint (third) parameter\n link: ApolloLink.split((operation) => operation.getContext().version === Endpoint.anime, animeEndpoint, countriesEndpoint),\n cache: new InMemoryCache(),\n})\n\nexport default client\n```\n\n```text\n'use client'\nimport { useQuery } from '@apollo/client'\nimport GetAnimeQuery from '@/libs/gql/GetAnime' // Just a graphql query\nimport { Endpoint } from '@/libs/apollo'\nimport GetCountriesQuery from '@/libs/gql/GetCountries' // Just a graphql query\n\nexport default function Home() {\n // Anime data\n const { loading: loadingAnime, error: errorAnime, data: dataAnime } = useQuery(GetAnimeQuery, { context: { version: Endpoint.anime } })\n // Countries data\n const {\n loading: loadingCountries,\n error: errorCountries,\n data: dataCountries,\n } = useQuery(GetCountriesQuery, { context: { version: Endpoint.country } })\n console.log('Countries', dataCountries)\n console.log('Anime', dataAnime)\n return (\n <main>\n {loadingAnime && <p>Loading Anime...</p>}\n {errorAnime && <p>Error Anime :{errorAnime.message}</p>}\n {loadingCountries && <p>Loading Countries...</p>}\n {errorCountries && <p>Error Countries:{errorCountries.message}</p>}\n </main>\n )\n}\n```\n\n```text\nimport { gql } from '@apollo/client'\n\nconst GetAnimeQuery = gql`\n query Get {\n Page(page: 1, perPage: 5) {\n pageInfo {\n total\n currentPage\n lastPage\n hasNextPage\n perPage\n }\n media {\n id\n title {\n romaji\n }\n }\n }\n }\n`\n\nexport default GetAnimeQuery\n```\n\n```text\nimport { gql } from '@apollo/client'\n\nconst GetCountriesQuery = gql`\n query GetAllCountries {\n countries {\n code\n currency\n name\n }\n }\n`\n\nexport default GetCountriesQuery\n```\n\n```text\nApolloLink.split\n```\n\n```text\nApollo Link\n```\n\n```text\nlibs/apollo/index.ts\n```\n\n```text\napp/page.tsx\n```\n\n```text\nlibs/gql/GetAnime.ts\n```\n\n```text\nlibs/gql/GetCountries.ts\n```\n\n========================================\n\nComments:\n- Can you provide your ApolloClient configuration code?\n- Hi, here is what I have written for my first client endpoint. I'm planning to add another endpoint but I can't really find any solution on the Internet.\n- `import { ApolloClient, InMemoryCache, createHttpLink } from \"@apollo/client\"; const client = new ApolloClient({ ssrMode: true, link: createHttpLink({ uri: \"https://api.hashnode.com/\", credentials: \"same-origin\", headers: { Authorization: process.env.HASHNODE_AUTH, }, }), cache: new InMemoryCache(), }); export default client;` @JacekWalasik Above is my code. :)\n- @JacekWalasik Can you check my comment below? I'm facing issue my headers is not working anymore when I put my token into `.env.local` file & use the token in other file.\n- May I know how to add headers? `//Declare your endpoints const endpoint1 = new HttpLink({ uri: 'https://api.hashnode.com/graphql', ... }) const endpoint2 = new HttpLink({ uri: 'endpoint2/graphql', ... }) //pass them to apollo-client config const client = new ApolloClient({ link: ApolloLink.split( operation => operation.getContext().clientName === 'endpoint2', endpoint2, //if above endpoint1 ) ... }) //pass client name in query/mutation useQuery(QUERY, {variables, context: {clientName: 'endpoint2'}})`\n- I assume in the same way you did before: `const endpoint1 = new HttpLink({ uri: '...', credentials: credentials, headers: headers})`. Doesnt work like this?\n- thank you. I solved my problems.\n- My headers is not working anymore if I put it in this way: `const endpoint2 = new HttpLink({ uri: \"https://api.github.com/graphql\", headers: { Authorization:`Bearer ${process.env.GITHUB_ACCESS_TOKEN}`, }, });`\n- That's unexpected, maybe incorrect use of Template literals - try `headers: { authorization: `Bearer ${process.env.GITHUB_ACCESS_TOKEN}`}`\n- For some reason, my requests are also missing headers when doing it this way. However, it is not missing authorization headers. but things like `:path:` and `:authority:`. Any idea what might be causing this? im sharing code of all the middleware and links between both clients","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":349,"estimatedTokens":2537}}21{"id":"stack-40381998","source":"stackoverflow","questionId":40381998,"title":"graphene-django - How to filter?","tags":["python","django","graphql","graphene-python"],"text":"Title: graphene-django - How to filter?\nTags: python, django, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI use graphen-django for build a GraphQL API.\nI have succesfully create this API, but I can't pass a argument for filter my response.\n\nThis is my **models.py**:\n\n```\nfrom django.db import models\n\nclass Application(models.Model):\n name = models.CharField(\"nom\", unique=True, max_length=255)\n sonarQube_URL = models.CharField(\"Url SonarQube\", max_length=255, blank=True, null=True)\n\n def __unicode__(self):\n return self.name\n```\n\nThis is my **schema.py**:\n import graphene\n from graphene_django import DjangoObjectType\n from models import Application\n\n```\nclass Applications(DjangoObjectType):\n class Meta:\n model = Application\n\nclass Query(graphene.ObjectType):\n applications = graphene.List(Applications)\n\n @graphene.resolve_only_args\n def resolve_applications(self):\n return Application.objects.all()\n\nschema = graphene.Schema(query=Query)\n```\n\nMy **urls.py**:\n\n```\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^admin/', admin.site.urls),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'^api-token-auth/', authviews.obtain_auth_token),\n url(r'^graphql', GraphQLView.as_view(graphiql=True)),\n]\n```\n\nAs you can see, I also have a REST API.\n\nMy **settings.py** contains this:\n\n```\nGRAPHENE = {\n 'SCHEMA': 'tibco.schema.schema'\n}\n```\n\nI this: https://github.com/graphql-python/graphene-django\n\nWhen I send this resquest: \n\n```\n{\n applications {\n name\n }\n}\n```\n\nI've got this response:\n\n```\n{\n \"data\": {\n \"applications\": [\n {\n \"name\": \"foo\"\n },\n {\n \"name\": \"bar\"\n }\n ]\n }\n}\n```\n\nSo, it's works!\n\nBut when I try to pass an argument like this:\n\n```\n{\n applications(name: \"foo\") {\n name\n id\n }\n}\n```\n\nI have this response:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"name\\\" on field \\\"applications\\\" of type \\\"Query\\\".\",\n \"locations\": [\n {\n \"column\": 16,\n \"line\": 2\n }\n ]\n }\n ]\n}\n```\n\nWhat i have missed? Or maybe I do something wrong?\n\n========================================\n\nTop Answer:\nIf you're in my case and don't want to use Relay, you can also handle filtering directly in you resolvers using Django orm filtering. Example here: Filter graphql query in django\n\n========================================\n\nCode:\n```text\nfrom django.db import models\n\nclass Application(models.Model):\n name = models.CharField(\"nom\", unique=True, max_length=255)\n sonarQube_URL = models.CharField(\"Url SonarQube\", max_length=255, blank=True, null=True)\n\n def __unicode__(self):\n return self.name\n```\n\n```text\nclass Applications(DjangoObjectType):\n class Meta:\n model = Application\n\nclass Query(graphene.ObjectType):\n applications = graphene.List(Applications)\n\n @graphene.resolve_only_args\n def resolve_applications(self):\n return Application.objects.all()\n\n\nschema = graphene.Schema(query=Query)\n```\n\n```text\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^admin/', admin.site.urls),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'^api-token-auth/', authviews.obtain_auth_token),\n url(r'^graphql', GraphQLView.as_view(graphiql=True)),\n]\n```\n\n```text\nGRAPHENE = {\n 'SCHEMA': 'tibco.schema.schema'\n}\n```\n\n```text\n{\n applications {\n name\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"applications\": [\n {\n \"name\": \"foo\"\n },\n {\n \"name\": \"bar\"\n }\n ]\n }\n}\n```\n\n```text\n{\n applications(name: \"foo\") {\n name\n id\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"name\\\" on field \\\"applications\\\" of type \\\"Query\\\".\",\n \"locations\": [\n {\n \"column\": 16,\n \"line\": 2\n }\n ]\n }\n ]\n}\n```\n\n```text\nimport graphene\nfrom graphene import relay, AbstractType, ObjectType\nfrom graphene_django import DjangoObjectType\nfrom graphene_django.filter import DjangoFilterConnectionField\nfrom models import Application\n\nclass ApplicationNode(DjangoObjectType):\n class Meta:\n model = Application\n filter_fields = ['name', 'sonarQube_URL']\n interfaces = (relay.Node, )\n\nclass Query(ObjectType):\n application = relay.Node.Field(ApplicationNode)\n all_applications = DjangoFilterConnectionField(ApplicationNode)\n\nschema = graphene.Schema(query=Query)\n```\n\n```text\nquery {\n allApplications(name: \"Foo\") {\n edges {\n node {\n name\n }\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"allApplications\": {\n \"edges\": [\n {\n \"node\": {\n \"name\": \"Foo\"\n }\n }\n ]\n }\n }\n}\n```\n\n```text\nclass ApplicationNode(DjangoObjectType):\n class Meta:\n model = Application\n # Provide more complex lookup types\n filter_fields = {\n 'name': ['exact', 'icontains', 'istartswith']\n }\n interfaces = (relay.Node, )\n```\n\n```text\nquery {\n allApplications(name_Icontains: \"test\") {\n edges {\n node {\n id,\n name\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- It's insane that there's a coupling to replay in the otherwise-generic sounding `DjangoListField`","metadata":{"transformedAt":"2026-08-18T18:32:36.019Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":300,"estimatedTokens":1294}}22{"id":"stack-41716781","source":"stackoverflow","questionId":41716781,"title":"Graphical presentation of GraphQL schema","tags":["graphql"],"text":"Title: Graphical presentation of GraphQL schema\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nIs there a way to provide visual diagram (UML like) of GraphQL Schema design?\n\nBackground:\nI already have a schema design with me, which is to be converted into GraphQL API. However, before starting GraphQL development, I want to create visual representation of schema that I have. Diagram should essentially show atleast Query Types and Relations, which will help developer knowing what to develop in GraphQL.\n\nIs there a way or standards?\n\n========================================\n\nTop Answer:\nGalaxy Modeler supports visual definition of GraphQL Schema, incl. types, interfaces, enums, inputs and references.\n\n========================================\n\nComments:\n- It's not clear to me what you actually want. Do you want a diagram given *the schema* that you have developed (what kind of schema is it, by the way)? or you want a diagram, given a GraphQL schema?\n- It is the former; I want to create a diagram given the DB schema. The output diagram to act as an input for a GraphQL developer to know what I am expecting in GraphQL schema (like query types and relations). Question is to know if there is any standard diagram by which I can provide my requirements to GraphQL developer.\n- GraphQL schema and DB schema don't directly correlate to each other. It's possible that GraphQL schema flattens many things that are not in DB schema. I haven't seen anything like that you need.\n- Agreed. Thanks for sharing your view...\n- You can use any diagramming tool. Personally I used Omnigraffle (OSX Only), but you can use Visio (Windows), or any of the numerous online diagramming apps (e.g. draw.io, etc). I focused my diagram on just the query types and their relationships. All in, the resulting GraphQL API has over 200 types and diagramming it first helped guide both my GraphQL schema design and made it a lot easier to keep everything straight when I built out my resolvers\n- Thanks for reply. And the tool looks to be useful for my other requirements. However, my current requirement is to create GraphQL diagram from the DB schema I know (I don't have GraphQL API yet, it is yet to be developed). I am happy to create diagram manually, but then other question is to know if there are any standards to show GraphQL diagram. (like we have class diagram, sequence diagram using UML tool)\n- Ah okay I understand. Unfortunately, I'm not sure if there is a standard practice for this yet. One option would be to write your schema using the GraphQL schema language and then load it with blank resolvers using a library like graphql-tools github.com/apollostack/graphql-tools. You could then run the graphqlviz tool on it to automatically generate the diagram.\n- Yes, looks to be the closest solution to this problem. Will try it out. Thanks!\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- +1 this is what I was looking for, it's free, can be deployed locally and can be used as a dependency too https://github.com/IvanGoncharov/graphql-voyager","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":30,"estimatedTokens":819}}23{"id":"stack-47704615","source":"stackoverflow","questionId":47704615,"title":"GraphQL - Passing an enum value directly to a mutation as an argument?","tags":["types","enums","graphql"],"text":"Title: GraphQL - Passing an enum value directly to a mutation as an argument?\nTags: types, enums, graphql\nSource: Stack Overflow\n\nQuestion:\nGiven the following GraphQL type definition:\n\n```\nconst typeDefs = `\n enum Action {\n update\n delete\n } \n\n type Mutation {\n doSomething(action: Action)\n }\n`;\n```\n\nThis query works:\n\n```\nconst query = `\n mutation($action: Action) {\n doSomething(action: $action)\n }\n`\nconst variables = { action: \"update\" }\n```\n\nBut this one does not:\n\n```\nconst query = `\n mutation {\n doSomething(action: \"update\")\n }\n`\n```\n\nDoes GraphQL not support passing an enum value directly as an argument?\n\n========================================\n\nTop Answer:\nenum defined in backend is:\n\n```\nenum Gender {\n MALE\n FEMALE\n}\n```\n\nI am using Vue for frontend so passing data to the mutation from Vue can be done like this.\nI have defined gender as a string in my local state of the component as:\n\n```\ndata(){\n return {\n gender: ''\n }\n}\n```\n\nThe method from Vue is:\n\n```\nasync handleEditProfile () {\n const response = await this.$apollo.mutate({\n query: EDIT_PROFILE,\n variables: {\n nameAsInPan: this.nameAsInPan,\n gender: this.gender,\n dateOfBirth: this.dateOfBirth\n }\n })\n }\n```\n\nmutation used above EDIT_PROFILE:\n\n```\ngql`mutation editProfile($name: String!, $email: String!,$phone: String!, $gender: Gender!, $dateOfBirth: String!) {\n editProfile (profileInput:{name: $name, email: $email, phone: $phone, gender: $gender, dateOfBirth: $dateOfBirth}){\n id\n email\n phone\n firstName\n lastName\n nameAsInPan\n gender\n dateOfBirth\n }\n}\n`\n```\n\nuse the enum variable name as defined in the mutation and send it to Graphql, like I have used gender As\n`$gender: Gender!` in gql mutation.You don't have to worry about sending data as enum, just send it as String otherwise you will have to face JSON error, Graphql will take care of the value you send as a string (like 'MALE' or 'FEMALE') just don't forget to mention that gender is type of Gender(which is enum) in gql mutation as I did above.\n\n========================================\n\nCode:\n```text\nconst typeDefs = `\n enum Action {\n update\n delete\n } \n\n type Mutation {\n doSomething(action: Action)\n }\n`;\n```\n\n```text\nconst query = `\n mutation($action: Action) {\n doSomething(action: $action)\n }\n`\nconst variables = { action: \"update\" }\n```\n\n```text\nconst query = `\n mutation {\n doSomething(action: \"update\")\n }\n`\n```\n\n```js\nconst query = `\n mutation {\n doSomething(action: update)\n }\n`\n```\n\n```text\nenum Gender {\n MALE\n FEMALE\n}\n```\n\n```text\ndata(){\n return {\n gender: ''\n }\n}\n```\n\n```text\nasync handleEditProfile () {\n const response = await this.$apollo.mutate({\n query: EDIT_PROFILE,\n variables: {\n nameAsInPan: this.nameAsInPan,\n gender: this.gender,\n dateOfBirth: this.dateOfBirth\n }\n })\n }\n```\n\n```text\ngql`mutation editProfile($name: String!, $email: String!,$phone: String!, $gender: Gender!, $dateOfBirth: String!) {\n editProfile (profileInput:{name: $name, email: $email, phone: $phone, gender: $gender, dateOfBirth: $dateOfBirth}){\n id\n email\n phone\n firstName\n lastName\n nameAsInPan\n gender\n dateOfBirth\n }\n}\n`\n```\n\n```text\n$gender: Gender!\n```\n\n========================================\n\nComments:\n- Is it just me, or does using an enum make it difficult to pass arguments in via a variables object?","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":195,"estimatedTokens":854}}24{"id":"stack-46061755","source":"stackoverflow","questionId":46061755,"title":"HATEOAS vs GraphQL decision criteria set for microservices?","tags":["graphql","hateoas"],"text":"Title: HATEOAS vs GraphQL decision criteria set for microservices?\nTags: graphql, hateoas\nSource: Stack Overflow\n\nQuestion:\nI was talking to someone recently who said they are skipping the development of HATEOAS REST endpoints completely in favor of GraphQL. So I'm curious as to what the criteria set is for deciding when to use GraphQL vs. HATEOAS or is GraphQL just a better choice in general for an API Gateway / Edge Server architecture?\n\n========================================\n\nTop Answer:\nI love that Ed posted a link to my overview, but there's another article that I believe to be more relevant than that one.\n\nThe representation of state is completely different between the two.\n\nhttps://apisyouwonthate.com/blog/representing-state-in-rest-and-graphql/\n\nGraphQL is entirely unable to offer a series of \"next steps\" in a meaningful and standardized way, other than maybe shoving an array of strings containing potentially relevant mutations that you should try to hit up.\n\nEven if you do that, it certainly cannot help you communicate with other HTTP APIs, which is a real shame.\n\nAnyway, it's all that article! :)\n\n========================================\n\nComments:\n- Pretty good overview. Note that nothing prevents you from wrtiting a quick POST based aggregation endpoint that will just GET links from an initial resource. I find this is the best of both worlds even if it still doesn't give you standardisation.\n- Bespoke complexity plus no standardisation might be seen as the worst of both worlds ;-)\n- @Ed., I have one question for ya. Which one has more complexity?","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":28,"estimatedTokens":397}}25{"id":"stack-48329511","source":"stackoverflow","questionId":48329511,"title":"Custom frontmatter variables with Markdown Remark in Gatsby.js","tags":["markdown","graphql","gatsby","yaml-front-matter","remarkjs"],"text":"Title: Custom frontmatter variables with Markdown Remark in Gatsby.js\nTags: markdown, graphql, gatsby, yaml-front-matter, remarkjs\nSource: Stack Overflow\n\nQuestion:\nI am building a website using Gatsbyjs and NetlifyCMS. I've started using this starter https://github.com/AustinGreen/gatsby-starter-netlify-cms, and I am trying to customise it now.\n\nI want to use custom variables in the frontmatter of a markdown file like this:\n\n```\n---\ntemplateKey: mirror\nnazev: ΔernobΓlΓ‘\ntitle: Black and White\ncena: '2700'\nprice: '108'\nthumbnail: /img/img_1659.jpeg\n---\n```\n\nI want to acess this data with GraphQL. I use gatsby-source-filesystem and gatsby-transform-remark. This is my query:\n\n```\n{\n allMarkdownRemark {\n edges {\n node {\n frontmatter {\n templateKey\n nazev\n title\n cena\n price\n }\n }\n }\n }\n}\n```\n\nI can't get the GraphQL to read my own variables, it recognises only `title` and `templateKey` (those, that were already used in the starter). I get this error:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Cannot query field \\\"nazev\\\" on type \\\"frontmatter_2\\\".\",\n \"locations\": [\n {\n \"line\": 7,\n \"column\": 11\n }\n ]\n },\n {\n \"message\": \"Cannot query field \\\"cena\\\" on type \\\"frontmatter_2\\\".\",\n \"locations\": [\n {\n \"line\": 9,\n \"column\": 11\n }\n ]\n },\n {\n \"message\": \"Cannot query field \\\"price\\\" on type \\\"frontmatter_2\\\". Did you mean \\\"pricing\\\"?\",\n \"locations\": [\n {\n \"line\": 10,\n \"column\": 11\n }\n ]\n }\n ]\n}\n```\n\nI've searched for days, but found nothing. Would someone help me please?\n\n========================================\n\nTop Answer:\n### Some background information that might help you anticipate similar issues in the future\n\n`gatsby-transformer-remark` and all other plugins that are dependant on GraphQL queries can only read newly added variables when the GraphQL queries are run.\n\nIn Gatsby, GraphQL queries are run **ONCE at startup of your development server**. \nThe queries will not be refreshed if you alter the code while `gatsby develop` is still live. You can run your GraphQL queries again by restarting with `gatsby develop`. \n\nThe Gatsby documentation has its own entry of the Gatsby Build Process that shows when exactly the queries are run:\n\n```\nsuccess open and validate gatsby-configs - 0.051 s\n// ...\nsuccess onPostBootstrap - 0.130 s\nβ \ninfo bootstrap finished - 3.674 s\nβ \nsuccess run static queries - 0.057 s β 3/3 89.08 queries/second // GraphQL queries here\nsuccess run page queries - 0.033 s β 5/5 347.81 queries/second // GraphQL queries here\nsuccess start webpack server - 1.707 s β 1/1 6.06 pages/second\n```\n\nAs a rule of thumb that I learned from experience, if you are wondering why your code changes are not hot reloading\n\n- refresh the browser.\n\n- If that doesn't work, restart `gatsby develop`.\n\n- If that doesn't work, run `gatsby clean`, clear your browser's site cache, and run `gatsby develop`.\n\n- If that doesn't work you can be *almost* 100% certain you made a mistake.\n\n========================================\n\nCode:\n```text\n---\ntemplateKey: mirror\nnazev: ΔernobΓlΓ‘\ntitle: Black and White\ncena: '2700'\nprice: '108'\nthumbnail: /img/img_1659.jpeg\n---\n```\n\n```text\n{\n allMarkdownRemark {\n edges {\n node {\n frontmatter {\n templateKey\n nazev\n title\n cena\n price\n }\n }\n }\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Cannot query field \\\"nazev\\\" on type \\\"frontmatter_2\\\".\",\n \"locations\": [\n {\n \"line\": 7,\n \"column\": 11\n }\n ]\n },\n {\n \"message\": \"Cannot query field \\\"cena\\\" on type \\\"frontmatter_2\\\".\",\n \"locations\": [\n {\n \"line\": 9,\n \"column\": 11\n }\n ]\n },\n {\n \"message\": \"Cannot query field \\\"price\\\" on type \\\"frontmatter_2\\\". Did you mean \\\"pricing\\\"?\",\n \"locations\": [\n {\n \"line\": 10,\n \"column\": 11\n }\n ]\n }\n ]\n}\n```\n\n```text\ntitle\n```\n\n```text\ntemplateKey\n```\n\n```text\nsuccess open and validate gatsby-configs - 0.051 s\n// ...\nsuccess onPostBootstrap - 0.130 s\nβ \ninfo bootstrap finished - 3.674 s\nβ \nsuccess run static queries - 0.057 s β 3/3 89.08 queries/second // GraphQL queries here\nsuccess run page queries - 0.033 s β 5/5 347.81 queries/second // GraphQL queries here\nsuccess start webpack server - 1.707 s β 1/1 6.06 pages/second\n```\n\n```text\ngatsby-transformer-remark\n```\n\n```text\ngatsby develop\n```\n\n```text\ngatsby develop\n```\n\n```text\ngatsby develop\n```\n\n```text\ngatsby clean\n```\n\n```text\ngatsby develop\n```\n\n========================================\n\nComments:\n- Can you explain more? I can't figure this out!\n- Just restart Gatsby to let the 'gatsby-transformer-remark' know that you have done changes to the frontmatter :)\n- I'm truly impressed you didn't need to restart gatsby for days. I literally restart it every 5 minutes because of errors\n- If you using GraphiQL might need to reload browser too.\n- @RobertWolf thanks a lot, I also had the same question and I wasn't finding nothing in the documentation, but restart the service and reload the page of GraphiQL is all the needed. Thanks!\n- Also found that the directory with the markdown files has to be read by `gatsby-source-filesystem`, otherwise `gatsby-transformer-remark` will not work with that information { resolve: `gatsby-source-filesystem`, options: { path: `${__dirname}/content/mycollection`, name: `mycollection`, }, },\n- Don't you also have to add this data to the definitions in gatsby-node `exports.createPages` ? for an initial page list setup?","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":232,"estimatedTokens":1381}}26{"id":"stack-48412164","source":"stackoverflow","questionId":48412164,"title":"Graphql mutations without arguments","tags":["graphql","graphql-ruby"],"text":"Title: Graphql mutations without arguments\nTags: graphql, graphql-ruby\nSource: Stack Overflow\n\nQuestion:\nGenerally a query is when you fetch data and mutation is when you manipulate data. But how would I implement a mutation without any arguments? \n\nIn my particular case I have delete and create 2fa token endpoints. Both the delete and create token have no arguments as they rely on the logged in user id. They both either destroy or create a record in the database. So I would prefer that they be mutations. But that is not possible?\n\nI'm using Graphql-Ruby. But this is more of a general Graphql question.\n\n**EDIT:**\n\nSo turns out I was wrong. I couldn't find any info about it so I just assumed it wasn't possible. I hope this helps someone else. In Graphql-Ruby you can do:\n\n```\nmutation {\n createFoo(input: {})\n}\n```\n\n========================================\n\nTop Answer:\nIf a mutation doesn't declare any parameters than it must looks this way:\n\n```\nmutation {\n createFoo : Payload\n}\n```\n\nSo you just must not to write parentheses at all.\n\n========================================\n\nCode:\n```text\nmutation {\n createFoo(input: {})\n}\n```\n\n```text\nquery\n```\n\n```text\nmutation\n```\n\n```text\nmutation {\n createFoo : Payload\n}\n```\n\n```text\nconst query = gql`\n query {\n queryName {\n someProperty\n }\n }\n`\n```\n\n========================================\n\nComments:\n- If you are encountering some error when trying to compile your schema or run a query, you should update your question to include that.\n- Daniel Rearden : Can you pls help me on this ---> stackoverflow.com/questions/49280814/…","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":72,"estimatedTokens":403}}27{"id":"stack-56989560","source":"stackoverflow","questionId":56989560,"title":"How to get a cursor for pagination in Graphql from a database?","tags":["database","graphql","graphql-js","cursor-position","resolver"],"text":"Title: How to get a cursor for pagination in Graphql from a database?\nTags: database, graphql, graphql-js, cursor-position, resolver\nSource: Stack Overflow\n\nQuestion:\nI am having terrible problems getting a real cursor for resolving a database pagination result in GraphQL. No matter what kind of database (SQL e.g. mysql or NoSQL document e.g. mongodb) I am using, there is no way, I seem to be able to get a cursor or cursorlike object.\n\nPropably I am missing out on some fundamental concepts but after searching my b... off I am beginning to seriously doubt whether the official GraphQL pagination documentation\n\nhttps://graphql.org/learn/pagination/\n\nis based on any real live experience at all.\n\nHere's my question: How can I get anything even remotely resembling a cursor from a SQL query like this?\n\n```\nSELECT authors.id, authors.last_name, authors.created_at FROM authors\nORDER BY authors.last_name, author.created_at\nLIMIT 10\nOFFSET 20\n```\n\nI know, offset based pagination should not be used and instead cursor based navigation is considered a remedy. And I'd definitely like to cure my application from the offset disease. But in order to do that I need to be able to retrieve a cursor from **somewhere**.\n\nI also understand (forgot where I read that) that primary keys should not be used for pagination either.\n\nSo, I am stuck here.\n\n========================================\n\nCode:\n```text\nSELECT authors.id, authors.last_name, authors.created_at FROM authors\nORDER BY authors.last_name, author.created_at\nLIMIT 10\nOFFSET 20\n```\n\n```text\nSELECT * FROM TABLE T\nWHERE T.id > $cursorId;\n```\n\n```text\nSELECT A FROM T\n WHERE A.v > C.v\n ORDER BY T.v ASC\n LIMIT n\n```\n\n```text\nSELECT A FROM T\n WHERE A.id > $cursorIdGivenByClient\n LIMIT n\n```\n\n```text\nSELECT A FROM T\n WHERE A.v > C.v\n OR (A.v = C.v AND A.w > C.w)\n ORDER BY T.v ASC, T.w ASC\n LIMIT n\n```\n\n```text\nSELECT A FROM T\n WHERE A.v > C.v\n OR (A.v = C.v AND A.w > C.w)\n OR (A.v = C.v AND A.w = C.w AND A.x > C.x)\n ORDER BY T.v ASC, T.w ASC, T.x ASC\n LIMIT n\n```\n\n```text\nSELECT A FROM T\n WHERE A.v > C.v\n OR (A.v = C.v AND A.w > C.w)\n OR (A.v = C.v AND A.w = C.w AND A.x > C.x)\n OR (A.v = C.v AND A.w = C.w AND A.x = C.x AND A.y > C.y)\n ORDER BY T.v ASC, T.w ASC, T.x ASC, T.y ASC\n LIMIT n\n```\n\n```text\nSELECT A FROM T\n WHERE A.v > C.v\n OR (A.v = C.v AND A.w > C.w)\n OR (A.v = C.v AND A.w = C.w AND A.x > C.x)\n OR (A.v = C.v AND A.w = C.w AND A.x = C.x AND A.y > C.y)\n OR (A.v = C.v AND A.w = C.w AND A.x = C.x AND A.y = C.y AND A.z > C.z)\n ORDER BY T.v ASC, T.w ASC, T.x ASC, T.y ASC, T.z ASC\n LIMIT n\n```\n\n```text\nSELECT A FROM T\n WHERE (A.v > C.v OR\n (A.v = C.v AND \n (A.w > C.w OR\n (A.w = C.w AND\n (A.x > C.x OR\n (A.x = C.x AND\n (A.y > C.y OR\n (A.y = C.y AND\n (A.z > C.z)))))))))\n ORDER BY T.v ASC, T.w ASC, T.x ASC, T.y ASC, T.z ASC\n LIMIT n\n```\n\n```text\nSELECT authors.id, authors.last_name, authors.created_at FROM authors\n ORDER BY authors.last_name, author.created_at\n```\n\n```text\n$authorLastName, $authorCreatedAt =\n SELECT authors.last_name, authors.created_at from author where id = 15;\n```\n\n```text\nSELECT a.id, a.last_name, a.created_at FROM authors a\n WHERE (a.last_name > $authorLastName OR\n (a.last_name = $authorLastName AND \n (a.created_at > $authorCreatedAt OR\n (a.created_at = $authorCreatedAt AND\n (a.id > 15)))))\n ORDER BY a.last_name, a.created_at, a.id\n LIMIT 20;\n```\n\n```text\nSELECT a.id, a.last_name, a.created_at FROM authors a\n WHERE (a.last_name > (select last_name from authors where id 15) OR\n (a.last_name = (select last_name from authors where id 15) AND \n (a.created_at > (select created_at from authors where id 15) OR\n (a.created_at = (select created_at from authors where id 15) AND\n (a.id > 15)))))\n ORDER BY a.last_name, a.created_at, a.id\n LIMIT 20;\n```\n\n```text\nSELECT A FROM T\n WHERE (A.v < C.v OR\n (A.v = C.v AND \n (A.w < C.w OR\n (A.w = C.w AND\n (A.x < C.x OR\n (A.x = C.x AND\n (A.y < C.y OR\n (A.y = C.y AND\n (A.z < C.z)))))))))\n ORDER BY T.v ASC, T.w ASC, T.x ASC, T.y ASC, T.z ASC\n LIMIT n\n```\n\n```text\nWHERE A.v > C.v\n```\n\n```text\nA.v = C.v\n```\n\n```text\nA.w > C.w\n```\n\n========================================\n\nComments:\n- Maybe this article could help. You could first get the row number of the element and then use that to return the rows after that row using traditional offset.\n- You will not believe how helpful this was. Thank you so much for taking the time to write this detailer answer.\n- This was super helpful! Are there any best practices on how to tackle this if not having Int IDs as primary Key? As we are usually leveraging GUIDs, but they are not sorted of course...\n- If you order for last name and another user change the last name you could get the same record on two different pages. Is there a way to guarantee no duplications with cursor-pagination when results are sorted by a field different than an id?","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":175,"estimatedTokens":1342}}28{"id":"stack-51303530","source":"stackoverflow","questionId":51303530,"title":"github graphql api, what does \"clientMutationId\" mean?","tags":["graphql","github-api","relay","github-graphql","graphql-relay"],"text":"Title: github graphql api, what does \"clientMutationId\" mean?\nTags: graphql, github-api, relay, github-graphql, graphql-relay\nSource: Stack Overflow\n\nQuestion:\nI saw `clientMutationId` field in example-strong-typing documentation.\n\n```\nmutation {\n addComment(input:{clientMutationId: 1234, subjectId: \"MDA6SXNzdWUyMjcyMDA2MTT=\", body: \"Looks good to me!\"}) {\n clientMutationId\n commentEdge {\n node {\n body\n repository {\n id\n name\n nameWithOwner\n }\n issue {\n number\n }\n }\n }\n }\n}\n```\n\nwhat does `clientMutationId` mean? How can I generate it?\n\n========================================\n\nCode:\n```js\nmutation {\n addComment(input:{clientMutationId: 1234, subjectId: \"MDA6SXNzdWUyMjcyMDA2MTT=\", body: \"Looks good to me!\"}) {\n clientMutationId\n commentEdge {\n node {\n body\n repository {\n id\n name\n nameWithOwner\n }\n issue {\n number\n }\n }\n }\n }\n}\n```\n\n```text\nclientMutationId\n```\n\n```text\nclientMutationId\n```\n\n```text\nclientMutationId\n```\n\n========================================\n\nComments:\n- Also note, it's optional. Personally wasn't sure if it was required at first.","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":70,"estimatedTokens":290}}29{"id":"stack-32304486","source":"stackoverflow","questionId":32304486,"title":"How to make a mutation query for inserting a list of (Array) fields in GraphQL","tags":["node.js","mongodb-query","graphql"],"text":"Title: How to make a mutation query for inserting a list of (Array) fields in GraphQL\nTags: node.js, mongodb-query, graphql\nSource: Stack Overflow\n\nQuestion:\nrecently I started working on GraphQL, I am able to insert data in flat schema without any problem but when it comes to an Array of data I am getting an error like\n\n```\n{ \"errors\": [ { \"message\": \"Must be input type\" } ]}\n```\n\nI am testing my query using postman, my mutation query is \n\n```\nmutation M { \n\nAddEvent\n (\n\n title: \"Birthday event\" \n\n description:\"Welcome to all\" \n\n media:[{url:\"www.google.com\", mediaType:\"image\" }]\n\n location:[{address:{state:\"***\", city:\"****\"}}]\n\n ) \n\n{title,description,media,location,created,_id}}\n```\n\nThis is my Event Schema:\n\n```\nEventType = new GraphQLObjectType({\n name: 'Event',\n description: 'A Event',\n fields: () => ({\n _id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n title: {\n type: GraphQLString,\n description: 'The title of the event.',\n },\n description: {\n type: GraphQLString,\n description: 'The description of the event.',\n },\n media:{\n type:new GraphQLList(mediaType),\n description:'List of media', \n },\n location:{\n type:new GraphQLList(locationType),\n description:'List of location', \n } \n })\n});\n\n// Media Type\n\nexport var mediaType = new GraphQLObjectType({\n name: 'Media',\n description: 'A Media',\n fields: () => ({\n _id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n url:{\n type: GraphQLString,\n description: 'The url of the event.',\n },\n mediaType:{\n type: GraphQLString,\n description: 'The mediaTypa of the event.',\n }\n })\n});\n\n // Location Type\n\nexport var locationType = new GraphQLObjectType({\n name: 'Location',\n description: 'A location',\n fields: () => ({\n _id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n address:{\n type: GraphQLString,\n description: 'The address.',\n },\n state:{\n type: GraphQLString,\n description: 'The state.',\n },\n city:{\n type: GraphQLString,\n description: 'The city.',\n },\n zip:{\n type: GraphQLString,\n description: 'The zip code.',\n },\n country:{\n type: GraphQLString,\n description: 'The country.',\n }\n })\n});\n```\n\nMongoose Schema:\n\n```\nvar EventSchema = new mongoose.Schema({\n title: {\n required: true,\n type: String,\n trim: true,\n match: /^([\\w ,.!?]{1,100})$/\n },\n description: {\n required: false,\n type: String,\n trim: true,\n match: /^([\\w ,.!?]{1,100})$/\n },\n media: [{\n url: {\n type: String,\n trim: true\n },\n mediaType: {\n type: String,\n trim: true\n }\n }],\n location: [{\n address: {\n type: String\n },\n city: {\n type: String\n },\n state: {\n type: String\n },\n zip: {\n type: String\n },\n country: {\n type: String\n }\n }]\n})\n```\n\nMutation Type:\n\n```\naddEvent: {\n type: EventType,\n args: {\n\n _id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n title: {\n type: GraphQLString,\n description: 'The title of the event.',\n },\n description: {\n type: GraphQLString,\n description: 'The description of the event.',\n },\n media:{\n type:new GraphQLList(mediaType),\n description:'List of media', \n },\n location:{\n type:new GraphQLList(locationType),\n description:'List of media', \n },\n created: {\n type: GraphQLInt,\n description: 'The created of the user.', \n } \n },\n resolve: (obj, {title,description,media,location,created,_id}) => {\n\n let toCreateEvent = {\n title,\n description,\n created:new Date(),\n start: new Date(),\n media,\n location,\n _id,\n };\n\n return mongo()\n .then(db => {\n return new Promise(\n function(resolve,reject){\n let collection = db.collection('events');\n collection.insert(toCreateEvent, (err, result) => {\n db.close();\n\n if (err) {\n reject(err);\n return;\n }\n resolve(result);\n });\n })\n });\n }\n }\n```\n\n========================================\n\nTop Answer:\nI ran into the same problem - I did not know how to specify array of objects in the input definition. So for those who wants to see a \"text\" schema solution:\n\n```\ntype Book {\n title: String!\n}\n```\n\nto have an array of Books in your input type\n\n```\ninput AuthorInput {\n name: String!\n age: Int!\n}\n```\n\nyou can not just add `books: [Book!]` inside the input statement, you will need deliberately create input type containing needed fields (duplicate if you like):\n\n```\ninput BookInput {\n title: String!\n}\n```\n\nand then you can:\n\n```\ninput AuthorInput {\n name: String!\n age: Int!\n books: [BookInput!]\n}\n```\n\n========================================\n\nCode:\n```text\n{ \"errors\": [ { \"message\": \"Must be input type\" } ]}\n```\n\n```text\nmutation M { \n\nAddEvent\n (\n\n title: \"Birthday event\" \n\n description:\"Welcome to all\" \n\n media:[{url:\"www.google.com\", mediaType:\"image\" }]\n\n location:[{address:{state:\"***\", city:\"****\"}}]\n\n ) \n\n{title,description,media,location,created,_id}}\n```\n\n```text\nEventType = new GraphQLObjectType({\n name: 'Event',\n description: 'A Event',\n fields: () => ({\n _id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n title: {\n type: GraphQLString,\n description: 'The title of the event.',\n },\n description: {\n type: GraphQLString,\n description: 'The description of the event.',\n },\n media:{\n type:new GraphQLList(mediaType),\n description:'List of media', \n },\n location:{\n type:new GraphQLList(locationType),\n description:'List of location', \n } \n })\n});\n\n// Media Type\n\nexport var mediaType = new GraphQLObjectType({\n name: 'Media',\n description: 'A Media',\n fields: () => ({\n _id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n url:{\n type: GraphQLString,\n description: 'The url of the event.',\n },\n mediaType:{\n type: GraphQLString,\n description: 'The mediaTypa of the event.',\n }\n })\n});\n\n // Location Type\n\nexport var locationType = new GraphQLObjectType({\n name: 'Location',\n description: 'A location',\n fields: () => ({\n _id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n address:{\n type: GraphQLString,\n description: 'The address.',\n },\n state:{\n type: GraphQLString,\n description: 'The state.',\n },\n city:{\n type: GraphQLString,\n description: 'The city.',\n },\n zip:{\n type: GraphQLString,\n description: 'The zip code.',\n },\n country:{\n type: GraphQLString,\n description: 'The country.',\n }\n })\n});\n```\n\n```text\nvar EventSchema = new mongoose.Schema({\n title: {\n required: true,\n type: String,\n trim: true,\n match: /^([\\w ,.!?]{1,100})$/\n },\n description: {\n required: false,\n type: String,\n trim: true,\n match: /^([\\w ,.!?]{1,100})$/\n },\n media: [{\n url: {\n type: String,\n trim: true\n },\n mediaType: {\n type: String,\n trim: true\n }\n }],\n location: [{\n address: {\n type: String\n },\n city: {\n type: String\n },\n state: {\n type: String\n },\n zip: {\n type: String\n },\n country: {\n type: String\n }\n }]\n})\n```\n\n```text\naddEvent: {\n type: EventType,\n args: {\n\n _id: {\n type: GraphQLString,\n description: 'The id of the event.',\n },\n title: {\n type: GraphQLString,\n description: 'The title of the event.',\n },\n description: {\n type: GraphQLString,\n description: 'The description of the event.',\n },\n media:{\n type:new GraphQLList(mediaType),\n description:'List of media', \n },\n location:{\n type:new GraphQLList(locationType),\n description:'List of media', \n },\n created: {\n type: GraphQLInt,\n description: 'The created of the user.', \n } \n },\n resolve: (obj, {title,description,media,location,created,_id}) => {\n\n let toCreateEvent = {\n title,\n description,\n created:new Date(),\n start: new Date(),\n media,\n location,\n _id,\n };\n\n return mongo()\n .then(db => {\n return new Promise(\n function(resolve,reject){\n let collection = db.collection('events');\n collection.insert(toCreateEvent, (err, result) => {\n db.close();\n\n if (err) {\n reject(err);\n return;\n }\n resolve(result);\n });\n })\n });\n }\n }\n```\n\n```text\nmedia:{\n type:new GraphQLList(mediaType),\n description:'List of media', \n},\nlocation:{\n type:new GraphQLList(locationType),\n description:'List of media', \n},\n```\n\n```text\n\"Must be input type\"\n```\n\n```text\nGraphQLList\n```\n\n```text\nmediaType\n```\n\n```text\nlocationType\n```\n\n```text\nGraphQLList\n```\n\n```text\nmediaType\n```\n\n```text\nlocationType\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\nmediaType\n```\n\n```text\nlocationType\n```\n\n```text\nmediaInputType\n```\n\n```text\nlocationInputType\n```\n\n```text\nmediaType\n```\n\n```text\nlocationType\n```\n\n```text\nnew GraphQLInputObjectType({...\n```\n\n```text\nnew GraphQLObjectType({...\n```\n\n```text\ntype Book {\n title: String!\n}\n```\n\n```text\ninput AuthorInput {\n name: String!\n age: Int!\n}\n```\n\n```text\ninput BookInput {\n title: String!\n}\n```\n\n```text\ninput AuthorInput {\n name: String!\n age: Int!\n books: [BookInput!]\n}\n```\n\n```text\nbooks: [Book!]\n```\n\n========================================\n\nComments:\n- I've done something similar to this (using arrays) and it works. Could you your schema?\n- Hi mfirry, I added my Mongoose and GraphQL Schemas to the post. Please check them and give me reply as soon as possible. Thank you!!\n- I also need the `MutationType` in which you define `AddEvent`\n- Please check my code i added the mutation type. thank you...\n- Sorry, not enough time to work on your example. I'll link you to my little (working) sample hoping this helps you anyway. gist.github.com/mfirry/1ba61efcd31f7c744476\n- Thank you for your help, but i am not in this exact situation.I am trying to insert an array with dictionary, not a direct array. Please check LOCATION in event Schema(mongoose Schema).\n- @mfirry this example works because in your `airports` mutation definition, `type: new GraphQLList(GraphQLString)`, `GraphQLList` and `GraphQLString` are already input types but when you create a custom type like @Mahesh you need to create it with `GraphQLInputObjectType` if you want to use it in mutations. See my answer below.\n- This is awesome but it doesn't seem to work for me.. What am I doing wrong? Heres my mutationType gist.github.com/piq9117/64cee784677915edc1da8ffec7ffa383\n- Hi @adriantoine, can you provide the code of the mutation with usage of input.","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":610,"estimatedTokens":2784}}30{"id":"stack-55885337","source":"stackoverflow","questionId":55885337,"title":"\"Default Apollo Queries\" VS \"AsyncData\" (Nuxt.js)","tags":["vue.js","async-await","graphql","nuxt.js","vue-apollo"],"text":"Title: \"Default Apollo Queries\" VS \"AsyncData\" (Nuxt.js)\nTags: vue.js, async-await, graphql, nuxt.js, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm building a site with Nuxt/Vue, and it's using a GraphQL backend API. We access this using the Apollo module for Nuxt.\n\nIn a page component, you can do this (I think this is called a Smart Query, but I'm not sure):\n\n```\napollo: {\n pages: {\n query: pagesQuery,\n update(data) {\n return _get(data, \"pageBy\", {});\n }\n },\n }\n}\n```\n\nBut you can also do the query like this I think, using the Nuxt asyncData hook:\n\n```\nasyncData(context) {\n let client = context.app.apolloProvider.defaultClient;\n client.query({query, variables})\n .then(({ data }) => {\n // do what you want with data\n });\n }\n}\n```\n\nI'm not sure what the difference is between these two ways, and which is better. Does anyone know? I couldn't find an explanation in the docs anywhere.\n\n========================================\n\nCode:\n```js\napollo: {\n pages: {\n query: pagesQuery,\n update(data) {\n return _get(data, \"pageBy\", {});\n }\n },\n }\n}\n```\n\n```js\nasyncData(context) {\n let client = context.app.apolloProvider.defaultClient;\n client.query({query, variables})\n .then(({ data }) => {\n // do what you want with data\n });\n }\n}\n```\n\n========================================\n\nComments:\n- Using `asyncData` doesn't update Apollo cache automatically while smart query does.\n- So a smart query isn't blocking in anyway? I worry that my SSR page is going to have to wait for all these queries to finish before showing anything to the user.\n- My understanding is that the query behaves in the same manner as asyncData would, in that it is asynchronous, and the server prefetches data into a dedicated data store while pre-rendering and injects that into the client when complete. I've not noticed any blocking behaviour but only have a couple of projects utilising them to go by.\n- Asyncdata wait for data to be ready before rendering both on client and server","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":69,"estimatedTokens":504}}31{"id":"stack-45842544","source":"stackoverflow","questionId":45842544,"title":"GraphQL ObjectType with dynamic fields based on arguments","tags":["javascript","graphql"],"text":"Title: GraphQL ObjectType with dynamic fields based on arguments\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nWe are in the situation that the response of our GraphQL Query has to return some dynamic properties of an object. In our case we are not able to predefine all possible properties - so it has to be dynamic.\n\nAs we think there are two options to solve it.\n\n```\nconst MyType = new GraphQLObjectType({\n name: 'SomeType',\n fields: {\n name: {\n type: GraphQLString,\n },\n elements: {\n /*\n THIS is our special field which needs to return a dynamic object \n */\n },\n // ...\n },\n});\n```\n\nAs you can see in the example code is element the property which has to return an object. A response when resolve this could be:\n\n```\n{\n name: 'some name',\n elements: {\n an_unkonwn_key: {\n some_nested_field: {\n some_other: true,\n },\n },\n another_unknown_prop: 'foo',\n },\n}\n```\n\n**1) Return a \"Any-Object\"**\n\nWe could just return any object - so GraphQL do not need to know which fields the Object has. When we tell GraphQL that the field is the type GraphQlObjectType it needs to define fields. Because of this it seems not to be possible to tell GraphQL that someone is just an Object. \n\nFo this we have changed it like this:\n\n```\nelements: {\n type: new GraphQLObjectType({ name: 'elements' });\n },\n```\n\n**2) We could define dynamic field properties because its in an function**\n\nWhen we define fields as an function we could define our object dynamically. But the field function would need some information (in our case information which would be passed to elements) and we would need to access them to build the field object.\n\nExample:\n\n```\nconst MyType = new GraphQLObjectType({\n name: 'SomeType',\n fields: {\n name: {\n type: GraphQLString,\n },\n elements: {\n type: new GraphQLObjectType({\n name: 'elements',\n fields: (argsFromElements) => {\n // here we can now access keys from \"args\"\n const fields = {};\n argsFromElements.keys.forEach((key) => {\n // some logic here ..\n fields[someGeneratedProperty] = someGeneratedGraphQLType;\n });\n return fields;\n },\n }),\n args: {\n keys: {\n type: new GraphQLList(GraphQLString),\n },\n },\n },\n // ...\n },\n});\n```\n\nThis could work but the question would be if there is a way to pass the args and/or resolve object to the fields.\n\n**Question**\nSo our question is now: Which way would be recommended in our case in GraphQL and is solution 1 or 2 possible ? Maybe there is another solution ?\n\n**Edit**\nSolution 1 would work when using the ScalarType. Example:\n\n```\ntype: new GraphQLScalarType({\n name: 'elements',\n serialize(value) {\n return value;\n },\n }),\n```\n\nI am not sure if this is a recommended way to solve our situation.\n\n========================================\n\nTop Answer:\nOne more possible solution could be to declare any such dynamic object as a string. And then pass a stringified version of the object as value to that object from your resolver functions. And then eventually you can parse that string to JSON again to make it again an object on the client side.\n\nI'm not sure if its recommended way or not but I tried to make it work with this approach and it did work smoothly, so I'm sharing it here.\n\n========================================\n\nCode:\n```text\nconst MyType = new GraphQLObjectType({\n name: 'SomeType',\n fields: {\n name: {\n type: GraphQLString,\n },\n elements: {\n /*\n THIS is our special field which needs to return a dynamic object \n */\n },\n // ...\n },\n});\n```\n\n```text\n{\n name: 'some name',\n elements: {\n an_unkonwn_key: {\n some_nested_field: {\n some_other: true,\n },\n },\n another_unknown_prop: 'foo',\n },\n}\n```\n\n```text\nelements: {\n type: new GraphQLObjectType({ name: 'elements' });\n },\n```\n\n```text\nconst MyType = new GraphQLObjectType({\n name: 'SomeType',\n fields: {\n name: {\n type: GraphQLString,\n },\n elements: {\n type: new GraphQLObjectType({\n name: 'elements',\n fields: (argsFromElements) => {\n // here we can now access keys from \"args\"\n const fields = {};\n argsFromElements.keys.forEach((key) => {\n // some logic here ..\n fields[someGeneratedProperty] = someGeneratedGraphQLType;\n });\n return fields;\n },\n }),\n args: {\n keys: {\n type: new GraphQLList(GraphQLString),\n },\n },\n },\n // ...\n },\n});\n```\n\n```text\ntype: new GraphQLScalarType({\n name: 'elements',\n serialize(value) {\n return value;\n },\n }),\n```\n\n```text\nany\n```\n\n```text\nfields\n```\n\n```text\nelements\n```\n\n========================================\n\nComments:\n- Your answer sounds good. We will try out the defined JSON type as in your answer. Of course the flexibility will be limited when we just return \"any object\" without the possibility to control its data which are rly in need. But in our special case we have no other options because the properties are unknown on our graphql server. But: This case is just very special and unique in our logic.\n- how about use JSON.stringify() to make any json obj to a string, and then give the string to a key, e.g. {any_data: 'stringified json object'}\n- @NicolasS.Xu that is a great idea! I have this same problem, but solved it by turning my data into a string on the backend then using regex to parse it out on the client side.\n- @ToriHuang Regex? Why wouldn't you just do `JSON.parse(string)`?","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":216,"estimatedTokens":1361}}32{"id":"stack-36773858","source":"stackoverflow","questionId":36773858,"title":"GraphQL client libraries for iOS","tags":["ios","json","rest","graphql"],"text":"Title: GraphQL client libraries for iOS\nTags: ios, json, rest, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQL service that I need to hit from an iOS app, and I'm trying to survey what my options are for client libraries geared towards this purpose. My initial impression is that there are not many good options out there, and I'm a little surprised by this since Facebook's mobile app is always cited among the motivational material for GraphQL itself.\n\nWhat follows is my current understanding of my options. My questions is: what client library options am I overlooking? I'm also curious if you were to imagine the ideal GraphQL client library for iOS, what might it look like?\n\n- Just Alamofire, AFNetworking, or `NSURLSession` directly, passing in lovingly hand-crafted Query Documents and spelunking through a `Dictionary` representing the resulting JSON, or\n\n- Chester\n\n- GraphQLicious\n\n- Swift-GraphQL\n\n========================================\n\nTop Answer:\nThis question was asked a long time ago - I think today the standard answer to this will be to use Apollo Client.\n\nIt uses a similar API as the Apollo Client on the web and has a couple of really nice features:\n\n- Static type generation based on GraphQL Queries & Mutations\n\n- Normalized cache\n\n- Query watching & automatic UI updates\n\n- Manual store updates\n\nIt has not yet reached 1.0 but overall is a super promising project!\n\n**Here are some resources that should help you get started:**\n\n- Apollo iOS Quickstart\n\n- Apollo iOS on GitHub\n\n- Ray Wenderlich GraphQL Tutorial\n\n- Learn Apollo iOS Track\n\n========================================\n\nCode:\n```text\nNSURLSession\n```\n\n```text\nDictionary\n```\n\n========================================\n\nComments:\n- I was thinking about using a JavaScript GraphQL client, like Apollo docs.apollostack.com/apollo-client implement a few JS functions to handle network calls, return results or errors etc. bundle it with the app and run it using JavaScriptCore, here's good tutorial raywenderlich.com/124075/javascriptcore-tutorial\n- UPDATE: just found out that the JavaScript running in JavaScriptCore engine can't access the network, there's no http request implementation there and its just pure ECMAScript, so the network part should be native code, or (hate to say this) JS running in a hidden WebView... I wish there were mature implementations of GraphQL client in Swift, if you've found one please let me know... Cheers.\n- I learned about this one just this morning: github.com/apollostack/apollo-ios\n- If you are looking for Objective-C take a look at github.com/funcompany/graphql-ios\n- update: Swift-GraphQL has not been updated for two years.","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":63,"estimatedTokens":667}}33{"id":"stack-55415125","source":"stackoverflow","questionId":55415125,"title":"How to pass parameter to graphql fragment?","tags":["react-native","graphql"],"text":"Title: How to pass parameter to graphql fragment?\nTags: react-native, graphql\nSource: Stack Overflow\n\nQuestion:\nIt's easy to pass a parameter to a GraphQL query. But what about GraphQL fragments?\n\nThis code contains some perfectly normal querying with a parameter (itemId) and a hint at what I attempt to do (includeExtraResults) :\n\n```\nexport const GET_ITEM = gql`\n query GetItem($itemId: ID!, $includeExtraResults:BOOLEAN) {\n container {\n item(itemId: $itemId) {\n itemId\n someField\n innerItem(someExtraOption: $includeExtraResults) {\n ...InnerItemFragment\n }\n }\n }\n }\n ${INNER_ITEM_FRAGMENT}\n`;\n\nexport const INNER_ITEM_FRAGMENT = gql`\n fragment InnerItemFragment on InnerItemType {\n innerItemId\n innerInnerItem(someExtraOption: $includeExtraResults) {\n someFields\n }\n }\n ${INNER_INNER_ITEM_FRAGMENT}\n`;\n\nexport const INNER_INNER_ITEM_FRAGMENT = gql`\n /* (not detailed here) */\n`;\n```\n\nWhen inner-inner items get automatically queried as part of inner items, I don't want them to return the *field* based upon which the filter works. The client doesn't know the logic either. Instead I want to use the *parameter*, and the logic is decided on server side.\n\nStill, their query is implemented in a way that it wants the (optional) parameter \"includeExtraResults\", which is passed to GetItem in the first place.\n\nSo, is there a way to pass \"includeExtraResults\" to the inner fragment? What should be changed for this to make sense? In real life this is a complex system with many levels of inner fragments.\n\n========================================\n\nTop Answer:\nAs outlined here, you have to explicitly enable fragment variables before using them:\n\n```\nimport { enableExperimentalFragmentVariables } from 'graphql-tag'\n\nenableExperimentalFragmentVariables()\n```\n\nThat should at least let you use variables defined in your operation inside included fragments. Please note that this still is an experimental feature that's not officially part of the spec -- see this issue for the ongoing conversation.\n\n========================================\n\nCode:\n```js\nexport const GET_ITEM = gql`\n query GetItem($itemId: ID!, $includeExtraResults:BOOLEAN) {\n container {\n item(itemId: $itemId) {\n itemId\n someField\n innerItem(someExtraOption: $includeExtraResults) {\n ...InnerItemFragment\n }\n }\n }\n }\n ${INNER_ITEM_FRAGMENT}\n`;\n\nexport const INNER_ITEM_FRAGMENT = gql`\n fragment InnerItemFragment on InnerItemType {\n innerItemId\n innerInnerItem(someExtraOption: $includeExtraResults) {\n someFields\n }\n }\n ${INNER_INNER_ITEM_FRAGMENT}\n`;\n\n\nexport const INNER_INNER_ITEM_FRAGMENT = gql`\n /* (not detailed here) */\n`;\n```\n\n```text\nquery HeroComparison($first: Int = 3) {\n leftComparison: hero(episode: EMPIRE) {\n ...comparisonFields\n }\n rightComparison: hero(episode: JEDI) {\n ...comparisonFields\n }\n}\n\nfragment comparisonFields on Character {\n name\n friendsConnection(first: $first) {\n totalCount\n edges {\n node {\n name\n }\n }\n }\n}\n```\n\n```text\nimport { enableExperimentalFragmentVariables } from 'graphql-tag'\n\nenableExperimentalFragmentVariables()\n```\n\n========================================\n\nComments:\n- Could you maybe add an example to demonstrate the syntax right here in stackoverflow?\n- @jeancallisti The above should work with the code in your question. Other than enabling the feature, there's no changes needed. What is unclear about the syntax?\n- OK then, if it works \"as is\" and if includeExtraResults can be passed to innerInnerItem, then I'm good. I wonder how the compiler will react if I include that fragment in another query that doesn't have the parameter, but that's for another day.\n- I think `graphql-tag` will still parse that, but you'll definitely hit a server error since your query won't pass validation.\n- This was actually was I was trying to achieve, so I've changed \"correct answer\" to your answer (after almost 3 years of the other answer having the green tick ;-p). I don't remember why I was encountering issues and what led me to believe I couldn't use the global query parameter in the fragment. Maybe I was using some auto-generated Typescript wrappers and/or some syntax checking tool (Lint) which were throwing red flags about this. Or maybe I just wasn't bold enough to assume it would work.","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":131,"estimatedTokens":1083}}34{"id":"stack-39026831","source":"stackoverflow","questionId":39026831,"title":"How to use Graphene GraphQL framework with Django REST Framework authentication","tags":["python","django","rest","authentication","graphql"],"text":"Title: How to use Graphene GraphQL framework with Django REST Framework authentication\nTags: python, django, rest, authentication, graphql\nSource: Stack Overflow\n\nQuestion:\nI got some REST API endpoints in Django and I'd like to use the same authentication for Graphene. The documentation does not provide any guidance.\n\n========================================\n\nTop Answer:\nAdding some additional steps that I had to take when following this integration:\n\n```\nclass RTGraphQLView(GraphQLView):\n\ndef parse_body(self, request):\n if type(request) is rest_framework.request.Request:\n return request.data\n return super().parse_body(request)\n```\n\nGraphene was expecting the `.body` attr but DRF reads it and attaches it to `.data` before being passed to GraphQLView.\n\n========================================\n\nCode:\n```text\n# ...\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.decorators import authentication_classes, permission_classes, api_view\n\ndef graphql_token_view():\n view = GraphQLView.as_view(schema=schema)\n view = permission_classes((IsAuthenticated,))(view)\n view = authentication_classes((TokenAuthentication,))(view)\n view = api_view(['GET', 'POST'])(view)\n return view\n\nurlpatterns = [\n# ...\n url(r'^graphql_token', graphql_token_view()),\n url(r'^graphql', csrf_exempt(GraphQLView.as_view(schema=schema))),\n url(r'^graphiql', include('django_graphiql.urls')),\n# ...\n```\n\n```text\nauthentication_classes = (TokenAuthentication,)\n```\n\n```text\n^graphql_token\n```\n\n```text\n^graphql\n```\n\n```text\nAuthorization\n```\n\n```text\ngraphql_token\n```\n\n```py\nclass RTGraphQLView(GraphQLView):\n\ndef parse_body(self, request):\n if type(request) is rest_framework.request.Request:\n return request.data\n return super().parse_body(request)\n```\n\n```text\n.body\n```\n\n```text\n.data\n```\n\n========================================\n\nComments:\n- Does this still work for you? I am trying to do the same with SessionAuthentication but I get an error back from graphene-django when it tries to read the body of the request?\n- Still works, but I haven't the most up-to-date versions of packages. My answer used: Django==1.8.3 djangorestframework==3.2.2 django-graphiql==0.4.4 graphene==0.10.2 graphql-core==0.5.3 graphql-django-view==1.3 graphql-relay==0.4.4\n- is it possible to do a post request ?\n- @KentDelaCruzFueconcillo Yes.\n- Can you further explain what this means? Note that we added a new ^graphql_token endpoint and kept the original ^graphql which is used by the GraphiQL tool. Why do you have 2 seperate endpoints?","metadata":{"transformedAt":"2026-08-18T18:32:36.020Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":92,"estimatedTokens":658}}35{"id":"stack-37969096","source":"stackoverflow","questionId":37969096,"title":"Graphql query only not null objects","tags":["express","meteor","graphql","graphql-js"],"text":"Title: Graphql query only not null objects\nTags: express, meteor, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nim trying to perform a query like this:\n\n```\n{\n people{\n pet{\n name\n }\n }\n}\n```\n\nresult:\n\n```\n{\n \"people\": {\n \"pet\": null\n }\n},\n{\n \"people\": {\n \"pet\": {\n name: \"steve\"\n }\n }\n}\n```\n\nWhat i want is to get only people that contains a pet, is there any way to achieve this not coding on my resolver ?\n\n========================================\n\nTop Answer:\nActually, it is possible with the `filter: { pet: {ne: null} }` filtering:\n\n```\nquery allPeople(filter: { people: { pet: {ne: null} } }) {\n people {\n pet\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n people{\n pet{\n name\n }\n }\n}\n```\n\n```text\n{\n \"people\": {\n \"pet\": null\n }\n},\n{\n \"people\": {\n \"pet\": {\n name: \"steve\"\n }\n }\n}\n```\n\n```text\npeople(root, { hasPet }){\n // get allPeople\n if (typeof hasPet === 'undefined'){\n return allPeople\n }\n return allPeople.filter((person) => person.hasPet() === hasPet)\n}\n```\n\n```text\nhasPet\n```\n\n```text\nquery allPeople(filter: { people: { pet: {ne: null} } }) {\n people {\n pet\n }\n}\n```\n\n```text\nfilter: { pet: {ne: null} }\n```\n\n```text\nimport { Not, Repository } from 'typeorm';\n\n\nreturn await this.MyRepository.find({\n where: { My_Field: Not(null) }\n});\n```\n\n========================================\n\nComments:\n- stackoverflow.com/questions/36451910/…\n- You can have a look at this github.com/gridsome/gridsome/issues/1053#issuecomment-605328‌​928\n- Do you have any documentation reference for this? I wonder whether this filter functionality is specific to a particular stack, as it doesn't seem to work in Apollo Studio Star Wars API\n- @Philzen Actually I've been looking at `gatsby`'s docs - Don't know why it doesn't work on apollo and didn't find much info in their docs unfortunately. Hopefully this resource might help you find the needed info.","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":119,"estimatedTokens":486}}36{"id":"stack-58734176","source":"stackoverflow","questionId":58734176,"title":"How to use GitHub API to get a repository's dependents information in GitHub?","tags":["github","graphql","github-api"],"text":"Title: How to use GitHub API to get a repository's dependents information in GitHub?\nTags: github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nWhen I was using GitHub API v4 to get some information, I can easily get dependencies by using `repository.dependencyGraphManifests`. But I can't find any way to use GitHub API v4 to get the dependents information, though I can see it in the `Insights->Dependency Graph->Dependents`.\nI want to know if there is any possible way to get the dependents information in a GitHub repository? Whether GitHub API or something else.\n\n========================================\n\nTop Answer:\nI improved and packaged all the answers in a python command line utility github-dependents-info\n\n```\npip install github-dependents-info\ngithub-dependents-info --repo nvuillam/npm-groovy-lint --markdownfile ./package-usage.md --sort stars --verbose\n```\n\nIn addition to already existing features, it can:\n\n- Output as text, JSON or markdown file\n\n- Manage multiple packages in a single repo (ex: megalinter)\n\n- Retry HTTP requests when failing\n\n- Generate shields.io badges\n\nhttps://i.sstatic.net/sArUf.png\n\nExample result Link\n\n========================================\n\nCode:\n```text\nrepository.dependencyGraphManifests\n```\n\n```text\nInsights->Dependency Graph->Dependents\n```\n\n```python\nimport requests\nfrom bs4 import BeautifulSoup\n\nrepo = \"expressjs/express\"\npage_num = 3\nurl = 'https://github.com/{}/network/dependents'.format(repo)\n\nfor i in range(page_num):\n print(\"GET \" + url)\n r = requests.get(url)\n soup = BeautifulSoup(r.content, \"html.parser\")\n\n data = [\n \"{}/{}\".format(\n t.find('a', {\"data-repository-hovercards-enabled\":\"\"}).text,\n t.find('a', {\"data-hovercard-type\":\"repository\"}).text\n )\n for t in soup.findAll(\"div\", {\"class\": \"Box-row\"})\n ]\n\n print(data)\n print(len(data))\n paginationContainer = soup.find(\"div\", {\"class\":\"paginate-container\"}).find('a')\n if paginationContainer:\n url = paginationContainer[\"href\"]\n else:\n break\n```\n\n```py\n...\n paginationContainer = soup.find(\"div\", {\"class\":\"paginate-container\"}).find_all('a')\n if len(paginationContainer) > 1:\n paginationContainer = paginationContainer[1]\n else:\n paginationContainer = paginationContainer[0]\n...\n```\n\n```text\n<a>\n```\n\n```rb\n# frozen_string_literal: true\n\nrequire 'json'\nrequire 'nokogiri'\nrequire 'open-uri'\n\n$repo = ARGV.fetch(0, \"rgeo/rgeo\")\n\nRepo = Struct.new(:org, :repo, :stars, :forks)\n\nurl = \"https://github.com/#$repo/network/dependents\"\nrepos = []\n\nwhile url\n doc = Nokogiri::HTML(URI.open(url))\n doc.css('#dependents .Box .Box-row').each do |el|\n repos << Repo.new(\n *el.css('.f5 > a').map(&:inner_text),\n *el.at_css('.d-flex').content.delete(\" ,\").scan(/\\d+/).map(&:to_i)\n )\nrescue\n binding.irb\n end\n url = doc.at_css('.paginate-container > .BtnGroup > .BtnGroup-item:nth-child(2)').attr(\"href\")\nend\n\nif $stdin.tty? && $stdout.tty?\n # check `repos`\n binding.irb\nelse\n jj repos.map { { name: \"#{_1.org}/#{_1.repo}\", stars: _1.stars, forks: _1.forks } }\nend\n```\n\n```py\nimport requests\nfrom bs4 import BeautifulSoup\n\nrepo = \"expressjs/express\"\nurl = 'https://github.com/{}/network/dependents'.format(repo)\nnextExists = True\nresult = []\nwhile nextExists:\n r = requests.get(url)\n soup = BeautifulSoup(r.content, \"html.parser\")\n\n result = result + [\n \"{}/{}\".format(\n t.find('a', {\"data-repository-hovercards-enabled\":\"\"}).text,\n t.find('a', {\"data-hovercard-type\":\"repository\"}).text\n )\n for t in soup.findAll(\"div\", {\"class\": \"Box-row\"})\n ]\n nextExists = False\n for u in soup.find(\"div\", {\"class\":\"paginate-container\"}).findAll('a'):\n if u.text == \"Next\":\n nextExists = True\n url = u[\"href\"]\n\nfor r in result:\n print(r)\nprint(len(result))\n```\n\n```text\npage_num\n```\n\n```py\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\n\nrepo = \"mochajs/mocha\"\nurl = 'https://github.com/{}/network/dependents'.format(repo)\nnextExists = True\nmin_stars_cnt = 50\nresult_cnt = 100\nresult = []\nwhile nextExists and len(result) < result_cnt:\n # uncomment the line below to see progress.\n # print(\"url: \" + url + \" \" + \"cnt: \" + str(len(result)))\n r = requests.get(url)\n soup = BeautifulSoup(r.content, \"html.parser\")\n\n tmp = [\n {\n \"name\": \"{}/{}\".format(\n t.find('a', {\"data-repository-hovercards-enabled\":\"\"}).text,\n t.find('a', {\"data-hovercard-type\":\"repository\"}).text\n ),\n \"stars\": int(t.find(\"svg\", {\"class\": \"octicon-star\"}).parent.text.strip().replace(',', ''))\n }\n for t in soup.findAll(\"div\", {\"class\": \"Box-row\"})\n ]\n tmp = list(filter(lambda repo: repo[\"stars\"] > min_stars_cnt, tmp))\n result = result + tmp\n nextExists = False\n try:\n for u in soup.find(\"div\", {\"class\":\"paginate-container\"}).findAll('a'):\n if u.text == \"Next\":\n nextExists = True\n url = u[\"href\"]\n except Exception as e:\n print(e)\n print(\"waiting for 10 seconds...\")\n time.sleep(10)\n nextExists = True\n\nfor r in result:\n print(r[\"name\"] + \", \" + str(r[\"stars\"]))\nprint(len(result))\n```\n\n```text\nmin_stars_cnt\n```\n\n```text\nresult_cnt\n```\n\n```text\npip install github-dependents-info\ngithub-dependents-info --repo nvuillam/npm-groovy-lint --markdownfile ./package-usage.md --sort stars --verbose\n```\n\n```text\nfrom bs4 import BeautifulSoup\nimport collections\n\n\ndef get_dependents(repo_of_interest):\n dependents = set()\n \n for type in [\"PACKAGE\", \"REPOSITORY\"]:\n \n url = f'https://github.com/{repo_of_interest}/network/dependents?dependent_type={type}'\n \n nextExists = True\n while nextExists:\n\n r = requests.get(url)\n \n soup = BeautifulSoup(r.content, \"html.parser\")\n \n for t in soup.find_all(\"div\", {\"class\": \"Box-row\"}):\n \n user = t.find('a', {\"data-hovercard-type\":\"user\"})\n repo = t.find('a', {\"data-hovercard-type\":\"repository\"})\n if not user:\n user = t.find('a', {\"data-hovercard-type\":\"organization\"})\n \n if not user:\n img = t.find('img', {\"alt\": \"@ghost\"})\n if img:\n print(\"ghost account\")\n continue\n \n dependents.add(f\"{user.text}/{repo.text}\")\n \n nextExists = False\n if not soup.find(\"div\", {\"class\":\"paginate-container\"}):\n nextExists = True\n continue\n for u in soup.find(\"div\", {\"class\":\"paginate-container\"}).find_all('a'):\n if u.text == \"Next\":\n nextExists = True\n url = u[\"href\"]\n\n dependents = sorted(dependents)\n\n repo_names = set(x.split(\"/\")[1] for x in dependents)\n duplicates = [item for item, count in collections.Counter(repo_names).items() if count > 1]\n if duplicates:\n print(\"Contain repos with same names: probably forks?\")\n print(duplicates)\n\n return dependents\n\ndependents = get_dependents(\"nilearn/nilearn\")\n```\n\n========================================\n\nComments:\n- There are a few CLI tools which can do it (quite slowly by crawling github). github.com/github-tooling/ghtopdep or github.com/nvuillam/github-dependents-info for example.\n- There is `DependencyGraphManifest`, but at the time of this writing it only includes `dependencies` without `dependents`.\n- @Bertrand Martel: I tried to find you on linkedin to credit you, but without success... Add me if you like ! linkedin.com/posts/…\n- Hi @muvaf, first of all, thanks for your answer. I'm using your script to get all the dependent repos for a project. e.g. psf/requests. requests has more than 1.4 million dependent repos on github, but when I use this script, it only can grab 2831 results. And I can see it navigated 111 pages. Do you why it stopped collecting more results? Thank you very much.\n- After running a couple of more times, found the total number of results is not consistency, e.g. the last run got 2842 results and navigated 116 pages.\n- Looks like it is because the page is not fully loaded. I have replaced requests.get with selenium. Now it is getting all dependent repos.","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":280,"estimatedTokens":2121}}37{"id":"stack-62512778","source":"stackoverflow","questionId":62512778,"title":"How to get an array as an input for a GraphQL resolver","tags":["typescript","rest","graphql","nestjs","graphql-js"],"text":"Title: How to get an array as an input for a GraphQL resolver\nTags: typescript, rest, graphql, nestjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI want to get an array of strings as `ids` parameter from the query variables and use it inside my resolver. Below here is my code.\n\n### People.resolver.ts\n\n```\nimport {\n Resolver, Query, Mutation, Args,\n} from '@nestjs/graphql';\nimport { People } from './People.entity';\nimport { PeopleService } from './People.service';\n\n@Resolver(() => People)\nexport class PeopleResolver {\n constructor(private readonly peopleService: PeopleService) { }\n\n @Mutation(() => String)\n async deletePeople(@Args('ids') ids: string[]) : Promise {\n const result = await this.peopleService.deletePeople(ids);\n return JSON.stringify(result);\n }\n}\n```\n\nHowever, I am getting the following error,\n\n```\n[Nest] 8247 - 06/22/2020, 6:32:53 PM [RouterExplorer] Mapped {/run-migrations, POST} route +1ms\n(node:8247) UnhandledPromiseRejectionWarning: Error: You need to provide explicit type for PeopleResolver#deletePeople parameter #0 !\n at Object.findType (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/findType.js:17:15)\n at Object.getParamInfo (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/params.js:9:49)\n at /Users/eranga/Documents/Project/node_modules/type-graphql/dist/decorators/Arg.js:9:159\n at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/decorators/args.decorator.js:34:113\n at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:36\n at Array.forEach ()\n at LazyMetadataStorageHost.load (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:22)\n at GraphQLSchemaBuilder. (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:31:57)\n at Generator.next ()\n at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:17:71\n(node:8247) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)\n(node:8247) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\nI also tried the following variations,\n\n```\n@Args('ids', () => string[]) ids: string[]\n\n@Args('ids', () => String[]) ids: String[]\n\n@Args('ids', () => [String]) ids: String[]\n\n@Args('ids', { type: () => String[] }) ids: String[]\n```\n\nBut if I am to change my mutation like below to take a single string it works.\n\n```\n@Mutation(() => String)\nasync deletePeople(@Args('id') id: string) : Promise {\n const result = await this.peopleService.deletePeople([id]);\n return JSON.stringify(result);\n}\n```\n\nAny idea why this happens?\n\n========================================\n\nCode:\n```js\nimport {\n Resolver, Query, Mutation, Args,\n} from '@nestjs/graphql';\nimport { People } from './People.entity';\nimport { PeopleService } from './People.service';\n\n@Resolver(() => People)\nexport class PeopleResolver {\n constructor(private readonly peopleService: PeopleService) { }\n\n @Mutation(() => String)\n async deletePeople(@Args('ids') ids: string[]) : Promise<String> {\n const result = await this.peopleService.deletePeople(ids);\n return JSON.stringify(result);\n }\n}\n```\n\n```bash\n[Nest] 8247 - 06/22/2020, 6:32:53 PM [RouterExplorer] Mapped {/run-migrations, POST} route +1ms\n(node:8247) UnhandledPromiseRejectionWarning: Error: You need to provide explicit type for PeopleResolver#deletePeople parameter #0 !\n at Object.findType (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/findType.js:17:15)\n at Object.getParamInfo (/Users/eranga/Documents/Project/node_modules/type-graphql/dist/helpers/params.js:9:49)\n at /Users/eranga/Documents/Project/node_modules/type-graphql/dist/decorators/Arg.js:9:159\n at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/decorators/args.decorator.js:34:113\n at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:36\n at Array.forEach (<anonymous>)\n at LazyMetadataStorageHost.load (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/storages/lazy-metadata.storage.js:11:22)\n at GraphQLSchemaBuilder.<anonymous> (/Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:31:57)\n at Generator.next (<anonymous>)\n at /Users/eranga/Documents/Project/node_modules/@nestjs/graphql/dist/graphql-schema-builder.js:17:71\n(node:8247) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)\n(node:8247) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```js\n@Args('ids', () => string[]) ids: string[]\n\n@Args('ids', () => String[]) ids: String[]\n\n@Args('ids', () => [String]) ids: String[]\n\n@Args('ids', { type: () => String[] }) ids: String[]\n```\n\n```js\n@Mutation(() => String)\nasync deletePeople(@Args('id') id: string) : Promise<String> {\n const result = await this.peopleService.deletePeople([id]);\n return JSON.stringify(result);\n}\n```\n\n```text\nids\n```\n\n```js\n@Args({ name: 'ids', type: () => [String] }) ids: String[]\n```\n\n```js\n@UseGuards(GraphqlAuthGuard)\n@Mutation(() => String)\nasync deletePeople(@Args({ name: 'ids', type: () => [String] }) ids: String[]) : Promise<String> {\n const result = await this.peopleService.deletePeople(ids);\n return JSON.stringify(result);\n}\n```\n\n========================================\n\nComments:\n- I am trieng to achieve simular with an array of objects. Do you have any idea how to achieve this?\n- You should change your resolver to get the argument like `@Args({ name: , type: () => [<YOUR_OBJECT_INPUT_TYPE_AS_A_GRAPHQL_TYPE] }`\n- how can we pass multiple arguments? let's say we have updated mutations. i need to pass id and payload separatley. Is there any way to do that?\n- You can create 2 arg parameters. `deletePeople(@Args({ name: 'ids', type: () => [String] }) ids: String[], @Args({ name: 'payload', type: () => PayloadInputType }) payload: PayloadInputType)`\n- Is this outdated? it seems it answers no overload in this call\n- The answer is not outdated. I didn't understand what you meant by \"it answers no overload in this call\".\n- Yes, it is outdated, the new overload is like this - `@Args('', () => [ [String]) ids: String[])`\n- I think the answer is still valid as of today. I can see that the latest version (v10.0.16) still contains the overload matching the answer. However, I don't see an overload matching your answer though.","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":156,"estimatedTokens":1767}}38{"id":"stack-52595547","source":"stackoverflow","questionId":52595547,"title":"Graphql Field doesn't exist on type","tags":["ruby-on-rails","reactjs","graphql"],"text":"Title: Graphql Field doesn't exist on type\nTags: ruby-on-rails, reactjs, graphql\nSource: Stack Overflow\n\nQuestion:\nAfter skimming through the docs of Graphql I've started to implement it on a toy rails/reactJS project. The projects allows an user to sign in through devise then access a dummy /artist route that displays a list of artists. Everything seems to work fine until I try to consume api data with GraphQL from the react app to get artists and display them. \n\nOn the server side, I have a **graphql_controller.rb** such as:\n\n```\nclass GraphqlController Then, following to my model logic, I have set up graphql under graph/ with the following files: \n\n**graph/queries/artist_query.rb**\n\n```\nArtistQuery = GraphQL::ObjectType.define do\n name 'ArtistQuery'\n description 'The query root for this schema'\n\n field :artists, types[Types::ArtistType] do\n resolve(->(_, _, _) {\n Artist.all\n })\n end\nend\n```\n\n**types/artist_type.rb**\n\n```\nTypes::ArtistType = GraphQL::ObjectType.define do\n name 'Artist'\n description 'A single artist.'\n\n field :id, !types.ID\n field :name, types.String\n field :description, types.String\nend\n```\n\n**schema.rb**\n\n```\nSchema = GraphQL::Schema.define do\n query ArtistQuery\nend\n```\n\nOn the client side, for the sake of keeping things organized, I use 3 files to render this artist list:\n\nFirst, **ArtistSchema.js** \n\n```\nimport { gql } from 'react-apollo';\n\nconst artistListQuery = gql`\n {\n query {\n artists {\n id\n name\n description \n }\n }\n }\n`;\n\nexport default artistListQuery;\n```\n\nThen, an **`Artist.js`**\n\n```\nimport React, { Component } from 'react';\n\nclass Artist extends Component {\n render() {\n return (\n \n {this.props.index + 1}\n {this.props.data.name}\n {this.props.data.description} min\n \n );\n }\n}\n\nexport default Artist;\n```\n\nAnd finally, wrapping these two together in a larger layout: **Artists.jsx**:\n\n```\nimport React, { Component } from 'react';\nimport {graphql} from 'react-apollo';\nimport Artist from './Artist';\nimport artistListQuery from './ArtistSchema';\n\nclass Artists extends Component {\n render() {\n if(this.props.data.loading) {\n return (Loading\n\n)\n } else {\n\n console.log(this.props.data)\n const ArtistsItems = this.props.data.artists.map((data,i) => {\n return ();\n });\n return (\n \n \n\n### Artists\n\n \n \n \n #\n Name\n Description\n \n \n \n { ArtistsItems }\n \n \n \n );\n }\n\n }\n}\n\nexport default graphql(artistListQuery)(Artists);\n```\n\nWhat happens when this code is executed:\n\nOn server-side (sorry for the unformatted output, but it displays like this in console): \n\n```\nProcessing by GraphqlController#index as */*\n18:49:46 api.1 | Parameters: {\"query\"=>\"{\\n query {\\n artists {\\n id\\n name\\n description\\n __typename\\n }\\n __typename\\n }\\n}\\n\", \"operationName\"=>nil, \"graphql\"=>{\"query\"=>\"{\\n query {\\n artists {\\n id\\n name\\n description\\n __typename\\n }\\n __typename\\n }\\n}\\n\", \"operationName\"=>nil}}\n```\n\nFollowed by the error:\n\n```\nCompleted 422 Unprocessable Entity in 36ms (Views: 0.2ms | ActiveRecord: 0.0ms)\n```\n\nOn the client side, if I monitor Network > Response for graphql, I (of course) receive a 422 error code and the following error message:\n\n```\n{\"errors\":[{\"message\":\"Field 'query' doesn't exist on type 'ArtistQuery'\",\"locations\":[{\"line\":2,\"column\":3}],\"fields\":[\"query\",\"query\"]}]}\n```\n\nI assume my query is not done correctly. I have been trying various queries formats (from docs or gists examples) but I cannot end finding a correct way to get back my artist data. \n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\nIn my case the issue was that I had a structure like this:\n\n```\nmodule Types\n class SomeType BUT in the query I had other nested structure called **data** that I forgot about:\n\n```\nmutation {\n myMutation(\n ... \n ) {\n someType {\n comparator {\n ...\n }\n data {\n options {\n ...\n }\n }\n }\n }\n}\n```\n\nSo after changing `SomeType` class to add that missing key solved my issue. So now it look like this:\n\n```\nmodule Types\n class SomeType < Types::BaseObject\n field :comparator,\n Types::ComparatorType\n field :data,\n Types::DataType\n end\nend\n\n# New file\nmodule Types\n class DataType < Types::BaseObject\n field :options,\n [Types::OptionType]\n end\nend\n```\n\n========================================\n\nCode:\n```text\nclass GraphqlController < ApiController\n rescue_from Errors::Unauthorized do |exception|\n render json: {errors: ['Unauthorized.']}, status: :unauthorized\n end\n\n def index\n result = Schema.execute params[:query], variables: params[:variables], context: context\n render json: result, status: result['errors'] ? 422 : 200\n end\n\nprivate\n\n def context\n token, options = ActionController::HttpAuthentication::Token.token_and_options request\n {\n ip_address: request.remote_ip\n }\n end\nend\n```\n\n```text\nArtistQuery = GraphQL::ObjectType.define do\n name 'ArtistQuery'\n description 'The query root for this schema'\n\n field :artists, types[Types::ArtistType] do\n resolve(->(_, _, _) {\n Artist.all\n })\n end\nend\n```\n\n```text\nTypes::ArtistType = GraphQL::ObjectType.define do\n name 'Artist'\n description 'A single artist.'\n\n field :id, !types.ID\n field :name, types.String\n field :description, types.String\nend\n```\n\n```text\nSchema = GraphQL::Schema.define do\n query ArtistQuery\nend\n```\n\n```text\nimport { gql } from 'react-apollo';\n\nconst artistListQuery = gql`\n {\n query {\n artists {\n id\n name\n description \n }\n }\n }\n`;\n\nexport default artistListQuery;\n```\n\n```text\nimport React, { Component } from 'react';\n\nclass Artist extends Component {\n render() {\n return (\n <tr>\n <td>{this.props.index + 1}</td>\n <td>{this.props.data.name}</td>\n <td>{this.props.data.description} min</td>\n </tr>\n );\n }\n}\n\nexport default Artist;\n```\n\n```text\nimport React, { Component } from 'react';\nimport {graphql} from 'react-apollo';\nimport Artist from './Artist';\nimport artistListQuery from './ArtistSchema';\n\nclass Artists extends Component {\n render() {\n if(this.props.data.loading) {\n return (<p>Loading</p>)\n } else {\n\n console.log(this.props.data)\n const ArtistsItems = this.props.data.artists.map((data,i) => {\n return (<Artist key={i} index={i} data={data}></Artist>);\n });\n return (\n <div>\n <h1>Artists</h1>\n <table className=\"table table-striped table\">\n <thead>\n <tr>\n <th>#</th>\n <th>Name</th>\n <th>Description</th>\n </tr>\n </thead>\n <tbody>\n { ArtistsItems }\n </tbody>\n </table>\n </div>\n );\n }\n\n }\n}\n\nexport default graphql(artistListQuery)(Artists);\n```\n\n```text\nProcessing by GraphqlController#index as */*\n18:49:46 api.1 | Parameters: {\"query\"=>\"{\\n query {\\n artists {\\n id\\n name\\n description\\n __typename\\n }\\n __typename\\n }\\n}\\n\", \"operationName\"=>nil, \"graphql\"=>{\"query\"=>\"{\\n query {\\n artists {\\n id\\n name\\n description\\n __typename\\n }\\n __typename\\n }\\n}\\n\", \"operationName\"=>nil}}\n```\n\n```text\nCompleted 422 Unprocessable Entity in 36ms (Views: 0.2ms | ActiveRecord: 0.0ms)\n```\n\n```text\n{\"errors\":[{\"message\":\"Field 'query' doesn't exist on type 'ArtistQuery'\",\"locations\":[{\"line\":2,\"column\":3}],\"fields\":[\"query\",\"query\"]}]}\n```\n\n```text\nArtist.js\n```\n\n```text\nconst artistListQuery = gql`\n query UseTheNameYouWantHere {\n artists {\n id\n name\n description \n }\n }\n`;\n```\n\n```text\nquery\n```\n\n```text\nQuery\n```\n\n```text\ngraphiql\n```\n\n```text\n<<~QUERY\n query users {\n posts {\n ...\n }\n }\nQUERY\n```\n\n```text\n<<~QUERY\n query users {\n users {\n posts {\n ...\n }\n }\n }\nQUERY\n```\n\n```text\nmodule Types\n class SomeType < Types::BaseObject\n field :comparator,\n Types::ComparatorType\n field :options,\n [Types::OptionType]\n end\nend\n```\n\n```text\nmutation {\n myMutation(\n ... \n ) {\n someType {\n comparator {\n ...\n }\n data {\n options {\n ...\n }\n }\n }\n }\n}\n```\n\n```text\nmodule Types\n class SomeType < Types::BaseObject\n field :comparator,\n Types::ComparatorType\n field :data,\n Types::DataType\n end\nend\n\n# New file\nmodule Types\n class DataType < Types::BaseObject\n field :options,\n [Types::OptionType]\n end\nend\n```\n\n```text\nSomeType\n```\n\n```rb\nfield :visit_count, Integer, :null => false, :description => \"The sum of..\"\n```\n\n```text\n{\n user {\n nodes {\n blogs {\n name\n visitCount\n }\n }\n }\n}\n```\n\n```html\nFailed to implement Blog.visitCount, tried:\n\n- `Types::BlogType#visit_count`, which did not exist\n- `AppGraphql#visit_count`, which did not exist\n- Looking up hash key `:visit_count` or `\"visit_count\"` on `#<AppGraphql:0x00007f8394982e88>`, but it wasn't a Hash.\n\nTo implement this field, define one of the methods above (and check for typos)\n```\n\n```rb\nfield :visit_count, Integer, :null => false\n```\n\n```rb\nfield :visit_count, Integer, :null => false, :hash_key => :visitCount\n```\n\n```text\nvisitCount\n```\n\n```text\nvisit_count\n```\n\n```text\nvisit_count\n```\n\n```text\nBlogType\n```\n\n```text\nLooking up hash key\n```\n\n```text\nvisit_count\n```\n\n```text\nvisitCount\n```\n\n```text\nhash_key\n```\n\n========================================\n\nComments:\n- thanks a lot for your answer but I tried that before, doing what you advice me results in an error on the client side like: `apollo.umd.js:1409 Uncaught Error: Encountered a sub-selection on the query, but the store doesn't have an object reference. This should never happen during normal use unless you have custom code that is directly manipulating the store; please file an issue.` The server doesnt even get the request when I use the query code you provided. Concerning the graphiql client provided by the game I dont have access to it because my app is an api without views.\n- Ooof I spent an hour or more around not understanding why my 2nd returned field worked... it was this. Doh. Thanks\n- Ugggggggh this was killing me for over an hour. Thank you so much for posting this!\n- this is da....m right!!!!! thx\n- I owe you many internet points for this. Thank you for dispelling my ignorance.\n- page doesnt exist, even without the asterisks","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":536,"estimatedTokens":2667}}39{"id":"stack-40184367","source":"stackoverflow","questionId":40184367,"title":"Do GraphQL fields support polymorphism based on passed in arguments?","tags":["graphql","graphql-js"],"text":"Title: Do GraphQL fields support polymorphism based on passed in arguments?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI would like to define the following queries\n\n```\n{\n// return all individuals\nindividuals {\n id\n }\n}\n\n// return ONE individual by id\nindividuals(id:\"123\") {\n id\n }\n}\n```\n\nnote that the query name is the same, only the parameters are different.\n\nToday, the only workaround I found is to define different query names.\n\nHow can I define polymorphic queries? Is it even possible?\n\n========================================\n\nCode:\n```text\n{\n// return all individuals\nindividuals {\n id\n }\n}\n\n// return ONE individual by id\nindividuals(id:\"123\") {\n id\n }\n}\n```\n\n```text\nQuery\n```\n\n```text\nindividuals\n```\n\n```text\nindividuals(search: \"Dan\")\n```\n\n```text\nindividuals(status: \"admin\")\n```\n\n```text\nindividuals\n```\n\n```text\nindividuals(status: \"admin\", search: \"Dan\")\n```\n\n========================================\n\nComments:\n- I'm not sure what you mean here by \"query name\" - are you referring to the field name on the root query type?\n- It's explained here graphql.org/learn/queries In the examples above, the query name is \"individuals\"\n- For an item by `id`, I am returning an array of `1`, without an `id`, an array of `n`. Seems to work well.","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":76,"estimatedTokens":320}}40{"id":"stack-39691111","source":"stackoverflow","questionId":39691111,"title":"Graphql Unknown argument on field","tags":["javascript","graphql"],"text":"Title: Graphql Unknown argument on field\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI am new to GraphQL. Whenever I try to send args on (posts) child node like the query below, I get an error msg \"Unknown argument id on field posts of type user\". I want to bring a particular post only, not all of them.\n\n```\n{ people(id:[1,2]) {\n id\n username\n posts(id:2) {\n title\n tags {\n name\n }\n }\n }\n }\n```\n\nHere is my Schema.js file ..\n\n```\nvar graphql = require('graphql');\nvar Db = require('./db');\nvar users = new graphql.GraphQLObjectType({\n name : 'user',\n description : 'this is user info',\n fields : function(){\n return {\n id :{\n type : graphql.GraphQLInt,\n resolve(user){\n return user.id;\n }\n },\n username :{\n type : graphql.GraphQLString,\n resolve(user){\n return user.username;\n }\n },\n\n posts:{\n id:{\n type : graphql.GraphQLString,\n resolve(post){\n return post.id;\n }\n },\n type: new graphql.GraphQLList(posts),\n resolve(user){\n return user.getPosts();\n }\n }\n\n }\n }\n});\n\nvar posts = new graphql.GraphQLObjectType({\n name : 'Posts',\n description : 'this is post info',\n fields : function(){\n return {\n id :{\n type : graphql.GraphQLInt,\n resolve(post){\n return post.id;\n }\n },\n title :{\n type : graphql.GraphQLString,\n resolve(post){\n return post.title;\n }\n },\n content:{\n type : graphql.GraphQLString,\n resolve(post){\n return post.content;\n }\n },\n person :{\n type: users,\n resolve(post){\n return post.getUser();\n }\n },\n\n tags :{\n type: new graphql.GraphQLList(tags),\n resolve(post){\n return post.getTags();\n }\n }\n }\n }\n});\n\nvar tags = new graphql.GraphQLObjectType({\n name : 'Tags',\n description : 'this is Tags info',\n fields : function(){\n return {\n id :{\n type : graphql.GraphQLInt,\n resolve(tag){\n return tag.id;\n }\n },\n name:{\n type : graphql.GraphQLString,\n resolve(tag){\n return tag.name;\n }\n },\n posts :{\n type: new graphql.GraphQLList(posts),\n resolve(tag){\n return tag.getPosts();\n }\n }\n }\n }\n});\n\nvar query = new graphql.GraphQLObjectType({\n name : 'query',\n description : 'Root query',\n fields : function(){\n return {\n people :{\n type : new graphql.GraphQLList(users),\n args :{\n id:{type: new graphql.GraphQLList(graphql.GraphQLInt)},\n username:{\n type: graphql.GraphQLString\n }\n },\n resolve(root,args){\n return Db.models.user.findAll({where:args});\n }\n },\n\n posts:{\n type : new graphql.GraphQLList(posts),\n args :{\n id:{\n type: graphql.GraphQLInt\n },\n title:{\n type: graphql.GraphQLString\n },\n },\n resolve(root,args){\n return Db.models.post.findAll({where:args});\n }\n },\n\n tags :{\n type : new graphql.GraphQLList(tags),\n args :{\n id:{\n type: graphql.GraphQLInt\n },\n name:{\n type: graphql.GraphQLString\n },\n },\n resolve(root,args){\n return Db.models.tag.findAll({where:args});\n }\n }\n\n }\n }\n\n});\nvar Schama = new graphql.GraphQLSchema({\n query : query,\n mutation : Mutation\n})\n\nmodule.exports = Schama;\n```\n\n========================================\n\nTop Answer:\nYou get this error if the argument does not exist in the field.\n\nFor example, in this case, `invalidArg` does not exist in the list. The only possible arguments are `last`, `after`, `first`, `before`, `orderBy` and `ownedByViewer`. If you try to pass anything else, you will get an error.\n\nhttps://i.sstatic.net/ZtAPy.png\n\n========================================\n\nCode:\n```text\n{ people(id:[1,2]) {\n id\n username\n posts(id:2) {\n title\n tags {\n name\n }\n }\n }\n }\n```\n\n```text\nvar graphql = require('graphql');\nvar Db = require('./db');\nvar users = new graphql.GraphQLObjectType({\n name : 'user',\n description : 'this is user info',\n fields : function(){\n return {\n id :{\n type : graphql.GraphQLInt,\n resolve(user){\n return user.id;\n }\n },\n username :{\n type : graphql.GraphQLString,\n resolve(user){\n return user.username;\n }\n },\n\n posts:{\n id:{\n type : graphql.GraphQLString,\n resolve(post){\n return post.id;\n }\n },\n type: new graphql.GraphQLList(posts),\n resolve(user){\n return user.getPosts();\n }\n }\n\n\n }\n }\n});\n\n\n\nvar posts = new graphql.GraphQLObjectType({\n name : 'Posts',\n description : 'this is post info',\n fields : function(){\n return {\n id :{\n type : graphql.GraphQLInt,\n resolve(post){\n return post.id;\n }\n },\n title :{\n type : graphql.GraphQLString,\n resolve(post){\n return post.title;\n }\n },\n content:{\n type : graphql.GraphQLString,\n resolve(post){\n return post.content;\n }\n },\n person :{\n type: users,\n resolve(post){\n return post.getUser();\n }\n },\n\n tags :{\n type: new graphql.GraphQLList(tags),\n resolve(post){\n return post.getTags();\n }\n }\n }\n }\n});\n\nvar tags = new graphql.GraphQLObjectType({\n name : 'Tags',\n description : 'this is Tags info',\n fields : function(){\n return {\n id :{\n type : graphql.GraphQLInt,\n resolve(tag){\n return tag.id;\n }\n },\n name:{\n type : graphql.GraphQLString,\n resolve(tag){\n return tag.name;\n }\n },\n posts :{\n type: new graphql.GraphQLList(posts),\n resolve(tag){\n return tag.getPosts();\n }\n }\n }\n }\n});\n\nvar query = new graphql.GraphQLObjectType({\n name : 'query',\n description : 'Root query',\n fields : function(){\n return {\n people :{\n type : new graphql.GraphQLList(users),\n args :{\n id:{type: new graphql.GraphQLList(graphql.GraphQLInt)},\n username:{\n type: graphql.GraphQLString\n }\n },\n resolve(root,args){\n return Db.models.user.findAll({where:args});\n }\n },\n\n posts:{\n type : new graphql.GraphQLList(posts),\n args :{\n id:{\n type: graphql.GraphQLInt\n },\n title:{\n type: graphql.GraphQLString\n },\n },\n resolve(root,args){\n return Db.models.post.findAll({where:args});\n }\n },\n\n tags :{\n type : new graphql.GraphQLList(tags),\n args :{\n id:{\n type: graphql.GraphQLInt\n },\n name:{\n type: graphql.GraphQLString\n },\n },\n resolve(root,args){\n return Db.models.tag.findAll({where:args});\n }\n }\n\n }\n }\n\n});\nvar Schama = new graphql.GraphQLSchema({\n query : query,\n mutation : Mutation\n})\n\nmodule.exports = Schama;\n```\n\n```text\nvar users = new graphql.GraphQLObjectType({\n name : 'user',\n description : 'this is user info',\n fields : function(){\n return {\n id :{\n type : graphql.GraphQLInt,\n resolve(user){\n return user.id;\n }\n },\n username :{\n type : graphql.GraphQLString,\n resolve(user){\n return user.username;\n }\n },\n\n posts:{\n args: {\n id:{\n type : graphql.GraphQLInt,\n },\n type: new graphql.GraphQLList(posts),\n resolve(user, args){\n // Code here to use args.id\n return user.getPosts();\n }\n }\n\n\n }\n }\n});\n```\n\n```text\ninvalidArg\n```\n\n```text\nlast\n```\n\n```text\nafter\n```\n\n```text\nfirst\n```\n\n```text\nbefore\n```\n\n```text\norderBy\n```\n\n```text\nownedByViewer\n```\n\n```text\npost(id:2) {\n title\n tags {\n name\n }\n }\n```\n\n```text\nposts\n```\n\n```text\npost\n```\n\n========================================\n\nComments:\n- What does your schema look like? Most likely you didn't declare the id argument correctly in the schema.\n- I have added my schema.js file please check once @helfer\n- Because of your tip I no longer have my issues with red swirlies on nested types, thank you! However, in my example, I had to put the args-tag on my INPUT definition and not the OUTPUT definition as you are giving an example of above... Maybe Achyat does not need to use both...? Also, you are missing a curly bracket before type, as I believe args should not contain type and resolver... I just wanted to point out this for those that might be in a similar situation...","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":470,"estimatedTokens":2091}}41{"id":"stack-55827337","source":"stackoverflow","questionId":55827337,"title":"GraphQL query to access first item in an array?","tags":["graphql"],"text":"Title: GraphQL query to access first item in an array?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nHad a good search, but can't seem to find anything for this. Is there a way in GraphQL to only access the first item in an array?\n\nSomething like:\n\n```\nquery {\n allDBItems {\n edges {\n node {\n exampleArray([0])\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nNOT this way - there is no such 'client only' syntax.\n\nGeneral rule **'ask for what you need'** requires an explicit expression when passing [named] parameters (variables).\n\n**Just tell your API what you need** - pass a `limit` (and `index`?) parameter - sth recognizable for your API [resolvers]. \n\nWithout that you can just use only the first of all returned array elements - suitable only for small datasets.\n\nRead graphql docs about pagination.\n\n========================================\n\nCode:\n```text\nquery {\n allDBItems {\n edges {\n node {\n exampleArray([0])\n }\n }\n }\n}\n```\n\n```text\n@skip\n```\n\n```text\n@include\n```\n\n```text\nlimit\n```\n\n```text\nfirst\n```\n\n```text\nlast\n```\n\n```text\ngraphql-lodash\n```\n\n```text\nlimit\n```\n\n```text\nindex\n```\n\n========================================\n\nComments:\n- Thank you for taking the time to respond. So you can't put a limit on the size of the returned arrays? As in, you can only retrieve the full arrays? I have some very large arrays and need only the first item in each. I'm guessing you can't use `(first:x)` on an individual array.\n- You can pass variables to tell API how many records you need - resolver should use this parameter for SQL LIMIT (f.e.).\n- I think this approach will undermine the GraphQL ability to statically verify upfront if an operation is valid before deployment.","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":87,"estimatedTokens":435}}42{"id":"stack-36498163","source":"stackoverflow","questionId":36498163,"title":"GraphQL \"not equal\" operator?","tags":["graphql"],"text":"Title: GraphQL \"not equal\" operator?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQl API for listing a bunch of items, and I can query it perfectly etc.\nBut now I'd like to query for a subset of that list where one property can have 'all possible values except one specific one'.\n\nFor example, I want to query something like this:\n\n```\n{\n items(status: !\"Unwanted\"){\n id\n }\n}\n```\n\nThat exclamation mark obviously doesn't work, but it illustrates what I am after.\nCan't find any information about this online.\n\nDoes anybody know of a way to do this?\nI would really hate having to enumerate all possible wanted values instead of just excluding the one unwanted value. This would be really bad design and is not scalable.\n\nThanks.\n\n========================================\n\nTop Answer:\nUse `ne` :\n\n```\n{\n items(filter: {status: {ne: \"Unwanted\"}}){\n id\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n items(status: !\"Unwanted\"){\n id\n }\n}\n```\n\n```text\nstatusExcept\n```\n\n```text\nitems\n```\n\n```text\n{\n items(filter: {status: {ne: \"Unwanted\"}}){\n id\n }\n}\n```\n\n```text\nne\n```\n\n```text\n{\n items(filter: {status: {notIn: \"Unwanted\"}}){\n id\n }\n}\n```\n\n```text\n4.3.2\n```\n\n```text\nnotIn\n```\n\n========================================\n\nComments:\n- Thanks for the tip. I can see how that would work easily. Does GraphQL really have no concept of \"not\"? Seems like such a glaring omission.\n- @batijo GraphQL has no concept of search, rather you have to implement the search using tools given to you by GraphQL, for example arguments. GraphQL is just a language specification, it remains neutral about how search should work in your particular API or application.\n- But it does! It's a query language. It has query parameters that allow you to search for specific values (however they may be implemented by the schema in the background). So if I can look for e.g. { status: \"New\"}, which is status=\"New\", why does it not have a concept of status != \"New\", for example: { $not: { status: \"New\"} }? Seems like an obvious thing to add.\n- I did end up adding a kind of \"notNew\" query parameter, which the resolve() function translates into a more complex query, as suggested by @Matthias247 above.\n- @batjko It's not really like that :) When you do `status: \"New\"`you just pass an argument to the GraphQL resolve function. It can be for a search, but it can also be for other purposes. Eg pagination, choosing the needed size of the image. For those arguments $not doesn't make much sense.\n- Good point. I didn't really see it as \"passing arguments to the resolve function\" before but it makes a lot of sense. I usually just understood it as \"query parameters\" and all that the term implies. Fair enough. Thanks for the explanation, @freiksenet!\n- I think graphql to put \"query\" in their acronym but no advanced search capabilities is really disappointing, I hope it gets the power of a mongo query ($not, $lt, etc...) our of the box with no serverside changes to make it work\n- missing `filter: {}` around `status: {ne: \"Unwanted\"}`. This should read `items(filter: { status: {ne: \"Unwanted\"} })`\n- Thanks for the answer! How would this work on the resolver side?\n- This is not GraphQL. That \"filter\" parameter must be custom-defined as part of the schema and have your custom resolver that can take and apply that filter object. See this rejected proposal on the GraphQL spec: github.com/graphql/graphql-spec/issues/…","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":99,"estimatedTokens":864}}43{"id":"stack-73379691","source":"stackoverflow","questionId":73379691,"title":"Unexpected LAMBDA_RUNTIME Failed to post handler success response. Http response code: 413 error","tags":["amazon-web-services","express","aws-lambda","graphql","serverless"],"text":"Title: Unexpected LAMBDA_RUNTIME Failed to post handler success response. Http response code: 413 error\nTags: amazon-web-services, express, aws-lambda, graphql, serverless\nSource: Stack Overflow\n\nQuestion:\nSo I have a serverless express application running in a Lambda. One request (response size around 800KB) keeps returning a `LAMBDA_RUNTIME Failed to post handler success response. Http response code: 413.` error.\nI thought it could be due to some internal logic timing out, and added logs, and all the fetch and processing takes maximum 6 seconds, but the lamdba still returns this error.\n\nThese are the response headers\n\n```\nx-amz-cf-pop: YTO50-C3\nx-amzn-errortype: InternalServerErrorException\nx-amzn-requestid: f291230-342-4324-324-cb7df188944c\nx-cache: Error from cloudfront\n```\n\nThe response size is definitely not too big, I am returning a response with right data, no errors are being thrown in the logs. Any idea why this could be happening? Also any suggestions on how I can debug this issue? Everything of course works in local, but is there a way for me debug the actual lambda? The logs I added indicate that the full process completes, yet somehow there is an error being returned.\n\nUpdated my serverless.yml config\n\n```\nservice: my-service\nvariablesResolutionMode: 20210326\nuseDotenv: true\n\ncustom:\n serverless-offline:\n useChildProcesses: true\n webpack:\n webpackConfig: ./webpack.config.js\n packager: \"yarn\"\n includeModules: true\n prune:\n automatic: true\n includeLayers: true\n number: 3\n customDomain:\n domainName: \"abc.com\"\n basePath: \"val\"\n stage: ${someval}\n createRoute53Record: true\n\nplugins:\n - serverless-domain-manager\n - serverless-webpack\n - serverless-prune-plugin\n - serverless-webpack-prisma\n - serverless-offline\n\nprovider:\n lambdaHashingVersion: \"20201221\"\n name: aws\n runtime: nodejs14.x\n region: us-east-1\n timeout: 30\n apiGateway:\n minimumCompressionSize: 1024 \n iamRoleStatements:\n - Effect: Allow\n Action: ssm:Get*\n Resource:\n - \"abc/${opt:stage}/backend/*\"\n - \"abc/${opt:stage}/services/*\"\n - Effect: Allow\n Action: kms:Decrypt\n Resource: \"*\"\n - Effect: \"Allow\"\n Action: s3:PutObject\n Resource: \"abc/*\"\n - Effect: \"Allow\"\n Action:\n - sns:Publish\n Resource: \"*\"\n\n environment:\n - myvars: 'abc'\n\nfunctions:\n graphql:\n handler: src/index.graphqlHandler\n events:\n - http:\n path: /graphql\n method: options\n - http:\n path: /graphql\n method: get\n - http:\n path: /graphql\n method: post\n```\n\n========================================\n\nTop Answer:\nYou can use streamed response for larger payloads. The default limit for streams is 20MB that can be increased. source\n\nI had an 8MB file that didn't fit to the normal limit. I changed it to stream and it worked fine.\n\nStreaming requires some implementation changes on the Lambda side, but my curl/node client requests work without any changes.\n\nI used Lambda URL and astuyve/lambda-stream library in my project.\n\n========================================\n\nCode:\n```text\nx-amz-cf-pop: YTO50-C3\nx-amzn-errortype: InternalServerErrorException\nx-amzn-requestid: f291230-342-4324-324-cb7df188944c\nx-cache: Error from cloudfront\n```\n\n```text\nservice: my-service\nvariablesResolutionMode: 20210326\nuseDotenv: true\n\ncustom:\n serverless-offline:\n useChildProcesses: true\n webpack:\n webpackConfig: ./webpack.config.js\n packager: \"yarn\"\n includeModules: true\n prune:\n automatic: true\n includeLayers: true\n number: 3\n customDomain:\n domainName: \"abc.com\"\n basePath: \"val\"\n stage: ${someval}\n createRoute53Record: true\n\nplugins:\n - serverless-domain-manager\n - serverless-webpack\n - serverless-prune-plugin\n - serverless-webpack-prisma\n - serverless-offline\n\nprovider:\n lambdaHashingVersion: \"20201221\"\n name: aws\n runtime: nodejs14.x\n region: us-east-1\n timeout: 30\n apiGateway:\n minimumCompressionSize: 1024 \n iamRoleStatements:\n - Effect: Allow\n Action: ssm:Get*\n Resource:\n - \"abc/${opt:stage}/backend/*\"\n - \"abc/${opt:stage}/services/*\"\n - Effect: Allow\n Action: kms:Decrypt\n Resource: \"*\"\n - Effect: \"Allow\"\n Action: s3:PutObject\n Resource: \"abc/*\"\n - Effect: \"Allow\"\n Action:\n - sns:Publish\n Resource: \"*\"\n\n environment:\n - myvars: 'abc'\n\nfunctions:\n graphql:\n handler: src/index.graphqlHandler\n events:\n - http:\n path: /graphql\n method: options\n - http:\n path: /graphql\n method: get\n - http:\n path: /graphql\n method: post\n```\n\n```text\nLAMBDA_RUNTIME Failed to post handler success response. Http response code: 413.\n```\n\n```text\nget_size\n```\n\n```text\nsend_back_list\n```\n\n```text\nsend_back_list\n```\n\n========================================\n\nComments:\n- This appears to be from CloudFront, not Lambda. I'd look into CloudFront logging to understand why CloudFront is failing. You're nowhere near the 30GB limit of CloudFront.\n- @stdunbar - I'm not an expert so please excuse the ignorance, but I don't actively have Cloudfront set up, I cannot find any reference to it in my Cloudformation resources either. How would I go about debugging this? Also this is happening with a single request and the Lambda is throwing the error, I can see it in Cloudwatch.\n- According to this blog using your own domain with `serverless-domain-manager` creates that for you. This is part of the requirement to have a custom domain in front of API Gateway with or without the serverless framework. Why it's failing though is still unclear. I can only tell you to turn on logging - I'm not positive how to debug it other than logging in the Lambda how big of a response you're sending.\n- Wow, great answer. Too bad the error messages or logs or some part of the Lambda didn't actually just say \"payload total greater than 6MB\". Ugh. For the record, apparently unbufferred payloads have a soft limit of 20mb as quoted in the lambda quotas, so that's an option if someone needs that functionality.\n- Another option is mentioned here: stackoverflow.com/a/51711126/6281925. You can upload the data to a document in an S3 bucket, get a signed download URL for this document and redirect to this URL.","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":210,"estimatedTokens":1538}}44{"id":"stack-37059523","source":"stackoverflow","questionId":37059523,"title":"GraphQL - Get all fields from nested JSON object","tags":["graphql"],"text":"Title: GraphQL - Get all fields from nested JSON object\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI'm putting a GraphQL wrapper over an exiting REST API as described in Zero to GraphQL in 30 minutes. I've got an API endpoint for a product with one property that points to a nested object:\n\n```\n// API Response\n{\n entity_id: 1,\n nested_object: {\n key1: val1,\n key2: val2,\n ...\n }\n}\n```\n\nIs it possible to define the schema so that I can get this entire nested object without explicitly defining the nested object and all of its properties? I want my query to just specify that I want the nested object, and not need to specify all the properties I want from the nested object:\n\n```\n// What I want\n{\n product(id: \"1\") {\n entityId\n nestedObject\n }\n}\n\n// What I don't want\n{\n product(id: \"1\") {\n entityId\n nestedObject {\n key1\n key2\n ...\n }\n }\n}\n```\n\nI can do the second version, but it requires lots of extra code, including creating a `NestedObjectType` and specifying all the nested properties. I've also figured out how to automatically get a list of all the keys, like so:\n\n```\nconst ProductType = new GraphQLObjectType({\n ...\n\n fields: () => ({\n nestedObject: {\n type: new GraphQLList(GraphQLString),\n resolve: product => Object.keys(product.nested_object)\n }\n })\n})\n```\n\nI haven't figured out a way to automatically return the entire object, though.\n\n========================================\n\nTop Answer:\nYou may try to use scalar JSON type. You can find more here (based on apollographql).\n\n- add `scalar JSON` to a schema definition;\n\n- add `{JSON: GraphQLJSON}` to a resolve functions;\n\n- use JSON type in a shema:\n\n```\nscalar JSON\n type Query {\n getObject: JSON\n }\n```\n\n- an example of a query:\n\n```\nquery {\n getObject\n }\n```\n\n- a result:\n\n```\n{\n \"data\": {\n \"getObject\": {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n }\n }\n```\n\nBasic code:\n\n```\nconst express = require(\"express\");\n const graphqlHTTP = require(\"express-graphql\");\n const { buildSchema } = require(\"graphql\");\n const GraphQLJSON = require(\"graphql-type-json\");\n\n const schema = buildSchema(`\n scalar JSON\n\n type Query {\n getObject: JSON\n }\n `);\n\n const root = {\n JSON: GraphQLJSON,\n\n getObject: () => {\n return {\n key1: \"value1\",\n key2: \"value2\",\n key3: \"value3\"\n };\n }\n };\n\n const app = express();\n app.use(\n \"/graphql\",\n graphqlHTTP({\n schema: schema,\n rootValue: root,\n graphiql: true\n })\n );\n app.listen(4000);\n console.log(\"Running a GraphQL API server at localhost:4000/graphql\");\n```\n\n========================================\n\nCode:\n```text\n// API Response\n{\n entity_id: 1,\n nested_object: {\n key1: val1,\n key2: val2,\n ...\n }\n}\n```\n\n```text\n// What I want\n{\n product(id: \"1\") {\n entityId\n nestedObject\n }\n}\n\n// What I don't want\n{\n product(id: \"1\") {\n entityId\n nestedObject {\n key1\n key2\n ...\n }\n }\n}\n```\n\n```text\nconst ProductType = new GraphQLObjectType({\n ...\n\n fields: () => ({\n nestedObject: {\n type: new GraphQLList(GraphQLString),\n resolve: product => Object.keys(product.nested_object)\n }\n })\n})\n```\n\n```text\nNestedObjectType\n```\n\n```text\nJSON.stringify\n```\n\n```text\nscalar JSON\n type Query {\n getObject: JSON\n }\n```\n\n```text\nquery {\n getObject\n }\n```\n\n```text\n{\n \"data\": {\n \"getObject\": {\n \"key1\": \"value1\",\n \"key2\": \"value2\",\n \"key3\": \"value3\"\n }\n }\n }\n```\n\n```text\nconst express = require(\"express\");\n const graphqlHTTP = require(\"express-graphql\");\n const { buildSchema } = require(\"graphql\");\n const GraphQLJSON = require(\"graphql-type-json\");\n\n const schema = buildSchema(`\n scalar JSON\n\n type Query {\n getObject: JSON\n }\n `);\n\n const root = {\n JSON: GraphQLJSON,\n\n getObject: () => {\n return {\n key1: \"value1\",\n key2: \"value2\",\n key3: \"value3\"\n };\n }\n };\n\n const app = express();\n app.use(\n \"/graphql\",\n graphqlHTTP({\n schema: schema,\n rootValue: root,\n graphiql: true\n })\n );\n app.listen(4000);\n console.log(\"Running a GraphQL API server at localhost:4000/graphql\");\n```\n\n```text\nscalar JSON\n```\n\n```text\n{JSON: GraphQLJSON}\n```\n\n========================================\n\nComments:\n- AFAIK, providing the entire nested object without explicitly specifying its fields is not doable in GraphQL at the moment. It kind of goes against the principle of GraphQL, which aims at providing only the needed / requested pieces of data, rather than providing all data at once. You should seriously consider the motivation for using GraphQL. If you're concerned with mobile data bandwidth, it can be a good choice.\n- Thanks for the response. I'm just playing around with it for learning purposes. I figured that might be the case. To me, it makes sense for the top level queries, but not so much for nested objects. In the component, I just want to iterate through everything in the nested object - it seems like if something is added to that object on the server, the client shouldn't need to worry about it. I guess this problem would be more easily avoided if you're using GraphQL as the main api instead of wrapping an existing REST api.\n- \"it seems like if something is added to that object on the server, the client shouldn't need to worry about it.\" Do you mean push-based notification/update (from server to client)?\n- No, I meant changing the code - if you add a new key to the object on the server, it seems like you shouldn't need to update the code on the client side as well. All the client wants to do is display every key-value pair in the nested object, it doesn't need to know what those keys are called.\n- Fetching data newly introduced on the server side without having modification on the client side is not doable at the moment. If `nested_object` does not have anymore nested object as value, there's an ugly alternative that you can try - defining `nested_object` as an array of strings where first element is the key, the next is its value and so on. This way, the array can be arbitrarily long and your `nested_object` becomes flexible w.r.t. change on the server side.","metadata":{"transformedAt":"2026-08-18T18:32:36.021Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":279,"estimatedTokens":1547}}45{"id":"stack-47674558","source":"stackoverflow","questionId":47674558,"title":"Return HashMap from GraphQL-Java","tags":["java","graphql","graphql-java"],"text":"Title: Return HashMap from GraphQL-Java\nTags: java, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI tried few variant and had no luck to return a map in GraphQL. So I have the following two objects: \n\n```\npublic class Customer {\n\n private String name, age;\n // getters & setters\n}\n\npublic class Person {\n\n private String type;\n private Map customers;\n // getters & setters\n}\n```\n\nMy schema looks like this:\n\n```\ntype Customer {\n name: String!\n age: String!\n}\n\ntype Person {\n type: String!\n customers: [Customer!] // Here I tried all combination but had no luck, is there a Map type support for GQL?\n}\n```\n\nCan someone please tell me how to achieve this so that GraphQL magically process this or an alternative approach. \n\nMany thanks!\n\n========================================\n\nTop Answer:\nAs you yourself noted, there's no map type in GraphQL, mostly because maps are data with dynamic structure and, as such, do not translate well into static types that GraphQL expects. Still, you have a few options.\n\nYou could change the value type so it includes the key, and give up on the map and use a list instead. This is the approach you took in your own answer. I won't go into detail here as you've already exemplified it.\n\nAs long as the key and value Java types are known (and not e.g. `Object`), you can treat a map as list of key-value pairs. You can create a type to represent the pair:\n\ntype Person {\ntype: String!\ncustomers: [CustomerEntry!]\n}\n\ntype CustomerEntry {\nkey: String!\nvalue: Customer!\n}\n\nOn the down side, you now have uglier queries:\n\n```\n{\n person {\n type\n customers {\n key\n value {\n name\n }\n }\n }\n}\n```\n\nOn the up side, you keep type safety and (mostly) the semantics. It is possible to keep nesting this approach to e.g. represent a `Map>`.\n\n- If you ever have a completely unknown type, i.e. `Object`, the only option is to treat it as a complex scalar. In JavaScript, this approach is known as *JSON scalar* as it boils down to stuffing an arbitrary JSON structure in and treating it as a scalar. The same approach can be implemented in Java. graphql-java now has a project for extended scalars. Here's their ObjectScalar (aliased as JsonScalar) implementation.\n\nNow, if you want to represent a type such as `Map`, you can opt to represent it using the key-value pair approach from above, with only the value type being the JSON scalar, or you can represent the entire map as a JSON scalar.\n\nAs a matter of fact, you can decide to represent *any* map (well, any type really, but that's not useful) as a JSON scalar.\n\n```\ntype MapEntry {\n key: String!\n value: [ObjectScalar!]\n}\n\nscalar ObjectScalar\n```\n\nOn the upside, you can now keep any dynamic structure's shape exactly.\nOn the downside, since it is a scalar, it is impossible to make sub-selections, and you're stuck fetching it all, without knowing what's inside in advance.\n\n========================================\n\nCode:\n```text\npublic class Customer {\n\n private String name, age;\n // getters & setters\n}\n\npublic class Person {\n\n private String type;\n private Map<String, Customer> customers;\n // getters & setters\n}\n```\n\n```text\ntype Customer {\n name: String!\n age: String!\n}\n\ntype Person {\n type: String!\n customers: [Customer!] // Here I tried all combination but had no luck, is there a Map type support for GQL?\n}\n```\n\n```text\npublic class Person {\n\n private String type;\n private Map<String, Customer> customers;\n // getters & setters\n}\n```\n\n```text\ntype Person {\n type: String!\n customers: String!\n}\n```\n\n```text\npublic DataFetcher<String> fetchCustomers() {\n return environment -> {\n Person person = environment.getSource();\n try {\n ObjectMapper objectMapper = new ObjectMapper();\n return objectMapper.writeValueAsString(person.getCustomers());\n } catch (JsonProcessingException e) {\n log.error(\"There was a problem fetching the person!\");\n throw new RuntimeException(e);\n }\n };\n }\n```\n\n```text\n\"person\": {\n \"type\": \"2\",\n \"customers\": \"{\\\"VIP\\\":{\\\"name\\\":\\\"John\\\",\\\"age\\\":\\\"19\\\"},\\\"Platinum VIP\\\":{\\\"name\\\":\\\"Peter\\\",\\\"age\\\":\\\"65\\\"}}\"\n }\n```\n\n```text\npublic class Person {\n private String type;\n private List<Customer> customers;\n}\n```\n\n```text\npublic class Customer {\n private String key; // or another meaningful name\n private String name, age;\n}\n```\n\n```text\ntype Customer {\n key: String! // or another meaningful name\n name: String!\n age: String!\n}\n\ntype Person {\n type: String!\n customers: [Customer!]!\n}\n```\n\n```text\ncustomers\n```\n\n```text\nList\n```\n\n```text\nCustomer\n```\n\n```text\nCustomer\n```\n\n```text\n{\n person {\n type\n customers {\n key\n value {\n name\n }\n }\n }\n}\n```\n\n```text\ntype MapEntry {\n key: String!\n value: [ObjectScalar!]\n}\n\nscalar ObjectScalar\n```\n\n```text\nObject\n```\n\n```text\nMap<String, Map<Long, Customer>>\n```\n\n```text\nObject\n```\n\n```text\nMap<String, Object>\n```\n\n========================================\n\nComments:\n- \"mostly because maps are basically untyped data\". I disagree. IMO, a map is as typed as an array is.\n- How about set / hashset?\n- @KokHowTeh Nothing special needed there, just represent it as a list in GraphQL.\n- @kaqqao, how do you ensure uniqueness of the items then?\n- @KokHowTeh Why would GraphQL be doing that? Java does that.\n- I've tested your 2) option - but it does not work. See: pastebin.com/riaCkDmu for code. I get this error: `type mismatch error, expected type LIST got class java.util.HashMap` I ask for it like this: `query { getSimpleMapExample { key value } }`\n- @yami Your fetcher is returning a Map where a list is expected. There's no magic that will do the conversion for you - you have to do it yourself in the fetcher.\n- ok - so you meant above to create two Lists in the code one for `keys` and second for `values` right?\n- @yami You need a List of entries, something like a `List>`. See e.g. this implementation.\n- Ok - now i receive `null` `null` as `key` and `value` pastebin.com/BQT4syMp do you may know why is that ? In debug i see that the method is executed and returns list of one map. I ask for it like this: `query { getSimpleMapExample { key value } }`\n- @yami Not a list of maps, a list of entries. I really can't help you further.\n- Caused by: java.lang.ClassCastException: class graphql.kickstart.tools.util.ParameterizedTypeImpl cannot be cast to class java.lang.Class (graphql.kickstart.tools.util.ParameterizedTypeImpl is in unnamed module of loader 'app'; java.lang.Class is in module java.base of loader 'bootstrap')\n- stackoverflow.com/questions/68594917/… input WorkspaceInput{ metadata: WorkspaceMetadata! entities: [Entities!] permissionList: [Permissions]! } input Entities { key: Domain value: EntityType! } enum Domain { PRODUCT_BUILDER } input EntityType { key: String value: EntityKey } input EntityKey { key: String defPackageKey: String entityId: Int entityNumber: EntityNumber } enum EntityNumber { PRODUCT, PRODUCT_VERSION, PRODUCT_VERSION_LOB }","metadata":{"transformedAt":"2026-08-18T18:32:36.022Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":261,"estimatedTokens":1767}}46{"id":"stack-49507035","source":"stackoverflow","questionId":49507035,"title":"How to use apollo-link-http with apollo-upload-client?","tags":["javascript","reactjs","file-upload","graphql","apollo"],"text":"Title: How to use apollo-link-http with apollo-upload-client?\nTags: javascript, reactjs, file-upload, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nIm trying to figure out how to use apollo-link-http with apollo-upload-client.\n\nBoth create a terminating link, but how could I use those 2 together? In my index.js I have like this, but it wont work because both links are terminating =>\n\n```\nconst uploadLink = createUploadLink({ uri: process.env.REACT_APP_GRAPHQL_URL });\n\nconst httpLink = new HttpLink({ uri: process.env.REACT_APP_GRAPHQL_URL });\n\nconst client = new ApolloClient({\n link: ApolloLink.from([ authLink, logoutLink, stateLink, uploadLink, httpLink ]),\n cache,\n});\n```\n\nAny help? I have not much experience with Apollo/Graphql, but I would like to use the file upload component.\n\n========================================\n\nCode:\n```text\nconst uploadLink = createUploadLink({ uri: process.env.REACT_APP_GRAPHQL_URL });\n\nconst httpLink = new HttpLink({ uri: process.env.REACT_APP_GRAPHQL_URL });\n\nconst client = new ApolloClient({\n link: ApolloLink.from([ authLink, logoutLink, stateLink, uploadLink, httpLink ]),\n cache,\n});\n```\n\n```text\nconst uploadLink = createUploadLink({ uri: process.env.REACT_APP_GRAPHQL_URL });\n\nconst client = new ApolloClient({\n link: ApolloLink.from([ authLink, logoutLink, stateLink, uploadLink ]),\n cache,\n});\n```\n\n```text\napollo-upload-client\n```\n\n========================================\n\nComments:\n- This is correct. The final problem however was that I had too old react-scripts package. Updated to 1.1.2 and now working.\n- Thanks a lot. I was forgetting to create an uploadLink.\n- How do you pass http link options to it (like useGETForQueries)?","metadata":{"transformedAt":"2026-08-18T18:32:36.022Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":55,"estimatedTokens":427}}47{"id":"stack-57577102","source":"stackoverflow","questionId":57577102,"title":"Store data from useQuery with useState","tags":["javascript","reactjs","graphql","react-hooks","react-apollo"],"text":"Title: Store data from useQuery with useState\nTags: javascript, reactjs, graphql, react-hooks, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm using React hooks both to fetch GraphQL data with `react-apollo` and to store local state:\n\n```\nconst [userData, setUserData] = useState({})\nconst { loading, error, data } = useQuery(USER_QUERY)\n```\n\nHowever, I'm wondering how to store `data` to `userData`. Is this how it's supposed to work:\n\n```\nuseEffect(() => {\n setUserData(data)\n}, [Object.entries(data).length])\n```\n\n========================================\n\nTop Answer:\nWhat are you trying to do with the returned data that you are unable to accomplish by simply using it as destructured from the query hook? In most use cases it can be used immediately, as it will update itself when refetched.\n\nIf it is necessary (and it could be), as the other answer says, the `useEffect` hook you posted should work, but I would replace the dependency with simply `data`, to prevent an edge case where the response has an equal length consisting of different data and does not update:\n\n```\nuseEffect(() => {\n setUserData(data)\n}, [data])\n```\n\n========================================\n\nCode:\n```text\nconst [userData, setUserData] = useState({})\nconst { loading, error, data } = useQuery(USER_QUERY)\n```\n\n```text\nuseEffect(() => {\n setUserData(data)\n}, [Object.entries(data).length])\n```\n\n```text\nreact-apollo\n```\n\n```text\ndata\n```\n\n```text\nuserData\n```\n\n```text\n(data: TData | {}) => void\n```\n\n```text\nconst { loading, error, data } = useQuery(USER_QUERY, {onCompleted: setUserData})\n```\n\n```text\nonCompleted\n```\n\n```text\noptions\n```\n\n```text\nuseEffect(() => {\n setUserData(data)\n}, [data])\n```\n\n```text\nuseEffect\n```\n\n```text\ndata\n```\n\n```js\nconst [transactionsData, setTransactionsData] = React.useState([]);\n\nconst { error, data } = useQuery(GET_TRANSACTIONS, {\n onCompleted: () => {\n setTransactionsData(data.transactions);\n },\n});\n```\n\n```text\nconst [getLegalStatement] = useLazyQuery(GET_LEGAL_STATEMENT, {\n fetchPolicy: 'network-only',\n onCompleted: (data) => {\n setTempLegalStatement(data.getLegalStatement);\n },\n onError: () => {\n setTempLegalStatement({\n consentedLegalStatementHash: '',\n consentedSuppliersHash: '',\n statement: '',\n suppliersModal: '',\n });\n setTimeout(() => {\n setRefetchNeeded(true);\n }, 10000);\n },\n });\n```\n\n```text\nevery render when state or props change\n```\n\n```text\nconst [userData, setUserData] = useState({})\nconst { data, isLoading, error } = useQuery('QueryKey', QueryFunction, { onSuccess: setUserData })\n```\n\n```text\nonSuccess\n```\n\n```text\nonSuccess\n```\n\n```text\nsetUserData(data)\n```\n\n========================================\n\nComments:\n- I think \"onCompleted\" should be \"onSuccess\".\n- @d0utone at least in version 3.5.10, it is `onCompleted`\n- Why is data is not being used in onCompleted? How does it know what to set use state to?\n- Using `useEffect` in this way is not recommended because it will run only after the component is mounted resulting in a delay between `loading` === true and `setUserData` being populated. More information in the react docs beta.reactjs.org/learn/you-might-not-need-an-effect\n- This will cause a warning: 'data' was used before it was defined.\n- We use this pattern pretty widely, have you tested your error? I think I wrote it correctly.\n- I'm not sure why I am seeing a warning. I copied your code exactly.\n- Have updated with another example, it definitely works, may be a setup thing.\n- This will cause a warning: `'data' was used before it was defined`. There is no obvious way to get around that, so another solution would probably be better.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review","metadata":{"transformedAt":"2026-08-18T18:32:36.022Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":154,"estimatedTokens":1049}}48{"id":"stack-59620803","source":"stackoverflow","questionId":59620803,"title":"createReadStream() throwing RangeError: Maximum call stack size exceeded when uploading file","tags":["node.js","graphql","apollo-server","express-graphql"],"text":"Title: createReadStream() throwing RangeError: Maximum call stack size exceeded when uploading file\nTags: node.js, graphql, apollo-server, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Apollo Server's `Upload` scalar to send files to S3 directly. My schema:\n\n```\nconst { gql } = require('apollo-server-express')\n\nmodule.exports = gql`\n\nextend type Mutation {\n createPicture(\n name: String!\n picture: Upload!\n ): Picture!\n}\n\ntype Picture {\n name: String!\n picture: String!\n}\n`\n```\n\nResolver:\n\n```\nconst { combineResolvers } = require('graphql-resolvers')\nconst isAuthenticated = require('./auth')\nconst { uploadPhoto } = require('../services/picture')\n\nmodule.exports = {\n Mutation: {\n createPicture: combineResolvers(\n isAuthenticated,\n async (\n parent,\n { name, picture = null },\n { models, me }\n ) => {\n const { createReadStream, filename, mimetype, encoding } = await picture\n // Does not get past this line\n const stream = createReadStream()\n\n uploadPhoto(stream, filename)\n\n const pictureModel = models.Picture.create({\n name,\n picture\n })\n return pictureModel\n }\n )\n }\n}\n```\n\nBut my code errors like this:\n\n```\ninternal/util.js:55\n function deprecated(...args) {\n ^\n\nRangeError: Maximum call stack size exceeded\n at ReadStream.deprecated [as open] (internal/util.js:55:22)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream. (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream. (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream. (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream. (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream. (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n```\n\n**Note: I am sure the image was sent correctly, as `filename` is correct**\n\n========================================\n\nTop Answer:\nAdd this to package.json: \n\n```\n\"resolutions\": {\n \"**/**/fs-capacitor\":\"^6.2.0\",\n \"**/graphql-upload\": \"^11.0.0\"\n }\n```\n\nsource: https://github.com/jaydenseric/graphql-upload/issues/170#issuecomment-641938198\n\n========================================\n\nCode:\n```js\nconst { gql } = require('apollo-server-express')\n\nmodule.exports = gql`\n\nextend type Mutation {\n createPicture(\n name: String!\n picture: Upload!\n ): Picture!\n}\n\ntype Picture {\n name: String!\n picture: String!\n}\n`\n```\n\n```text\nconst { combineResolvers } = require('graphql-resolvers')\nconst isAuthenticated = require('./auth')\nconst { uploadPhoto } = require('../services/picture')\n\nmodule.exports = {\n Mutation: {\n createPicture: combineResolvers(\n isAuthenticated,\n async (\n parent,\n { name, picture = null },\n { models, me }\n ) => {\n const { createReadStream, filename, mimetype, encoding } = await picture\n // Does not get past this line\n const stream = createReadStream()\n\n uploadPhoto(stream, filename)\n\n const pictureModel = models.Picture.create({\n name,\n picture\n })\n return pictureModel\n }\n )\n }\n}\n```\n\n```js\ninternal/util.js:55\n function deprecated(...args) {\n ^\n\nRangeError: Maximum call stack size exceeded\n at ReadStream.deprecated [as open] (internal/util.js:55:22)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream.<anonymous> (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream.<anonymous> (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream.<anonymous> (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream.<anonymous> (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n at _openReadFs (internal/fs/streams.js:123:12)\n at ReadStream.<anonymous> (internal/fs/streams.js:116:3)\n at ReadStream.deprecated [as open] (internal/util.js:70:15)\n at ReadStream.open ([truncated]/node_modules/fs-capacitor/lib/index.js:90:11)\n```\n\n```text\nUpload\n```\n\n```text\nfilename\n```\n\n```text\ngraphql-upload\n```\n\n```text\nimport { graphqlUploadExpress } from \"graphql-upload\";\nconst app = express()\napp.use(graphqlUploadExpress({ maxFileSize: 1000000000, maxFiles: 10 }));\n```\n\n```text\nconst server = new ApolloServer({\n uploads: false,\n schema,\n });\n```\n\n```text\n\"resolutions\": {\n \"**/**/fs-capacitor\":\"^6.2.0\",\n \"**/graphql-upload\": \"^11.0.0\"\n }\n```\n\n```text\n\"apollo-server\": \"^2.18.2\",\n \"apollo-server-express\": \"2.18.2\",\n \"aws-sdk\": \"^2.771.0\",\n \"express-fileupload\": \"^1.2.0\",\n \"graphql\": \"^15.3.0\",\n \"graphql-upload\": \"^11.0.0\",\n \"fs-capacitor\": \"^6.2.0\",\n```\n\n```text\nyarn add fs-capacitor\n```\n\n```text\nfs-capacitor\n```\n\n```text\n\"resolutions\": {\n \"graphql-upload\": \"^11.0.0\"\n }\n```\n\n```text\n\"scripts\": {\n ....\n \"preinstall\": \"npx npm-force-resolutions\", //This one\n ....\n}\n```\n\n```text\nnvm install 12; nvm use 12\n```\n\n```text\n\"resolutions\": {\n \"**/**/fs-capacitor\":\"^6.2.0\",\n \"**/graphql-upload\": \"^11.0.0\"\n }\n```\n\n```text\n\"resolutions\": {\n \"fs-capacitor\": \"^6.2.0\",\n \"graphql-upload\": \"^11.0.0\"\n}\n```\n\n```text\n\"scripts\": {\n ....\n \"preinstall\": \"npx npm-force-resolutions\"\n}\n```\n\n```text\nimport { ApolloServer } from \"apollo-server-express\";\nimport express from \"express\";\nimport { graphqlUploadExpress } from \"graphql-upload\";\nimport typeDefs from \"./typeDefs\";\nimport resolvers from \"./resolvers\";\n\n// Import your database configuration\nimport connect from \"./db\";\n\nexport default (async function () {\n try {\n await connect.then(() => {\n console.log(\"Connected π To MongoDB Successfully\");\n });\n\n const server = new ApolloServer({\n uploads: false, // Disables the bundled ApolloServer old graphql-upload that doesn't work on NodeJS 14\n typeDefs,\n resolvers,\n });\n await server.start();\n\n const app = express();\n app.use(graphqlUploadExpress({ maxFileSize: 1000000000, maxFiles: 10 }));\n server.applyMiddleware({ app });\n\n await new Promise((resolve) => app.listen({ port: 7000 }, resolve));\n console.log(\n `π Server ready at http://localhost:7000${server.graphqlPath}`\n );\n } catch (err) {\n console.error(err);\n }\n})();\n```\n\n```text\nimport { gql } from \"apollo-server-express\";\n\nexport default gql`\n scalar Upload\n\n type File {\n id: ID!\n ...\n```\n\n```text\n...\n\nimport { GraphQLUpload } from 'graphql-upload';\n\n...\n\nexport default {\n Upload: GraphQLUpload,\n\n Query: {\n hello: () => \"Hello world\"\n },\n Mutation: {\n...\n```\n\n```html\nconst typeDefs = gql`\n scalar Upload\n ...\n `\n```\n\n```html\nconst { GraphQLUpload } = require('graphql-upload')\nconst { graphqlUploadExpress } = require('graphql-upload')\nconst express = require('express')\n \nconst app = express()\n\napp.use(graphqlUploadExpress({ \n maxFileSize: 10000000, \n maxFiles: 10 \n}))\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers: {\n Upload: GraphQLUpload,\n ...resolvers\n }\n uploads: false\n ...\n})\n\nserver.applyMiddleware({\n app\n})\n```\n\n```text\ngraphql-upload\n```\n\n```text\nnpm install graphql-upload\n```\n\n```text\nTypeDefs\n```\n\n```text\nindex.js\n```\n\n========================================\n\nComments:\n- Where do `createReadStream()` come from? What is it?\n- @jfriend00 From here: github.com/jaydenseric/graphql-upload#type-fileupload\n- don't need this anymore, use this answer instead: stackoverflow.com/a/67083012/12411087, worked for me\n- I tried everything but notihng works :-( Can anyone help me pls?\n- could you explain why we need to set the uploads to false? why does the OP need to install a separate library for this to work now?\n- @JohhanSantana Apollo server bundles inside a clone of graphql-upload that is broken on Node 14. To use the newer fixed graphql-upload package you need to tell apollo not to use it's bundled one. and then use it yourself by registering the body handler with express and adding the upload schema stuff.\n- This answer is really the correct one, just remember to call `app.use(graphqlUploadExpress({ maxFileSize: 1000000000, maxFiles: 10 }));` before applying Apollo sever middleware.\n- Hi dude.I did this but now I'm getting another error: \"message\": \"args.file.then is not a function\", Here is my code: const singleUpload = (parent, args) => { return args.file.then((file) => { const { createReadStream, filename } = file const fileStream = createReadStream() fileStream.pipe(fs.createWriteStream(`../../assets/img/grid/$‌​{filename}`)) return file }) }\n- @JulianoCosta you probably forgot to add this to the resolvers you pass into your schema: `resolvers: { Upload: GraphQLUpload, }` As per the documentation: Upload: github.com/jaydenseric/graphql-upload#class-graphqlupload In version 8, it worked without this resolver.\n- @Narretz, yes, it was the problem. I did it yet and it solved my problem. Tnx 4 ur help\n- This worked for me. Its also the right approach and better than the approach of fixing fs-capacitor version. As it removes the dependency on Apollo on the version of `apollo-upload` to use. Nicely done!!\n- This is a palliative solution. What is the package that loads the wrong versions in the first place? Edit: right ticket on Apollo Server Github: github.com/apollographql/apollo-server/issues/4190\n- Adding fs-capacitor 6.2.0 as a resolution worked for me.\n- Thanks, this saves me a lot\n- Thanks, this saves me a lot\n- Ok but which package is loading them in the first place?","metadata":{"transformedAt":"2026-08-18T18:32:36.022Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":413,"estimatedTokens":2729}}49{"id":"stack-51342523","source":"stackoverflow","questionId":51342523,"title":"AppSync: Nested Type Resolver","tags":["amazon-dynamodb","graphql","velocity","aws-appsync"],"text":"Title: AppSync: Nested Type Resolver\nTags: amazon-dynamodb, graphql, velocity, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI try to include nested types defined in the following graphql schema:\n\n```\ntype User {\n id: String!\n posts: [Post]\n}\n\ntype Post {\n id: String!\n}\n\ntype Query {\n getUser(id: String!): User\n getPost(id: String!): Post\n}\n```\n\nAs you can see a User has multiple Posts. I am using AppSync with an Adjacent List Dynamodb Table (which contains both the User and the Post relevant row) as a data source. Within AppSync I have to use a *request mapping template*, but after reading the documentation I have not understood how nested types are resolved?\n\nI would imagine that on querying `getUser` the Post resolver should be called with the User_id. If so how do I access the parent id within the post resolver? Is this where `${context.source}` comes into place? \n\nAs the `getPost` query resolver would be the same as the Post resolver, called by the getUser Post child, would I have to integrate some logic with request template of the resolver to deal with both cases? \n\nAn example would be really helpful!\n\n========================================\n\nTop Answer:\nHere is another stackoverflow post where, I describe how to do this in detail. The title says mutation but it goes over both mutations and queries. mutation to create relations on AWS AppSync\n\n========================================\n\nCode:\n```text\ntype User {\n id: String!\n posts: [Post]\n}\n\ntype Post {\n id: String!\n}\n\ntype Query {\n getUser(id: String!): User\n getPost(id: String!): Post\n}\n```\n\n```text\ngetUser\n```\n\n```text\n${context.source}\n```\n\n```text\ngetPost\n```\n\n```text\nUserResolver:\n Type: \"AWS::AppSync::Resolver\"\n DependsOn: Schema\n Properties:\n ApiId: !Ref YourApiId\n TypeName: Query\n FieldName: getUser\n DataSourceName: !Ref YourDataSource\n RequestMappingTemplate: # you already have this\n ResponseMappingTemplate: ...\n\n UserPostsResolver:\n Type: \"AWS::AppSync::Resolver\"\n DependsOn: Schema\n Properties:\n ApiId: !Ref YourApiId\n TypeName: User\n FieldName: posts\n DataSourceName: !Ref YourDataSource\n RequestMappingTemplate: |\n # use context.source.id here to reference the user id\n ResponseMappingTemplate: \"$util.toJson($ctx.result.items)\"\n```\n\n```text\nQuery.getUser\n```\n\n```text\n${context.source}\n```\n\n========================================\n\nComments:\n- I was struggling to find a decent answer to the same question, and finally found this Medium post, where at the end it explain very well how to retrieve data in a nested JSON object.\n- Thanks for this. It was not possible for me to find this in the documentation (I missed it I think because there were no nested examples like this), other than a vague reference to the context object containing the results of the parent. I now realized I had incorrectly assumed the resolvers were specified only within the Query or Mutation types and ignore that they could be specified anywhere, which is standard graphQL. Thanks again!\n- Glad it helped, @FrancisUpton. I've found the docs a little difficult to navigate too and it took us a while to figure out how to do this too.\n- @macbutch I didn't know that. Can I use that with Amplify and editing manually the JSON templates? (Note I am not using DynamoDB, but RDS). Thanks a lot.\n- What about if posts is paginated? Thanks\n- @Ricardo probably too late to help but we're not using Amplify so I don't know for sure but I don't see that it would be a problem. Pagination details will vary to some degree based on your backend but I'd recommend the graphql docs on pagination. We use a Connection type with Dynamo and the basic approach should work for you too (though I'd expect it to look a little different).\n- Thank you for this post. I tried to figure out how to handle nested objects for hours...","metadata":{"transformedAt":"2026-08-18T18:32:36.022Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":110,"estimatedTokens":971}}50{"id":"stack-37796902","source":"stackoverflow","questionId":37796902,"title":"Why doesn't GraphQL accept this scalar argument type, instead complaining \"argument type must be Input Type but got: undefined\"?","tags":["graphql"],"text":"Title: Why doesn't GraphQL accept this scalar argument type, instead complaining \"argument type must be Input Type but got: undefined\"?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI have\n\n```\nexport const getPicture = {\n type: GraphPicture,\n args: {\n type: new GraphQLNonNull(GraphQLInt)\n },\n resolve(_, args) {\n return Picture.findByPrimary(args.id);\n }\n};\n\nexport const getPictureList = {\n type: new GraphQLList(GraphPicture),\n resolve(_, __, session) {\n return Picture.findAll({where: {owner: session.userId}});\n }\n};\n```\n\nand\n\n```\nconst query = new GraphQLObjectType({\n name: 'Queries',\n fields: () => {\n return {\n getPictureList: getPictureList,\n getPicture: getPicture\n }\n }\n});\n\nconst schema = new GraphQLSchema({\n query: query,\n mutation: mutation\n});\n```\n\nWhich throws:\n\nError: Queries.getPicture(type:) argument type must be Input Type but got: undefined.\n`getPictureList` works fine; `getPicture` fails with a scalar argument type of `GraphQLInt` or `GraphQLNonNull(GraphQLInt)`. I have tried making `getPicture` a `GraphQLLIst`, but it didn't help. I have tried making the argument `type` an Input Type, but it didn't help.\n\nWhy is the code generating the error, and how can it be fixed?\n\nThe stack trace is:\n\nError: Queries.getPicture(type:) argument type must be Input Type but got: undefined.\n at invariant (/home/jrootham/dev/trytheseon/node_modules/graphql/jsutils/invariant.js:19:11)\n at /home/jrootham/dev/trytheseon/node_modules/graphql/type/definition.js:307:33\n at Array.map (native)\n at /home/jrootham/dev/trytheseon/node_modules/graphql/type/definition.js:304:52\n at Array.forEach (native)\n at defineFieldMap (/home/jrootham/dev/trytheseon/node_modules/graphql/type/definition.js:293:14)\n at GraphQLObjectType.getFields (/home/jrootham/dev/trytheseon/node_modules/graphql/type/definition.js:250:46)\n at /home/jrootham/dev/trytheseon/node_modules/graphql/type/schema.js:224:27\n at typeMapReducer (/home/jrootham/dev/trytheseon/node_modules/graphql/type/schema.js:236:7)\n at Array.reduce (native)\n at new GraphQLSchema (/home/jrootham/dev/trytheseon/node_modules/graphql/type/schema.js:104:34)\n at Object. (/home/jrootham/dev/trytheseon/server/graphQL.js:45:16)\n at Module._compile (module.js:399:26)\n at normalLoader (/usr/lib/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:160:5)\n at Object.require.extensions.(anonymous function) [as .js] (/usr/lib/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:173:7)\n at Module.load (module.js:345:32)\n at Function.Module._load (module.js:302:12)\n at Module.require (module.js:355:17)\n at require (internal/module.js:13:17)\n at Object. (/home/jrootham/dev/trytheseon/devServer.js:14:44)\n at Module._compile (module.js:399:26)\n at normalLoader (/usr/lib/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:160:5)\n\n========================================\n\nTop Answer:\nJust for reference, I got here searching the same error just not with `undefined`, but with my own `Product` type: \n\n```\n... argument * must be Input Type but got Product\n```\n\nTurned out that in GraphQL what you pass to a Mutation should be either scalar type (String, Integer, ...) or user defined **`input`** type, not `type` type. \n\nhttp://graphql.org/graphql-js/mutations-and-input-types/\n\n```\ninput ProductInput {\n id: ID\n name: String\n}\n```\n\nI was trying to pass in my Product `type`: \n\n```\ntype Product {\n id: ID\n name: String\n}\n```\n\nThis feels a bit redundant, but guess, I'll be glad for having it separated later.\n\n========================================\n\nCode:\n```text\nexport const getPicture = {\n type: GraphPicture,\n args: {\n type: new GraphQLNonNull(GraphQLInt)\n },\n resolve(_, args) {\n return Picture.findByPrimary(args.id);\n }\n};\n\nexport const getPictureList = {\n type: new GraphQLList(GraphPicture),\n resolve(_, __, session) {\n return Picture.findAll({where: {owner: session.userId}});\n }\n};\n```\n\n```text\nconst query = new GraphQLObjectType({\n name: 'Queries',\n fields: () => {\n return {\n getPictureList: getPictureList,\n getPicture: getPicture\n }\n }\n});\n\nconst schema = new GraphQLSchema({\n query: query,\n mutation: mutation\n});\n```\n\n```text\nError: Queries.getPicture(type:) argument type must be Input Type but got: undefined.\n```\n\n```text\nError: Queries.getPicture(type:) argument type must be Input Type but got: undefined.\n at invariant (/home/jrootham/dev/trytheseon/node_modules/graphql/jsutils/invariant.js:19:11)\n at /home/jrootham/dev/trytheseon/node_modules/graphql/type/definition.js:307:33\n at Array.map (native)\n at /home/jrootham/dev/trytheseon/node_modules/graphql/type/definition.js:304:52\n at Array.forEach (native)\n at defineFieldMap (/home/jrootham/dev/trytheseon/node_modules/graphql/type/definition.js:293:14)\n at GraphQLObjectType.getFields (/home/jrootham/dev/trytheseon/node_modules/graphql/type/definition.js:250:46)\n at /home/jrootham/dev/trytheseon/node_modules/graphql/type/schema.js:224:27\n at typeMapReducer (/home/jrootham/dev/trytheseon/node_modules/graphql/type/schema.js:236:7)\n at Array.reduce (native)\n at new GraphQLSchema (/home/jrootham/dev/trytheseon/node_modules/graphql/type/schema.js:104:34)\n at Object. (/home/jrootham/dev/trytheseon/server/graphQL.js:45:16)\n at Module._compile (module.js:399:26)\n at normalLoader (/usr/lib/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:160:5)\n at Object.require.extensions.(anonymous function) [as .js] (/usr/lib/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:173:7)\n at Module.load (module.js:345:32)\n at Function.Module._load (module.js:302:12)\n at Module.require (module.js:355:17)\n at require (internal/module.js:13:17)\n at Object. (/home/jrootham/dev/trytheseon/devServer.js:14:44)\n at Module._compile (module.js:399:26)\n at normalLoader (/usr/lib/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:160:5)\n```\n\n```text\ngetPictureList\n```\n\n```text\ngetPicture\n```\n\n```text\nGraphQLInt\n```\n\n```text\nGraphQLNonNull(GraphQLInt)\n```\n\n```text\ngetPicture\n```\n\n```text\nGraphQLLIst\n```\n\n```text\ntype\n```\n\n```text\nexport const getPicture = {\n type: GraphPicture,\n args: {\n type: new GraphQLNonNull(GraphQLInt)\n },\n resolve(_, args) {\n return Picture.findByPrimary(args.id);\n }\n};\n```\n\n```text\nexport const getPicture = {\n type: GraphPicture,\n args: {\n type: {\n type: new GraphQLNonNull(GraphQLInt)\n }\n },\n resolve(_, args) {\n return Picture.findByPrimary(args.id);\n }\n};\n```\n\n```text\nhero: {\n type: characterInterface,\n args: {\n episode: {\n description: 'If omitted, returns the hero of the whole saga. If ' +\n 'provided, returns the hero of that particular episode.',\n type: episodeEnum\n }\n },\n resolve: (root, { episode }) => getHero(episode),\n},\n```\n\n```text\n... argument * must be Input Type but got Product\n```\n\n```text\ninput ProductInput {\n id: ID\n name: String\n}\n```\n\n```text\ntype Product {\n id: ID\n name: String\n}\n```\n\n```text\nundefined\n```\n\n```text\nProduct\n```\n\n```text\ninput\n```\n\n```text\ntype\n```\n\n```text\ntype\n```\n\n========================================\n\nComments:\n- Not sure if it's related, but you only specified the type and seem to be missing the argument name (id).\n- @OP, parameterize `getPicture` in the root query. On a different note, you may consider naming `picture` instead of `getPicture`. It's more of a convention.\n- @AhmadFerdous queries passed into the schema definition do not need to be paramertized, they are passed parameters via the query call itself.\n- @BradDecker, thanks! I didn't know that.\n- To be even more specific, you need to define your input types as `new GraphQLObjectType` from `graphql`, like this answer explains: stackoverflow.com/a/35883106/4430640\n- I had this same problem and this helped me a lot. The link you have seems to be dead though, not sure what the right link is supposed to be.\n- @gkri Eventually yes. I am defining my schemas using *GraphQL schema language* and passing it to Apollo's `makeExecutableSchema` More here: apollographql.com/docs/graphql-tools/generate-schema.html","metadata":{"transformedAt":"2026-08-18T18:32:36.022Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":294,"estimatedTokens":2076}}51{"id":"stack-64607530","source":"stackoverflow","questionId":64607530,"title":"Use the same class as Input and Object type in GraphQL in NestJS","tags":["typescript","graphql","nestjs"],"text":"Title: Use the same class as Input and Object type in GraphQL in NestJS\nTags: typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup my graphql resover to handle an array of objects but cant get the @Args decorator configured.\n\nI created my own ArgsType\n\n```\nimportΒ {Β ArgsType,Β Field,Β Int,Β ObjectTypeΒ }Β from '@nestjs/graphql';\n\n@ArgsType()Β Β //Β toΒ beΒ usedΒ asΒ typeΒ inΒ theΒ resolver\n@ObjectType()Β Β //Β forΒ schemaΒ generationΒ \nexport class ClubΒ {\nΒ @Field(type => String)\n president: string;\n\nΒ @Field(type => Int)\n members?: number;\n}\n```\n\nResolver with adding a single Club works just fine!\n\n```\n@Query(()Β => Int)\n async addClub(@Args()Β club: Club)Β {\n // handle stuff\nΒ Β }\n```\n\nbut if I want to give an array of Club like this\n\n```\n@Query(()Β => Int)\n async addClubs(@Args({name:Β 'clubs',Β type:Β ()Β =>Β [Club]})Β clubs: Array)Β {\n // handle stuff\nΒ Β }\n```\n\nthis thows an error when nest is starting up\n\n```\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL input type for the \"clubs\". Make sure your class is decorated with an appropriate decorator.\n```\n\nalthough I am able to use an array of Strings like this\n\n```\n@Query(()Β =>Β [String])\n async addStrings(@Args({Β name:Β 'clubs',Β type:Β ()Β =>Β [String],Β })Β clubs: Array)Β {\n // handle stuff\nΒ Β }\n```\n\nI am pretty sure there should be an easy solution, but cant figure out where to go from here.\n\n========================================\n\nCode:\n```text\nimportΒ {Β ArgsType,Β Field,Β Int,Β ObjectTypeΒ }Β from '@nestjs/graphql';\n\n@ArgsType()Β Β //Β toΒ beΒ usedΒ asΒ typeΒ inΒ theΒ resolver\n@ObjectType()Β Β //Β forΒ schemaΒ generationΒ \nexport class ClubΒ {\nΒ @Field(type => String)\n president: string;\n\nΒ @Field(type => Int)\n members?: number;\n}\n```\n\n```text\n@Query(()Β => Int)\n async addClub(@Args()Β club: Club)Β {\n // handle stuff\nΒ Β }\n```\n\n```text\n@Query(()Β => Int)\n async addClubs(@Args({name:Β 'clubs',Β type:Β ()Β =>Β [Club]})Β clubs: Array<Club>)Β {\n // handle stuff\nΒ Β }\n```\n\n```text\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL input type for the \"clubs\". Make sure your class is decorated with an appropriate decorator.\n```\n\n```text\n@Query(()Β =>Β [String])\n async addStrings(@Args({Β name:Β 'clubs',Β type:Β ()Β =>Β [String],Β })Β clubs: Array<string>)Β {\n // handle stuff\nΒ Β }\n```\n\n```sh\nCannot determine a GraphQL input type for the \"clubs\". Make sure your class is decorated with an appropriate decorator\n```\n\n```js\nimport { InputType, Field } from '@nestjs/graphql';\n\n@InputType()\nexport class ClubInput {\n @Field()\n president: string;\n\n @Field()\n members?: number;\n}\n```\n\n```js\n@Query(() => Int)\nasync addClubs(@Args({name: 'clubs', type: () => [ClubInput]}) clubs: Array<ClubInput>) {\n // handle stuff\n}\n```\n\n```js\nimport { Field, Int, ObjectType, InputType } from '@nestjs/graphql';\n\n@InputType(\"ClubInput\")\n@ObjectType(\"ClubType\")\nexport class Club {\n @Field(type => String)\n president: string;\n\n @Field(type => Int)\n members?: number;\n}\n```\n\n```js\n@Query(() => Int)\nasync addClubs(@Args({name: 'clubs', type: () => [ClubInput]}) clubs: Array<ClubInput>) {\n // handle stuff\n}\n```\n\n```text\nClub\n```\n\n```text\n@ObjectType\n```\n\n```text\nClub\n```\n\n```text\nClub\n```\n\n```text\nClub\n```\n\n```text\nClub\n```\n\n```text\nInputType\n```\n\n```text\nObjectType\n```\n\n========================================\n\nComments:\n- Wow thanks for that thorough explanation. So it was basically me trying to use a screwdriver as a hammer xD had no time to try it out but after checking the nestjs docs about graphql mutation, I am sure that's the solution. I will stick with solution 1 since that's the common practice and my case is not special at all\n- Please do you know how someone can go about this case. I have an `InputType` and `ObjectType`, most of their properties are same but they have few differences, is there a way i can have 2 classes where one inherits the similar properties from the other so i won't have to define duplicate properties in both classes\n- Sure, You can create an abstract class and put the similar properties of `InputType` and `ObjectType` in it. Then you can extend that class in your `InputType` and `ObjectType` concrete classes.\n- docs.nestjs.com/graphql/mapped-types this gives you a nice abstraction to achieve what you wish","metadata":{"transformedAt":"2026-08-18T18:32:36.022Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":184,"estimatedTokens":1052}}52{"id":"stack-48382897","source":"stackoverflow","questionId":48382897,"title":"Graphql-Access arguments in child resolvers","tags":["graphql","apollo","graphql-js","apollo-server"],"text":"Title: Graphql-Access arguments in child resolvers\nTags: graphql, apollo, graphql-js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am using apollo-server and apollo-graphql-tools and I have following schema\n\n```\ntype TotalVehicleResponse {\n totalCars: Int\n totalTrucks: Int\n}\n\ntype RootQuery {\n getTotalVehicals(color: String): TotalVehicleResponse\n}\n\nschema {\n query: RootQuery\n}\n```\n\nand Resolver functions are like this\n\n```\n{\n RootQuery: {\n getTotalVehicals: async (root, args, context) => {\n // args = {color: 'something'}\n return {};\n },\n TotalVehicleResponse: {\n totalCars: async (root, args, conext) => {\n // args is empty({}) here\n .........\n .........\n },\n totalTrucks: async (root, args, conext) => {\n // args is empty({}) here\n .........\n .........\n }\n }\n }\n}\n```\n\nMy question is that how can I access `args` which is available in root resolver(`getTotalVehicals`) in any of the child resolvers?\n\n========================================\n\nTop Answer:\n### TLDR: Add your *arguments* to the *field*\n\n(Client Side) change from:\n\n```\nCar(type: $type, materialType: $materialType){\n id\n material\n name\n ...\n}\n```\n\n(Client Side) To:\n\n```\nCar(type: $type){\n id,\n material(materialType: $materialType) // moved here\n name\n ...\n}\n```\n\nThen, You can access `args` in server `fieldResolver` (`material` field in this case).\n\n### *Longer version*\n\nDo not pass your argument through `root`, except `IDs` or `parent object`, anything from client, use **field level argument**.\n\n### Why?\n\n*Tight Coupling* and hard to scale up schemas,\n\n*Difficult to troubleshoot* and debug,\n\n*Leaking unnecessary information to children*,\n\n*Mixing up parent object with arguments*\n\nA simple query can grow from this:\n\n```\n[Root] Car(\n color:white\n) {\n id,\n seat,\n ...\n}\n```\n\nTo this:\n\n```\n[Root] Car(\n color:white, \n type:sedan, \n seat:leather, \n seatColor:black,\n rimColor: blue,\n rimShape: OutOfTheWorld,\n ...\n) {\n id,\n seat,\n ...\n}\n```\n\nInstead of passing the argument around, you can do this\n\n```\n[Root] Car(\n color:white, \n type:sedan\n ...\n) {\n id\n seat(type:leather, color:black),\n rim(color: blue, shape: OutOfTheWorld){\n // nested query\n material(hardness: high), // solved `Why no.2`: deep argument. \n \n // More nested\n brand(trustWorthy: high) {\n priceRange(range: mid),\n area,\n ...\n },\n id\n }\n numberOfPassengers,\n ...\n}\n```\n\ninstead of squeezing all args into single root, now each field is responsible for its args and resolver.\n\n========================================\n\nCode:\n```text\ntype TotalVehicleResponse {\n totalCars: Int\n totalTrucks: Int\n}\n\ntype RootQuery {\n getTotalVehicals(color: String): TotalVehicleResponse\n}\n\nschema {\n query: RootQuery\n}\n```\n\n```text\n{\n RootQuery: {\n getTotalVehicals: async (root, args, context) => {\n // args = {color: 'something'}\n return {};\n },\n TotalVehicleResponse: {\n totalCars: async (root, args, conext) => {\n // args is empty({}) here\n .........\n .........\n },\n totalTrucks: async (root, args, conext) => {\n // args is empty({}) here\n .........\n .........\n }\n }\n }\n}\n```\n\n```text\nargs\n```\n\n```text\ngetTotalVehicals\n```\n\n```js\nconst resolvers = {\n RootQuery: {\n getTotalVehicles: async (root, args, context) => {\n return { color: args.color };\n },\n },\n TotalVehicleResponse: {\n totalCars: async (root, args, context) => {\n // root contains color here\n const color = root.color;\n // Logic to get totalCars based on color\n const totalCars = await getTotalCarsByColor(color);\n return totalCars;\n },\n totalTrucks: async (root, args, context) => {\n // root contains color here\n const color = root.color;\n // Logic to get totalTrucks based on color\n const totalTrucks = await getTotalTrucksByColor(color);\n return totalTrucks;\n }\n }\n}\n```\n\n```text\ntype TotalVehicleResponse {\n totalCars(color: String): Int\n totalCars(color: String): Int\n totalTrucks(color: String): Int\n\n}\n\ntype Query {\n getTotalVehicles(color: String): TotalVehicleResponse\n}\n```\n\n```text\nquery($color: String) {\n getTotalVehicles(color: $color) {\n totalCars(color: $color)\n totalTrucks(color: $color)\n }\n}\n```\n\n```text\ntype Query {\n car(id: ID!): Car! # Type resolver\n carsByColor(color: String!): [Car!] # Type resolver with argument\n brands: [Brand!] # Type resolver\n}\n\ntype Car {\n id: ID!\n brand: Brand! # Type resolver\n model: String\n color: String\n}\n\ntype Brand {\n id: ID!\n name: String\n cars(color: String): [Car!] # Type resolver with argument\n}\n```\n\n```text\nquery($color: String!) {\n # Type resolver with argument\n carsByColor(color: $color) { \n id\n model\n color\n brand {\n id\n name\n # Type resolver with argument\n cars(color: $color) { \n id\n model\n color\n }\n }\n }\n}\n```\n\n```js\nconst resolvers = {\n Query: {\n car: async (_, args) => {\n const car = await getCar(args.id);\n return car;\n },\n carsByColor: async (_, args) => {\n const cars = await getCarsByColor(args.color);\n return cars;\n },\n brands: async () => {\n const brands = await getAllBrands();\n return brands;\n }\n },\n Car: {\n brand: async (parent) => {\n const brand = await getBrand(parent.brandId);\n return brand;\n }\n },\n Brand: {\n cars: async (parent, args) => {\n const cars = await getCarsByBrandAndColor(parent.id, args.color);\n return cars;\n }\n }\n};\n```\n\n```text\nargs\n```\n\n```text\nargs\n```\n\n```text\nquery GetTotalVehicalsOperation($color: String) {\n getTotalVehicals(color: $color) {\n totalCars\n totalTrucks \n }\n}\n```\n\n```text\n{\n RootQuery: {\n getTotalVehicles: async (root, args, context, info) => {\n //info.variableValues contains {color: 'something'} \n return {};\n },\n TotalVehicleResponse: {\n totalCars: async (root, args, context, info) => {\n //same here: info.variableValues contains {color: 'something'}\n },\n totalTrucks: async (root, args, context, info) => {\n //and also here: info.variableValues contains {color: 'something'}\n }\n }\n }\n}\n```\n\n```text\ninfo\n```\n\n```text\ninfo\n```\n\n```text\nvariableValues\n```\n\n```text\nargs\n```\n\n```text\nCar(type: $type, materialType: $materialType){\n id\n material\n name\n ...\n}\n```\n\n```text\nCar(type: $type){\n id,\n material(materialType: $materialType) // moved here\n name\n ...\n}\n```\n\n```text\n[Root] Car(\n color:white\n) {\n id,\n seat,\n ...\n}\n```\n\n```text\n[Root] Car(\n color:white, \n type:sedan, \n seat:leather, \n seatColor:black,\n rimColor: blue,\n rimShape: OutOfTheWorld,\n ...\n) {\n id,\n seat,\n ...\n}\n```\n\n```text\n[Root] Car(\n color:white, \n type:sedan\n ...\n) {\n id\n seat(type:leather, color:black),\n rim(color: blue, shape: OutOfTheWorld){\n // nested query\n material(hardness: high), // solved `Why no.2`: deep argument. \n \n // More nested\n brand(trustWorthy: high) {\n priceRange(range: mid),\n area,\n ...\n },\n id\n }\n numberOfPassengers,\n ...\n}\n```\n\n```text\nargs\n```\n\n```text\nfieldResolver\n```\n\n```text\nmaterial\n```\n\n```text\nroot\n```\n\n```text\nIDs\n```\n\n```text\nparent object\n```\n\n========================================\n\nComments:\n- Please have look at this comprehensive link also prisma.io/blog/…\n- Please don't do this. It leads to tight coupling between resolvers and doesn't scale up well. Each resolver should receive its own args directly from the query. Please check cYee's answer for more: stackoverflow.com/a/63300135/7948938\n- This looks like a workaround, it's not a proper solution.\n- FYI, this only works when using variables. So it may not a good idea to rely on info.\n- Thanks, @Trevor. I've updated my answer to clarify that.\n- Please have look at this comprehensive link also prisma.io/blog/…\n- This is the correct answer. Args shouldn't be shared between resolvers; this leads to coupling and it's very hard to scale up schemas that way\n- the best and only correct answer! thanks! it is rather hard to find clair documentation on how to handl this issue!","metadata":{"transformedAt":"2026-08-18T18:32:36.022Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":477,"estimatedTokens":2021}}53{"id":"stack-42750054","source":"stackoverflow","questionId":42750054,"title":"Is Facebook's Graph API using GraphQL?","tags":["graphql"],"text":"Title: Is Facebook's Graph API using GraphQL?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nThey said Facebook used GraphQL since 2012. Is Facebook's Graph API using GraphQL? If not, is there any public Facebook's API using GraphQL?\n\nDo we need versioning for our APIs if we use GraphQL server?\n\n========================================\n\nComments:\n- The question was whether facebook Graph API is based on GraphQL (but not what GraphQL is)...","metadata":{"transformedAt":"2026-08-18T18:32:36.022Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":13,"estimatedTokens":111}}54{"id":"stack-61526823","source":"stackoverflow","questionId":61526823,"title":"What is `... on` doing in this GraphQL?","tags":["graphql"],"text":"Title: What is `... on` doing in this GraphQL?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to mimic what some GraphQL does, but I do not have access to be able to run the original. It is of the form:\n\n```\nquery {\n dataSources(dataType: Ais) {\n ... on AisDataSource {\n messages(filter: {broadcastType: Static}) {\n ... on AisStaticBroadcast {\n field1\n field2\n```\n\n(I have ommitted the closing parentheses).\n\nIt is my understanding that `... on` is either to include a fragment (none here), or to choose between alternatives (but these are nested). So is this query wrong, or is there more to `... on`?\n\n========================================\n\nTop Answer:\nFor those not yet clicked , here's an implementation using appolo graphql\n\nGraphql schema:\n\n```\ninterface Animal {\n name: String\n age: String\n dob: String\n owner: String\n sound: String\n }\n\n type Dog implements Animal {\n name: String\n age: String\n dob: String\n owner: String\n sound: String\n color: String\n }\n\n type Cat implements Animal {\n name: String\n age: String\n dob: String\n owner: String\n sound: String\n weight: String\n }\n```\n\nHere Animal is an abstract type and the Dog and Cat has similar properties excpet color and weight which is different.\n\nResolver:\n\n```\nOwner: {\n animal: (creator) => {\n return animals.find(anm => creator.name == anm.owner)\n }\n\n },\n\n Animal: {\n __resolveType(animal) {\n if (animal.sound == \"Bark\") {\n return 'Dog'\n } else {\n return 'Cat' \n }\n }\n },\n```\n\nSo a particular owner may have a cat or dog, so we have this scenario where if it's a dog output the color property and if it's a cat output weight. Consider it more like an if else statement.\n\nAn example query:\n\n```\nowner(id: $id) {\n animal {\n ... on Cat {\n weight\n }\n ... on Dog {\n color\n }\n }\n}\n```\n\nSame query using fragments:\n\n```\nowner(id: $id) {\n animal {\n ...Catto\n ...Doggo\n }\n}\n\nfragment Catto on Cat {\n weight\n}\n\nfragment Doggo on Dog {\n color\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n dataSources(dataType: Ais) {\n ... on AisDataSource {\n messages(filter: {broadcastType: Static}) {\n ... on AisStaticBroadcast {\n field1\n field2\n```\n\n```text\n... on\n```\n\n```text\n... on\n```\n\n```text\n{\n user {\n ... on User {\n id\n username\n }\n }\n}\n```\n\n```text\n{\n user {\n ...UserFragment\n }\n}\n\nfragment UserFragment on User {\n id\n username\n}\n```\n\n```text\n{\n user {\n ...RegularUserFragment\n ...AdminFragment\n }\n}\n\nfragment RegularUserFragment on RegularUser {\n id\n username\n}\n\nfragment AdminFragment on Admin {\n id\n username\n accessLevel\n}\n```\n\n```text\non\n```\n\n```text\ninterface Animal {\n name: String\n age: String\n dob: String\n owner: String\n sound: String\n }\n\n type Dog implements Animal {\n name: String\n age: String\n dob: String\n owner: String\n sound: String\n color: String\n }\n\n type Cat implements Animal {\n name: String\n age: String\n dob: String\n owner: String\n sound: String\n weight: String\n }\n```\n\n```text\nOwner: {\n animal: (creator) => {\n return animals.find(anm => creator.name == anm.owner)\n }\n\n },\n\n Animal: {\n __resolveType(animal) {\n if (animal.sound == \"Bark\") {\n return 'Dog'\n } else {\n return 'Cat' \n }\n }\n },\n```\n\n```text\nowner(id: $id) {\n animal {\n ... on Cat {\n weight\n }\n ... on Dog {\n color\n }\n }\n}\n```\n\n```text\nowner(id: $id) {\n animal {\n ...Catto\n ...Doggo\n }\n}\n\nfragment Catto on Cat {\n weight\n}\n\nfragment Doggo on Dog {\n color\n}\n```\n\n========================================\n\nComments:\n- Superb, many thanks! ! I must have missed that in the tutorial I read.","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":265,"estimatedTokens":931}}55{"id":"stack-63010460","source":"stackoverflow","questionId":63010460,"title":"Cannot represent non-enum value","tags":["typescript","enums","graphql","typegraphql"],"text":"Title: Cannot represent non-enum value\nTags: typescript, enums, graphql, typegraphql\nSource: Stack Overflow\n\nQuestion:\nIn my graphQL API(with typescript & type-graphql) I'm trying to run a mutation which ***inputType*** has an ***enum*** value defined as below\n\n```\nexport enum GenderType {\n female = 'female',\n male = 'male',\n}\n\nregisterEnumType(GenderType, {\n name: 'GenderType',\n});\n```\n\nand I'm trying to execute this mutation.\n\n```\nmutation {\n registerStudent(data: {\n name: \"John\",\n gender: \"male\",\n }) {\n id\n }\n}\n```\n\nbut when I'm trying to execute the mutation it gives an error saying\n\n**\"message\": \"Enum \"GenderType\" cannot represent non-enum value: \"female\". Did you mean the enum value \"female\" or \"male\"?\"**,\n\nI think this happens because how i defined the enum type using registerEnumType in ***type-graphql***.\n\nHow to defile an enum with type-graphql\n\n========================================\n\nCode:\n```text\nexport enum GenderType {\n female = 'female',\n male = 'male',\n}\n\nregisterEnumType(GenderType, {\n name: 'GenderType',\n});\n```\n\n```text\nmutation {\n registerStudent(data: {\n name: \"John\",\n gender: \"male\",\n }) {\n id\n }\n}\n```\n\n```text\nmutation {\n registerStudent(data: {\n name: \"John\",\n gender: \"male\",\n }) {\n id\n }\n}\n```\n\n```text\nmutation {\n registerStudent(data: {\n name: \"John\",\n gender: male,\n }) {\n id\n }\n}\n```\n\n========================================\n\nComments:\n- Found the problem... Actually problem located at mutation object types that i passed. First i passed gender: \"male\" but it's an enum so it has own values. then i tried as gender: male It worked. just pass it as male without \"male\" β‘\n- You can answer your own question and mark it as accepted. That way you'll be helping anyone else with the same problem and clearly indicating that there is an answer to this question.\n- Yeah this was confusing AF","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":92,"estimatedTokens":469}}56{"id":"stack-55395589","source":"stackoverflow","questionId":55395589,"title":"How to add header in Apollo GraphQL : iOS","tags":["ios","graphql","apollo","apollo-client"],"text":"Title: How to add header in Apollo GraphQL : iOS\nTags: ios, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nHy I am working in a project with `Apollo GraphQL` method and its working fine. But now the client required for adding additional header with Apollo API's. But after adding the header the API's response return as *unAuthorized*.\n\nI am adding the header as,\n\n```\nlet apolloAuth: ApolloClient = {\n let configuration = URLSessionConfiguration.default\n\n // Add additional headers as needed\n configuration.httpAdditionalHeaders = [\"Authorization\" : self.singleTonInstance.token]\n configuration.httpAdditionalHeaders = [\"channel\" : \"mobile\"]\n\n let url = URL(string: \"http://xxx/graphql\")!\n\n return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))\n\n }()\n```\n\nAnyone please help me to find out how to add headers with Apollo GraphQL.\n\n========================================\n\nTop Answer:\n**UPDATE: Solution for \"Apollo Client v0.41.0\" and \"Swift 5\"**\n\nI had the same issue with Apollo Client v0.41.0 and Swift 5.0 but none of the above solutions worked. Finally able to find a solution after the hours of try-out. The below solution is tested with Apollo Client v0.41.0 And Swift 5\n\n```\nimport Foundation\nimport Apollo\n\nclass Network {\n static let shared = Network()\n \n private(set) lazy var apollo: ApolloClient = {\n\n let cache = InMemoryNormalizedCache()\n let store1 = ApolloStore(cache: cache)\n let authPayloads = [\"Authorization\": \"Bearer >\"]\n let configuration = URLSessionConfiguration.default\n configuration.httpAdditionalHeaders = authPayloads\n \n let client1 = URLSessionClient(sessionConfiguration: configuration, callbackQueue: nil)\n let provider = NetworkInterceptorProvider(client: client1, shouldInvalidateClientOnDeinit: true, store: store1)\n \n let url = URL(string: \"https:///graphql\")!\n \n let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider,\n endpointURL: url)\n \n return ApolloClient(networkTransport: requestChainTransport,\n store: store1)\n }()\n}\nclass NetworkInterceptorProvider: DefaultInterceptorProvider {\n override func interceptors(for operation: Operation) -> [ApolloInterceptor] {\n var interceptors = super.interceptors(for: operation)\n interceptors.insert(CustomInterceptor(), at: 0)\n return interceptors\n }\n}\n\nclass CustomInterceptor: ApolloInterceptor {\n \n func interceptAsync(\n chain: RequestChain,\n request: HTTPRequest,\n response: HTTPResponse?,\n completion: @escaping (Swift.Result, Error>) -> Void) {\n request.addHeader(name: \"Authorization\", value: \"Bearer >\")\n \n print(\"request :\\(request)\")\n print(\"response :\\(String(describing: response))\")\n \n chain.proceedAsync(request: request,\n response: response,\n completion: completion)\n }\n}\n```\n\n========================================\n\nCode:\n```text\nlet apolloAuth: ApolloClient = {\n let configuration = URLSessionConfiguration.default\n\n // Add additional headers as needed\n configuration.httpAdditionalHeaders = [\"Authorization\" : self.singleTonInstance.token]\n configuration.httpAdditionalHeaders = [\"channel\" : \"mobile\"]\n\n let url = URL(string: \"http://xxx/graphql\")!\n\n return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))\n\n }()\n```\n\n```text\nApollo GraphQL\n```\n\n```text\nlet apolloAuth: ApolloClient = {\n let configuration = URLSessionConfiguration.default\n\n let token = UserDefaults.standard.value(forKey: \"token\")\n // Add additional headers as needed\n configuration.httpAdditionalHeaders = [\"authorization\":\"\\(token!)\", \"channel\":\"mobile\"]\n let url = URL(string: \"http://xxxx/graphql\")!\n\n return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))\n\n }()\n```\n\n```text\nimport Foundation\nimport Apollo\n\nclass Network {\n static let shared = Network()\n\n private(set) lazy var apollo: ApolloClient = {\n let token = UserDefaults.standard.string(forKey: \"accessToken\") ?? \"\"\n let url = URL(string: \"http://localhost:4000/graphql\")!\n\n let configuration = URLSessionConfiguration.default\n\n configuration.httpAdditionalHeaders = [\"authorization\": \"Bearer \\(token)\"]\n\n return ApolloClient(\n networkTransport: HTTPNetworkTransport(url: url, session: URLSession(configuration: configuration))\n )\n }()\n}\n```\n\n```text\nURLSession\n```\n\n```text\nURLSessionConfiguration\n```\n\n```text\nversion 0.21.0\n```\n\n```text\nimport Foundation\nimport Apollo\n\n final class Network {\n static let shared = Network()\n private lazy var networkTransport: HTTPNetworkTransport = { \n\n let transport = HTTPNetworkTransport(url: URL(string: \"https://example.com/graphql\")!)\n transport.delegate = self\n\n return transport\n }()\n\n private(set) lazy var apollo = ApolloClient(networkTransport: self.networkTransport)\n}\n\nextension Network: HTTPNetworkTransportPreflightDelegate {\n func networkTransport(_ networkTransport: HTTPNetworkTransport, shouldSend request: URLRequest) -> Bool {\n return true\n }\n\n func networkTransport(_ networkTransport: HTTPNetworkTransport, willSend request: inout URLRequest) {\n var headers = request.allHTTPHeaderFields ?? [String: String]()\n headers[\"Authorization\"] = \"Bearer \\(YOUR_TOKEN)\"\n\n request.allHTTPHeaderFields = headers\n }\n}\n```\n\n```text\nclass Network {\n static let shared = Network()\n \n private(set) lazy var apollo: ApolloClient = {\n let client = URLSessionClient()\n let cache = InMemoryNormalizedCache()\n let store = ApolloStore(cache: cache)\n let provider = NetworkInterceptorProvider(client: client, store: store)\n let url = URL(string: \"https://www.graphqlapi.com/\")!\n let transport = RequestChainNetworkTransport(interceptorProvider: provider,\n endpointURL: url)\n return ApolloClient(networkTransport: transport)\n }()\n}\n\nclass NetworkInterceptorProvider: LegacyInterceptorProvider {\n override func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {\n var interceptors = super.interceptors(for: operation)\n interceptors.insert(CustomInterceptor(), at: 0)\n return interceptors\n }\n}\n\nclass CustomInterceptor: ApolloInterceptor {\n // Find a better way to store your token this is just an example\n let token = \"YOUR TOKEN\"\n \n func interceptAsync<Operation: GraphQLOperation>(\n chain: RequestChain,\n request: HTTPRequest<Operation>,\n response: HTTPResponse<Operation>?,\n completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {\n \n request.addHeader(name: \"authorization\", value: \"Bearer: \\(token)\")\n\n chain.proceedAsync(request: request,\n response: response,\n completion: completion)\n }\n}\n```\n\n```text\nimport Foundation\nimport Apollo\n\nclass Network {\n static let shared = Network()\n \n private(set) lazy var apollo: ApolloClient = {\n\n let cache = InMemoryNormalizedCache()\n let store1 = ApolloStore(cache: cache)\n let authPayloads = [\"Authorization\": \"Bearer <<TOKEN>>\"]\n let configuration = URLSessionConfiguration.default\n configuration.httpAdditionalHeaders = authPayloads\n \n let client1 = URLSessionClient(sessionConfiguration: configuration, callbackQueue: nil)\n let provider = NetworkInterceptorProvider(client: client1, shouldInvalidateClientOnDeinit: true, store: store1)\n \n let url = URL(string: \"https://<HOST NAME>/graphql\")!\n \n let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider,\n endpointURL: url)\n \n return ApolloClient(networkTransport: requestChainTransport,\n store: store1)\n }()\n}\nclass NetworkInterceptorProvider: DefaultInterceptorProvider {\n override func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {\n var interceptors = super.interceptors(for: operation)\n interceptors.insert(CustomInterceptor(), at: 0)\n return interceptors\n }\n}\n\nclass CustomInterceptor: ApolloInterceptor {\n \n func interceptAsync<Operation: GraphQLOperation>(\n chain: RequestChain,\n request: HTTPRequest<Operation>,\n response: HTTPResponse<Operation>?,\n completion: @escaping (Swift.Result<GraphQLResult<Operation.Data>, Error>) -> Void) {\n request.addHeader(name: \"Authorization\", value: \"Bearer <<TOKEN>>\")\n \n print(\"request :\\(request)\")\n print(\"response :\\(String(describing: response))\")\n \n chain.proceedAsync(request: request,\n response: response,\n completion: completion)\n }\n}\n```\n\n```text\nimport UIKit\nimport Apollo\n```\n\n```text\nstruct Network {\n static var request = Network()\n private(set) lazy var apollo: ApolloClient = {\n\n let cache = InMemoryNormalizedCache()\n let store1 = ApolloStore(cache: cache)\n let authPayloads = [\"Authorization\": \"Bearer <TOKEN>\"]\n let configuration = URLSessionConfiguration.default\n configuration.httpAdditionalHeaders = authPayloads\n \n let client1 = URLSessionClient(sessionConfiguration: configuration, callbackQueue: nil)\n let provider = NetworkInterceptorProvider(client: client1, shouldInvalidateClientOnDeinit: true, store: store1)\n \n let url = URL(string: \"http://xxx/graphql\")!\n \n let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider,\n endpointURL: url)\n \n return ApolloClient(networkTransport: requestChainTransport,\n store: store1)\n }()\n}\n```\n\n```text\nclass NetworkInterceptorProvider: LegacyInterceptorProvider {\noverride func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {\n var interceptors = super.interceptors(for: operation)\n interceptors.insert(CustomInterceptor(), at: 0)\n return interceptors\n}\n```\n\n```text\nclass CustomInterceptor: ApolloInterceptor {\n\nfunc interceptAsync<Operation: GraphQLOperation>(\n chain: RequestChain,\n request: HTTPRequest<Operation>,\n response: HTTPResponse<Operation>?,\n completion: @escaping (Swift.Result<GraphQLResult<Operation.Data>, Error>) -> Void) {\n request.addHeader(name: \"Authorization\", value: \"Bearer <TOKEN>\")\n \n print(\"request :\\(request)\")\n print(\"response :\\(String(describing: response))\")\n \n chain.proceedAsync(request: request,\n response: response,\n completion: completion)\n}\n```\n\n```text\nfunc todoQueryCloud(){\n Network.request.apollo.fetch(query: ProgressionsQuery()){result in\n // 3\n switch result {\n case .success(let graphQLResult):\n guard let data = try? result.get().data else { return }\n if graphQLResult.data != nil {\n // 4\n print(\"Loaded data \\(String(describing: data.progressions))\")\n self.collectionView.reloadData()\n }\n \n case .failure(let error):\n // 5\n print(\"Error loading data \\(error)\")\n }\n }\n}\n```\n\n```text\nclass NetworkInterceptorProvider: DefaultInterceptorProvider {\noverride func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {\n var interceptors = super.interceptors(for: operation)\n interceptors.insert(CustomInterceptor(), at: 0)\n return interceptors\n}\n```\n\n```text\nimport Foundation\nimport Apollo\n\nclass DataCoordinator: NSObject {\n // MARK: Variables\n static let shared: DataCoordinator = DataCoordinator()\n private(set) lazy var apolloClient: ApolloClient = {\n let cache = InMemoryNormalizedCache()\n let store = ApolloStore(cache: cache)\n let authPayloads = [\"Authorization\": \"Bearer \\(token)\"]\n let configuration = URLSessionConfiguration.default\n configuration.httpAdditionalHeaders = authPayloads\n let client = URLSessionClient(sessionConfiguration: configuration, callbackQueue: nil)\n let provider = NetworkInterceptorProvider(store: store, client: client)\n let url = URL(string: \"https://xxxxxxxxx/graphql\")!\n let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: url)\n return ApolloClient(networkTransport: requestChainTransport, store: store)\n }()\n}\n\nstruct NetworkInterceptorProvider: InterceptorProvider {\n // These properties will remain the same throughout the life of the `InterceptorProvider`, even though they\n // will be handed to different interceptors.\n private let store: ApolloStore\n private let client: URLSessionClient\n \n init(store: ApolloStore,\n client: URLSessionClient) {\n self.store = store\n self.client = client\n }\n \n func interceptors<Operation>(for operation: Operation) -> [ApolloInterceptor] {\n return [\n MaxRetryInterceptor(),\n CacheReadInterceptor(store: self.store),\n NetworkFetchInterceptor(client: self.client),\n ResponseCodeInterceptor(),\n JSONResponseParsingInterceptor(),\n AutomaticPersistedQueryInterceptor(),\n CacheWriteInterceptor(store: self.store)\n ]\n }\n}\n```\n\n```text\nimport Apollo\nimport Foundation\n\nclass Network {\n static let shared = Network()\n\n private(set) lazy var apollo: ApolloClient = {\n let url = URL(string: \"https://example.com/v1/graphql\")!\n\n let configuration = URLSessionConfiguration.default\n configuration.httpAdditionalHeaders = [\"Authorization\": \"Bearer token\"] // Add your headers here\n\n let client = URLSessionClient(sessionConfiguration: configuration)\n let store = ApolloStore(cache: InMemoryNormalizedCache())\n let provider = DefaultInterceptorProvider(client: client, store: store)\n let networkTransport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: url)\n\n return ApolloClient(networkTransport: networkTransport, store: store)\n }()\n}\n```\n\n========================================\n\nComments:\n- Did you try to set the header to \"Bearer \" instead of \"\"? What's the authorization method your server is using? Do you have a working cURL statement against the server that uses an authorization token?\n- did you find any solution?\n- Please refer my answer.\n- it stops working from version 0.34, there is no HTTPNetworkTransport anymore\n- Am getting this errors `Cannot find type 'HTTPNetworkTransport' in scope` and `Cannot find type 'HTTPNetworkTransportPreflightDelegate' in scope` any help? Am using Appoloclient v0.34.1.\n- @GB I checked out the docs in the link above, and they have deprecated HTPPNetworkTransport. This can still be done using \"LegacyInterceptorProvider\", or you could look into the new protocol: NetworkTransport\".\n- I provided a solution you can have a look at it.\n- What a nightmare API! `NetworkInterceptorProvider: LegacyInterceptorProvider`!\n- Thanks! This is the only solution that works with Apollo 0.42.0\n- @Chamath Jeevan I have tried this solution with Apollo 0.43.0 version and it gives me failure reposne error as **failure(Apollo.LegacyParsingInterceptor.LegacyParsingError.c‌​ouldNotParseToLegacy‌​JSON(data: 1839 bytes))** please suggest me what can I do further\n- @JochenHolzer I too have tried the same code syntax but the request gives me HTML in failure block. Could you please help me to solve this issue Apollo GraphQL header always gives failure in iOS Swift\n- @Princess Perhaps there is an error message in the HTML response. If I were you, I would ask the endpoint development team what information about your failed request is in the server log files.\n- @JochenHolzer I am using a Shopify GraphQL Admin API to fetch customer's order details from the Shopify store. The same URL request working with Android Apollo Client.\n- This worked for 0.51.2 version. Note: Tokens expires. So using singleton won't work. Apollo recommends using UserManagementInterceptor for expiring tokens. github.com/apollographql/apollo-ios/discussions/1535\n- Can you update it to version 1.0\n- I am passing header like the above one but every time I get the response nil. Any solution? I am using pod 0.50.0\n- For me this isn't working I have asked a new question Apollo GraphQL header always gives failure in iOS Swift please check this.","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":463,"estimatedTokens":4218}}57{"id":"stack-61557542","source":"stackoverflow","questionId":61557542,"title":"aws cdk appsync Schema Creation Status is FAILED with details: Internal Failure while saving the schema","tags":["typescript","aws-lambda","graphql","aws-appsync","aws-cdk"],"text":"Title: aws cdk appsync Schema Creation Status is FAILED with details: Internal Failure while saving the schema\nTags: typescript, aws-lambda, graphql, aws-appsync, aws-cdk\nSource: Stack Overflow\n\nQuestion:\nGiven the following graphql schema\n\n```\n# graphql/schema.graphql\ntype AppUser {\n userId: String\n fullName: String\n}\n\ntype Query {\n getUser(userId: String): AppUser\n getUsers(): [AppUser]\n}\n\ntype Mutation {\n addUser(user: AppUser!): AppUser\n}\n```\n\nAnd the following cdk code defined at lib/mystack.ts:\n\n```\nconst graphql = new appsync.GraphQLApi(this, 'GraphQLApi', {\n name: 'metrolens-graphql-api',\n logConfig: {\n fieldLogLevel: appsync.FieldLogLevel.ALL,\n },\n authorizationConfig: {\n defaultAuthorization: {\n // userPool,\n defaultAction: appsync.UserPoolDefaultAction.ALLOW,\n },\n // additionalAuthorizationModes: [{ apiKeyDesc: 'My API Key' }],\n },\n schemaDefinitionFile: props?.schemaDirectory,\n })\n\n const lambdaRegister = new nodejs.NodejsFunction(this, 'register', {\n functionName: 'register',\n runtime: lambda.Runtime.NODEJS_12_X,\n timeout: cdk.Duration.seconds(10),\n entry: './lambda/register/register-0.ts',\n handler: 'handler',\n layers: [layer],\n description: 'Register a user.',\n })\n\n const lambdaLogin = new nodejs.NodejsFunction(this, 'login', {\n functionName: 'login',\n runtime: lambda.Runtime.NODEJS_12_X,\n timeout: cdk.Duration.seconds(10),\n entry: './lambda/login/login-0.ts',\n handler: 'handler',\n layers: [layer],\n description: 'Login a user.',\n })\n\n const lambdaRegisterDataSource = graphql.addLambdaDataSource(\n 'lambdaRegister',\n 'Register lambda triggered by appsync',\n lambdaRegister\n )\n lambdaRegisterDataSource.createResolver({\n typeName: 'Mutation',\n fieldName: 'addUser',\n requestMappingTemplate: appsync.MappingTemplate.lambdaRequest(),\n responseMappingTemplate: appsync.MappingTemplate.lambdaResult(),\n })\n\n const lambdaLoginDataSource = graphql.addLambdaDataSource(\n 'lambdaLogin',\n 'Login lambda triggered by appsync',\n lambdaLogin\n )\n\n lambdaLoginDataSource.createResolver({\n typeName: 'Query',\n fieldName: 'getUsers',\n requestMappingTemplate: appsync.MappingTemplate.lambdaRequest(),\n responseMappingTemplate: appsync.MappingTemplate.lambdaResult(),\n })\n```\n\nI get the following error message during the `AWS::AppSync::GraphQLSchema` deployment phase:\n\nGraphQLApi/Schema (GraphQLApiSchema5937B126) Schema Creation Status is FAILED with details: Internal Failure while saving the schema.\n\nHas anyone encountered this error before? I suspect there is something wrong with my graphql schema but I couldn't tell what it was. Another answer mentioned that the DynamoDB reserved words at https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html could cause conflicts, even if you don't use DynamoDB, so I renamed the `User` type to `AppSync`. However, it looks like `Query` is also a reserved word, but as far as I understand, that is also necessary for a graphql definition. Please help. AWS CDK suck hard.\n\n========================================\n\nTop Answer:\nTo understand where the issue appears with your graphql schema in this case, you can just go to your **AppSync API** and manually try to **add the schema** (copy/paste) and it will automatically throw an error.\n\nhttps://i.sstatic.net/faVLK.png\n\n========================================\n\nCode:\n```text\n# graphql/schema.graphql\ntype AppUser {\n userId: String\n fullName: String\n}\n\ntype Query {\n getUser(userId: String): AppUser\n getUsers(): [AppUser]\n}\n\ntype Mutation {\n addUser(user: AppUser!): AppUser\n}\n```\n\n```js\nconst graphql = new appsync.GraphQLApi(this, 'GraphQLApi', {\n name: 'metrolens-graphql-api',\n logConfig: {\n fieldLogLevel: appsync.FieldLogLevel.ALL,\n },\n authorizationConfig: {\n defaultAuthorization: {\n // userPool,\n defaultAction: appsync.UserPoolDefaultAction.ALLOW,\n },\n // additionalAuthorizationModes: [{ apiKeyDesc: 'My API Key' }],\n },\n schemaDefinitionFile: props?.schemaDirectory,\n })\n\n const lambdaRegister = new nodejs.NodejsFunction(this, 'register', {\n functionName: 'register',\n runtime: lambda.Runtime.NODEJS_12_X,\n timeout: cdk.Duration.seconds(10),\n entry: './lambda/register/register-0.ts',\n handler: 'handler',\n layers: [layer],\n description: 'Register a user.',\n })\n\n const lambdaLogin = new nodejs.NodejsFunction(this, 'login', {\n functionName: 'login',\n runtime: lambda.Runtime.NODEJS_12_X,\n timeout: cdk.Duration.seconds(10),\n entry: './lambda/login/login-0.ts',\n handler: 'handler',\n layers: [layer],\n description: 'Login a user.',\n })\n\n const lambdaRegisterDataSource = graphql.addLambdaDataSource(\n 'lambdaRegister',\n 'Register lambda triggered by appsync',\n lambdaRegister\n )\n lambdaRegisterDataSource.createResolver({\n typeName: 'Mutation',\n fieldName: 'addUser',\n requestMappingTemplate: appsync.MappingTemplate.lambdaRequest(),\n responseMappingTemplate: appsync.MappingTemplate.lambdaResult(),\n })\n\n const lambdaLoginDataSource = graphql.addLambdaDataSource(\n 'lambdaLogin',\n 'Login lambda triggered by appsync',\n lambdaLogin\n )\n\n lambdaLoginDataSource.createResolver({\n typeName: 'Query',\n fieldName: 'getUsers',\n requestMappingTemplate: appsync.MappingTemplate.lambdaRequest(),\n responseMappingTemplate: appsync.MappingTemplate.lambdaResult(),\n })\n```\n\n```text\nAWS::AppSync::GraphQLSchema\n```\n\n```text\nUser\n```\n\n```text\nAppSync\n```\n\n```text\nQuery\n```\n\n```text\ninput AppUserInput {\n userId: String\n fullName: String\n}\n```\n\n```text\nAppUser\n```\n\n```text\naddUser\n```\n\n```text\ninput\n```\n\n```text\nAppUser\n```\n\n```text\n{\n \"error\": \"Syntax error while parsing GraphQL query. Invalid input \\\"{\\\\n getUser(userId: String): AppUser\\\\n getUsers()\\\", expected ImplementsInterfaces, Directives, FieldDefinition or Comments (line 6, column 12):\\ntype Query {\\n ^\"\n}\n```\n\n```text\ngetUsers(): [AppUser]\n```\n\n```text\ngetUsers: [AppUser]\n```\n\n```text\nenum Status { PENDING APPROVED }\n```\n\n```text\nenum String { PENDING APPROVED }\n```\n\n========================================\n\nComments:\n- Which validator did you use? (and where is it located?). If possible could you please tell us the commands that you used to get that output?\n- Thanks, helped me a lot. That error was not really descriptive.\n- Adding a note - use the AppSync schema editor in the console - I had the same error - turns out AppSync doesn't recognize triple quote comments which most validators allow.\n- I was searching the docs and you can see in the generated schema how the inputs were used in the functions: docs.amplify.aws/cli-legacy/graphql-transformer/model/…","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":251,"estimatedTokens":1692}}58{"id":"stack-48532299","source":"stackoverflow","questionId":48532299,"title":"Gatsby.js: Filter GraphQL query by nested object property","tags":["filter","graphql","graphql-js","contentful","gatsby"],"text":"Title: Gatsby.js: Filter GraphQL query by nested object property\nTags: filter, graphql, graphql-js, contentful, gatsby\nSource: Stack Overflow\n\nQuestion:\nI'm working on a news site which will have articles, each with one or multiple respective authors. If you click on an author's name, it will take you to a page displaying their information and a list of articles they have contributed to.\n\nSo each article has an `authors` property, which in turn is an array of `author` objects with properties: full name, slug (*lowercase version of full name with spaces replaced by dashes*), etc.\n\nIs it possible to filter the articles by a particular author's slug when defining the query?\n\n```\nquery authorQuery($slug: String!) {\n allContentfulArticle(filter: { //not sure what to do here }) {\n edges {\n node {\n title\n slug\n authors {\n name\n slug\n }\n }\n }\n }\n}\n```\n\nMy other option would be to load all of the articles, then setup a filter in the component like so:\n\n```\nconst articles = data.allContentfulArticle.edges.filter(({ node }) => {\n return node.authors.some((author) => author.slug === data.contentfulAuthor.slug);\n});\n```\n\nThis wouldn't be the end of the world, however it goes against the GraphQL principle of only loading the data you need.\n\n========================================\n\nCode:\n```text\nquery authorQuery($slug: String!) {\n allContentfulArticle(filter: { //not sure what to do here }) {\n edges {\n node {\n title\n slug\n authors {\n name\n slug\n }\n }\n }\n }\n}\n```\n\n```text\nconst articles = data.allContentfulArticle.edges.filter(({ node }) => {\n return node.authors.some((author) => author.slug === data.contentfulAuthor.slug);\n});\n```\n\n```text\nauthors\n```\n\n```text\nauthor\n```\n\n```text\n{\n allContentfulAuthor(filter: {slug: {eq: \"myslug\"}}) {\n edges {\n node {\n name\n article {\n title\n slug\n }\n }\n }\n }\n}\n```\n\n```text\nallContentfulAuthor\n```\n\n```text\narticle\n```\n\n```text\narticle\n```\n\n========================================\n\nComments:\n- Would this work if Author did not have an article field?\n- Thanks Khaled! I did not realize that the author object would automatically contain an article field since I defined the relationship as articles containing authors, and not vice-versa. What is responsible for that magic, Contentful itself? Very cool. To answer your question @LukeFlournoy, the answer seems to be yes :)\n- Thatβs called back reference from the author to the article, that has nothing todo with Contentful itβs more GraphQl magic\n- Thanks again, loving graphql more and more each day. One quick followup question for you related to nesting: would it be possible to sort the articles by a field here as well? meaning in your example above put `article(sort:{fields:[date], order:DESC}) { title slug }`.\n- It could work, you can test that on localhost:8000/___graphql , Gatsbyjs spawn a grapgiql server for you when in develop mode, thatβs your best friend\n- yeah when I try to do that I get an error: `Unknown argument \\\"sort\\\" on field \\\"article\\\" of type \\\"ContentfulAuthor\\\".\"`. Meanwhile this same sort method works fine when querying articles directly, rather than querying them as a property of authors. wondering if it's an issue that has to do with the reference you alluded to earlier\n- Unfortunately, that is not possible\n- Gotcha, I will sort within the component definition. Thanks for all the help @KhaledGarbaya!\n- Is there a way to make the `\"myslug\"` in your example dynamic?\n- Yes , through `allContentfulAuthor(filter: {slug: {eq: $slug}}) {` where $slug is passed through the context object when creating this page in the gatsby-node.js","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":113,"estimatedTokens":925}}59{"id":"stack-54984035","source":"stackoverflow","questionId":54984035,"title":"How to know which fields were requested in a GraphQL query?","tags":["graphql","apollo","apollo-server","resolver"],"text":"Title: How to know which fields were requested in a GraphQL query?\nTags: graphql, apollo, apollo-server, resolver\nSource: Stack Overflow\n\nQuestion:\nI have written a GraphQL query which like the one below:\n\n```\n{\n posts {\n author {\n comments\n }\n comments\n }\n}\n```\n\nI want to know how can I get the details about the requested child fields inside the `posts` resolver.\n\nI want to do it to avoid nested calls of resolvers. I am using ApolloServer's `DataSource` API.\n\nI can change the API server to get all the data at once.\n\nI am using ApolloServer 2.0 and any other ways of avoiding nested calls are also welcome.\n\n========================================\n\nTop Answer:\nHere, are couple main points that you can use to optimize your queries for performance. \n\nIn your example there would be great help to use\nhttps://github.com/facebook/dataloader. If you load comments in your\nresolvers through data loader you will ensure that these are called\njust once. This will reduce the number of calls to database\nsignificantly as in your query is demonstrated N+1 problem.\nI am not sure what exact information you need to obtain in posts\nahead of time, but if you know the post ids you can consider to do a\n\"look ahead\" by passing already known ids into comments. This will\nensure that you do not need to wait for posts and you will avoid\ngraphql tree calls and you can do resolution of comments without\nwaiting for posts. This is great article for optimizing GraphQL\nwaterfall requests and might you give good idea how to optimize your\nqueries with data loader and do look ahead\nhttps://blog.apollographql.com/optimizing-your-graphql-request-waterfalls-7c3f3360b051\n\n========================================\n\nCode:\n```text\n{\n posts {\n author {\n comments\n }\n comments\n }\n}\n```\n\n```text\nposts\n```\n\n```text\nDataSource\n```\n\n```text\ntype GraphQLResolveInfo = {\n fieldName: string,\n fieldNodes: Array<Field>,\n returnType: GraphQLOutputType,\n parentType: GraphQLCompositeType,\n schema: GraphQLSchema,\n fragments: { [fragmentName: string]: FragmentDefinition },\n rootValue: any,\n operation: OperationDefinition,\n variableValues: { [variableName: string]: any },\n}\n```\n\n```text\nposts: (parent, args, context, info) => {\n const parsedResolveInfo = parseResolveInfo(info)\n console.log(parsedResolveInfo)\n}\n```\n\n```text\n{\n alias: 'posts',\n name: 'posts',\n args: {},\n fieldsByTypeName: {\n Post: {\n author: {\n alias: 'author',\n name: 'author',\n args: {},\n fieldsByTypeName: ...\n }\n comments: {\n alias: 'comments',\n name: 'comments',\n args: {},\n fieldsByTypeName: ...\n }\n }\n }\n}\n```\n\n```text\ninfo\n```\n\n```text\ngraphql-parse-resolve-info\n```\n\n```text\npostgraphile\n```\n\n```text\nexport const resolvers = {\n Query: {\n posts: async (_parent, _args, _context, info) => {\n if (lookahead({ info, until: ({ field }) => field === 'author' })) {\n // the author field is requested\n }\n\n const allRequestedFields = {}\n lookahead({\n info,\n state: allRequestedFields,\n\n next({ state, field }) {\n const nextState = {}\n state[field] = nextState\n\n return nextState\n },\n })\n\n // => { author: { comments: {} }, comments: {} }\n```\n\n========================================\n\nComments:\n- This is a essentially a duplicate of How to get the fields requested in a query from resolver\n- This is exactly what I was looking for.\n- The author of graphql-fields also recommends using `graphql-parse-resolve-info` going forward.","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":155,"estimatedTokens":896}}60{"id":"stack-39697575","source":"stackoverflow","questionId":39697575,"title":"Is there a way to represent an object of key-value pairs in GraphQL","tags":["javascript","key-value","graphql","key-value-store","graphql-js"],"text":"Title: Is there a way to represent an object of key-value pairs in GraphQL\nTags: javascript, key-value, graphql, key-value-store, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am using GraphQL in my Node.js application. And I want to store an object that uses keys as a locale short code and values for the string in the corresponding language. (like `{ en: \"Hello\", ru: \"ΠΡΠΈΠ²Π΅Ρ\" }` etc.)\n\nI want to represent this using GraphQL, both in input (like that):\n\n```\nmutation {\n addExercise(name: { en: \"Hello\", ru: \"ΠΡΠΈΠ²Π΅Ρ\" })\n}\n```\n\nand in output (like that)\n\n```\n{\n exercises {\n _id, name\n }\n}\n```\n\n(`name` should return an object of key-value pairs:)\n\n```\n[\n {_id: 1, name: { en: \"Hello\", ru: \"ΠΡΠΈΠ²Π΅Ρ\" }}\n]\n```\n\nHow can I do something like that?\n\nI know I can store my data this way \n\n```\n{ name: \"en\", value: \"Hello }`\n```\n\nbut the previous one seems to be easier.\n\n========================================\n\nCode:\n```text\nmutation {\n addExercise(name: { en: \"Hello\", ru: \"ΠΡΠΈΠ²Π΅Ρ\" })\n}\n```\n\n```text\n{\n exercises {\n _id, name\n }\n}\n```\n\n```text\n[\n {_id: 1, name: { en: \"Hello\", ru: \"ΠΡΠΈΠ²Π΅Ρ\" }}\n]\n```\n\n```text\n{ name: \"en\", value: \"Hello }`\n```\n\n```text\n{ en: \"Hello\", ru: \"ΠΡΠΈΠ²Π΅Ρ\" }\n```\n\n```text\nname\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":77,"estimatedTokens":303}}61{"id":"stack-44046754","source":"stackoverflow","questionId":44046754,"title":"Role of QueryRenderer in Relay Modern?","tags":["reactjs","graphql","relay"],"text":"Title: Role of QueryRenderer in Relay Modern?\nTags: reactjs, graphql, relay\nSource: Stack Overflow\n\nQuestion:\nSo, first **a bit of background**. \nI'm a native iOS/Android developer who is now starting my first ever React Native project. It comes with all the benefits and pains of Javascript, but I like it a lot so far :-) I decided to also try my hand at GraphQL for the first time as well.\n\nBeing new to the React milieu in general, I also donβt have any prior knowledge of Relay, but chose it on recommendation from friends in my startup community and my web-dev colleagues. I was also warned about a somewhat steep learning curve, but decided to go ahead anyway - I am already fighting an uphill battle with JS and a 0.xx version of a new mobile platform, so what the hell, right? :-) I managed to set up my project correctly and punch a whole through to my GQL server with a `QueryRenderer`, which was a great relief :-)\n\n**So, on to the questions**\n\nI'm having a hard time figuring out the container/component relationship, and container composition in general. Reading the docs on composition helped, but I'm still in doubt over the role of the `QueryRenderer`\n\n- `QueryRenderer` is said by the docs to be the root container for every Relay tree. Does that mean that one should have a `QueryRenderer` for the root in our app? Or at the root of each navigation path (i.e. tabs in our app)? Or just for each container component (as opposed to presentational/dumb/pure components, React wise)? Note that I'm not looking for opinions, but arguments for best practice :-)\n\n- Can a `FragmentContainer` (or any other container, for that matter) work without a `QueryRenderer` in the βparentβ component?\n\n- How is the `QueryRenderer` linked to child containers? Does it fetch the sum of all the data that child containers want, and then the child containers read from the cache, or? If so, Iβve misunderstood the pros of Relay - we are under the impression that each component can retrieve data independently from every other components, and that each component does not know anything about the data requirements of other components (including parent/child components). I think this assumption is also what confuses me about the `QueryRenderer`, and the need for a βRootβ container.\n\n- If `QueryRenderer` is a βparentβ/βrootβ Relay container to a Relay tree, how come it has to render view components based on itβs request? And why does it have to have a request? When and for what should we use a `QueryRenderer`?\n\nAny help is much appreciated :-)\n\n========================================\n\nTop Answer:\nThanks for bringing up this topic. I too have just been getting into Relay with ReactNative, and with some exciting results.\n\nFirstly, I am surprised how easy it has been to bring UI components reflecting GraphQL databases to the screen. After the initial overhead of learning the basics of JavaScript and the react-native pipeline, Relay has become a fantastic way to present data.\n\nIn regards to best practices I cannot say for sure how to present your \nQueryRenderer and the fragmentContainer, however I can describe our way of presenting the data.\n\nFirstly we create a react-navigation stack and tab. Inside each major screen we run a QueryRenderer. Then within that QueryRenderer, for each specific UI component, we seperate into a fragmentContainer.\n\n- Navigation Flow (react-navigation, Stack/Tab Navigators)\n\n- Screen (QueryRenderer) UI\n\n- Widget/Component (fragmentContainer)\n\nThis allows us to create the required primary query for the screen then break up the components data to fit within consumable components that are easily defined by the GraphQL query fragment they represent. However it does mean that we are running multiple queries across the app with no central account query to wrap the entire rendering up into a neat package.\n\nIdeally I would like to try a QueryRenderer at the top inside a Navigator, however I haven't quite yet got my head around how and if this would work as Navigators do not respond to a render() function, which is where the QueryRenderer is required.\n\nI would also be interested in hearing other peoples approaches to how they apply relay within a navigable react-native app.\n\n========================================\n\nCode:\n```text\nQueryRenderer\n```\n\n```text\nQueryRenderer\n```\n\n```text\nQueryRenderer\n```\n\n```text\nQueryRenderer\n```\n\n```text\nFragmentContainer\n```\n\n```text\nQueryRenderer\n```\n\n```text\nQueryRenderer\n```\n\n```text\nQueryRenderer\n```\n\n```text\nQueryRenderer\n```\n\n```text\nQueryRenderer\n```\n\n========================================\n\nComments:\n- Hey Peter, thanks for taking the time to write such a detailed answer :-) After some discussion, that was exactly the same strategy we arrived at, and wanted to try it today when I saw your post - so maybe neither of us are that far off ;-) I, unfortunately, ran into another problem when trying to implement it, and posted it (jhalborg) here github.com/facebook/relay/issues/1665 . Once I get it working, I'll come back here and sum up my experiences\n- I do wonder, however, if this is the best approach if you have a deep nav tree in a stack nav as a child of one of the tabs - in such a case, the queryrenderer would fetch a lot of data that might not be relevant to the user before he hits a screen deeper in the stack nav tree, and so it might make more sense to include a second QueryRenderer as a new \"root\" further down the stack nav tree - what do you think?\n- Great to hear we are on the same page. Thanks for the the message. With regards to superfluous data. We are currently looking at this. For now, anything we do not need is just removed from the query. I have actually run into an interesting issue regarding meta data. Where UI does not reflect the results of a query, but is passed down using a prop. The details are quite complex so won't go into it here. But so far our solution seems to meet our requirements. It's definitely a lot faster to produce results than Native even if there are a few anomalies along the way.\n- Also, check out the new SectionList -> facebook.github.io/react-native/releases/next/docs/…. We need to display different cell items in each section, each with a corresponding fragment from our query. Combined they make it so easy to show data in a neat UI. It's a little easier to deal with than a ListView with data source components.\n- If enough people upvote the answer, I will eventually mark it as \"accepted\" for whoever visits this post in the future. I'll await and see if others agree with our strategy first, though :-)\n- Isn't it Relay smart enough to fetch the data for fragments only when the component render?. For example, you might have a root query with a fragment ...User_friends; I believe that Relay will fetch data for such fragment only when the component that uses it renders. Please correct me if I'm wrong\n- Replying myself, I just tried a child fragmentContainer inside a parent QueryRenderer and indeed, the QueryRenderer fetches data for the child fragmentContainer, even when the child is not even rendered yet. Anyways, I'm going to have to upvote both answers, because actually it depends on the specific situation = )","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":101,"estimatedTokens":1801}}62{"id":"stack-52635916","source":"stackoverflow","questionId":52635916,"title":"Error: Cannot use GraphQLSchema \"[object GraphQLSchema]\" from another module or realm","tags":["javascript","node.js","ecmascript-6","graphql","graphql-js"],"text":"Title: Error: Cannot use GraphQLSchema \"[object GraphQLSchema]\" from another module or realm\nTags: javascript, node.js, ecmascript-6, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nGiven the following code:\n\n```\nimport { graphql } from 'graphql'\nimport graphqlTools from 'graphql-tools'\n\nconst { makeExecutableSchema } = graphqlTools\n\nconst typeDefs = `\ntype Query {\n as: [A]\n}\n\ntype A {\n x: Int,\n y: Int\n}\n`\nconst schema = makeExecutableSchema ({ typeDefs })\n\ngraphql(schema, '{ as { x, y } }').then(console.log)\n```\n\nI get this error:\n\n Error: Cannot use GraphQLSchema \"[object GraphQLSchema]\" from another\n module or realm.\n\n \n Ensure that there is only one instance of \"graphql\" in the\n node_modules directory. If different versions of \"graphql\" are the\n dependencies of other relied on modules, use \"resolutions\" to ensure\n only one version is installed.\n\nWhat's going on?\n\n========================================\n\nTop Answer:\nThis situation may also occur when the version of the `graphql` module you have installed is different from the version installed and used by `graphql-tools`.\n\nI have found you can correct this by either:\n\nChanging the version of `graphql` in your project's `package.json` file to match exactly what `graphql-tools` depends on in its `package.json` file.\n\nRemoving `graphql` as a dependency and just installing `graphql-tools`. Then you will automatically receive whatever `graphql` module version that `graphql-tools` installs (as long as you don't depend on any other packages that install another, conflicting version).\n\nIn other cases you might have the correct version, but it may be installed multiple times. You can use `npm ls graphql` to see all the installed versions. Try running `npm dedupe` to remove duplicate installations.\n\n========================================\n\nCode:\n```text\nimport { graphql } from 'graphql'\nimport graphqlTools from 'graphql-tools'\n\nconst { makeExecutableSchema } = graphqlTools\n\nconst typeDefs = `\ntype Query {\n as: [A]\n}\n\ntype A {\n x: Int,\n y: Int\n}\n`\nconst schema = makeExecutableSchema ({ typeDefs })\n\ngraphql(schema, '{ as { x, y } }').then(console.log)\n```\n\n```text\nimport graphql_ from 'graphql/index.js'\nimport graphqlTools from 'graphql-tools'\n\nconst { graphql } = graphql_\nconst { makeExecutableSchema } = graphqlTools\n\nconst typeDefs = `\ntype Query {\n as: [A]\n}\n\ntype A {\n x: Int,\n y: Int\n}\n`\nconst schema = makeExecutableSchema ({ typeDefs })\n\ngraphql(schema, '{ as { x, y } }').then(console.log)\n```\n\n```text\ngraphql-tools\n```\n\n```text\ngraphql\n```\n\n```text\ngraph-tool\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql-tools\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql-tools\n```\n\n```text\ngraphql\n```\n\n```text\npackage.json\n```\n\n```text\ngraphql-tools\n```\n\n```text\npackage.json\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql-tools\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql-tools\n```\n\n```text\nnpm ls graphql\n```\n\n```text\nnpm dedupe\n```\n\n```js\n{\n test: /\\.m?js/,\n include: /node_modules/,\n type: \"javascript/auto\",\n resolve: {\n fullySpecified: false\n }\n}\n```\n\n```js\nresolve: {\n extensions: [\".ts\", \".js\", \".mjs\"] // that was the actual problem\n}\n```\n\n```js\nresolve: {\n extensions: [\".ts\", \".mjs\", \".js\"]\n}\n```\n\n```text\n.js\n```\n\n```text\n.mjs\n```\n\n```text\nTypeMapper.mjs\n```\n\n```text\ngraphql-compose\n```\n\n```text\nfullySpecified:false\n```\n\n```text\nfullySpecified\n```\n\n```text\nfalse\n```\n\n```text\nresolve.extentions\n```\n\n```text\ngraphql\n```\n\n```text\n.js\n```\n\n```text\n.mjs\n```\n\n```text\nresolve.extensions\n```\n\n```text\n@<company-name>:registry=<registry-url>\n//<artifactory-name>:_password=${PASSWORD}\n//<artifactory-name>:username=${JFROG_USERNAME}\n//<artifactory-name>:email=${YOUR_EMAIL}\n//<artifactory-name>:always-auth=true\n```\n\n```text\nexternalsPresets: { node: true },\n externals: [nodeExternals()],\n```\n\n```text\n\"resolutions\": {\n \"graphql\": \"^15.3.0\"\n }\n```\n\n```text\nwebpack-node-externals\n```\n\n```text\nyarn\n```\n\n```text\nresolutions\n```\n\n```text\npackage.json\n```\n\n```text\n\"apollo\": \"^2.33.4\", \"graphql\": \"^15.5.0\",\n```\n\n```text\nnode_modules\n```\n\n```text\npackage-lock.json\n```\n\n========================================\n\nComments:\n- I have filed an issue with graphql-tools trying to sort that but while your patch works we cannot find source of issue.. Any ideas? still does it in latest versions\n- @cyberwombat Would you mind sharing the issue?\n- @PatrickDesjardins turns out that `graphql-tools` fixed that issue a while back so was not actually the culprit for me. My issue was that yarn was not upgrading `graphql-tools` fully - it oddly would tell me it upgraded but kept old files. A full `node_modules` delete/install with latest `graphql-tools` fixed the issue.\n- This worked for me, the `ls` command gave me context, but the `dedupe` cleaned it up.","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":45,"totalLines":297,"estimatedTokens":1195}}63{"id":"stack-51349801","source":"stackoverflow","questionId":51349801,"title":"Querying all images in folder using GraphQL","tags":["reactjs","graphql","gatsby"],"text":"Title: Querying all images in folder using GraphQL\nTags: reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI am currently learning Gatsby.js and GraphQL as a supplementary technology and got stuck with querying. I want to query all images from a folder, map trough them and display them in a react component as a grid. I am using gatsby-source-filesystem but can't figure out, how to address specifically that folder and get all images from it.\n\nMy plugin set up for source-filesystem looks like this.\n\n```\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/posts`,\n name: 'posts',\n },\n},\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `images`,\n path: `${__dirname}/src/assets/images`,\n },\n},\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `photos`,\n path: `${__dirname}/src/assets/photos`,\n },\n},\n```\n\nI have my images in src/assets/photos\n\nThanks for any help!\n\n========================================\n\nTop Answer:\nI like to use `sourceInstanceName` when using `gatsby-source-filesystem` plugin as documented in the plugin docs.\n\nYour `gatsby-config.js`\n\n```\n{\n resolve: \"gatsby-source-filesystem\",\n options: {\n path: `${__dirname}/content/legal`,\n name: \"legal\", // IMPORTANT: the name of your source instance\n },\n}, {\n resolve: \"gatsby-source-filesystem\",\n options: {\n path: `${__dirname}/content/blog`,\n name: \"blog\",\n },\n}\n```\n\nThen you can directly address them in your GraphQL query using `filter` and `sourceInstanceName`:\n\n```\nexport const query = graphql`\n{\n allFile(filter: {\n extension: {eq: \"png\"},\n sourceInstanceName: {eq: \"blog\"}\n })\n {\n edges {\n node {\n childImageSharp {\n fluid(maxWidth: 300, quality: 50) {\n originalName\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n }\n}\n```\n\nIn contrast to `relativeDirectory`, this way you never have to deal with changing relative paths you might refactor your project or whatever. Just let GraphQL handle it for you!\n\n========================================\n\nCode:\n```text\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/posts`,\n name: 'posts',\n },\n},\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `images`,\n path: `${__dirname}/src/assets/images`,\n },\n},\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `photos`,\n path: `${__dirname}/src/assets/photos`,\n },\n},\n```\n\n```text\nquery AssetsPhotos {\n allFile(filter: {extension: {regex: \"/(jpg)|(jpeg)|(png)/\"}, relativeDirectory: {eq: \"photos\"}}) {\n edges {\n node {\n id\n name\n }\n }\n }\n}\n```\n\n```text\neq: photos\n```\n\n```text\nallFile\n```\n\n```text\n{\n resolve: \"gatsby-source-filesystem\",\n options: {\n path: `${__dirname}/content/legal`,\n name: \"legal\", // IMPORTANT: the name of your source instance\n },\n}, {\n resolve: \"gatsby-source-filesystem\",\n options: {\n path: `${__dirname}/content/blog`,\n name: \"blog\",\n },\n}\n```\n\n```text\nexport const query = graphql`\n{\n allFile(filter: {\n extension: {eq: \"png\"},\n sourceInstanceName: {eq: \"blog\"}\n })\n {\n edges {\n node {\n childImageSharp {\n fluid(maxWidth: 300, quality: 50) {\n originalName\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n }\n}\n```\n\n```text\nsourceInstanceName\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\ngatsby-config.js\n```\n\n```text\nfilter\n```\n\n```text\nsourceInstanceName\n```\n\n```text\nrelativeDirectory\n```\n\n========================================\n\nComments:\n- This is an elegant solution","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":200,"estimatedTokens":879}}64{"id":"stack-60218757","source":"stackoverflow","questionId":60218757,"title":"graphql-codegen not running with config file","tags":["graphql","graphql-codegen"],"text":"Title: graphql-codegen not running with config file\nTags: graphql, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nIn my `package.json` file I've got script entry that runs `graphql-codegen` but it complains that the `--config` argument is invalid:\n\n```\n$> yarn gen\nyarn run v1.21.1\n$ graphql-codegen --config codegen.yml\nError: Unknown argument: config\n...\nerror Command failed with exit code 1.\ninfo Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n```\n\nSince I believe the default file name is `codegen.yml` anyway, I try to run it with out that argument and nothing gets generated:\n\n```\n$> yarn graphql-codegen\nyarn run v1.21.1\n$ /home/aaron/projects/my_app/node_modules/.bin/graphql-codegen\nDone in 0.17s.\n```\n\nAny ideas?\n\n========================================\n\nTop Answer:\nfor me this solved the issue\n\nYarn\n\n```\nyarn add -D @graphql-codegen/cli\n```\n\nnpm\n\n```\nnpm i -D @graphql-codegen/cli\n```\n\ninstallation guide doc\n\n========================================\n\nCode:\n```text\n$> yarn gen\nyarn run v1.21.1\n$ graphql-codegen --config codegen.yml\nError: Unknown argument: config\n...\nerror Command failed with exit code 1.\ninfo Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n```\n\n```text\n$> yarn graphql-codegen\nyarn run v1.21.1\n$ /home/aaron/projects/my_app/node_modules/.bin/graphql-codegen\nDone in 0.17s.\n```\n\n```text\npackage.json\n```\n\n```text\ngraphql-codegen\n```\n\n```text\n--config\n```\n\n```text\ncodegen.yml\n```\n\n```text\n$>which graphql-codegen\n/usr/bin/graphql-codegen\n```\n\n```text\ngraphql-codegen\n```\n\n```text\nsudo npm uninstall graphql-codegen\n```\n\n```text\nyarn graphql-codegen init\n```\n\n```text\ninit\n```\n\n```text\nctrl+C\n```\n\n```text\nyarn graphql-codegen\n```\n\n```text\nyarn graphql-codegen --watch\n```\n\n```text\nschema: http://localhost:8081/graphql\nextensions:\n codegen:\n generates:\n ./schema.graphql:\n - schema-ast\n```\n\n```text\n{\n \"codegen\": \"graphql codegen --config graphql.config.yml\"\n}\n```\n\n```text\nyarn add -D @graphql-codegen/cli\n```\n\n```text\nnpm i -D @graphql-codegen/cli\n```\n\n```text\ngraphql-codegen\n```\n\n```text\nschema\n```\n\n```text\noutput\n```\n\n```text\nconfig\n```\n\n```text\nrm -rf ./node_modules && npm install\n```\n\n```text\n\"scripts\": {\n \"graphql:generate\": \"graphql-code-generator\"\n}\n```\n\n```text\ngraphql-code-generator\n```\n\n```text\ncodegen.ts\n```\n\n```text\ncodegen.ts\n```\n\n```text\nyarn remove graphql-codegen\nrm -rf node_modules\n```\n\n```text\nimport { CodegenConfig } from \"@graphql-codegen/cli\";\n\nconst config: CodegenConfig = {\n schema: \"http://localhost:8081/graphql\",\n documents: [\"src/**/*.tsx\"],\n generates: {\n \"./src/__generated__/\": {\n preset: \"client\",\n presetConfig: {\n gqlTagName: \"gql\",\n },\n },\n },\n ignoreNoDocuments: true,\n};\n\nexport default config;\n```\n\n========================================\n\nComments:\n- Well its apollo's code gen that I am using but the exact packages I have installed are: `@graphql-codegen/cli`, `@graphql-codegen/introspection`, `@graphql-codegen/typescript`, `@graphql-codegen/typescript-operations`, `@graphql-codegen/typescript-react-apollo`.\n- this was my case as well, in my project i had `graphql-codegen` and bunch of `@graphql-codegen/etc` I just uninstalled `graphql-codegen` and it worked","metadata":{"transformedAt":"2026-08-18T18:32:36.023Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":207,"estimatedTokens":825}}65{"id":"stack-50603994","source":"stackoverflow","questionId":50603994,"title":"Apollo Optimistic UI does not work in Mutation Component?","tags":["reactjs","graphql","apollo","react-apollo","optimistic-ui"],"text":"Title: Apollo Optimistic UI does not work in Mutation Component?\nTags: reactjs, graphql, apollo, react-apollo, optimistic-ui\nSource: Stack Overflow\n\nQuestion:\nI am using `` component which has Render Prop API & trying to do Optimistic Response in the UI.\n\nSo far I have this chunk in an `_onSubmit` function -\n\n```\ncreateApp({\n variables: { id: uuid(), name, link },\n optimisticResponse: {\n __typename: \"Mutation\",\n createApp: {\n __typename: \"App\",\n id: negativeRandom(),\n name,\n link\n }\n }\n});\n```\n\nAnd my `` component looks like -\n\n```\n {\n const data = cache.readQuery({ query: LIST_APPS });\n if (typeof createApp.id == \"number\") {\n data.listApps.items.push(createApp);\n cache.writeQuery({\n query: LIST_APPS,\n data\n });\n }\n }}\n>\n\n{/* \nsome code here\n*/}\n\n```\n\nI know that `update` function in `` runs twice, once when `optimisticResponse` is ran & second time when server response comes back.\n\nOn the first time, I give them `id` as a `number`. Checkout `createApp` in `optimisticResponse` where `id: negativeRandom()`\n\nThat's why my `update` prop in `` component has a check if `createApp.id` is a `number` then push it in the array. It means that if data returned from local then push it in local cache & if returned from server don't push it.\n\nBut what happens is the data is only showed when returned from the server. The function `update` runs twice but it does not push it in the array.\n\nI think there might 3 problems -\n\nEither the `update` function does not run when local state is pushed\n\nI've tried making `fetchPolicy` equal to `cache-and-network` & `cache-first` but it didn't work too.\n\nThe `__typename` in `optimisticResponse`. Idk if `Mutation` is the correct value, so I tried `AppConnection` too but it still does not work.\n\nThe complete code can be found here. Whole code exist in one file for simplicity. Its a very simple app which has 2 inputs & 1 submit button. It looks like -\n\n### Note: Same thing works with React. Here's a link to React Repo - https://github.com/deadcoder0904/react-darkmodelist\n\n========================================\n\nCode:\n```text\ncreateApp({\n variables: { id: uuid(), name, link },\n optimisticResponse: {\n __typename: \"Mutation\",\n createApp: {\n __typename: \"App\",\n id: negativeRandom(),\n name,\n link\n }\n }\n});\n```\n\n```text\n<Mutation\n mutation={CREATE_APP}\n update={(cache, { data: { createApp } }) => {\n const data = cache.readQuery({ query: LIST_APPS });\n if (typeof createApp.id == \"number\") {\n data.listApps.items.push(createApp);\n cache.writeQuery({\n query: LIST_APPS,\n data\n });\n }\n }}\n>\n\n{/* \nsome code here\n*/}\n\n</Mutation>\n```\n\n```text\n<Mutation />\n```\n\n```text\n_onSubmit\n```\n\n```text\n<Mutation />\n```\n\n```text\nupdate\n```\n\n```text\n<Mutation />\n```\n\n```text\noptimisticResponse\n```\n\n```text\nid\n```\n\n```text\nnumber\n```\n\n```text\ncreateApp\n```\n\n```text\noptimisticResponse\n```\n\n```text\nid: negativeRandom()\n```\n\n```text\nupdate\n```\n\n```text\n<Mutation />\n```\n\n```text\ncreateApp.id\n```\n\n```text\nnumber\n```\n\n```text\nupdate\n```\n\n```text\nupdate\n```\n\n```text\nfetchPolicy\n```\n\n```text\ncache-and-network\n```\n\n```text\ncache-first\n```\n\n```text\n__typename\n```\n\n```text\noptimisticResponse\n```\n\n```text\nMutation\n```\n\n```text\nAppConnection\n```\n\n========================================\n\nComments:\n- I've ran your project and it seems to be working perfectly. I changed the UI to display the id before the name and Server responses and cached optimistic UI responses are both displayed.\n- Which project? React project works. React Native does not work with Optimistic UI. It shows the item in the list 2 seconds later after the server returns response. Can you provide more details about code? I do not understand what you are saying.\n- Apologies for my confusing explaination. To be clear, I ran your react native project on an iOS simulater. When connected to the internet, I added a new city and it responded from the server and displayed the server response in the list, as expected. When no connection is available, the optimistic UI works and shows the negative id. However, I've just re-read your question and realised what your actual problem is. It's not that you can't see anything when you aren't getting a response, it's that you aren't seeing anything before you get the response back, right? π\n- Yes exactly. And the funny thing is same code is written in React & it works perfectly. In React Code, I've just removed the `if (typeof createApp.id === \"number\")` & everything is the exact same & it works while in React Native if I remove the same `if` condition I get duplicate values from Optimistic Response & Actual Mutation. So inshort, same code with slight difference. React one works without an issue & React Native doesn't work (I mean only Optimistic UI) π\n- Check `__typename` of the `createApp` object returned by the mutation. It should be same type as `listApps.items` of your `listApps` query.\n- Yes they are both returning `App` as their `__typename`\n- @eronisko Thanks for adding a comment. I just updated my dependencies & now it works. I think it was a bug in Apollo Client or React Apollo in combo with React Native because I didn't change any code & it worked :)","metadata":{"transformedAt":"2026-08-18T18:32:36.024Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":211,"estimatedTokens":1326}}66{"id":"stack-44610310","source":"stackoverflow","questionId":44610310,"title":"Node Fetch Post Request using Graphql Query","tags":["javascript","node.js","express","graphql","node-fetch"],"text":"Title: Node Fetch Post Request using Graphql Query\nTags: javascript, node.js, express, graphql, node-fetch\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a POST request with a GraphQL query, but it's returning the error `Must provide query string`, even though my request works in PostMan.\n\nHere is how I have it running in PostMan:\n\nhttps://i.sstatic.net/UGXCy.png\n\nhttps://i.sstatic.net/wTzl2.png\n\nAnd here is the code I'm running in my application: \n\n```\nconst url = `http://localhost:3000/graphql`; \nreturn fetch(url, { \n method: 'POST',\n Accept: 'api_version=2',\n 'Content-Type': 'application/graphql',\n body: `\n {\n users(name: \"Thomas\") { \n firstName\n lastName \n } \n }\n `\n})\n.then(response => response.json())\n.then(data => {\n console.log('Here is the data: ', data);\n ...\n});\n```\n\nAny ideas what I'm doing wrong? Is it possible to make it so that the body attribute I'm passing in with the `fetch` request is formatted as `Text` like I've specified in the PostMan request's body?\n\n========================================\n\nCode:\n```text\nconst url = `http://localhost:3000/graphql`; \nreturn fetch(url, { \n method: 'POST',\n Accept: 'api_version=2',\n 'Content-Type': 'application/graphql',\n body: `\n {\n users(name: \"Thomas\") { \n firstName\n lastName \n } \n }\n `\n})\n.then(response => response.json())\n.then(data => {\n console.log('Here is the data: ', data);\n ...\n});\n```\n\n```text\nMust provide query string\n```\n\n```text\nfetch\n```\n\n```text\nText\n```\n\n```text\nconst url = `http://localhost:3000/graphql`;\nconst query = `\n {\n users(name: \"Thomas\") { \n firstName\n lastName \n } \n }\n `\n\nreturn fetch(url, { \n method: 'POST',\n Header: {\n 'Content-Type': 'application/graphql'\n }\n body: query\n})\n.then(response => response.json())\n.then(data => {\n console.log('Here is the data: ', data);\n ...\n});\n```\n\n```text\nconst query = `\n query movies($first: Int!) {\n allMovies(first: $first) {\n title\n }\n }\n`\n\nconst variables = {\n first: 3\n}\n\nreturn fetch('https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr', {\n method: 'post',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({query, variables})\n})\n.then(response => response.json())\n.then(data => {\n return data\n})\n.catch((e) => {\n console.log(e)\n})\n```\n\n```text\nquery\n```\n\n```text\nvariable\n```\n\n========================================\n\nComments:\n- Thank your sharing this solution. However, in the first example, I had to modify `'Content-Type': 'application/graphql'`. This was, in my case, within `headers` property. So, the `fetch` looks like... fetch(\"/graphql\", { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ query }), })\n- What to do if I get an error: \"message: \"You are not authorized to make this call.\"? How to authorize when making fetch request to graphql endpoint?","metadata":{"transformedAt":"2026-08-18T18:32:36.024Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":143,"estimatedTokens":724}}67{"id":"stack-51526079","source":"stackoverflow","questionId":51526079,"title":"How to use OR / AND in graphql query filter or make a case insensitive filter?","tags":["graphql","gatsby"],"text":"Title: How to use OR / AND in graphql query filter or make a case insensitive filter?\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nJust like the post ask I need to be able to search with 3 possible scenarios. I need to have all uppercase, or lowercase, or normal casing. \n\nIf that is not possible is there a way to do a case insensitive filter instead?\n\n```\nallMarkdownRemark(filter: { brand: { eq: $normalBrand } }) { //==> Need more here\n edges {\n node {\n webImages {\n url\n }\n }\n }\n }\n```\n\nI found some people doing this:\n\n```\nfilter: { OR: [\n {brand: { eq: $normalBrand }}, \n {brand: { eq: $normalBrand2 }}, \n {brand: { eq: $normalBrand3 }}\n]}\n```\n\nBut it does not work for me\n\n========================================\n\nTop Answer:\nDoes regex work? Something like\n\n```\nallMarkdownRemark(filter: { brand: { \n regex: \"/($normalBrand)|($normalBrand2)|($normalBrand3)/\" \n } }) { \n edges {\n node {\n webImages {\n url\n }\n }\n }\n }\n```\n\n========================================\n\nCode:\n```text\nallMarkdownRemark(filter: { brand: { eq: $normalBrand } }) { //==> Need more here\n edges {\n node {\n webImages {\n url\n }\n }\n }\n }\n```\n\n```text\nfilter: { OR: [\n {brand: { eq: $normalBrand }}, \n {brand: { eq: $normalBrand2 }}, \n {brand: { eq: $normalBrand3 }}\n]}\n```\n\n```text\ngetCaseByStatus(\"open\" OR \"closed\")\n```\n\n```text\n\"open\"\n```\n\n```text\n\"closed\"\n```\n\n```text\ngetCaseByStatus\n```\n\n```text\nallMarkdownRemark(filter: { brand: { \n regex: \"/($normalBrand)|($normalBrand2)|($normalBrand3)/\" \n } }) { \n edges {\n node {\n webImages {\n url\n }\n }\n }\n }\n```\n\n```text\nfilter: { or: [{brand: { eq: $normalBrand }}, {brand: { eq: $normalBrand2 }},{brand: { eq: $normalBrand3 }}]}\n```\n\n```text\nor\n```\n\n```text\n{brand: {regexp: \"/$normalBrand/i\"}}\n```\n\n========================================\n\nComments:\n- This might be relevant: github.com/graphql-compose/graphql-compose-mongoose/issues/9‌​3\n- Its not a query language if you cant ask it things.","metadata":{"transformedAt":"2026-08-18T18:32:36.024Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":122,"estimatedTokens":533}}68{"id":"stack-48631954","source":"stackoverflow","questionId":48631954,"title":"Apollo writeFragment not updating data","tags":["caching","graphql","react-apollo"],"text":"Title: Apollo writeFragment not updating data\nTags: caching, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nIn react-apollo 2.0.1 I have a graphql type that looks like this:\n\n```\ntype PagedThing {\n data: [Thing]\n total: Int\n}\n```\n\nWhen doing the following writeFragment\n\n```\nclient.writeFragment({\n id,\n fragment: gql`\n fragment my_thing on Thing {\n status\n }\n `,\n data: {\n status\n }\n })\n```\n\nThe cache is not update and the new data is not shown on the UI. Is there something else that need to be done?\n\nPS: To be safe I used fragment matching\n\nEdit 1:\n\nI receive an error of:\n\n Cannot match fragment because __typename property is missing: {\"status\":\"online\"}\n\nSo I changed the code to:\n\n```\nclient.writeFragment({\n id,\n fragment: gql`\n fragment my_thing on Thing {\n status\n }\n `,\n data: {\n __typename: 'Thing',\n status\n }\n })\n```\n\nAnd no error is thrown but the updated still do not happen\n\n========================================\n\nTop Answer:\nit appears that the framework has been extended to provide a method called 'identify' to avoid this problem (in case they change implementation later)\n\n```\ncache.modify({\n id: cache.identify(myPost),\n ^\n fields(fieldValue, details) {\n return details.INVALIDATE;\n },\n});\n```\n\nhttps://www.apollographql.com/docs/react/caching/cache-interaction/#example-invalidating-fields-within-a-cached-object\n\n========================================\n\nCode:\n```text\ntype PagedThing {\n data: [Thing]\n total: Int\n}\n```\n\n```text\nclient.writeFragment({\n id,\n fragment: gql`\n fragment my_thing on Thing {\n status\n }\n `,\n data: {\n status\n }\n })\n```\n\n```text\nclient.writeFragment({\n id,\n fragment: gql`\n fragment my_thing on Thing {\n status\n }\n `,\n data: {\n __typename: 'Thing',\n status\n }\n })\n```\n\n```text\nclient.writeFragment({\n id: `Thing:${id}`,\n fragment: gql`\n fragment my_thing on Thing {\n status\n }\n `,\n data: {\n __typename: 'Thing',\n status\n }\n})\n```\n\n```text\ncache.modify({\n id: cache.identify(myPost),\n ^\n fields(fieldValue, details) {\n return details.INVALIDATE;\n },\n});\n```\n\n========================================\n\nComments:\n- Closed page. Immediately, in a rush, reoponed to make sure I upvoted both question and answer. Whew.\n- Prefixing the `id` with the typename was the key, thank you!\n- You should probably use: `id: defaultDataIdFromObject({ id: parentId, __typename: parentType })...` Imported from : `import { defaultDataIdFromObject } from \"apollo-cache-inmemory\";` just if you want to override defaultDataIdFromObject in your apollo client setup in the future\n- The documentation around this method leaves a lot to be desired, it has to be said.\n- The link is dead for me. What was the explanation?\n- Updated the link with some equivalent. The cause is the ID not matching the default resolved id with __typename, although on the example it only adds the __typename on writeQuery at the time of the answer it was needed to add it on writeFragment as well.Not sure if no __typename works on writeFragment right now\n- What if it is list that I'm updating. I know we need to read the fragment first add the new item to the list and write the fragment. In my case reading the fragment is working but its unable to update the newly added item to the cache. Any inputs?","metadata":{"transformedAt":"2026-08-18T18:32:36.024Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":150,"estimatedTokens":837}}69{"id":"stack-55970271","source":"stackoverflow","questionId":55970271,"title":"\"Found @client directives in query but no client resolvers were specified\" Warning when using client cache","tags":["javascript","reactjs","graphql","apollo-client"],"text":"Title: \"Found @client directives in query but no client resolvers were specified\" Warning when using client cache\nTags: javascript, reactjs, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI've been following the Apollo Client docs on local state.\n\nI've implemented a very simple query of the client cache:\n\n```\nexport const GET_USER_ACCOUNTS = gql`\n query GetUserAccounts {\n userAccounts @client\n name @client\n }\n`;\n```\n\n`userAccounts` and `name` are both stored in my cache following authentication:\n\n```\n {\n localStorage.setItem('token', token);\n client.writeData({\n data: {\n isLoggedIn: true,\n userAccounts,\n name: `${givenName} ${familyName}`,\n },\n });\n }}\n >\n```\n\nand I've warmed the cache with default values:\n\n```\nimport { ApolloClient } from 'apollo-client';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { HttpLink } from 'apollo-link-http';\n\nconst cache = new InMemoryCache();\nconst link = new HttpLink({\n uri: 'http://localhost:8002/v1/graphql',\n headers: {\n Authorization: `${localStorage.getItem('token')}`,\n },\n});\nconst client = new ApolloClient({\n cache,\n link,\n});\n// set up the initial state\ncache.writeData({\n data: {\n name: '',\n userAccounts: [],\n isLoggedIn: !!localStorage.getItem('token'),\n },\n});\n\nexport default client;\n```\n\nI've not included any local resolvers, since the docs state:\n\nWhen Apollo Client executes this query and tries to find a result for the isInCart field, it runs through the following steps:\n\nHas a resolver function been set (either through the ApolloClient constructor resolvers parameter or Apollo Client's setResolvers / addResolvers methods) that is associated with the field name isInCart? If yes, run and return the result from the resolver function.\n\nIf a matching resolver function can't be found, check the Apollo Client cache to see if a isInCart value can be found directly. If so, return that value.\n\nHowever, despite the code working fine (it fetches the values I want no problem) I still get this warning:\n\nFound @client directives in query but no client resolvers were specified. You can now pass apollo-link-state resolvers to the ApolloClient constructor.\n\nHave I misunderstood? Should I be including a client resolver for this in some way?\n\nAny advice appreciated\n\n========================================\n\nTop Answer:\nAs Daniel later mentioned in the comments of the above answer, passing `resolvers={{}}` inside of `MockedProvider` worked wonderfully for me. Here's how it should look like: \n\n```\n\n \n\n```\n\nIt even solved a memory leakage problem I was having in Circle CI, as it seems there was nowhere to resolve to; here are the error messages I was getting:\n\n```\n\n 154665 ms: Mark-sweep 949.1 (1434.4) -> 948.2 (1434.4) MB, 1979.3 / 0 ms [allocation failure] [GC in old space requested].\n 156664 ms: Mark-sweep 948.2 (1434.4) -> 948.2 (1434.4) MB, 1999.7 / 0 ms [allocation failure] [GC in old space requested].\n 158734 ms: Mark-sweep 948.2 (1434.4) -> 948.2 (1434.4) MB, 2069.7 / 0 ms [last resort gc].\n 160810 ms: Mark-sweep 948.2 (1434.4) -> 948.1 (1434.4) MB, 2075.7 / 0 ms [last resort gc].\n\n==== JS stack trace =========================================\n\nSecurity context: 0x30ab306c9fa9 \n 2: convertPropertyValueToJson(aka convertPropertyValueToJson) [/home/circleci/project/node_modules/typescript/lib/typescript.js:24737] [pc=0x2953c91d9878] (this=0x30ab30604189 ,valueExpression=0x39effa032fa9 ,option=0x30ab30604189 )\n 3: /* anonymous */(aka /* anonymous */) [/home/circleci/project/node_modules/typescript/lib/type...\n\nFATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory\nAborted (core dumped)\n```\n\nCheers!\n\n========================================\n\nCode:\n```text\nexport const GET_USER_ACCOUNTS = gql`\n query GetUserAccounts {\n userAccounts @client\n name @client\n }\n`;\n```\n\n```js\n<Mutation\n mutation={API_TOKEN_AUTHENTICATION}\n variables={{ apiKey }}\n onCompleted={({\n apiTokenAuthentication: {\n token,\n userAccounts,\n user: { givenName, familyName },\n },\n }) => {\n localStorage.setItem('token', token);\n client.writeData({\n data: {\n isLoggedIn: true,\n userAccounts,\n name: `${givenName} ${familyName}`,\n },\n });\n }}\n >\n```\n\n```text\nimport { ApolloClient } from 'apollo-client';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { HttpLink } from 'apollo-link-http';\n\nconst cache = new InMemoryCache();\nconst link = new HttpLink({\n uri: 'http://localhost:8002/v1/graphql',\n headers: {\n Authorization: `${localStorage.getItem('token')}`,\n },\n});\nconst client = new ApolloClient({\n cache,\n link,\n});\n// set up the initial state\ncache.writeData({\n data: {\n name: '',\n userAccounts: [],\n isLoggedIn: !!localStorage.getItem('token'),\n },\n});\n\nexport default client;\n```\n\n```text\nuserAccounts\n```\n\n```text\nname\n```\n\n```text\nconst client = new ApolloClient({\n cache,\n link,\n resolvers: {},\n});\n```\n\n```text\n@client\n```\n\n```text\nApolloClient\n```\n\n```text\nresolvers\n```\n\n```text\n@client\n```\n\n```text\n@client\n```\n\n```text\n<MockedProvider mocks={mocks} addTypename={false} resolvers={{}}>\n <FooComponent />\n</MockedProvider>\n```\n\n```text\n<--- Last few GCs --->\n\n 154665 ms: Mark-sweep 949.1 (1434.4) -> 948.2 (1434.4) MB, 1979.3 / 0 ms [allocation failure] [GC in old space requested].\n 156664 ms: Mark-sweep 948.2 (1434.4) -> 948.2 (1434.4) MB, 1999.7 / 0 ms [allocation failure] [GC in old space requested].\n 158734 ms: Mark-sweep 948.2 (1434.4) -> 948.2 (1434.4) MB, 2069.7 / 0 ms [last resort gc].\n 160810 ms: Mark-sweep 948.2 (1434.4) -> 948.1 (1434.4) MB, 2075.7 / 0 ms [last resort gc].\n\n\n<--- JS stacktrace --->\n\n==== JS stack trace =========================================\n\nSecurity context: 0x30ab306c9fa9 <JS Object>\n 2: convertPropertyValueToJson(aka convertPropertyValueToJson) [/home/circleci/project/node_modules/typescript/lib/typescript.js:24737] [pc=0x2953c91d9878] (this=0x30ab30604189 <undefined>,valueExpression=0x39effa032fa9 <a NodeObject with map 0x35eb62463c11>,option=0x30ab30604189 <undefined>)\n 3: /* anonymous */(aka /* anonymous */) [/home/circleci/project/node_modules/typescript/lib/type...\n\nFATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory\nAborted (core dumped)\n```\n\n```text\nresolvers={{}}\n```\n\n```text\nMockedProvider\n```\n\n========================================\n\nComments:\n- Thanks, I did try this but I still get the warning\n- I take it back - of course that works, it just haven't included a client in my MockedProvider, so still got the warning in my test. Thanks so much!\n- I can ask this as another question, but I added the client here `` and still get the warning in my test. Do you happen to know where I can plug it in please?\n- Looks like `resolvers` should be passed directly to `MockedProvider`. Which makes sense -- you might want to swap out the resolvers for testing.","metadata":{"transformedAt":"2026-08-18T18:32:36.024Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":253,"estimatedTokens":1784}}70{"id":"stack-53209623","source":"stackoverflow","questionId":53209623,"title":"Network error: Unexpected token < in JSON at position 0 at new ApolloError","tags":["javascript","reactjs","express","graphql","apollo"],"text":"Title: Network error: Unexpected token < in JSON at position 0 at new ApolloError\nTags: javascript, reactjs, express, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/D25ai.png \n\n```\nconst httpLink = createHttpLink({\n uri: 'http://localhost:3090/'\n})\n\nconst client = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache()\n})\n\nclient.query({\n query: gql`\n query users {\n email\n }\n `,\n})\n .then(data => console.log(data))\n .catch(error => console.error(error));\n```\n\nThis query gives an error when fetching from client-side code but when i execute this query in browser on http://localhost:3090/graphql it fetches data correctly\n\n========================================\n\nTop Answer:\nFor posterity in case someone finds this in the future, another reason you might get this error is if your API is returning something other than JSON.\nhttps://medium.com/programmers-developers/one-simple-apollo-client-debugging-tip-youll-like-7877a97b9c16\n\nI ran into this issue because the content type that was being returned from my API was `text/plain` rather than `application/json`. Apollo lets you specify a different body serializer in this case.\nhttps://www.apollographql.com/docs/link/links/rest/\n\n========================================\n\nCode:\n```text\nconst httpLink = createHttpLink({\n uri: 'http://localhost:3090/'\n})\n\nconst client = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache()\n})\n\nclient.query({\n query: gql`\n query users {\n email\n }\n `,\n})\n .then(data => console.log(data))\n .catch(error => console.error(error));\n```\n\n```text\n{\n users {\n email\n }\n}\n```\n\n```text\nquery Users {\n users {\n email\n }\n}\n```\n\n```text\n/graphql\n```\n\n```text\n<\n```\n\n```text\n<html...\n```\n\n```text\nhttpLink\n```\n\n```text\nlocalhost:3090/graphql\n```\n\n```text\ntext/plain\n```\n\n```text\napplication/json\n```\n\n```text\n/\n```\n\n```text\ncreate-react-app\n```\n\n```text\nlocalhost:3000\n```\n\n========================================\n\nComments:\n- Open network tab in developers console and tell us what `ApolloError` is.\n- @kiarashws added a screenshot for the request\n- as you can see `Status Code` is 404(not found), which means given url is incorrect.\n- Looks like your request is not answered with a JSON object but an HTML page `...`. Typically the case for unhandled errors, where you are served a default error page. Because you're connecting to the root URL, my guess is a 404?\n- @MukeshKumar please add the full error message to your question.\n- after adding /graphql ..?\n- @MukeshKumar Yes. I can't tell you why it fails without the message.\n- POST localhost:3090/graphql 400 (Bad Request) index.js:1452 Error: Network error: Response not successful: Received status code 400 at new ApolloError (ApolloError.js:58) at QueryManager.js:522 at QueryManager.js:982 at Array.forEach () at QueryManager.js:981 at Map.forEach () at QueryManager.broadcastQueries (QueryManager.js:977) at QueryManager.js:477\n- @MukeshKumar I'm affraid that does not contain any helpful information. But I think that the syntax of your query is incorrect too. It must be just `gql`{ users { email } }` or `qgl`query Users { users { email } }``.\n- Looks like a network issue. Check where your backend is serving from. I made the same mistake","metadata":{"transformedAt":"2026-08-18T18:32:36.024Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":132,"estimatedTokens":819}}71{"id":"stack-48037601","source":"stackoverflow","questionId":48037601,"title":"LazyInitializationException with graphql-spring","tags":["spring","hibernate","spring-boot","graphql","graphql-java"],"text":"Title: LazyInitializationException with graphql-spring\nTags: spring, hibernate, spring-boot, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY.\n\nI am using:\nhttps://github.com/graphql-java/graphql-spring-boot\nand\nhttps://github.com/graphql-java/graphql-java-tools for the integration.\n\nHere is an example:\n\n**Entities:**\n\n```\n@Entity\nclass Show {\n private Long id;\n private String name;\n\n @OneToMany(mappedBy = \"show\")\n private List competition;\n}\n\n@Entity\nclass Competition {\n private Long id;\n private String name;\n\n @ManyToOne(fetch = FetchType.LAZY)\n private Show show;\n}\n```\n\n**Schema:**\n\n```\ntype Show {\n id: ID!\n name: String!\n competitions: [Competition]\n}\n\ntype Competition {\n id: ID!\n name: String\n}\n\nextend type Query {\n shows : [Show]\n}\n```\n\n**Resolver:**\n\n```\n@Component\npublic class ShowResolver implements GraphQLQueryResolver {\n @Autowired \n private ShowRepository showRepository;\n\n public List getShows() {\n return ((List)showRepository.findAll());\n }\n}\n```\n\nIf i now query the endpoint with this (shorthand) query:\n\n```\n{\n shows {\n id\n name\n competitions {\n id\n }\n }\n}\n```\n\ni get:\n\n org.hibernate.LazyInitializationException: failed to lazily initialize\n a collection of role: Show.competitions, could not initialize proxy -\n no Session\n\nNow i know why this error happens and what it means, but i don't really know were to apply a fix for this. I don't want to make my entites to eagerly fetch all relations, because that would negate some of the advantages of GraphQL. Any ideas where i might need to look for a solution?\nThanks!\n\n========================================\n\nTop Answer:\nMy prefered solution is to have the transaction open until the Servlet sends its response. With this small code change your LazyLoad will work right:\n\n```\nimport javax.servlet.Filter;\nimport org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;\n\n@SpringBootApplication\npublic class Application {\n\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n\n /**\n * Register the {@link OpenEntityManagerInViewFilter} so that the\n * GraphQL-Servlet can handle lazy loads during execution.\n *\n * @return\n */\n @Bean\n public Filter OpenFilter() {\n return new OpenEntityManagerInViewFilter();\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\n@Entity\nclass Show {\n private Long id;\n private String name;\n\n @OneToMany(mappedBy = \"show\")\n private List<Competition> competition;\n}\n\n@Entity\nclass Competition {\n private Long id;\n private String name;\n\n @ManyToOne(fetch = FetchType.LAZY)\n private Show show;\n}\n```\n\n```text\ntype Show {\n id: ID!\n name: String!\n competitions: [Competition]\n}\n\ntype Competition {\n id: ID!\n name: String\n}\n\nextend type Query {\n shows : [Show]\n}\n```\n\n```text\n@Component\npublic class ShowResolver implements GraphQLQueryResolver {\n @Autowired \n private ShowRepository showRepository;\n\n public List<Show> getShows() {\n return ((List<Show>)showRepository.findAll());\n }\n}\n```\n\n```text\n{\n shows {\n id\n name\n competitions {\n id\n }\n }\n}\n```\n\n```text\n@Component\npublic class ShowResolver implements GraphQLResolver<Show> {\n @Autowired\n private CompetitionRepository competitionRepository;\n\n public List<Competition> competitions(Show show) {\n return ((List<Competition>)competitionRepository.findByShowId(show.getId()));\n }\n}\n```\n\n```text\n@Service(GraphQLWebAutoConfiguration.QUERY_EXECUTION_STRATEGY)\npublic class AsyncTransactionalExecutionStrategy extends AsyncExecutionStrategy {\n\n @Override\n @Transactional\n public CompletableFuture<ExecutionResult> execute(ExecutionContext executionContext, ExecutionStrategyParameters parameters) throws NonNullableFieldWasNullException {\n return super.execute(executionContext, parameters);\n }\n}\n```\n\n```text\n@Bean(GraphQLWebAutoConfiguration.MUTATION_EXECUTION_STRATEGY)\npublic ExecutionStrategy queryExecutionStrategy() {\n return new AsyncSerialExecutionStrategy();\n}\n```\n\n```text\nGraphQLQueryResolver\n```\n\n```text\nGraphQLResolver<T>\n```\n\n```text\nShow\n```\n\n```text\nShow\n```\n\n```text\nCompetition\n```\n\n```text\ngraphql-spring-boot-starter\n```\n\n```text\ngraphql-java-tools\n```\n\n```text\nExecutionStrategy\n```\n\n```text\nExecutionStrategy\n```\n\n```text\nExecutionStrategy\n```\n\n```text\n@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)\nprivate List<Competition> competition;\n```\n\n```text\n@Transactional\n```\n\n```text\n@Entity\nclass Show {\n private Long id;\n private String name;\n\n @OneToMany(cascade = CascadeType.ALL, mappedBy = \"show\")\n private List<Competition> competition;\n\n public void addCompetition(Competition c) {\n c.setShow(this);\n competition.add(c);\n }\n}\n\n@Entity\nclass Competition {\n private Long id;\n private String name;\n\n @ManyToOne(fetch = FetchType.LAZY)\n private Show show;\n}\n```\n\n```text\n{\n shows {\n id\n name\n competitions {\n id\n }\n }\n}\n```\n\n```text\nCompetition\n```\n\n```text\nShowResolver\n```\n\n```text\ncompetitions\n```\n\n```text\ngetCompetition()\n```\n\n```text\nShow\n```\n\n```text\nLazyInitializationException\n```\n\n```text\nOneToMany\n```\n\n```text\n@Transactional\n```\n\n```text\nimport javax.servlet.Filter;\nimport org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;\n\n@SpringBootApplication\npublic class Application {\n\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n\n /**\n * Register the {@link OpenEntityManagerInViewFilter} so that the\n * GraphQL-Servlet can handle lazy loads during execution.\n *\n * @return\n */\n @Bean\n public Filter OpenFilter() {\n return new OpenEntityManagerInViewFilter();\n }\n\n}\n```\n\n```text\nAsyncTransactionalExecutionStrategy\n```\n\n```text\nexecute\n```\n\n```text\nHttpRequestHandlerImpl\n```\n\n```text\nInstrumentation\n```\n\n```java\npublic class UserFriendlyException extends RuntimeException {\n public UserFriendlyException(String message) {\n super(message);\n }\n}\n```\n\n```java\npublic class UserFriendlyGraphQLError implements GraphQLError {\n /** Message shown to user */\n private final String message;\n\n private final List<SourceLocation> locations;\n\n private final ExecutionPath path;\n\n public UserFriendlyGraphQLError(String message, List<SourceLocation> locations, ExecutionPath path) {\n this.message = message;\n this.locations = locations;\n this.path = path;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n\n @Override\n public List<SourceLocation> getLocations() {\n return locations;\n }\n\n @Override\n public ErrorClassification getErrorType() {\n return CustomErrorClassification.USER_FRIENDLY_ERROR;\n }\n\n @Override\n public List<Object> getPath() {\n return path.toList();\n }\n}\n```\n\n```java\npublic enum CustomErrorClassification implements ErrorClassification {\n USER_FRIENDLY_ERROR\n}\n```\n\n```java\n/**\n * Converts exceptions into error response\n */\npublic class GraphQLExceptionHandler implements DataFetcherExceptionHandler {\n\n private final DataFetcherExceptionHandler delegate = new SimpleDataFetcherExceptionHandler();\n\n @Override\n public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) {\n // handle user friendly errors\n if (handlerParameters.getException() instanceof UserFriendlyException) {\n GraphQLError error = new UserFriendlyGraphQLError(\n handlerParameters.getException().getMessage(),\n List.of(handlerParameters.getSourceLocation()),\n handlerParameters.getPath());\n\n return DataFetcherExceptionHandlerResult.newResult().error(error).build();\n }\n\n // delegate to default handler otherwise\n return delegate.onException(handlerParameters);\n }\n}\n```\n\n```java\n@Component\npublic class AsyncTransactionalExecutionStrategy extends AsyncExecutionStrategy {\n\n public AsyncTransactionalExecutionStrategy() {\n super(new GraphQLExceptionHandler());\n }\n\n @Override\n @Transactional\n public CompletableFuture<ExecutionResult> execute(ExecutionContext executionContext, ExecutionStrategyParameters parameters) throws NonNullableFieldWasNullException {\n return super.execute(executionContext, parameters);\n }\n}\n```\n\n```json\n{\n \"errors\": [\n {\n \"message\": \"Email already exists\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"createUser\"\n ],\n \"extensions\": {\n \"classification\": \"USER_FRIENDLY_ERROR\"\n }\n }\n ],\n \"data\": null\n}\n```\n\n```java\n@Transactional(propagation = Propagation.REQUIRES_NEW)\npublic class Mutation implements GraphQLMutationResolver {\n\n public User createUser(...) {\n ...\n }\n}\n```\n\n```text\nAsyncTransactionalExecutionStrategy\n```\n\n```text\nDataFetcherExceptionHandler\n```\n\n```text\nAsyncTransactionalExecutionStrategy\n```\n\n```text\n@Transactional\n```\n\n```text\nthrow new UserFriendlyException(\"Email already exists\");\n```\n\n```text\nUSER_FRIENDLY_ERROR\n```\n\n```text\nUserFriendlyException\n```\n\n```text\nthrow new UserFriendlyException(\"Email already exists\");\n```\n\n```text\n@Transactional\n```\n\n```text\n@Transactional(propagation = Propagation.REQUIRES_NEW)\n```\n\n```text\nMutation\n```\n\n========================================\n\nComments:\n- No, that is what i don't want, because i also want to be able to query all Shows without the competitions\n- OP said in his question that he didn't want to make all collections eager\n- Looks like you're using a bidirectional one-to-many association so you can call `competitionRepository.findByShowId(show.getId())`. Is this the only way you could access the competition collection from the show entity without eager loading?\n- I am not sure what you are asking, but without having the show inside the competition there would be no way of knowing what competitions belong to which show. I would think that while having an open session `show.getCompetitions()` just returns proxies (lazy) and then if a complete object is needed also hits the database similarily to how i have done it.\n- @puelo You `AsyncTransactionalExecutionStrategy` is already a `@Service` so Spring will create a bean for it. So there is no need to create a `new AsyncTransactionalExecutionStrategy()` inside the `executionStrategies()` method. You should simply inject the `AsyncTransactionalExecutionStrategy` bean there.\n- @puelo what kind of drawbacks did you face?\n- Another improvement for a specific QUERY execution strategy is to use `@Transactional(readOnly = true)`\n- You could also use `com.oembedler.moon.graphql.boot.GraphQLWebAutoConfiguration.‌​QUERY_EXECUTION_STRA‌​TEGY` instead of the \"magical\" string `\"queryExecutionStrategy\"`. Thanks to this you can discover that you can do the similar to mutations and subscriptions :)\n- Important note: both solutions introduce *N+1 problem*. GraphQL engine will evaluate `competitions` of each `Show` object one by one. So the more Show objects (records in database) you have the more requests will be made to database which dramatically affects performance.\n- @Lu55 True. Although i don't think that the solution here should aim to solve both type of problems. If you have the resolvers set up correctly it should not be to hard to replace your current solution with batch loaders.\n- @puelo Spring does not handle a Map map as instantiation of multiple beans with distinct names. In the GraphQLWebAutoConfiguration class this bean will be autowired, but with another name. The only reason this works is that the class has a fallback for the case where only one ExecutionStrategy Bean is present (github.com/graphql-java-kickstart/graphql-spring-boot/blob/‌​…); but it will actually use this strategy for query AND mutation execution.\n- @H.Schulz You are right. I think it is good pointing this out, since a big Transaction around the mutations can do some harm.\n- Are you sure? Wouldn't the session be closed once the resolver method is finished executing, and thus will still fail when the GraphQL DataFetcher executes any getter/type-resolver on the @OneToMany relationship entity? This was my expierence with this at least.\n- Ok, I did not test it for this case, but at least it lets you use lazily loaded collections within the resolver method (which otherwise yields this same exception).\n- `@Transactional` on the `ShowResolver` does not work, because by the time that GraphQL tries to resolve the competitions the transaction is already closed. I am currently using another solution (which i am also not sure if it is optimal): I defined a custom `ExecutionStrategy` (which basically is the same as the `AsyncExecutionStrategy`) where the `execute` method is annoted with `@Transactional`. I can provide an update to my answer if needed.\n- @puelo, please do as I am at a loss of how to do anything in graphql java.Nothing seems documented at all.\n- I added it to my original answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.024Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":52,"totalLines":566,"estimatedTokens":3357}}72{"id":"stack-54192483","source":"stackoverflow","questionId":54192483,"title":"Typeorm dynamic query builder from structured object","tags":["graphql","typeorm"],"text":"Title: Typeorm dynamic query builder from structured object\nTags: graphql, typeorm\nSource: Stack Overflow\n\nQuestion:\nFor use in a graphql server I have defined a structured input type where you can specify a number of filter conditions very similar to how prisma works:\n\nhttps://i.sstatic.net/mRvM9.png\n\nWhich allows me to submit structured filters in a query like:\n\n```\n{\n users(\n where: {\n OR: [{ email: { starts_with: \"ja\" } }, { email: { ends_with: \".com\" } }],\n AND: [{ email: { starts_with: \"ja\" } }, { email: { ends_with: \".com\" } }],\n email: {contains: \"lowe\"}\n }\n ) {\n id\n email\n }\n}\n```\n\nInside my resolver I feed the args.where through a function to parse the structure and utilize TypeOrm's query builder to convert it to proper sql. The entirety of the function is:\n\n```\nimport { Brackets } from \"typeorm\";\n\nexport const filterQuery = (query: any, where: any) => {\n if (!where) {\n return query;\n }\n\n Object.keys(where).forEach(key => {\n if (key === \"OR\") {\n where[key].map((queryArray: any) => {\n query.orWhere(new Brackets(qb => filterQuery(qb, queryArray)));\n });\n } else if (key === \"AND\") {\n where[key].map((queryArray: any) => {\n query.andWhere(new Brackets(qb => filterQuery(qb, queryArray)));\n });\n } else {\n const whereArgs = Object.entries(where);\n\n whereArgs.map(whereArg => {\n const [fieldName, filters] = whereArg;\n const ops = Object.entries(filters);\n\n ops.map(parameters => {\n const [operation, value] = parameters;\n\n switch (operation) {\n case \"is\": {\n query.andWhere(`${fieldName} = :isvalue`, { isvalue: value });\n break;\n }\n case \"not\": {\n query.andWhere(`${fieldName} != :notvalue`, { notvalue: value });\n break;\n }\n case \"in\": {\n query.andWhere(`${fieldName} IN :invalue`, { invalue: value });\n break;\n }\n case \"not_in\": {\n query.andWhere(`${fieldName} NOT IN :notinvalue`, {\n notinvalue: value\n });\n break;\n }\n case \"lt\": {\n query.andWhere(`${fieldName} :gtvalue`, { gtvalue: value });\n break;\n }\n case \"gte\": {\n query.andWhere(`${fieldName} >= :gtevalue`, { gtevalue: value });\n break;\n }\n case \"contains\": {\n query.andWhere(`${fieldName} ILIKE :convalue`, {\n convalue: `%${value}%`\n });\n break;\n }\n case \"not_contains\": {\n query.andWhere(`${fieldName} NOT ILIKE :notconvalue`, {\n notconvalue: `%${value}%`\n });\n break;\n }\n case \"starts_with\": {\n query\n .andWhere(`${fieldName} ILIKE :swvalue`)\n .setParameter(\"swvalue\", `${value}%`);\n break;\n }\n case \"not_starts_with\": {\n query\n .andWhere(`${fieldName} NOT ILIKE :nswvalue`)\n .setParameter(\"nswvalue\", `${value}%`);\n break;\n }\n case \"ends_with\": {\n query.andWhere(`${fieldName} ILIKE :ewvalue`, {\n ewvalue: `%${value}`\n });\n break;\n }\n case \"not_ends_with\": {\n query.andWhere(`${fieldName} ILIKE :newvalue`, {\n newvalue: `%${value}`\n });\n break;\n }\n default: {\n break;\n }\n }\n });\n });\n }\n });\n\n return query;\n};\n```\n\nWhich works (kinda) but does not nest the AND/OR queries like I would expect (and had previously got working in KNEX). The above function generates the SQL:\n\n```\nSELECT\n \"user\".\"id\" AS \"user_id\",\n \"user\".\"name\" AS \"user_name\",\n \"user\".\"email\" AS \"user_email\",\n \"user\".\"loginToken\" AS \"user_loginToken\",\n \"user\".\"loginTokenExpiry\" AS \"user_loginTokenExpiry\",\n \"user\".\"active\" AS \"user_active\",\n \"user\".\"visible\" AS \"user_visible\",\n \"user\".\"isStaff\" AS \"user_isStaff\",\n \"user\".\"isBilling\" AS \"user_isBilling\",\n \"user\".\"createdAt\" AS \"user_createdAt\",\n \"user\".\"updatedAt\" AS \"user_updatedAt\",\n \"user\".\"version\" AS \"user_version\"\nFROM \"user\" \"user\"\nWHERE (email ILIKE $1)\n AND (email ILIKE $2)\n OR (email ILIKE $3)\n OR (email ILIKE $4)\n AND email ILIKE $5\n-- PARAMETERS: [\"ja%\",\"%.com\",\"ja%\",\"%.com\",\"%lowe%\"]\n```\n\nBut I would expect to see something more like:\n\n```\n..... \nWHERE email ILIKE '%low%' \nAND (\n email ILIKE 'ja%' AND email ILIKE '%.com'\n) AND (\n email ILIKE 'ja%' OR email ILIKE '%.com'\n)\n```\n\nForgive the nonsense, repetitive query. I'm just trying to illustrated the expected NESTED statements.\n\nHow can I force the AND/OR branches of my query builder function to properly nest like expected?\n\n** Bonus points if someone can help me figure out the actual typescript typings here **\n\n========================================\n\nTop Answer:\nBased on Ben's answer, I tweaked a little the functions to allow a more versatile \"*filter*\" object:\n\n```\nSPDX-License-Identifier: Apache-2.0\n\n// enum\nexport enum Operator {\n AND = 'AND',\n OR = 'OR',\n}\n\n// interfaces\ninterface FieldOptions {\n is?: string;\n not?: string;\n in?: string;\n not_in?: string;\n lt?: string;\n lte?: string;\n gt?: string;\n gte?: string;\n contains?: string;\n not_contains?: string;\n starts_with?: string;\n not_starts_with?: string;\n ends_with?: string;\n not_ends_with?: string;\n}\n\nexport interface Field {\n [key: string]: FieldOptions;\n}\n\nexport type Where = {\n [K in Operator]?: (Where | Field)[];\n};\n\n// functions\nexport const filterQuery = (query: SelectQueryBuilder, where: Where) => {\n if (!where) {\n return query;\n } else {\n return traverseTree(query, where) as SelectQueryBuilder;\n }\n};\n\nconst traverseTree = (query: WhereExpression, where: Where, upperOperator = Operator.AND) => {\n Object.keys(where).forEach((key) => {\n if (key === Operator.OR) {\n query = query.orWhere(buildNewBrackets(where, Operator.OR));\n } else if (key === Operator.AND) {\n query = query.andWhere(buildNewBrackets(where, Operator.AND));\n } else {\n // Field\n query = handleArgs(query, where as Field, upperOperator === Operator.AND ? 'andWhere' : 'orWhere');\n }\n });\n\n return query;\n};\n\nconst buildNewBrackets = (where: Where, operator: Operator) => {\n return new Brackets((qb) =>\n where[operator].map((queryArray) => {\n traverseTree(qb, queryArray, operator);\n }),\n );\n};\n\nconst handleArgs = (query: WhereExpression, field: Field, andOr: 'andWhere' | 'orWhere') => {\n ...\n};\n```\n\nThis way we now can have this kind of object as a query parameter:\n\n```\n{\n AND: [\n {\n OR: [\n {\n name: {\n is: 'John'\n },\n },\n {\n surname: {\n is: 'Doe'\n },\n }\n ]\n },\n {\n AND: [\n {\n age: {\n gt: 30\n },\n },\n {\n type: {\n not: 'Employee'\n }\n }\n ]\n },\n {\n registered_date: {\n gte: '2000-01-01'\n }\n }\n ]\n}\n```\n\nThe resulting query would be:\n\n```\nSELECT *\nFROM users U \nWHERE (U.name = 'John' OR U.surname = 'Doe') AND (U.age > 30 AND U.type != 'Employee') AND U.registered_date >= '2000-01-01';\n```\n\n========================================\n\nCode:\n```js\n{\n users(\n where: {\n OR: [{ email: { starts_with: \"ja\" } }, { email: { ends_with: \".com\" } }],\n AND: [{ email: { starts_with: \"ja\" } }, { email: { ends_with: \".com\" } }],\n email: {contains: \"lowe\"}\n }\n ) {\n id\n email\n }\n}\n```\n\n```js\nimport { Brackets } from \"typeorm\";\n\nexport const filterQuery = (query: any, where: any) => {\n if (!where) {\n return query;\n }\n\n Object.keys(where).forEach(key => {\n if (key === \"OR\") {\n where[key].map((queryArray: any) => {\n query.orWhere(new Brackets(qb => filterQuery(qb, queryArray)));\n });\n } else if (key === \"AND\") {\n where[key].map((queryArray: any) => {\n query.andWhere(new Brackets(qb => filterQuery(qb, queryArray)));\n });\n } else {\n const whereArgs = Object.entries(where);\n\n whereArgs.map(whereArg => {\n const [fieldName, filters] = whereArg;\n const ops = Object.entries(filters);\n\n ops.map(parameters => {\n const [operation, value] = parameters;\n\n switch (operation) {\n case \"is\": {\n query.andWhere(`${fieldName} = :isvalue`, { isvalue: value });\n break;\n }\n case \"not\": {\n query.andWhere(`${fieldName} != :notvalue`, { notvalue: value });\n break;\n }\n case \"in\": {\n query.andWhere(`${fieldName} IN :invalue`, { invalue: value });\n break;\n }\n case \"not_in\": {\n query.andWhere(`${fieldName} NOT IN :notinvalue`, {\n notinvalue: value\n });\n break;\n }\n case \"lt\": {\n query.andWhere(`${fieldName} < :ltvalue`, { ltvalue: value });\n break;\n }\n case \"lte\": {\n query.andWhere(`${fieldName} <= :ltevalue`, { ltevalue: value });\n break;\n }\n case \"gt\": {\n query.andWhere(`${fieldName} > :gtvalue`, { gtvalue: value });\n break;\n }\n case \"gte\": {\n query.andWhere(`${fieldName} >= :gtevalue`, { gtevalue: value });\n break;\n }\n case \"contains\": {\n query.andWhere(`${fieldName} ILIKE :convalue`, {\n convalue: `%${value}%`\n });\n break;\n }\n case \"not_contains\": {\n query.andWhere(`${fieldName} NOT ILIKE :notconvalue`, {\n notconvalue: `%${value}%`\n });\n break;\n }\n case \"starts_with\": {\n query\n .andWhere(`${fieldName} ILIKE :swvalue`)\n .setParameter(\"swvalue\", `${value}%`);\n break;\n }\n case \"not_starts_with\": {\n query\n .andWhere(`${fieldName} NOT ILIKE :nswvalue`)\n .setParameter(\"nswvalue\", `${value}%`);\n break;\n }\n case \"ends_with\": {\n query.andWhere(`${fieldName} ILIKE :ewvalue`, {\n ewvalue: `%${value}`\n });\n break;\n }\n case \"not_ends_with\": {\n query.andWhere(`${fieldName} ILIKE :newvalue`, {\n newvalue: `%${value}`\n });\n break;\n }\n default: {\n break;\n }\n }\n });\n });\n }\n });\n\n return query;\n};\n```\n\n```sql\nSELECT\n \"user\".\"id\" AS \"user_id\",\n \"user\".\"name\" AS \"user_name\",\n \"user\".\"email\" AS \"user_email\",\n \"user\".\"loginToken\" AS \"user_loginToken\",\n \"user\".\"loginTokenExpiry\" AS \"user_loginTokenExpiry\",\n \"user\".\"active\" AS \"user_active\",\n \"user\".\"visible\" AS \"user_visible\",\n \"user\".\"isStaff\" AS \"user_isStaff\",\n \"user\".\"isBilling\" AS \"user_isBilling\",\n \"user\".\"createdAt\" AS \"user_createdAt\",\n \"user\".\"updatedAt\" AS \"user_updatedAt\",\n \"user\".\"version\" AS \"user_version\"\nFROM \"user\" \"user\"\nWHERE (email ILIKE $1)\n AND (email ILIKE $2)\n OR (email ILIKE $3)\n OR (email ILIKE $4)\n AND email ILIKE $5\n-- PARAMETERS: [\"ja%\",\"%.com\",\"ja%\",\"%.com\",\"%lowe%\"]\n```\n\n```js\n..... \nWHERE email ILIKE '%low%' \nAND (\n email ILIKE 'ja%' AND email ILIKE '%.com'\n) AND (\n email ILIKE 'ja%' OR email ILIKE '%.com'\n)\n```\n\n```js\nimport { Brackets, WhereExpression, SelectQueryBuilder } from \"typeorm\";\n\ninterface FieldOptions {\n starts_with?: string;\n ends_with?: string;\n contains?: string;\n}\n\ninterface Fields {\n email?: FieldOptions;\n}\n\ninterface Where extends Fields {\n OR?: Fields[];\n AND?: Fields[];\n}\n\nconst handleArgs = (\n query: WhereExpression,\n where: Where,\n andOr: \"andWhere\" | \"orWhere\"\n) => {\n const whereArgs = Object.entries(where);\n\n whereArgs.map(whereArg => {\n const [fieldName, filters] = whereArg;\n const ops = Object.entries(filters);\n\n ops.map(parameters => {\n const [operation, value] = parameters;\n\n switch (operation) {\n case \"is\": {\n query[andOr](`${fieldName} = :isvalue`, { isvalue: value });\n break;\n }\n case \"not\": {\n query[andOr](`${fieldName} != :notvalue`, { notvalue: value });\n break;\n }\n case \"in\": {\n query[andOr](`${fieldName} IN :invalue`, { invalue: value });\n break;\n }\n case \"not_in\": {\n query[andOr](`${fieldName} NOT IN :notinvalue`, {\n notinvalue: value\n });\n break;\n }\n case \"lt\": {\n query[andOr](`${fieldName} < :ltvalue`, { ltvalue: value });\n break;\n }\n case \"lte\": {\n query[andOr](`${fieldName} <= :ltevalue`, { ltevalue: value });\n break;\n }\n case \"gt\": {\n query[andOr](`${fieldName} > :gtvalue`, { gtvalue: value });\n break;\n }\n case \"gte\": {\n query[andOr](`${fieldName} >= :gtevalue`, { gtevalue: value });\n break;\n }\n case \"contains\": {\n query[andOr](`${fieldName} ILIKE :convalue`, {\n convalue: `%${value}%`\n });\n break;\n }\n case \"not_contains\": {\n query[andOr](`${fieldName} NOT ILIKE :notconvalue`, {\n notconvalue: `%${value}%`\n });\n break;\n }\n case \"starts_with\": {\n query[andOr](`${fieldName} ILIKE :swvalue`, {\n swvalue: `${value}%`\n });\n break;\n }\n case \"not_starts_with\": {\n query[andOr](`${fieldName} NOT ILIKE :nswvalue`, {\n nswvalue: `${value}%`\n });\n break;\n }\n case \"ends_with\": {\n query[andOr](`${fieldName} ILIKE :ewvalue`, {\n ewvalue: `%${value}`\n });\n break;\n }\n case \"not_ends_with\": {\n query[andOr](`${fieldName} ILIKE :newvalue`, {\n newvalue: `%${value}`\n });\n break;\n }\n default: {\n break;\n }\n }\n });\n });\n\n return query;\n};\n\nexport const filterQuery = <T>(query: SelectQueryBuilder<T>, where: Where) => {\n if (!where) {\n return query;\n }\n\n Object.keys(where).forEach(key => {\n if (key === \"OR\") {\n query.andWhere(\n new Brackets(qb =>\n where[key]!.map(queryArray => {\n handleArgs(qb, queryArray, \"orWhere\");\n })\n )\n );\n } else if (key === \"AND\") {\n query.andWhere(\n new Brackets(qb =>\n where[key]!.map(queryArray => {\n handleArgs(qb, queryArray, \"andWhere\");\n })\n )\n );\n }\n });\n\n return query;\n};\n```\n\n```text\nSPDX-License-Identifier: Apache-2.0\n\n// enum\nexport enum Operator {\n AND = 'AND',\n OR = 'OR',\n}\n\n// interfaces\ninterface FieldOptions {\n is?: string;\n not?: string;\n in?: string;\n not_in?: string;\n lt?: string;\n lte?: string;\n gt?: string;\n gte?: string;\n contains?: string;\n not_contains?: string;\n starts_with?: string;\n not_starts_with?: string;\n ends_with?: string;\n not_ends_with?: string;\n}\n\nexport interface Field {\n [key: string]: FieldOptions;\n}\n\nexport type Where = {\n [K in Operator]?: (Where | Field)[];\n};\n\n// functions\nexport const filterQuery = <T>(query: SelectQueryBuilder<T>, where: Where) => {\n if (!where) {\n return query;\n } else {\n return traverseTree(query, where) as SelectQueryBuilder<T>;\n }\n};\n\nconst traverseTree = (query: WhereExpression, where: Where, upperOperator = Operator.AND) => {\n Object.keys(where).forEach((key) => {\n if (key === Operator.OR) {\n query = query.orWhere(buildNewBrackets(where, Operator.OR));\n } else if (key === Operator.AND) {\n query = query.andWhere(buildNewBrackets(where, Operator.AND));\n } else {\n // Field\n query = handleArgs(query, where as Field, upperOperator === Operator.AND ? 'andWhere' : 'orWhere');\n }\n });\n\n return query;\n};\n\nconst buildNewBrackets = (where: Where, operator: Operator) => {\n return new Brackets((qb) =>\n where[operator].map((queryArray) => {\n traverseTree(qb, queryArray, operator);\n }),\n );\n};\n\nconst handleArgs = (query: WhereExpression, field: Field, andOr: 'andWhere' | 'orWhere') => {\n ...\n};\n```\n\n```text\n{\n AND: [\n {\n OR: [\n {\n name: {\n is: 'John'\n },\n },\n {\n surname: {\n is: 'Doe'\n },\n }\n ]\n },\n {\n AND: [\n {\n age: {\n gt: 30\n },\n },\n {\n type: {\n not: 'Employee'\n }\n }\n ]\n },\n {\n registered_date: {\n gte: '2000-01-01'\n }\n }\n ]\n}\n```\n\n```text\nSELECT *\nFROM users U \nWHERE (U.name = 'John' OR U.surname = 'Doe') AND (U.age > 30 AND U.type != 'Employee') AND U.registered_date >= '2000-01-01';\n```\n\n```sql\nSELECT *\nFROM users U \nWHERE (U.name = 'John' OR U.surname = 'Doe') OR (U.age > 30 AND U.type != 'Employee') AND U.registered_date >= '2000-01-01';\n```\n\n```sql\nSELECT *\nFROM users U \nWHERE (U.name = 'John' OR U.surname = 'Doe') AND (U.age > 30 AND U.type != 'Employee') AND U.registered_date >= '2000-01-01';\n```\n\n========================================\n\nComments:\n- in your example query, there is { id email}, are you sure this is you are getting because it is seems to be a json, json should have pair. Also what is query? you are calling query.orWhere\n- Thanks Shadab. It's not json, its a standard Graphql query. Id and email represent the return fields I want back from the query.\n- This is FANTASTIC. Thank you Ben. The only case this does not cover is the root level statements not nested under AND or WHERE.. In the case of my example query above the `email: {contains: \"lowe\"}` is ignored. In your opinion should I accept root level where statements or do should I require all statements to be nested in either OR or AND? ```\n- Now as I tinker more It starts to make more sense to only have AND/OR as the root level elements. It is far more explicit that way and not much of an inconvenience.\n- and if you did want to add it at the root level you can add an else where you call the function `else { handleArgs(query, where, \"andWhere\") }`\n- This assumes no fields have a duplicate name, however, how might one address a case where two tables are joined and the function must distinguish between `id` in the first entity vs `id` in the second entity without getting error: `Error: ER_NON_UNIQ_ERROR: Column 'id' in where clause is ambiguous`?\n- @benawad Sorry for that but are you the ben awad?\n- This opens code to SQL injections if used on user input.","metadata":{"transformedAt":"2026-08-18T18:32:36.024Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":746,"estimatedTokens":4477}}73{"id":"stack-46352168","source":"stackoverflow","questionId":46352168,"title":"Passing down arguments using Facebook's DataLoader","tags":["javascript","graphql","graphql-js"],"text":"Title: Passing down arguments using Facebook's DataLoader\nTags: javascript, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm using DataLoader for batching the requests/queries together.\nIn my loader function I need to know the requested fields to avoid having a `SELECT * FROM query` but rather a `SELECT field1, field2, ... FROM query`...\n\nWhat would be the best approach using DataLoader to pass down the `resolveInfo` needed for it? (I use `resolveInfo.fieldNodes` to get the requested fields)\n\nAt the moment, I'm doing something like this:\n\n```\nawait someDataLoader.load({ ids, args, context, info });\n```\n\nand then in the actual loaderFn:\n\n```\nconst loadFn = async options => {\nconst ids = [];\nlet args;\nlet context;\nlet info;\noptions.forEach(a => {\n ids.push(a.ids);\n if (!args && !context && !info) {\n args = a.args;\n context = a.context;\n info = a.info;\n }\n});\n\nreturn Promise.resolve(await new DataProvider().get({ ...args, ids}, context, info));};\n```\n\nbut as you can see, it's hacky and doesn't really feel good...\n\nDoes anyone have an idea how I could achieve this?\n\n========================================\n\nCode:\n```text\nawait someDataLoader.load({ ids, args, context, info });\n```\n\n```text\nconst loadFn = async options => {\nconst ids = [];\nlet args;\nlet context;\nlet info;\noptions.forEach(a => {\n ids.push(a.ids);\n if (!args && !context && !info) {\n args = a.args;\n context = a.context;\n info = a.info;\n }\n});\n\nreturn Promise.resolve(await new DataProvider().get({ ...args, ids}, context, info));};\n```\n\n```text\nSELECT * FROM query\n```\n\n```text\nSELECT field1, field2, ... FROM query\n```\n\n```text\nresolveInfo\n```\n\n```text\nresolveInfo.fieldNodes\n```\n\n```text\nawait someDataLoader.load({ ids, args, context, info });\n```\n\n```js\n// This function creates unique cache keys for different selected\n// fields\nfunction cacheKeyFn({ id, fields }) {\n const sortedFields = [...(new Set(fields))].sort().join(';');\n return `${id}[${sortedFields}]`;\n}\n\nfunction createLoaders(db) {\n const userLoader = new Dataloader(async keys => {\n // Create a set with all requested fields\n const fields = keys.reduce((acc, key) => {\n key.fields.forEach(field => acc.add(field));\n return acc;\n }, new Set());\n // Get all our ids for the DB query\n const ids = keys.map(key => key.id);\n // Please be aware of possible SQL injection, don't copy + paste\n const result = await db.query(`\n SELECT\n ${fields.entries().join()}\n FROM\n user\n WHERE\n id IN (${ids.join()})\n `);\n }, { cacheKeyFn });\n\n return { userLoader };\n}\n\n// now in a resolver\nresolve(parent, args, ctx, info) {\n // https://www.npmjs.com/package/graphql-fields\n return ctx.userLoader.load({ id: args.id, fields: Object.keys(graphqlFields(info)) });\n}\n```\n\n```text\n1\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\n1\n```\n\n```text\nid\n```\n\n```text\nemail\n```\n\n```text\n1\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\n1\n```\n\n```text\nname\n```\n\n```text\nid\n```\n\n```text\n1[id,name]\n```\n\n```text\n1[id]\n```\n\n```text\n1[name]\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.024Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":182,"estimatedTokens":770}}74{"id":"stack-53804219","source":"stackoverflow","questionId":53804219,"title":"Variables in graphQL queries","tags":["javascript","reactjs","graphql","gatsby"],"text":"Title: Variables in graphQL queries\nTags: javascript, reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nEDIT: now with working code below\n\n### The GraphiQL version\n\nI have this query to fetch a gatsby-image:\n\n```\nquery getImages($fileName: String) {\n landscape: file(relativePath: {eq: $fileName}) {\n childImageSharp {\n fluid(maxWidth: 1000) {\n base64\n tracedSVG\n aspectRatio\n src\n srcSet\n srcWebp\n srcSetWebp\n sizes\n originalImg\n originalName\n }\n }\n }\n}\n```\n\nAnd then this query variable:\n\n```\n{\n \"fileName\": \"titanic.jpg\"\n}\n```\n\nThe above works fine in GraphiQL. \n\n### The Gatsby version\n\nNow I want to use it in Gatsby, so I have the following code:\n\n```\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\nimport Img from \"gatsby-image\"\n\nexport default ({ data }) => (\n \n \n \n)\n\nexport const query = (\n graphql`\n query getImages($fileName: String) {\n landscape: file(relativePath: {eq: $fileName}) {\n childImageSharp {\n fluid(maxWidth: 1000) {\n base64\n tracedSVG\n aspectRatio\n src\n srcSet\n srcWebp\n srcSetWebp\n sizes\n originalImg\n originalName\n }\n }\n }\n }\n `,\n {fileName: \"knight.jpg\"}\n)\n```\n\nThe above doesn't work. `data.landscape.childImageSharp === null` \n\nWhat am I doing wrong?\n\nEDIT:\n\n### The working version\n\nThanks for the help! The following code works pretty well. This post was particularly helpful. This is not an ideal solution, but it works for me.\n\n```\nimport React from 'react';\nimport Img from 'gatsby-image';\nimport { StaticQuery, graphql } from 'gatsby';\n\nfunction renderImage(file) {\n return (\n \n )\n}\n\nconst MyImg = function (props) {\n\n return {\n const image = data.images.edges.find(\n image => image.node.relativePath === \"knight.jpg\"\n )\n return(renderImage(image))\n }}\n />\n}\n\nexport default MyImg;\n```\n\n========================================\n\nTop Answer:\nSo to pass variables you have to use the following syntax\n\n```\ngraphql(``, { indexPage: })\n```\n\nSo the query will come something like this\n\n```\nexport const query = grapqhl(\n `query getImages($fileName: String) {\n landscape: file(relativePath: {eq: $fileName}) {\n childImageSharp {\n fluid(maxWidth: 1000) {\n base64\n tracedSVG\n aspectRatio\n src\n srcSet\n srcWebp\n srcSetWebp\n sizes\n originalImg\n originalName\n }\n }\n }\n }\n `,\n {fileName: \"knight.jpg\"}\n )\n```\n\n========================================\n\nCode:\n```text\nquery getImages($fileName: String) {\n landscape: file(relativePath: {eq: $fileName}) {\n childImageSharp {\n fluid(maxWidth: 1000) {\n base64\n tracedSVG\n aspectRatio\n src\n srcSet\n srcWebp\n srcSetWebp\n sizes\n originalImg\n originalName\n }\n }\n }\n}\n```\n\n```text\n{\n \"fileName\": \"titanic.jpg\"\n}\n```\n\n```text\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\nimport Img from \"gatsby-image\"\n\nexport default ({ data }) => (\n <div>\n <Img fluid={data.landscape.childImageSharp.fluid} />\n </div>\n)\n\nexport const query = (\n graphql`\n query getImages($fileName: String) {\n landscape: file(relativePath: {eq: $fileName}) {\n childImageSharp {\n fluid(maxWidth: 1000) {\n base64\n tracedSVG\n aspectRatio\n src\n srcSet\n srcWebp\n srcSetWebp\n sizes\n originalImg\n originalName\n }\n }\n }\n }\n `,\n {fileName: \"knight.jpg\"}\n)\n```\n\n```text\nimport React from 'react';\nimport Img from 'gatsby-image';\nimport { StaticQuery, graphql } from 'gatsby';\n\nfunction renderImage(file) {\n return (\n <Img fluid={file.node.childImageSharp.fluid} />\n )\n}\n\nconst MyImg = function (props) {\n\n return <StaticQuery\n query={graphql`\n query {\n images: allFile(filter: { sourceInstanceName: { eq: \"images\" } }) {\n edges {\n node {\n extension\n relativePath\n childImageSharp {\n fluid(maxWidth: 1000) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n }\n }\n `}\n render={(data) => {\n const image = data.images.edges.find(\n image => image.node.relativePath === \"knight.jpg\"\n )\n return(renderImage(image))\n }}\n />\n}\n\nexport default MyImg;\n```\n\n```text\ndata.landscape.childImageSharp === null\n```\n\n```text\ncreatePage\n```\n\n```text\ngatsby-node.js\n```\n\n```text\ngraphql(`<your_query_with_variable>`, { indexPage: <value_of_variable> })\n```\n\n```text\nexport const query = grapqhl(\n `query getImages($fileName: String) {\n landscape: file(relativePath: {eq: $fileName}) {\n childImageSharp {\n fluid(maxWidth: 1000) {\n base64\n tracedSVG\n aspectRatio\n src\n srcSet\n srcWebp\n srcSetWebp\n sizes\n originalImg\n originalName\n }\n }\n }\n }\n `,\n {fileName: \"knight.jpg\"}\n )\n```\n\n========================================\n\nComments:\n- Thank you so much for providing a working version! You saved me hours of work.\n- Anyway to pass maxWidth: 1000 or fragment (GatsbyImageSharpFluid) as a variable. That would make it more dynamic.\n- Note: this will only work in the `gatsby-node` file, passing in a variable to the graphql method with a static query (for example) won't allow variables.\n- Sadly, this is the case. I've added some working code based on that second link.\n- Your spectrum.chat link doesn't work anymore, is the mentioned discussion available somewhere still?","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":311,"estimatedTokens":1378}}75{"id":"stack-50935193","source":"stackoverflow","questionId":50935193,"title":"In GraphQL .NET, how do I specify that a query can take optional parameters?","tags":["graphql","graphql-dotnet"],"text":"Title: In GraphQL .NET, how do I specify that a query can take optional parameters?\nTags: graphql, graphql-dotnet\nSource: Stack Overflow\n\nQuestion:\nLet's say I want to be able to query for a user by specifying their ID, *or* by specifying some other identifier, like email address.\n\nHow do you construct the root Query object to accept that?\n\nGiven this\n\n```\npublic class MyQuery : ObjectGraphType\n{\n public MyQuery(IUserService userService)\n {\n Name = \"Query\";\n\n Field(\n \"user\",\n arguments: new QueryArguments(\n new QueryArgument() { Name = \"id\" },\n new QueryArgument() { Name = \"email\" }\n ),\n resolve: context =>\n {\n int? id = context.GetArgument(\"id\");\n if (id != null)\n {\n return userService.GetUserById(id);\n }\n string email = context.GetArgument(\"email\");\n if (email != null)\n {\n return userService.GetUserByEmail(email);\n }\n return null;\n }\n );\n }\n}\n```\n\nIs that the right way to do it? Will `context.GetArgument()` return `null` if it doesn't find the argument in the query? Or does providing two arguments to the `QueryArguments` mean that both arguments are required for the query?\n\n========================================\n\nCode:\n```text\npublic class MyQuery : ObjectGraphType\n{\n public MyQuery(IUserService userService)\n {\n Name = \"Query\";\n\n Field<UserType>(\n \"user\",\n arguments: new QueryArguments(\n new QueryArgument<IntGraphType>() { Name = \"id\" },\n new QueryArgument<StringGraphType>() { Name = \"email\" }\n ),\n resolve: context =>\n {\n int? id = context.GetArgument<int>(\"id\");\n if (id != null)\n {\n return userService.GetUserById(id);\n }\n string email = context.GetArgument<string>(\"email\");\n if (email != null)\n {\n return userService.GetUserByEmail(email);\n }\n return null;\n }\n );\n }\n}\n```\n\n```text\ncontext.GetArgument()\n```\n\n```text\nnull\n```\n\n```text\nQueryArguments\n```\n\n```text\narguments: new QueryArguments(\n new QueryArgument<IntGraphType>() { Name = \"id\" },\n new QueryArgument<StringGraphType>() { Name = \"email\" }\n)\n```\n\n```text\narguments: new QueryArguments(\n new QueryArgument<NonNullGraphType<IntGraphType>>() { Name = \"id\" },\n new QueryArgument<NonNullGraphType<StringGraphType>>() { Name = \"email\" }\n)\n```\n\n```text\ncontext.GetArgument<string>(\"email\", defaultValue: \"my default value\");\n```\n\n```text\nGraphType\n```\n\n```text\nNonNullGraphType\n```\n\n```text\nGetArgument<TType>\n```\n\n```text\ndefault(TType)\n```\n\n========================================\n\nComments:\n- So I could force `GetArgument` to return `null` if the argument does not exist by doing `context.GetArgument(\"email\", defaultValue: null)`?\n- Yes. Providing a default value is optional (`defaultValue` is an optional parameter). The default for a string would be null.","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":131,"estimatedTokens":739}}76{"id":"stack-75163140","source":"stackoverflow","questionId":75163140,"title":"Query data cannot be undefined. Please make sure to return a value other than undefined from your query function","tags":["javascript","reactjs","next.js","graphql","react-query"],"text":"Title: Query data cannot be undefined. Please make sure to return a value other than undefined from your query function\nTags: javascript, reactjs, next.js, graphql, react-query\nSource: Stack Overflow\n\nQuestion:\nI'm sending a request to a graphql endpoint using a useQuery hook, I work with react.js and next.js. This request is to show a list of projects on my website. When I check the network tab in the inspect tool in chrome browser, the request is ok, showing the response data without problem, but in the console, I got the next errors:\n\nQuery data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: [\"newProjects\"]\n\nError: undefined\nat Object.onSuccess (query.mjs?b194:316:1)\nat resolve (retryer.mjs?bd96:54:1)\n\nI created a hook to make the request and get the data in another component:\n\n```\nimport { useQuery } from \"@tanstack/react-query\";\nimport { request, gql } from 'graphql-request'\nimport { endpointProjects } from \"../settings\";\n\nexport function useAllProjects() {\n\n return useQuery(\n ['newProjects'],\n async () => {\n const data = await request(\n endpointProjects.newProjects,\n gql`\n query MyQuery {\n newProjects(orderBy: blockTimestamp, orderDirection: desc, first: 10, skip: 0) {\n id\n project\n name\n symbol\n uri\n blockNumber\n blockTimestamp\n transactionHash\n }\n }\n `,\n )\n }\n )\n}\n```\n\nIn another component, I just use the hook and show it in the console to see if I get the data:\n\n```\nconst {data} = useAllProjects()\nconsole.log('projects list: ', data)\n```\n\n========================================\n\nTop Answer:\nThe problem is that you're not returning the data from your async function in the useQuery hook. When you don't explicitly return a value from a function in JavaScript, it implicitly returns `undefined`.\n\n\r\n\r\n\n```\nexport function useAllProjects() {\n return useQuery(\n ['newProjects'],\n async () => {\n const data = await request(\n endpointProjects.newProjects,\n gql`\n query MyQuery {\n newProjects(orderBy: blockTimestamp, orderDirection: desc, first: 10, skip: 0) {\n id\n project\n name\n symbol\n uri\n blockNumber\n blockTimestamp\n transactionHash\n }\n }\n `\n );\n \n return data; \n }\n );\n}\n```\n\n\r\n\r\n\r\n\nyou can reuse it in your other component after importing\n\n```\nconst {data, isLoading} = useAllProjects()\n```\n\n========================================\n\nCode:\n```text\nimport { useQuery } from \"@tanstack/react-query\";\nimport { request, gql } from 'graphql-request'\nimport { endpointProjects } from \"../settings\";\n\nexport function useAllProjects() {\n\n return useQuery(\n ['newProjects'],\n async () => {\n const data = await request(\n endpointProjects.newProjects,\n gql`\n query MyQuery {\n newProjects(orderBy: blockTimestamp, orderDirection: desc, first: 10, skip: 0) {\n id\n project\n name\n symbol\n uri\n blockNumber\n blockTimestamp\n transactionHash\n }\n }\n `,\n )\n }\n )\n}\n```\n\n```text\nconst {data} = useAllProjects()\nconsole.log('projects list: ', data)\n```\n\n```text\n// imports \n\nexport function useAllProjects() {\n return useQuery({\n queryKey: [\"newProjects\"],\n queryFn: async () =>\n request(\n endpointProjects.newProjects,\n gql`\n query MyQuery {\n newProjects(orderBy: blockTimestamp, orderDirection: desc, first: 10, skip: 0) {\n id\n project\n name\n symbol\n uri\n blockNumber\n blockTimestamp\n transactionHash\n }\n }\n `\n ),\n });\n}\n```\n\n```text\n{}\n```\n\n```text\nreturn\n```\n\n```text\nuseQuery\n```\n\n```text\nrequest(...)\n```\n\n```text\nconst { data, isLoading } = useQuery({\n queryKey: [\"check\", \"+\", isAccess ? \"yes\" : \"not\"],\n queryFn: async () => {\n try {\n const res = await axios.get(\"http://localhost:5000/api/auth/me\", {\n withCredentials: true,\n headers: {\n Authorization: `Bearer ${token && JSON.parse(token).accessToken}`,\n },\n });\n\n if (res.status === 200) {\n setIsAccess(true);\n return res.data; // Ensure you return the data\n } else {\n router.push(\"/\");\n return null; // Return a value instead of undefined\n }\n } catch (error) {\n console.error(\"Error fetching data:\", error);\n return null; // Handle errors gracefully\n }\n },\n});\n```\n\n```js\nexport function useAllProjects() {\n return useQuery(\n ['newProjects'],\n async () => {\n const data = await request(\n endpointProjects.newProjects,\n gql`\n query MyQuery {\n newProjects(orderBy: blockTimestamp, orderDirection: desc, first: 10, skip: 0) {\n id\n project\n name\n symbol\n uri\n blockNumber\n blockTimestamp\n transactionHash\n }\n }\n `\n );\n \n return data; \n }\n );\n}\n```\n\n```text\nconst {data, isLoading} = useAllProjects()\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- This is also a useful thread regarding this issue: github.com/TanStack/query/discussions/4457","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":253,"estimatedTokens":1323}}77{"id":"stack-38339442","source":"stackoverflow","questionId":38339442,"title":"JSON Schema to GraphQL schema converters","tags":["swagger","graphql","jsonschema"],"text":"Title: JSON Schema to GraphQL schema converters\nTags: swagger, graphql, jsonschema\nSource: Stack Overflow\n\nQuestion:\nAre there any adapters which are converting JSON Schema schemas (e.g from Swagger) to GraphQL schemas?\nThere is even an official article about wrapping around REST http://graphql.org/blog/rest-api-graphql-wrapper/, but usually REST already described and Swagger is the most popular format for it.\nWouldn't like to write it by my own if there is already existing implementation.\n\n========================================\n\nTop Answer:\nI actually put some time into trying this out a few months ago. You can read the my post detailing the results here: https://medium.com/apollo-stack/will-graphql-replace-rest-documentation-f1a55092ef9d#.m50im46o0\n\nAfter looking at a lot of the Swagger schemas available online, I think that Swagger or similar API description languages can be a good starting point for defining a GraphQL schema, but they often don't contain enough information to generate a schema on their own. Specifically, there is usually not enough data about relationships between objects.\n\nIf you want to start from a JSON-formatted schema description, all you need to do is write some code that loops over your different data types in Swagger, and generate `GraphQLObjectType` objects. You can see a simple approach to this in the example repository for the blog post I linked above: https://github.com/apollostack/swapi-rest-graphql/blob/951e50ec29732c93e7aa0bc6880210fdd1816a2f/schema.js#L28\n\nBasically, you are just converting one format of data into another, and then you need to add some relationships between the data (foreign keys, IDs, and such), and add some root queries to create an entry point. In the case of a REST API, it often makes sense to have your single and multiple resource endpoints act as your root query fields.\n\n========================================\n\nCode:\n```text\nSwagger\n```\n\n```text\nGraphQLObjectType\n```\n\n========================================\n\nComments:\n- Perfectly reasonable question.\n- But that's only for the types right ? The full contract (message parameters, etc.) can be mapped ?\n- Everything which is needed to make API working is mapped\n- Does anyone know if there is a similar tool for Java? I looked all over the web and found nothing.","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":38,"estimatedTokens":578}}78{"id":"stack-55030434","source":"stackoverflow","questionId":55030434,"title":"What does 'locations' refer to in GraphQL errors?","tags":["graphql","prisma-graphql"],"text":"Title: What does 'locations' refer to in GraphQL errors?\nTags: graphql, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm working through a GraphQL Node/Prisma server tutorial and encountered an error due to something wrong in my code. I've solved the error but I want to understand the error message, in particular, what does `locations` refers to? That is, I have a `location` of line 2, column 3, but line 2, column 3 of what? The relevant method in my code (`signup`, in this case)? Of my mutation? \n\n```\n// error message \n{\n \"data\": {\n \"signup\": null\n },\n \"errors\": [\n {\n \"message\": \"secretOrPrivateKey must have a value\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"signup\"\n ]\n }\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n// error message \n{\n \"data\": {\n \"signup\": null\n },\n \"errors\": [\n {\n \"message\": \"secretOrPrivateKey must have a value\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"signup\"\n ]\n }\n ]\n}\n```\n\n```text\nlocations\n```\n\n```text\nlocation\n```\n\n```text\nsignup\n```\n\n```text\n{\n allFilmz\n}\n```\n\n```text\n[\n {\n \"line\": 2,\n \"column\": 3\n }\n]\n```\n\n```text\n{allFilmz}\n```\n\n```text\n[\n {\n \"line\": 1,\n \"column\": 2\n }\n]\n```\n\n```text\npath\n```\n\n```text\nlocations\n```\n\n```text\nlocations\n```\n\n```text\npath\n```\n\n```text\nlocations\n```\n\n```text\npath\n```\n\n```text\nlocations\n```\n\n```text\nlocations\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":127,"estimatedTokens":364}}79{"id":"stack-56340948","source":"stackoverflow","questionId":56340948,"title":"How to call GraphQL outside a component","tags":["reactjs","graphql","apollo"],"text":"Title: How to call GraphQL outside a component\nTags: reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI have made a bunch of React component calling GraphQL using the Query component and everything is working fine.\n\nIn one component I need to have some initial data from the database, but without any visual representation.\n\nI have tried to use the query component but it seems to be triggered only on the render cycle. I have tried to package it into a function and call this function in the component that needs the data. But the code / query is not executed since there's no component to show.\n\nHow do I go about getting this data from the database without a component?\n\nI can't find any documentation on how to solve this problem. But I can't be \nthe only one doing this.\n\nIs ApolloConsumer or ApolloProvider the answer to my problems?\n\nI'm working with conferences and sessions. A conference runs over a couple of days and each day has a number of sessions.\n\nWhat I'm trying to achieve is to render a page with X numbers of tabs one for each day. Each tab represents a day and it shows the number of sessions for the day.\n\nMy sessions page:\n\n```\nimport React from 'react';\nimport FullWidthTabs from '../components/Sessions';\nimport SessionTab from '../components/SessionTab';\nimport BwAppBar2 from '../components/BwAppBar2';\nimport ConferenceDays from '../components/ConferenceDays';\n\nclass SessionsPage extends React.Component {\n\n static async getInitialProps() {\n console.log(\"GetInitProps SessionsPage\");\n }\n\n render() {\n let a = ConferenceDays();\n return (\n\n \n \n {a}\n } \n day2={ } day3={ }>\n \n \n );\n }\n}\nexport default (SessionsPage);\n```\n\nHere the dates have been hardcoded in the page just for testing.\n\nBut order to know how many days the conference spans i'll have to find the conference and decide the start and end date and generate all the dates in between:\n\n```\nimport React, { Component } from 'react'\nimport { graphql } from 'react-apollo'\nimport { Query } from 'react-apollo'\nimport gql from 'graphql-tag'\nimport Link from '@material-ui/core/Link';\nimport { useQuery } from \"react-apollo-hooks\";\n\nimport conferencesQuery from '../queries/conferences'\nimport { Table, Head, Cell } from './Table'\nimport ConferenceCard from './ConferenceCard';\nimport Grid from '@material-ui/core/Grid';\nimport Paper from '@material-ui/core/Paper';\nimport moment from 'moment';\n\nconst CONFERENCE_QUERY = gql`\n query conference($conferenceId : ID!){\n conference(id: $conferenceId){\n title\n start_date\n end_date\n } \n}\n`\nlet index = 0;\nlet loopDate = 0;\nlet dates = [];\nlet conferenceId = 57;\n\nconst ConferenceDays = () => (\n\n {({ loading, error, data }) => {\n if (loading)\n return Fetching\n if (error)\n return Error\n const startDate = moment(data.conference.start_date, 'x');\n const endDate = moment(data.conference.end_date, 'x');\n\n for (loopDate = parseInt(data.conference.start_date);\n loopDate );\n\nexport default ConferenceDays\n```\n\nBut is this approach incorrect? \n\nWould it be more correct to lift the ConferenceDates component up in the hierarchy?\n\nKim\n\n========================================\n\nTop Answer:\nYou could separate the creation of the `ApolloClient` to a separate file and use an init function to access the client outside of React components.\n\n```\nimport React from 'react';\nimport {\n ApolloClient,\n HttpLink,\n InMemoryCache,\n} from \"@apollo/client\";\n\nlet apolloClient;\n\nconst httpLink = new HttpLink({\n uri: \"http://localhost:4000/graphql\",\n credentials: \"same-origin\",\n});\n\nfunction createApolloClient() {\n return new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n });\n}\n\nexport function initializeApollo() {\n const _apolloClient = apolloClient ?? createApolloClient();\n if (!apolloClient) apolloClient = _apolloClient;\n\n return _apolloClient;\n}\n\nexport function useApollo() {\n const store = useMemo(() => initializeApollo(initialState), [initialState]);\n return store;\n}\n```\n\nThen you would use this outside components like this:\n\n```\nconst client = initializeApollo()\nconst res = await client.query({\n query: MY_QUERY,\n variables: {},\n})\n```\n\nI didn't try this myself, but I think this you an idea on how to go about this and how to access the `ApolloClient`.\n\n========================================\n\nCode:\n```text\nimport React from 'react';\nimport FullWidthTabs from '../components/Sessions';\nimport SessionTab from '../components/SessionTab';\nimport BwAppBar2 from '../components/BwAppBar2';\nimport ConferenceDays from '../components/ConferenceDays';\n\n\nclass SessionsPage extends React.Component {\n\n static async getInitialProps() {\n console.log(\"GetInitProps SessionsPage\");\n }\n\n render() {\n let a = ConferenceDays();\n return (\n\n <div>\n <BwAppBar2 />\n {a}\n <FullWidthTabs days={['2018-06-11', '2018-06-12', '2018-06-13']} day1={ < SessionTab conferenceId = \"57\" day = '2018-06-11' / > } \n day2={ < SessionTab conferenceId = \"57\" day = '2018-06-12' / > } day3={ < SessionTab conferenceId = \"57\" day = '2018-06-13' / > }>\n </FullWidthTabs>\n </div>\n );\n }\n}\nexport default (SessionsPage);\n```\n\n```text\nimport React, { Component } from 'react'\nimport { graphql } from 'react-apollo'\nimport { Query } from 'react-apollo'\nimport gql from 'graphql-tag'\nimport Link from '@material-ui/core/Link';\nimport { useQuery } from \"react-apollo-hooks\";\n\nimport conferencesQuery from '../queries/conferences'\nimport { Table, Head, Cell } from './Table'\nimport ConferenceCard from './ConferenceCard';\nimport Grid from '@material-ui/core/Grid';\nimport Paper from '@material-ui/core/Paper';\nimport moment from 'moment';\n\n\nconst CONFERENCE_QUERY = gql`\n query conference($conferenceId : ID!){\n conference(id: $conferenceId){\n title\n start_date\n end_date\n } \n}\n`\nlet index = 0;\nlet loopDate = 0;\nlet dates = [];\nlet conferenceId = 57;\n\nconst ConferenceDays = () => (\n<Query query={CONFERENCE_QUERY} variables={{conferenceId}}>\n {({ loading, error, data }) => {\n if (loading)\n return <div>Fetching</div>\n if (error)\n return <div>Error</div>\n const startDate = moment(data.conference.start_date, 'x');\n const endDate = moment(data.conference.end_date, 'x');\n\n for (loopDate = parseInt(data.conference.start_date);\n loopDate < parseInt(data.conference.end_date);\n loopDate += 86400000) {\n\n let aDate = moment(loopDate, 'x');\n dates.push(aDate.format('YYYY-MM-DD').toString());\n }\n console.log(dates);\n return(dates);\n }}\n</Query>);\n\nexport default ConferenceDays\n```\n\n```text\nimport { useApolloClient, gql } from \"@apollo/client\";\n\n MY_QUERY = gql'\n query OUR_QUERY {\n books{\n edges{\n node{\n id\n title\n author\n }\n }\n }\n }\n'\n\nconst myFunctionalComponent = () => { // outside function component\n\n const client = useApolloClient();\n\n const aNormalFunction = () => { // please note that this is not a component \n client.query({\n query: MY_QUERY,\n fetchPolicy: \"cache-first\" // select appropriate fetchPolicy\n }).then((data) => {\n console.log(data) //do whatever you like with the data\n }).catch((err) => {\n console.log(err)\n })\n };\n\n // just call it as a function whenever you want\n aNormalFunction() \n \n // you can even call it conditionally which is not possible with useQuery hook\n if (true) {\n aNormalFunction()\n }\n\n return (\n <p>Hello Hook!</>\n );\n};\n\nexport default myFunctionalComponent;\n```\n\n```js\nimport React from 'react';\nimport {\n ApolloClient,\n HttpLink,\n InMemoryCache,\n} from \"@apollo/client\";\n\nlet apolloClient;\n\nconst httpLink = new HttpLink({\n uri: \"http://localhost:4000/graphql\",\n credentials: \"same-origin\",\n});\n\nfunction createApolloClient() {\n return new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n });\n}\n\nexport function initializeApollo() {\n const _apolloClient = apolloClient ?? createApolloClient();\n if (!apolloClient) apolloClient = _apolloClient;\n\n return _apolloClient;\n}\n\nexport function useApollo() {\n const store = useMemo(() => initializeApollo(initialState), [initialState]);\n return store;\n}\n```\n\n```js\nconst client = initializeApollo()\nconst res = await client.query({\n query: MY_QUERY,\n variables: {},\n})\n```\n\n```text\nApolloClient\n```\n\n```text\nApolloClient\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nApolloClient\n```\n\n```text\nmutate\n```\n\n```text\napolloClient.mutate\n```\n\n```text\nconst graphqlClient = createClient({\n url: '',\n fetchOptions: () => {\n return {\n headers: { }\n };\n }\n});\n\nconst fetchCountries = () => (dispatch: Dispatch) => {\n graphqlClient\n .query(countriesQuery, getCountriesVariable())\n .toPromise()\n .then(result => {\n dispatch({\n type: UPDATE_COUNTRIES,\n payload: result.data.countries\n });\n if (result.error?.message) {\n // https://formidable.com/open-source/urql/docs/basics/errors/\n logErrorMessage(result.error?.message, 'AppActions.fetchCountries');\n }\n })\n .catch(error => {\n logError(error, 'AppActions.fetchCountries');\n });\n};\n```\n\n```text\nurql\n```\n\n========================================\n\nComments:\n- This looked promising, but I get this warning in Visual Studio Code: `React Hook \"useApolloClient\" is called in function \"getPostTagId\" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. eslint(react-hooks/rules-of-hooks)`\n- Sorry Ryan, my mistake. The example I showed did not show the context. Actually, \"aNormalFunction\" should stay in a functional component. Only then, useApolloClient hook can be declared. I will update the code.\n- If aNormalFunction stays in a functional component, then you're still using a hook. So how would this possibly work?\n- What I wanted to say here is that I can now call a query any time I want, while loading and error handling are managed inside the function. useQuery and useLazyQuery are linked with component's life cycle, so you need to handle 'loading' and 'error' status within the component's life cycle. In other way, the approach I mentioned is 'asynchronous' to component's life cycle events.","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":406,"estimatedTokens":2689}}80{"id":"stack-45920986","source":"stackoverflow","questionId":45920986,"title":"How to send GraphQL mutation from one server to another?","tags":["lambda","aws-lambda","graphql","apollo","graphcool"],"text":"Title: How to send GraphQL mutation from one server to another?\nTags: lambda, aws-lambda, graphql, apollo, graphcool\nSource: Stack Overflow\n\nQuestion:\nI would like to save some Slack messages to a GraphQL backend. I can use the Slack API and what they call \"Slack App Commands\" so everytime a message is send to my Slack channel, Slack will automatically send a HTTP POST request to my server with the new message as data.\n\nI was thinking using an AWS lambda function to forward this post request to my GraphQL server endpoint (I am using GraphCool). I am pretty new to GraphQL, I've used Apollo to create mutations from the browser. Now I need to send mutation from my Node server (AWS Lambda function) instead of the browser. How can I achieve that?\n\nThanks.\n\n========================================\n\nTop Answer:\nSetting up an AWS Lambda is left as an exercise for the reader.\n\nTo get to see what GraphQL queries (or in this case, mutations) your Apollo client code is sending to the server, for cutting+pasting (and presumably parameterising) into your lambda code, this tool exists: Apollo GraphQL Dev Tools which now allows you to watch your mutations being executed.\n\n========================================\n\nCode:\n```text\nmutation ($id: Int!) {\n upvotePost(postId: $id) {\n id\n }\n}\n```\n\n```text\n$id = 1\n```\n\n```text\n{\n \"query\": \"mutation ($id: Int!) { upvotePost(postId: $id) { id } } \", \n \"variables\": { \"id\": 1 } \n}\n```\n\n```text\naxios({\n method: 'post',\n url: '/graphql',\n // payload is the payload above\n data: payload,\n});\n```\n\n```text\nrequest\n```\n\n```text\naxios\n```\n\n```text\nquery\n```\n\n```text\naxios\n```\n\n========================================\n\nComments:\n- Thank you! I finaly used graphql-request wich works fine but now I understand better how it works. :)","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":69,"estimatedTokens":446}}81{"id":"stack-46582319","source":"stackoverflow","questionId":46582319,"title":"Webpack html plugin is not generating html","tags":["javascript","node.js","webpack","graphql","html-webpack-plugin"],"text":"Title: Webpack html plugin is not generating html\nTags: javascript, node.js, webpack, graphql, html-webpack-plugin\nSource: Stack Overflow\n\nQuestion:\nI am using webpack html plugin to generate the html page from the graphiql.ejs but it is not generating html page when I am running `npm start`\n\nwebpack.config.js\n\n```\nvar HtmlWebpackPlugin = require(\"html-webpack-plugin\");\nmodule.exports = {\n plugins: [\n new HtmlWebpackPlugin({\n filename: \"public/graphql/index.html\", // Write the file to /graphql/index.html\n inject: false, // Do not inject any of your project assets into the template\n GRAPHQL_VERSION: packageJSON.dependencies.graphql.replace(/[^0-9.]/g, \"\"), // Get the graphql version from my package.json\n template: \"graphiql.ejs\" // path to template\n })\n ]\n};\n```\n\nI want to generate the index.html inside the /public/graphql directory. Does anyone know what I am doing wrong ? Is there any other command to run webpack ?\n\n========================================\n\nTop Answer:\nHere is the one that worked for me. If still you face any issue let me know. I will the code with github.\n\n```\nconst path = require('path');\nconst HtmlWebpackPlugin = require(\"html-webpack-plugin\");\nconst packageJson = require(\"./package.json\");\n\nconst GRAPHQL_VERSION = packageJson.dependencies.graphql.replace(/[^0-9.]/g, '');\n\nmodule.exports = {\n entry: 'index.js',\n output: {\n path: path.resolve(__dirname, 'public'),\n filename: 'index.bundle.js'\n },\n plugins: [\n new HtmlWebpackPlugin({ \n filename: 'index.html',\n inject: false,\n GRAPHQL_VERSION: GRAPHQL_VERSION,\n template: 'graphiql.ejs'\n })\n ]\n}\n```\n\nhttps://i.sstatic.net/Vl924.png\n\n========================================\n\nCode:\n```text\nvar HtmlWebpackPlugin = require(\"html-webpack-plugin\");\nmodule.exports = {\n plugins: [\n new HtmlWebpackPlugin({\n filename: \"public/graphql/index.html\", // Write the file to <public-path>/graphql/index.html\n inject: false, // Do not inject any of your project assets into the template\n GRAPHQL_VERSION: packageJSON.dependencies.graphql.replace(/[^0-9.]/g, \"\"), // Get the graphql version from my package.json\n template: \"graphiql.ejs\" // path to template\n })\n ]\n};\n```\n\n```text\nnpm start\n```\n\n```text\nconst path = require('path');\n const HtmlWebpackPlugin = require(\"html-webpack-plugin\");\n const packageJSON=require(\"./package.json\");\n module.exports = {\n entry: './src/app.js',\n output: {\n path: path.resolve(__dirname, 'public'),\n filename:\"build.js\"\n },\n plugins: [\n new HtmlWebpackPlugin({\n filename: \"graphql/index.html\", // Write the file to <public-path>/graphql/index.html\n inject: false, // Do not inject any of your project assets into the template\n GRAPHQL_VERSION: packageJSON.dependencies.graphql.replace(/[^0-9.]/g, \"\"), // Get the graphql version from my package.json\n template: \"graphiql.ejs\" // path to template\n })\n ] \n }\n```\n\n```text\nconst path = require('path');\nconst HtmlWebpackPlugin = require(\"html-webpack-plugin\");\nconst packageJson = require(\"./package.json\");\n\nconst GRAPHQL_VERSION = packageJson.dependencies.graphql.replace(/[^0-9.]/g, '');\n\nmodule.exports = {\n entry: 'index.js',\n output: {\n path: path.resolve(__dirname, 'public'),\n filename: 'index.bundle.js'\n },\n plugins: [\n new HtmlWebpackPlugin({ \n filename: 'index.html',\n inject: false,\n GRAPHQL_VERSION: GRAPHQL_VERSION,\n template: 'graphiql.ejs'\n })\n ]\n}\n```\n\n```text\n{\n \"version\": \"1.0.0,\n \"name\": \"my-app\",\n \"scripts\": {\n \"prestart\": \"webpack\",\n \"start\": \"nodemon server.js --exec babel-node --presets es2015,stage-2\"\n }\n}\n```\n\n```text\nnpm start\n```\n\n```text\nprestart\n```\n\n```text\npackage.json\n```\n\n```text\nstart\n```\n\n```text\nnpm start\n```\n\n========================================\n\nComments:\n- You need to put it into the `plugins` array and export it webpack.github.io/docs/using-plugins.html\n- @serge1peshcoff I did pastebin.com/1NgiM3kY but still it is not generating\n- Does your `npm start` script run `webpack.config.js` file?\n- @Jehy Nope. it runs \"start\": \"nodemon server.js --exec babel-node --presets es2015,stage-2\"\n- @Jehy How to enable webpack too ?\n- can you please provide full webpack.config.js?\n- You simply don't run webpack anywhere - so you don't get any result. Check `a config file` section in this article: webpack.github.io/docs/tutorials/getting-started - you should just run `webpack` command.\n- whats use of output file name and template\n- I ran by `webpack -p`\n- what;s use of template ?\n- graphql.ejs is the source file. Which will get converted to index.html. it's useful when you want to customize the default index.html of HtmlWebpackPlugin.\n- Then what is entry I thought entry file get converted into index.html","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":168,"estimatedTokens":1217}}82{"id":"stack-61997401","source":"stackoverflow","questionId":61997401,"title":"How to logout user when token expires in react app","tags":["javascript","reactjs","graphql","react-hooks","react-apollo"],"text":"Title: How to logout user when token expires in react app\nTags: javascript, reactjs, graphql, react-hooks, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI am working on a app where I am using React as my front-end and `React-apollo-graphql` for my API calling.\n\nI am using `react-hooks` i.e in React 16.8 +.\n\n**What I am doing**\n\nI have crated a `auth.js` file where I am storing my values when user is loging in and also checking the token is it valid or not, (expiry I am checking), but that file is only loading my I am refreshing or reloading the page, That is not how it should work\n\n**My auth.js file**\n\n```\nconst initialstate = {\n user: null,\n};\nif (localStorage.getItem(\"JWT_Token\")) {\n const jwt_Token_decoded = Jwt_Decode(localStorage.getItem(\"JWT_Token\"));\n console.log(jwt_Token_decoded.exp * 1000);\n console.log(Date.now());\n if (jwt_Token_decoded.exp * 1000 {},\n logout: () => {},\n});\nconst AuthReducer = (state, action) => {\n switch (action.type) {\n case \"LOGIN\":\n return {\n ...state,\n user: action.payload,\n };\n case \"LOGOUT\":\n return {\n ...state,\n user: null,\n };\n default:\n return state;\n }\n};\n \nconst AuthProvider = (props) => {\n const [state, dispatch] = useReducer(AuthReducer, initialstate);\n const login = (userData) => {\n localStorage.setItem(\"JWT_Token\", userData.token);\n dispatch({\n type: \"LOGIN\",\n payload: userData,\n });\n };\n const logout = () => {\n localStorage.clear();\n dispatch({ action: \"LOGOUT\" });\n };\n \n return (\n \n );\n};\n \nexport { AuthContext, AuthProvider };\n```\n\nAs I have commented the line where I am checking the token expiry.\n\nMy only issue is why it is working on page reload not on each route like we do in store file when we use Redux.\n\n**My App.js**\n\n```\n\n \n \n \n \n \n\n```\n\n**My index.js**\n\n```\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\nimport ApolloClient from 'apollo-boost'\nimport { ApolloProvider } from '@apollo/react-hooks';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\n \nconst client = new ApolloClient({\n uri: 'my url',\n cache: new InMemoryCache(),\n});\nReactDOM.render(\n \n \n ,\n document.getElementById('root')\n);\n```\n\n**Important points**\n\nAs I am using `react-apollo-graphql` so do they provide ant Authentication flow ? like how redux does, we have to create a store file which will store our data\n\nI am using React 16.8 + so I am using react-hooks so here I am using `use Reducer` from that only.\n\nMy only question is am I doing it right? I am open to other approaches.\n\nI have done authentication and authorization in Vue using Vuex there I use to create a store file which runs on ever route\n\nSame I have done with Redux, In my store file I use to store the states and all.\n\nNow if I am using react-hooks and react-apollo-graphql so no need to do this things with redux.\n\n**I am using `apollo-link-context`** for passing the header (Authorization) like below\n\n```\nconst authLink = setContext(() => {\n const token = localStorage.getItem('JWT_Token')\n return {\n headers:{\n Authorization: token ? `${token}` : ''\n }\n }\n});\n```\n\nI think here I can check on each route or on each request if the token is valid or not ( check exp time) if it is invalid then I will logout and clear my local storage, Clearing the storage is not a big deal the main thing is how to redirect to login page.\n\n========================================\n\nTop Answer:\nFor your your problem the solution might be like:\n\n- Remove the auth part from the context. (Bad practice)\n\n- Create a component with `react-router` subscribed to check the auth state of the user.\n\n- Render it in the `main` component.\n\n`authverify.component.js`\n\n```\nimport { withRouter } from \"react-router-dom\";\n\nconst AuthVerifyComponent = ({ history }) => {\n history.listen(() => { // ;\n};\n\nexport default withRouter(AuthVerifyComponent);\n```\n\n`app.js`\n\n```\n\n \n \n \n \n \n \n;\n```\n\n========================================\n\nCode:\n```text\nconst initialstate = {\n user: null,\n};\nif (localStorage.getItem(\"JWT_Token\")) {\n const jwt_Token_decoded = Jwt_Decode(localStorage.getItem(\"JWT_Token\"));\n console.log(jwt_Token_decoded.exp * 1000);\n console.log(Date.now());\n if (jwt_Token_decoded.exp * 1000 < Date.now()) {\n localStorage.clear(); // this runs only when I refresh the page or reload on route change it dosent work\n } else {\n initialstate.user = jwt_Token_decoded;\n }\n}\n\nconst AuthContext = createContext({\n user: null,\n login: (userData) => {},\n logout: () => {},\n});\nconst AuthReducer = (state, action) => {\n switch (action.type) {\n case \"LOGIN\":\n return {\n ...state,\n user: action.payload,\n };\n case \"LOGOUT\":\n return {\n ...state,\n user: null,\n };\n default:\n return state;\n }\n};\n \nconst AuthProvider = (props) => {\n const [state, dispatch] = useReducer(AuthReducer, initialstate);\n const login = (userData) => {\n localStorage.setItem(\"JWT_Token\", userData.token);\n dispatch({\n type: \"LOGIN\",\n payload: userData,\n });\n };\n const logout = () => {\n localStorage.clear();\n dispatch({ action: \"LOGOUT\" });\n };\n \n return (\n <AuthContext.Provider\n value={{ user: state.user, login, logout }}\n {...props}\n />\n );\n};\n \nexport { AuthContext, AuthProvider };\n```\n\n```text\n<AuthProvider>\n <Router>\n <div className=\"App wrapper\">\n <Routes/>\n </div>\n </Router>\n</AuthProvider>\n```\n\n```text\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\nimport ApolloClient from 'apollo-boost'\nimport { ApolloProvider } from '@apollo/react-hooks';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\n \nconst client = new ApolloClient({\n uri: 'my url',\n cache: new InMemoryCache(),\n});\nReactDOM.render(\n <ApolloProvider client={client}>\n <App />\n </ApolloProvider>,\n document.getElementById('root')\n);\n```\n\n```text\nconst authLink = setContext(() => {\n const token = localStorage.getItem('JWT_Token')\n return {\n headers:{\n Authorization: token ? `${token}` : ''\n }\n }\n});\n```\n\n```text\nReact-apollo-graphql\n```\n\n```text\nreact-hooks\n```\n\n```text\nauth.js\n```\n\n```text\nreact-apollo-graphql\n```\n\n```text\nuse Reducer\n```\n\n```text\napollo-link-context\n```\n\n```text\nconst authLink = setContext(async () => {\n let token = localStorage.getItem('JWT_Token')\n const { exp } = jwtDecode(token)\n // Refresh the token a minute early to avoid latency issues\n const expirationTime = (exp * 1000) - 60000\n if (Date.now() >= expirationTime) {\n token = await refreshToken()\n // set LocalStorage here based on response;\n }\n return {\n // you can set your headers directly here based on the new token/old token\n headers: {\n ...\n }\n }\n})\n```\n\n```text\nimport { createBrowserHistory } from 'history';\nconst history = createBrowserHistory()\nexport default history;\n```\n\n```text\nimport history from '/path/to/history.js';\nimport { Router } from 'react-router-dom';\n\n<AuthProvider>\n <Router history={history}>\n <div className=\"App wrapper\">\n <Routes/>\n </div>\n </Router>\n</AuthProvider>\n```\n\n```text\nimport history from '/path/to/history';\nconst authLink = setContext(async () => {\n let token = localStorage.getItem('JWT_Token')\n const { exp } = jwtDecode(token)\n const expirationTime = (exp * 1000) - 60000\n if (Date.now() >= expirationTime) {\n localStorage.clear();\n history.push('/login');\n }\n return {\n // you can set your headers directly here based on the old token\n headers: {\n ...\n }\n }\n})\n```\n\n```text\nsetContext\n```\n\n```text\njwtDecode\n```\n\n```js\nimport { withRouter } from \"react-router-dom\";\n\nconst AuthVerifyComponent = ({ history }) => {\n history.listen(() => { // <--- Here you subscribe to the route change\n if (localStorage.getItem(\"JWT_Token\")) {\n const jwt_Token_decoded = Jwt_Decode(localStorage.getItem(\"JWT_Token\"));\n console.log(jwt_Token_decoded.exp * 1000);\n console.log(Date.now());\n if (jwt_Token_decoded.exp * 1000 < Date.now()) {\n localStorage.clear();\n } else {\n initialstate.user = jwt_Token_decoded;\n }\n }\n });\n return <div></div>;\n};\n\nexport default withRouter(AuthVerifyComponent);\n```\n\n```js\n<AuthProvider>\n <Router>\n <div className=\"App wrapper\">\n <Routes />\n <AuthVerifyComponent />\n </div>\n </Router>\n</AuthProvider>;\n```\n\n```text\nreact-router\n```\n\n```text\nmain\n```\n\n```text\nauthverify.component.js\n```\n\n```text\napp.js\n```\n\n```text\nimport React from 'react';\nimport {useLocation, useHistory} from 'react-router-dom';\n\nconst AuthProvider = () => {\n const pathName = useLocation().pathname;\n const history = useHistory();\n\n if (pathName === your_path_that_need_authentication) {\n // if token expired then history.push(login_page));\n }\n\n return null;\n};\n\nexport default AuthProvider;\n```\n\n========================================\n\nComments:\n- I already have a separate route file where all routes are written, And will this run on each route check, I mean on each rout render ?\n- Yes, you can try that out. I have done that before but not tried now.\n- hey, basically you are saying to delete the auth.js file and put all my code inside the new component you have created `AuthVerifyComponent` ?\n- Nope, just move the verification part to the `AuthVerifyComponent` so that you can use the `withRouter` hook & rest will remain the same.\n- So there it says initial state is not defined, i have to pass the initial state also, How ?\n- hey your answer is fine I tried this and it is working fine but my one issue is it only runs when route changes, what if I am in a page and there I have a add or delete button with respective functionality, so suppose I have 2 minutes of exp time to my token and from last 2 minutes I am there now I click on add but my token is expired so it will be deleted when i ll change the route but here I am not changing the route I am in same route doing other stuff so it will cause issue.\n- Just use `settimeout` to expire the token. When the route changes, the component will re-render & the timer get reset (I guess)\n- no no that is not a cool thing to do, there is something called as http link in react-apollo graphql that will do i think\n- So, are you now sorted?\n- Actually in your case there is issue in initialstate as it throws error as initial state is not defined\n- Okay so what are you trying to say? π\n- I didn't get this refreshToken() I have not created this function, And I have tried this approach like when token is expored by checking with `jwtDecode` I want to logout i.e redirect to login page and clear token, but here I don't know how to use redirect or route.\n- Ok, updating my answer for this\n- hey `'/path/to/history'` what path I should put here ?\n- relative path to history.js file\n- I have not created a history file, I am using react useHistory Hook for this.\n- Since you want to use history outside of the component hierarchy you need to create the customhistory as I showed in the above code. You can continue to use `useHistory` in your custom components. Also note how the Router component usage is changed\n- Hey to use `history` the custome one do i need to install something because it throws error as `Unexpected use of 'history'`\n- yes, please install the history module `yarn add history`\n- Hey please check the chat I have one issue, with this approach\n- Hey I am stuck on one problem from very long time could you please help me out with some approach stackoverflow.com/questions/63814645/…\n- This might help someone in the future: useHistory can be imported from the react-router-dom, no need to add 'history'\n- can anyone help ! i dont understand how the expire time is set (const expirationTime = (exp * 1000) - 60000 ) ? how do i set for 5 days ?\n- @ShubhamKhatri can uh tell me how to logout the user when working with refresh tokens expiration?? also if we have multiple routes wrapped in protected route file and multiple different files for diff routes??\n- I did it a similar way to this but used useEffect inside AuthProvider, with pathName (from useLocation) as the condition to useEffect, rather than pathName === your_path... (using react router v5)\n- how do we know whether the token is expired or not? via webhook push or pulling data from backend or simply create a setTimeout method to expire the token in the frontend.","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":459,"estimatedTokens":3111}}83{"id":"stack-41515226","source":"stackoverflow","questionId":41515226,"title":"GraphQL: Filter data in an array","tags":["graphql","graphcool"],"text":"Title: GraphQL: Filter data in an array\nTags: graphql, graphcool\nSource: Stack Overflow\n\nQuestion:\nI'm sure it's a simple thing to do, but I couldn't find anything in either GraphQL's doc or Graphcool's.\n\nSay I have an entity with this schema (new GraphQL user, sorry if I make mistake in the schema representation):\n\n```\nBook {\n name: String!\n author: String!\n categories: [String!]\n}\n```\n\nHow would I do a query for all books that are part of the `\"mystery\"` category? I know I can filter with `allBooks(filter: {})`, but `categories_in: [\"mystery\"]` and `categories_contains: \"mystery\"` didn't do the trick.\n\n========================================\n\nTop Answer:\nIf you are interested in using a hosted GraphQL service, scaphold.io has had this feature for a while now. All connection fields in your API come with a `WhereArgs` argument that exposes filters that let you really dig into your data. When you have a list of scalars like this, the WhereArgs include a `contains` & `notContains` field that allow you to filter results based off the values in your list. This allows you to make a query like this.\n\n```\nquery MysteriousBooks($where:BookWhereArgs) {\n viewer {\n allBooks(where:$where) {\n edges { node { title, ... } }\n }\n }\n}\n\n# Variables\n{\n \"where\": {\n \"categories\": {\n \"contains\": \"mystery\"\n }\n }\n}\n```\n\nJust to be complete, you could also do a slight schema readjustment to make this work without having to filter on a scalar list. For example, you could make `Category` a node implementing type and then create a connection between `Category` and `Book`. Although a `Book` will likely not have many categories, this would allow you to issue a query like this:\n\n```\nquery MysteriousBooks($where: CategoryWhereArgs) {\n viewer {\n allCategories(where: $where) {\n books {\n edges { node { title, ... } }\n }\n }\n }\n}\n\n# Variables\n{\n \"where\": { \n \"name\": { \n \"eq\": \"mystery\" \n } \n }\n}\n```\n\nIf you structure your schema this way then you would also be able to do more filtering on the books in the category without having to loop through every book in your archive. E.G. you could efficiently ask for \"all the mystery books written in the last year.\"\n\nFull disclosure: I work at Scaphold and although I'd love you to try it out no hard feelings if you don't switch over. I'm excited to see people trying and loving GraphQL. If you're curious about how to implement this type of behavior on your own server let me know and I'd be happy to help there as well!\n\nI hope this helps!\n\n========================================\n\nCode:\n```text\nBook {\n name: String!\n author: String!\n categories: [String!]\n}\n```\n\n```text\n\"mystery\"\n```\n\n```text\nallBooks(filter: {})\n```\n\n```text\ncategories_in: [\"mystery\"]\n```\n\n```text\ncategories_contains: \"mystery\"\n```\n\n```text\nquery {\n # query books by unique category tag\n Category(tag: MYSTERY) {\n books {\n id\n }\n }\n # query books by specific category text\n Category(filter: {\n text: \"mystery\"\n }) {\n books {\n id\n }\n }\n}\n```\n\n```text\nquery {\n allCategories(filter: {\n OR: [{\n tag: MYSTERY\n }, {\n tag: MAGIC\n }]\n }) {\n books {\n id\n }\n }\n}\n```\n\n```text\nquery {\n allCategories(filter: {\n AND: [{\n tag: MYSTERY\n }, {\n tag: MAGIC\n }]\n }) {\n books {\n id\n }\n }\n}\n```\n\n```text\nquery {\n allBooks(filter: {\n OR: [{\n categories_some: {\n tag: MYSTERY\n },\n categories_some: {\n tag: MAGIC\n }\n }]\n }) {\n id\n }\n}\n```\n\n```text\nCategory\n```\n\n```text\nCategory\n```\n\n```text\nCategory\n```\n\n```text\nCategory\n```\n\n```text\nBook\n```\n\n```text\ntag\n```\n\n```text\ntext\n```\n\n```text\ntag\n```\n\n```text\nCategory\n```\n\n```text\nquery MysteriousBooks($where:BookWhereArgs) {\n viewer {\n allBooks(where:$where) {\n edges { node { title, ... } }\n }\n }\n}\n\n# Variables\n{\n \"where\": {\n \"categories\": {\n \"contains\": \"mystery\"\n }\n }\n}\n```\n\n```text\nquery MysteriousBooks($where: CategoryWhereArgs) {\n viewer {\n allCategories(where: $where) {\n books {\n edges { node { title, ... } }\n }\n }\n }\n}\n\n# Variables\n{\n \"where\": { \n \"name\": { \n \"eq\": \"mystery\" \n } \n }\n}\n```\n\n```text\nWhereArgs\n```\n\n```text\ncontains\n```\n\n```text\nnotContains\n```\n\n```text\nCategory\n```\n\n```text\nCategory\n```\n\n```text\nBook\n```\n\n```text\nBook\n```\n\n========================================\n\nComments:\n- This is currently no supported on Graphcool. I have added a feature request to track this: github.com/graphcool/feature-requests/issues/60\n- Well, that's good to know. I'll go and +1 your issue. Let's hope we can get this soon!\n- A current workaround might be to introduce a new model `Category` with a many-to-many relation to `Book`. Then you can do this : `allCategories(filter: {tag: \"mystery\"}) { books { id } }`. I imagine having a `Category` model might be advantageous for future meta data or something like that anyway.\n- Unfortunately it doesn't really answer the question. I am trying to query shopify products and each product contains an array of tags, which are strings. I guess it is impossible to query for all products that contain a given tag?! Hmm. Solution: get all products and filter them on the client!","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":278,"estimatedTokens":1298}}84{"id":"stack-50389859","source":"stackoverflow","questionId":50389859,"title":"Difference between AWS Amplify & Apollo Client for GraphQL?","tags":["reactjs","graphql","apollo-client","aws-appsync","aws-amplify"],"text":"Title: Difference between AWS Amplify & Apollo Client for GraphQL?\nTags: reactjs, graphql, apollo-client, aws-appsync, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI agree Apollo Client is a pain to set up because of lots of boilerplate (although it becomes simple after reading the docs) & things like AWS Amplify, URQL, Apollo Boost & Micro GraphQL React makes it easy to work with GraphQL on the client.\n\nI am currently working with AWS AppSync & want to choose between AWS Amplify & Apollo Client & I was thinking of going in all AWS. \n\nSo what is the difference between AWS Amplify & Apollo Client?\n\n========================================\n\nComments:\n- Is that it or anything else? I mean I get it, Amplify is made to work with AWS so it will handle all that but I think there is a SDK which if you connect with Apollo, it will do all the things you mentioned. Can you elaborate if you have more points to mention?\n- The Apollo client also currently has caching capabilities and the AppSync SDK for Apollo will let you do offline programming as well. Depending on your use case, if you don't need all of the features offered by Apollo it might be easier to use Amplify.\n- Apollo is faster than Amplify (tested for serverless application that uses a Node12 Lambda). So if time is critical for your application and you are dealing with a lot of data then you should go for Apollo.","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":17,"estimatedTokens":347}}85{"id":"stack-58636833","source":"stackoverflow","questionId":58636833,"title":"TypeError: String cannot represent value: graphql Query not working","tags":["node.js","graphql","apollo"],"text":"Title: TypeError: String cannot represent value: graphql Query not working\nTags: node.js, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI am trying to run a graphql Query but it keeps giving me the \"TypeError: String cannot represent value:\" error.\n\nThe schema for my query:\n\n```\ntype User {\n active: Boolean!\n email: String!\n fullname: String!\n description: String!\n tags: [String!]!\n }\n\n type Query {\n getAllUsers: [User]!\n }\n```\n\nMy resolver:\n\n```\nQuery: {\n getAllUsers: (_, __, { dataSources }) => {\n return dataSources.userAPI.getAllUsers();\n }\n }\n```\n\nuserAPI:\n\n```\ngetAllUsers() {\n const params = {\n TableName: 'Users',\n Select: 'ALL_ATTRIBUTES'\n };\n\n return new Promise((resolve, reject) => {\n dynamodb.scan(params, function(err, data) {\n if (err) {\n console.log('Error: ', err);\n reject(err);\n } else {\n console.log('Success');\n resolve(data.Items);\n }\n });\n });\n }\n```\n\nThe query:\n\n```\nquery getAllUsers{\n getAllUsers{\n email\n }\n}\n```\n\nSince my email is a string, the error I'm getting is \"String cannot represent value\".\n\n========================================\n\nCode:\n```text\ntype User {\n active: Boolean!\n email: String!\n fullname: String!\n description: String!\n tags: [String!]!\n }\n\n type Query {\n getAllUsers: [User]!\n }\n```\n\n```text\nQuery: {\n getAllUsers: (_, __, { dataSources }) => {\n return dataSources.userAPI.getAllUsers();\n }\n }\n```\n\n```js\ngetAllUsers() {\n const params = {\n TableName: 'Users',\n Select: 'ALL_ATTRIBUTES'\n };\n\n return new Promise((resolve, reject) => {\n dynamodb.scan(params, function(err, data) {\n if (err) {\n console.log('Error: ', err);\n reject(err);\n } else {\n console.log('Success');\n resolve(data.Items);\n }\n });\n });\n }\n```\n\n```text\nquery getAllUsers{\n getAllUsers{\n email\n }\n}\n```\n\n```text\ntype User {\n active: Boolean!\n email: String!\n fullname: String!\n description: String!\n tags: [String!]!\n}\n```\n\n```text\n[{\n active: true,\n email: 'kaisinnn@li.com',\n fullname: 'Kaisin Li',\n description: 'Test',\n tags: ['SOME_TAG']\n}]\n```\n\n```text\n[{\n active: {\n BOOL: true\n },\n description: {\n S: 'Test'\n },\n fullname: {\n S: 'Kaisin Li'\n },\n email: {\n S: 'kaisinnn@li.com'\n },\n}]\n```\n\n```text\nconst resolvers = {\n User: {\n active: (user) => user.active.BOOL,\n description: (user) => user.description.S,\n // and so on\n }\n}\n```\n\n========================================\n\nComments:\n- input setInput { email: String! } getAllUsers(input: setInput): [User]\n- Please tell me what you want? are you want user object with condition like email address or other value\n- @MaheshBhatnagar I am expecting the query to return an array of the user emails. No need for an input as I'm trying to return all of them so I'm not setting any conditions\n- Please write that query query getAllUsers{ getAllUsers{ User[email] } }\n- that wouldnt work, can't include [] in queries. Now it's giving me syntax errors\n- ok i am checking\n- Please use that query getAllUsers{ getAllUsers{ User{email} } }\n- No, that wont work because it will be looking for the field User within my User type\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:32:36.025Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":181,"estimatedTokens":842}}86{"id":"stack-50905873","source":"stackoverflow","questionId":50905873,"title":"Apollo GraphQL Server + TypeScript","tags":["typescript","graphql","nodes","apollo","apollo-server"],"text":"Title: Apollo GraphQL Server + TypeScript\nTags: typescript, graphql, nodes, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI've been working on a project lately, which has node.js + express + typescript + Apollo server stack. And while researching on Apollo client, I've stumbled upon TypeScript section. But nothing like that was for server, which leaves me to freedom of choice in this case.\n\nSo the question is: are there any best practices on implementing Apollo graphql server with typescript or what should I avoid at least?\n\n========================================\n\nTop Answer:\nI am using a GraphQL CLI. You would install it like so\n\n```\nnpm install -g graphql-cli\n```\n\nthen generate your GraphQL project with TypeScript support \n\nhttps://i.sstatic.net/WAyRg.png\n\nMore information: https://oss.prisma.io/content/graphql-cli/05-Boilerplates.html\n\n========================================\n\nCode:\n```text\nbest practices\n```\n\n```text\napollo-server-express\n```\n\n```text\ngraphqlExpress\n```\n\n```text\ngraphiqlExpress\n```\n\n```text\nnpm install -g graphql-cli\n```\n\n```text\n@Type()\nclass Student {\n @Field(ID)\n id: string;\n\n @Field()\n name: string;\n\n @Field(String)\n friendNames: string[];\n\n @Field({ type: Int, nullable: true })\n room: number;\n\n @Field()\n gpa: number;\n\n @Field(Course)\n courses: Course[];\n}\n```\n\n```text\ntype-graphql + apollo-server-express\n```\n\n========================================\n\nComments:\n- Having head the same problem I found: typegraphql.ml . It solved all my problems and is so absolutely great to use. You define your Models with Decorators/Annotations and the framework does all the rest to keep it in sync. Its based on node+express+apollo+ts. Absolutely awesome.\n- Thanks for your reply! I get the server setup and implementation, but I'm looking for ways to use TypeScript more intensely. For example, in your app here: github.com/guloggratislabs/zendesk-graphql-api/blob/master/s‌​rc/… How can I reuse the interface to define GraphQL scheme and etc.\n- @naffiq Yeah, I get it. I'm afraid that is something that is not supported (yet?). For the clients you can generate interfaces based on the schema, but generate schema based on interfaces is not possible. We'll have to define GraphQLObjectType and Interface(is a bit annoying to repeat code).\n- discovered this little project github.com/19majkel94/type-graphql. Has great idea behind, but not ready for production though\n- Cool package, though it looks like t's used for frontend development, not the server. Am I right?\n- It based on graphql-yoga, a server. github.com/prismagraphql/graphql-yoga\n- I can wholeheartedly back this library. It's absolutely fantastic.","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":84,"estimatedTokens":673}}87{"id":"stack-45534453","source":"stackoverflow","questionId":45534453,"title":"Apollo-client (react) - Update on create mutation - \"Can't find field Fund({}) on object (ROOT_QUERY)\"","tags":["javascript","reactjs","graphql","react-apollo","apollo-client"],"text":"Title: Apollo-client (react) - Update on create mutation - \"Can't find field Fund({}) on object (ROOT_QUERY)\"\nTags: javascript, reactjs, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nUsing: \"react-apollo\": \"^1.4.3\"\n\nIn the parent component I query using GraphQL a parent node 'Fund' with children 'fundQuarterlyMetric'. This returns data in the following format:\n\n```\n{ \n id\n name\n ...\n fundQuarterlyMetrics (orderBy: asAtDate_ASC) {\n id\n year\n quarter\n ...\n }\n}\n```\n\nWhen I try to create a new fundQuarterlyMetrics I have to update the local store on react-apollo using the update feature (Apollo Client docs). It gives me an error:\n\n```\nCan't find field Fund({}) on object (ROOT_QUERY) {\n \"Fund({\\\"id\\\":\\\"cj57hpfips0x7014414u5tk8m\\\"})\": {\n \"type\": \"id\",\n \"id\": \"Fund:cj57hpfips0x7014414u5tk8m\",\n \"generated\": false\n }\n```\n\nThe thing is, is that when I console.log the proxy, I can see the Fund and it's children under data.... not sure what to do..\n\nUPDATE following comment:\n\nHere is the parent component data request:\n\n```\nexport const fundPageQuery = gql`\n query Fund($fundId: ID!) {\nFund(id: $fundId) {\n id\n name\n ....other variables\n fundQuarterlyMetrics (orderBy: asAtDate_ASC) {\n id\n year\n quarter\n ....other variables\n }\n}\n```\n\n}\n `;\n\nHere are the options I used:\n\n```\nvar optionsForCreateFundMetric = {\n update: (proxy, {data: {createFundMetrics}}) => {\n try {\n console.log('proxy', proxy);\n const data = proxy.readQuery({query: FundQL.fundPageQuery});\n console.log('data', data);\n data.Fund.fundQuarterlyMetrics.push(createFundMetrics);\n proxy.writeQuery({query: FundQL.fundPageQuery, data})\n} catch (e) {\n console.log('error adding to store', e);\n}\n```\n\n}\n };\n\n```\nexport default compose(\n graphql(FundQL.createFundMetrics, {name: 'createFundMetrics', options: \n optionsForCreateFundMetric}),\n graphql(FundQL.updateFundMetrics, {name: 'updateFundMetrics'})\n )(FundMetricsForm);\n```\n\nHere is my create mutation:\n\n```\nexport const createFundMetrics = gql`\n mutation createFundQuarterlyMetric(\n$fundId: ID\n$year: Int!\n$quarter: FUND_QUARTERLY_METRIC_QUARTER!\n$netIRR: Float!\n$tvpi: Float!\n$rvpi: Float!\n$dpi: Float!\n$asAtDate: DateTime\n$calledThisQuarter: Float!\n$distributedThisQuarter: Float!\n$cumulativeCalled: Float!\n$cumulativeDistributed: Float!\n$limitedPartnersNAV: Float!\n$quarterlyValuationChangeLCY: Float\n$quarterlyTotalReturn: Float\n ) {\ncreateFundQuarterlyMetric(\n fundId: $fundId\n year: $year\n quarter: $quarter\n netIRR: $netIRR\n tvpi: $tvpi\n rvpi: $rvpi\n dpi: $dpi\n asAtDate: $asAtDate\n calledThisQuarter: $calledThisQuarter\n distributedThisQuarter: $distributedThisQuarter\n cumulativeCalled: $cumulativeCalled\n cumulativeDistributed: $cumulativeDistributed\n limitedPartnersNAV: $limitedPartnersNAV\n quarterlyValuationChangeLCY: $quarterlyValuationChangeLCY\n quarterlyTotalReturn: $quarterlyTotalReturn\n) {\n id\n year\n quarter\n netIRR\n tvpi\n rvpi\n dpi\n asAtDate\n calledThisQuarter\n distributedThisQuarter\n cumulativeCalled\n cumulativeDistributed\n limitedPartnersNAV\n quarterlyValuationChangeLCY\n quarterlyTotalReturn\n}\n```\n\n}\n`;\n\nSOLUTION\nThanks Daniel - I had to return the fund ID to make it work so thank you!\n\n```\nexport default compose(\n graphql(FundQL.createFundMetrics, {name: 'createFundMetrics', options: \noptionsForCreateFundMetric, variables: {fundId: \ncreateFundQuarterlyMetric.fund.id}}),\n graphql(FundQL.updateFundMetrics, {name: 'updateFundMetrics'})\n )(FundMetricsForm);\n```\n\n========================================\n\nCode:\n```text\n{ \n id\n name\n ...\n fundQuarterlyMetrics (orderBy: asAtDate_ASC) {\n id\n year\n quarter\n ...\n }\n}\n```\n\n```text\nCan't find field Fund({}) on object (ROOT_QUERY) {\n \"Fund({\\\"id\\\":\\\"cj57hpfips0x7014414u5tk8m\\\"})\": {\n \"type\": \"id\",\n \"id\": \"Fund:cj57hpfips0x7014414u5tk8m\",\n \"generated\": false\n }\n```\n\n```text\nexport const fundPageQuery = gql`\n query Fund($fundId: ID!) {\nFund(id: $fundId) {\n id\n name\n ....other variables\n fundQuarterlyMetrics (orderBy: asAtDate_ASC) {\n id\n year\n quarter\n ....other variables\n }\n}\n```\n\n```text\nvar optionsForCreateFundMetric = {\n update: (proxy, {data: {createFundMetrics}}) => {\n try {\n console.log('proxy', proxy);\n const data = proxy.readQuery({query: FundQL.fundPageQuery});\n console.log('data', data);\n data.Fund.fundQuarterlyMetrics.push(createFundMetrics);\n proxy.writeQuery({query: FundQL.fundPageQuery, data})\n} catch (e) {\n console.log('error adding to store', e);\n}\n```\n\n```text\nexport default compose(\n graphql(FundQL.createFundMetrics, {name: 'createFundMetrics', options: \n optionsForCreateFundMetric}),\n graphql(FundQL.updateFundMetrics, {name: 'updateFundMetrics'})\n )(FundMetricsForm);\n```\n\n```text\nexport const createFundMetrics = gql`\n mutation createFundQuarterlyMetric(\n$fundId: ID\n$year: Int!\n$quarter: FUND_QUARTERLY_METRIC_QUARTER!\n$netIRR: Float!\n$tvpi: Float!\n$rvpi: Float!\n$dpi: Float!\n$asAtDate: DateTime\n$calledThisQuarter: Float!\n$distributedThisQuarter: Float!\n$cumulativeCalled: Float!\n$cumulativeDistributed: Float!\n$limitedPartnersNAV: Float!\n$quarterlyValuationChangeLCY: Float\n$quarterlyTotalReturn: Float\n ) {\ncreateFundQuarterlyMetric(\n fundId: $fundId\n year: $year\n quarter: $quarter\n netIRR: $netIRR\n tvpi: $tvpi\n rvpi: $rvpi\n dpi: $dpi\n asAtDate: $asAtDate\n calledThisQuarter: $calledThisQuarter\n distributedThisQuarter: $distributedThisQuarter\n cumulativeCalled: $cumulativeCalled\n cumulativeDistributed: $cumulativeDistributed\n limitedPartnersNAV: $limitedPartnersNAV\n quarterlyValuationChangeLCY: $quarterlyValuationChangeLCY\n quarterlyTotalReturn: $quarterlyTotalReturn\n) {\n id\n year\n quarter\n netIRR\n tvpi\n rvpi\n dpi\n asAtDate\n calledThisQuarter\n distributedThisQuarter\n cumulativeCalled\n cumulativeDistributed\n limitedPartnersNAV\n quarterlyValuationChangeLCY\n quarterlyTotalReturn\n}\n```\n\n```text\nexport default compose(\n graphql(FundQL.createFundMetrics, {name: 'createFundMetrics', options: \noptionsForCreateFundMetric, variables: {fundId: \ncreateFundQuarterlyMetric.fund.id}}),\n graphql(FundQL.updateFundMetrics, {name: 'updateFundMetrics'})\n )(FundMetricsForm);\n```\n\n```text\nconst data = proxy.readQuery({\n query: FundQL.fundPageQuery,\n variables: { id: createFundMetrics.id },\n});\n```\n\n```text\nreadQuery\n```\n\n========================================\n\nComments:\n- It sounds like there's a problem with the way you're executing your mutation through Apollo -- you shouldn't be seeing errors about your root query if you're dealing with mutations. Please update your question to include your code, particularly where you define your graphql HOC and any relevant logic (like your call to `update`).\n- Thanks Dan for your comment. I've added the code to the question\n- Thanks Daniel - that worked so I had to return the fund ID to make it work -> {fundId: createFundQuarterlyMetric.fund.id} and it worked! Thank you so much!\n- @Blackstone4 No problem, glad you got it working :) You can still just accept that as the correct answer\n- I've tried to correct this poor job with this PR/\n- It seems to me that the mutation should return as many fields as the initial query. The field can actually be missing, because the mutation doesn't return enough information for updating the queries. Solution would be to add missing fields to the mutation expected result.","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":304,"estimatedTokens":1832}}88{"id":"stack-60853978","source":"stackoverflow","questionId":60853978,"title":"How to Filter List/Queries With AND/OR operators AWS Amplify JavaScript GraphQL","tags":["react-native","graphql","aws-amplify","graphql-js","aws-amplify-cli"],"text":"Title: How to Filter List/Queries With AND/OR operators AWS Amplify JavaScript GraphQL\nTags: react-native, graphql, aws-amplify, graphql-js, aws-amplify-cli\nSource: Stack Overflow\n\nQuestion:\nI am new to using AWS Amplify and GraphQL.\nAlso just started building out React Native App - which is a lot of fun! \n\nI have a table called TimePeriods schema for it looks like this\n\n```\ntype TimePeriod @model {\n id: ID!\n name: String!\n startYear: String!\n endYear: String!,\n artworks: [ArtWorkTimePeriod] @connection (name: \"TimePeriodArtWorks\") #Many to Many Relationship\n artists: [ArtistTimePeriod] @connection (name: \"TimePeriodArtists\") #Many to Many Relationship\n}\n```\n\nIn the queries file generated by amplify I have a function called listTimePeriods. \n\n```\nexport const listTimePeriods = /* GraphQL */ `\n query ListTimePeriods(\n $filter: ModelTimePeriodFilterInput\n $limit: Int\n $nextToken: String\n ) {\n listTimePeriods(filter: $filter, limit: $limit, nextToken: $nextToken) {\n items {\n id\n name\n startYear\n endYear\n artworks {\n nextToken\n }\n artists {\n nextToken\n }\n }\n nextToken\n }\n }\n`;\n```\n\nWhat I am trying to do is filter this by condition for example I'd like to get list of all Time Periods where IDs equal 1, 2 or 3. \nI was assuming it could be done in a following manner\n\n```\nexport async function GetTimePeriodsByIds(idArr=[]){\n let filter = {\n id: {\n eq: [1,2,3]\n }\n };\n return await API.graphql(graphqlOperation(listTimePeriods, {limit: 20, filter:filter}));\n}\n```\n\nbut I do not think you can do that. If you have any kinds of solution regarding this, it would mean a lot - even just the insight like\n\n- If it does not work at all - is there any reason why they decided not to implement it?\nWould it be better in the case to use a for loop and call \n\nawait API.graphql(graphqlOperation(getTimePeriod, {id: id}));\n\nor would it be better to get the whole list and filter it out myself? And by better I mean efficiency - maybe it depends on the number of data that will be listed in the TimePeriod table (if many entries then get one by one from DB, if small number of entries get all and filter it out?)\n\n========================================\n\nTop Answer:\nYou can create a helper function similar to the following:\n\n```\nconst searchArray = [1,2,3,4,5]\nlet fieldName = \"id\";\n \nlet filterMembers = searchArray.map((item)=> JSON.parse(`{\"${fieldName}\":{\"eq\":${item}}}`));\nlet filter = {or:filterMembers};\n```\n\nand use the filter object in as a query parameter.\n\n========================================\n\nCode:\n```text\ntype TimePeriod @model {\n id: ID!\n name: String!\n startYear: String!\n endYear: String!,\n artworks: [ArtWorkTimePeriod] @connection (name: \"TimePeriodArtWorks\") #Many to Many Relationship\n artists: [ArtistTimePeriod] @connection (name: \"TimePeriodArtists\") #Many to Many Relationship\n}\n```\n\n```text\nexport const listTimePeriods = /* GraphQL */ `\n query ListTimePeriods(\n $filter: ModelTimePeriodFilterInput\n $limit: Int\n $nextToken: String\n ) {\n listTimePeriods(filter: $filter, limit: $limit, nextToken: $nextToken) {\n items {\n id\n name\n startYear\n endYear\n artworks {\n nextToken\n }\n artists {\n nextToken\n }\n }\n nextToken\n }\n }\n`;\n```\n\n```text\nexport async function GetTimePeriodsByIds(idArr=[]){\n let filter = {\n id: {\n eq: [1,2,3]\n }\n };\n return await API.graphql(graphqlOperation(listTimePeriods, {limit: 20, filter:filter}));\n}\n```\n\n```text\nlet filter = {\n or: [\n {\n id: {eq:1}\n },\n {\n id: {eq:2}\n }]\n };\nreturn await API.graphql(graphqlOperation(listTimePeriods, {limit: 20, filter:filter}));\n```\n\n```text\ninput ModelTimePeriodFilterInput {\n id: ModelIDInput\n name: ModelStringInput\n startYear: ModelStringInput\n endYear: ModelStringInput\n and: [ModelTimePeriodFilterInput]\n or: [ModelTimePeriodFilterInput]\n not: ModelTimePeriodFilterInput\n}\n```\n\n```js\nconst searchArray = [1,2,3,4,5]\nlet fieldName = \"id\";\n \nlet filterMembers = searchArray.map((item)=> JSON.parse(`{\"${fieldName}\":{\"eq\":${item}}}`));\nlet filter = {or:filterMembers};\n```\n\n========================================\n\nComments:\n- The official docs for filtering are here: docs.amplify.aws/lib/graphqlapi/query-data/q/platform/…\n- Wouldn't using `filter = { id: { in: [1, 2] } }` work? Using the IN operator I mean...","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":176,"estimatedTokens":1124}}89{"id":"stack-43983286","source":"stackoverflow","questionId":43983286,"title":"GraphQL and Microservices","tags":["rest","architecture","microservices","graphql"],"text":"Title: GraphQL and Microservices\nTags: rest, architecture, microservices, graphql\nSource: Stack Overflow\n\nQuestion:\nAt my company we've decided on a microservice architecture for a new project.\nWe've taken a look at GraphQL and realised its potential and advantages for using as our single API endpoint.\n\nWhat we disagree on is how the communication should be done between GraphQL and each micro service. Some argue for REST, others say we should also have a graphQL endpoint for each service. \n\nI was wondering what are some of the pros and cons of each.\nFor example, having everything in graphQL seems a bit redundant, as we'd be replicating parts of the schema in each service.\nOn the other hand, we're using GraphQL to avoid some REST pitfalls. We're afraid having REST endpoints will nullify the advantages gained from gQL.\n\nHas anyone come across a similar dilemma?\nNone of us are experienced with GraphQL, so is there some obvious pro and con here that we might be missing?\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nMy company has been using GraphQL in production for about a year. Maintaining the schemas in our \"Platform API\" and also in our microservices became arduous. Developers kept asking us why they needed to do double work and what the benefit was. Especially since we required in-depth code reviews to change/update the production GraphQL schema\n\nApollo GraphQL released schema stitching which has solved most of the problems we were having. Essentially individual microservices each maintain their own GraphQL endpoint, then our Node.js Platform API stitches them all together. The resulting API is a client developer's dream, and the backend developers get the level of autonomy about their code they're used to. I highly recommend trying schema stitching. We've been adopting it incrementally for a few months and it's been wonderful.\n\nAs an added benefit, while defining our sub-schemas we started decoupling certain microservices, instead relying on the stitched data extensions to fill in holes in objects. Feels like the missing piece in DDD\n\n========================================\n\nCode:\n```text\nimport request from 'request';\n\n// GraphQL resolver to get authors\nconst resolverMap = {\n Query: {\n author(obj, args, context, info) {\n // GET request to fetch authors from my microservice\n return request.get('https://example.com/my-authors-microservice');\n },\n },\n};\n```\n\n========================================\n\nComments:\n- There's something about questions about GraphQL and software architecture that seems to invite the use of h1 titles and multiple sections. I know I have answered that invitation :-)\n- question i have been doing a lot research regarding this, and the thing that keeps me wonder is, if we have a service acting as some sort of gateway with graphql, wont this make it a synchronous service? Or are you saying that graphql service should only connect synchronously with services that are public?","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":50,"estimatedTokens":749}}90{"id":"stack-67045344","source":"stackoverflow","questionId":67045344,"title":"Unable to resolve signature of property decorator when called as an expression","tags":["typescript","graphql","typegraphql","class-validator"],"text":"Title: Unable to resolve signature of property decorator when called as an expression\nTags: typescript, graphql, typegraphql, class-validator\nSource: Stack Overflow\n\nQuestion:\n```\nimport { isEmail, isEmpty, isPhoneNumber, Length } from \"class-validator\"\nimport { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class RegisterInput {\n @Field()\n @Length(2, 15, { message: \"Username Must Be At Least 2 characters\" })\n username?: string;\n\n @Field()\n @isEmail()\n email?: string;\n\n @Field()\n @Length(1, 20)\n @isPhoneNumber()\n phoneNumber?: string;\n\n @isEmpty()\n password?: string\n\n}\n```\n\nThe thing is @isEmail() and @isPhoneNumber() and @isEmpty() throw the same error:\n\n```\nUnable to resolve signature of property decorator when called as an expression.\n This expression is not callable.\n Type 'Boolean' has no call signatures.ts(1240)\n```\n\nPlease help me out I've been stuck with this bug the whole day\n\n========================================\n\nTop Answer:\nYou might need to add this property to your `tsconfig.json` file, under the `compilerOptions` property:\n\n```\n\"experimentalDecorators\": true\n```\n\nKudos to Technical Rajni for the youtube video solution, here.\n\n========================================\n\nCode:\n```text\nimport { isEmail, isEmpty, isPhoneNumber, Length } from \"class-validator\"\nimport { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class RegisterInput {\n @Field()\n @Length(2, 15, { message: \"Username Must Be At Least 2 characters\" })\n username?: string;\n\n @Field()\n @isEmail()\n email?: string;\n\n @Field()\n @Length(1, 20)\n @isPhoneNumber()\n phoneNumber?: string;\n\n @isEmpty()\n password?: string\n\n}\n```\n\n```text\nUnable to resolve signature of property decorator when called as an expression.\n This expression is not callable.\n Type 'Boolean' has no call signatures.ts(1240)\n```\n\n```text\nimport { IsEmail, IsEmpty, IsPhoneNumber, Length } from \"class-validator\";\n\n@Field()\n@IsEmail()\nemail?: string;\n\n@Field()\n@Length(1, 20)\n@IsPhoneNumber()\nphoneNumber?: string;\n\n@IsEmpty()\npassword?: string\n```\n\n```text\n.js\n```\n\n```text\n()\n```\n\n```text\n@InputType()\n```\n\n```text\n@InputType\n```\n\n```text\n@minimumValue(\"quantity\", 5);\nasync getItems(): Promise<Item[]> {\n...\n```\n\n```text\n@minimumValue(\"quantity\", 5)\nasync getItems(): Promise<Item[]> {\n...\n```\n\n```text\n;\n```\n\n```text\nTS1240: Unable to resolve signature of property decorator when called as an expression.\n```\n\n```text\n;\n```\n\n```text\n\"experimentalDecorators\": true\n```\n\n```text\ntsconfig.json\n```\n\n```text\ncompilerOptions\n```\n\n```json\n\"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true\n```\n\n========================================\n\nComments:\n- oh god, i feel so dumb. Thank you though !\n- Nevermind, I don't know anyone who did not run in such self made problems. π You're welcome. π\n- This worked for `@Entity()` decorator too. Thanks!\n- It has worked for me without removing node_modules","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":165,"estimatedTokens":735}}91{"id":"stack-51269168","source":"stackoverflow","questionId":51269168,"title":"How to use GraphQL fragment on multiple types","tags":["graphql","dry","gatsby","contentful"],"text":"Title: How to use GraphQL fragment on multiple types\nTags: graphql, dry, gatsby, contentful\nSource: Stack Overflow\n\nQuestion:\nI have a Gatsby project with very similar GraphQL queries for two different types of content: regular pages and wiki articles.\n\n**Page by slug**\n\n```\nexport const query = graphql`\n query($slug: String!) {\n page: contentfulPage(slug: {eq: $slug}) {\n title\n slug\n body {\n remark: childMarkdownRemark {\n excerpt\n html\n headings {\n value\n depth\n }\n }\n }\n updatedAt(formatString: \"D. MMM YYYY\")\n authors {\n name\n email\n }\n }\n }\n`\n```\n\n**Wiki article by slug**\n\n```\nexport const query = graphql`\n query($slug: String!) {\n article: contentfulWikiArticle(slug: {eq: $slug}) {\n title\n slug\n body {\n remark: childMarkdownRemark {\n excerpt\n html\n headings {\n value\n depth\n }\n }\n }\n updatedAt(formatString: \"D. MMM YYYY\")\n authors {\n name\n email\n }\n + section {\n + title\n + slug\n + }\n + subsection {\n + title\n + slug\n + }\n }\n }\n`\n```\n\nExcept for the additional section and subsection for wiki articles, the queries are identical. To keep things DRY, how can I move the page fields into a separate fragment that can also be spread into the wiki article query despite being of different type? Could GraphQL provide something like:\n\n```\nfragment pageFields on [ContenfulPage, ContenfulWikiArticle] {\n ...\n}\n```\n\n========================================\n\nCode:\n```text\nexport const query = graphql`\n query($slug: String!) {\n page: contentfulPage(slug: {eq: $slug}) {\n title\n slug\n body {\n remark: childMarkdownRemark {\n excerpt\n html\n headings {\n value\n depth\n }\n }\n }\n updatedAt(formatString: \"D. MMM YYYY\")\n authors {\n name\n email\n }\n }\n }\n`\n```\n\n```text\nexport const query = graphql`\n query($slug: String!) {\n article: contentfulWikiArticle(slug: {eq: $slug}) {\n title\n slug\n body {\n remark: childMarkdownRemark {\n excerpt\n html\n headings {\n value\n depth\n }\n }\n }\n updatedAt(formatString: \"D. MMM YYYY\")\n authors {\n name\n email\n }\n + section {\n + title\n + slug\n + }\n + subsection {\n + title\n + slug\n + }\n }\n }\n`\n```\n\n```text\nfragment pageFields on [ContenfulPage, ContenfulWikiArticle] {\n ...\n}\n```\n\n```text\njsonFolder\n |--one.json { \"type\": \"One\", \"name\": \"a\", \"food\": \"pizza\" }\n `--two.json { \"type\": \"Two\", \"name\": \"b\", \"game\": \"chess\" }\n```\n\n```text\n{\n resolve: `gatsby-transformer-json`,\n options: { \n typeName: ({ object }) => object.type,\n },\n},\n```\n\n```text\nexport const name = graphql`\n fragment name on One {\n name\n }\n`\n\nexport const pageQuery = graphql`\n query {\n one {\n ...name\n }\n two {\n ...name <-- β οΈ throw type error\n }\n }\n`\n```\n\n```text\nexports.sourceNodes = ({ actions }) => {\n const { createTypes } = actions\n const typeDefs = `\n interface JsonNode {\n name: String\n type: String!\n }\n\n type One implements Node & JsonNode {\n name: String\n type: String!\n food: String\n }\n\n type Two implements Node & JsonNode {\n name: String\n type: String!\n game: String\n }\n `\n createTypes(typeDefs)\n}\n```\n\n```text\ntype One implements Node & JsonNode { ... }\n```\n\n```text\n// blogPostTemplate.js\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\n\nexport default ({ data }) => <div>{JSON.Stringify(data)}</div>\n\nexport const name = graphql`\n fragment name on JsonNode {\n name\n level\n }\n`\n\nexport const pageQuery = graphql`\n query {\n one {\n ...name <- π works\n }\n two {\n ...name <- π works\n }\n }\n`\n```\n\n```text\ngatsby-transformer-json\n```\n\n```text\ncreateTypes\n```\n\n```text\nJsonNode\n```\n\n```text\nOne\n```\n\n```text\nTwo\n```\n\n```text\nOne\n```\n\n```text\nTwo\n```\n\n```text\nJsonNode\n```\n\n```text\nNode\n```\n\n```text\nJsonNode\n```\n\n========================================\n\nComments:\n- Great question I have a similar question ? Did you figure this out.\n- @me-me Not yet, Iβm afraid.\n- Not sure if you resolved, It's hard to explain but If I saw the source I would be able to answer in a well formatted way but consider making a \"TemplateWrapper Component\" From layout.js in the components folder and making a \"LayoutfFagment\" for Contentful fields you are building in components then declared shared data or fields that is repeated null then on export the query and filter the shared data or fields. there is a few more steps after this like I side reach out if you are still stuck.\n- @NickC Thanks for your comment but what I'm really asking is if GraphQL provides a native way to do this. I don't quite understand what you're suggesting but it sounds a little hacky.\n- Using Apollo would \"natively\" accomplish this\n- Very cool! Like you said, quite some setup so thanks for this detailed answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":286,"estimatedTokens":1232}}92{"id":"stack-48285888","source":"stackoverflow","questionId":48285888,"title":"Github GraphQL - Getting a repository's list of commits","tags":["github","graphql","github-api","github-graphql"],"text":"Title: Github GraphQL - Getting a repository's list of commits\nTags: github, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI am using GraphQL to get some data from a list of repositories using Github's GraphQL (v4) API. I want to get a list of the **latest commits** from a repository, no matter what is the commit's branch/tag/ref.\n\nFor now I am doing the following to get the list of commits from a certain repository:\n\n```\n... on Repository{\n refs(refPrefix:\"refs/\",orderBy:$refOrder,first:1){\n edges{\n node{\n ... on Ref{\n target{\n ... on Commit{\n history(first:10){\n totalCount\n edges{\n node{\n ... on Commit{\n committedDate\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\nWhere `$refOrder` is an object I am sending together with the request and it is defined below:\n\n```\n{\n \"refOrder\": {\n \"direction\": \"DESC\",\n \"field\": \"TAG_COMMIT_DATE\"\n }\n}\n```\n\nThis piece of code is working, but not retrieving the results I want. The response comes back with a list of commits, **but not necessarily the last commits from the repository**. When I go to the repository page and click on \"Commits\", I usually see a list of commits that are more recent than what I got as results from my API call.\n\nWhat am I missing? Should I try a different `refPrefix` or `orderBy` argument? I have already tried \"master\" as the `refPrefix`, but faced the same problem.\n\n========================================\n\nTop Answer:\nIf you are also interested in getting the latest commits for all branches (not just the default branch), you can request reference with prefix `refs/heads/` :\n\n```\n{\n repository(owner: \"bertrandmartel\", name: \"callflow-workshop\") {\n refs(refPrefix: \"refs/heads/\", orderBy: {direction: DESC, field: TAG_COMMIT_DATE}, first: 100) {\n edges {\n node {\n ... on Ref {\n name\n target {\n ... on Commit {\n history(first: 2) {\n edges {\n node {\n ... on Commit {\n committedDate\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\nIn your case using `refs/` also gave you tag ref.\n\nTry it in the explorer\n\n========================================\n\nCode:\n```graphql\n... on Repository{\n refs(refPrefix:\"refs/\",orderBy:$refOrder,first:1){\n edges{\n node{\n ... on Ref{\n target{\n ... on Commit{\n history(first:10){\n totalCount\n edges{\n node{\n ... on Commit{\n committedDate\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```json\n{\n \"refOrder\": {\n \"direction\": \"DESC\",\n \"field\": \"TAG_COMMIT_DATE\"\n }\n}\n```\n\n```text\n$refOrder\n```\n\n```text\nrefPrefix\n```\n\n```text\norderBy\n```\n\n```text\nrefPrefix\n```\n\n```graphql\n... on Repository{\n defaultBranchRef{\n target{\n ... on Commit{\n history(first:10){\n edges{\n node{\n ... on Commit{\n committedDate\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nRepository\n```\n\n```text\ndefaultBranchRef\n```\n\n```graphql\n{\n repository(owner: \"bertrandmartel\", name: \"callflow-workshop\") {\n refs(refPrefix: \"refs/heads/\", orderBy: {direction: DESC, field: TAG_COMMIT_DATE}, first: 100) {\n edges {\n node {\n ... on Ref {\n name\n target {\n ... on Commit {\n history(first: 2) {\n edges {\n node {\n ... on Commit {\n committedDate\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nrefs/heads/\n```\n\n```text\nrefs/\n```\n\n========================================\n\nComments:\n- Learned so much in the last few days about GraphQL that I summarized my endeavor with a post on Medium: medium.com/@fabiomolinar/…\n- can you please tell me what would be the base URL for this?\n- @anjujo For the Github GQL API? If so, here it is: api.github.com/graphql\n- The request is blocked in the link.\n- Repository doesn't have a `refs` field...?\n- @detly the missing refs tag/field could be because your link refers to gitlab and not github.","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":218,"estimatedTokens":1156}}93{"id":"stack-61495727","source":"stackoverflow","questionId":61495727,"title":"Setting Apollo client header dynamically is not working","tags":["javascript","react-native","graphql"],"text":"Title: Setting Apollo client header dynamically is not working\nTags: javascript, react-native, graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to set the header of Apollo client dynamically according to official doc, but I am getting an error:\n\n```\nTypeError: (0 , _apollo.default) is not a function\n```\n\nThis is my **apollo.js**\n\n```\nimport { ApolloClient } from 'apollo-client';\nimport { createHttpLink } from 'apollo-link-http';\nimport { setContext } from 'apollo-link-context';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { AsyncStorage } from 'react-native';\n\nconst httpLink = createHttpLink({\n uri: 'http://192.168.2.4:8000/api/',\n});\n\nconst authLink = setContext((_, { headers }) => {\n const token = AsyncStorage.getItem('token');\n\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n});\n\nexport default client;\n```\n\n**UPDATE**\n\nI am adding **App.js**:\n\n```\nimport { ApolloProvider } from 'react-apollo';\nimport Routes from './app/config/routes';\nimport makeApolloClient from './app/config/apollo';\n\nexport default function App() {\n const client = makeApolloClient();\n\n return (\n \n \n );\n}\n```\n\nHow can I solve this issue?\n\n========================================\n\nTop Answer:\nApollo usequery has a context option that allows you to dynamically change or update the values of the header object.\n\n```\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n cache: new InMemoryCache(),\n uri: \"/graphql\"\n});\n\nclient.query({\n query: MY_QUERY,\n context: {\n // example of setting the headers with context per operation\n headers: {\n special: \"Special header value\"\n }\n }\n});\n```\n\nThe code above was copied from the Apollo docs.\nTo find out more check out https://www.apollographql.com/docs/react/networking/advanced-http-networking/#overriding-options\n\n========================================\n\nCode:\n```sh\nTypeError: (0 , _apollo.default) is not a function\n```\n\n```js\nimport { ApolloClient } from 'apollo-client';\nimport { createHttpLink } from 'apollo-link-http';\nimport { setContext } from 'apollo-link-context';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { AsyncStorage } from 'react-native';\n\nconst httpLink = createHttpLink({\n uri: 'http://192.168.2.4:8000/api/',\n});\n\nconst authLink = setContext((_, { headers }) => {\n const token = AsyncStorage.getItem('token');\n\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n});\n\nexport default client;\n```\n\n```text\nimport { ApolloProvider } from 'react-apollo';\nimport Routes from './app/config/routes';\nimport makeApolloClient from './app/config/apollo';\n\nexport default function App() {\n const client = makeApolloClient();\n\n return (\n <ApolloProvider client={client}>\n <Routes />\n </ApolloProvider>);\n}\n```\n\n```text\nimport client from './app/config/apollo'\n\nexport default function App() {\n return (\n <ApolloProvider client={client}>\n <Routes />\n </ApolloProvider>\n );\n}\n```\n\n```js\nconst authLink = setContext(async (_, { headers }) => {\n const token = await AsyncStorage.getItem('token');\n\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n```\n\n```text\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n cache: new InMemoryCache(),\n uri: \"/graphql\"\n});\n\nclient.query({\n query: MY_QUERY,\n context: {\n // example of setting the headers with context per operation\n headers: {\n special: \"Special header value\"\n }\n }\n});\n```\n\n```text\nimport {ApolloClient, createHttpLink} from \"@apollo/client\";\nimport {setContext} from \"@apollo/client/link/context\";\nimport {InMemoryCache} from \"@apollo/client\";\n\nconst apolloHttpLink = createHttpLink({\n uri: process.env.REACT_APP_APOLLO_SERVER_URI || 'http://localhost/graphql',\n})\n\nconst apolloAuthContext = setContext(async (_, {headers}) => {\n const jwt_token = localStorage.getItem('jwt_token')\n return {\n headers: {\n ...headers,\n Authorization: jwt_token ? `Bearer ${jwt_token}` : ''\n },\n }\n})\n\nexport const apolloClient = new ApolloClient({\n link: apolloAuthContext.concat(apolloHttpLink),\n cache: new InMemoryCache(),\n})\n```\n\n```text\nlocalStorage.setItem('jwt_token', jwt_token)\n```\n\n========================================\n\nComments:\n- It looks like it is not possible to place async in front of setContext, because now I get error: `Error: TransformError SyntaxError:../apollo.js: Unexpected token, expected \"=>\" (11:33)`\n- Updated answer please check.\n- Now error is again `TypeError: (0 , _apollo.default) is not a function`\n- const token = await AsyncStorage.getItem('@token');I am getting value null after login\n- This header setting is done in `App` component. Is there any way to set in another screen or component ? Dynamically ?\n- this is not working for me\n- I'd love this to work as well, but it doesn't work for me either.","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":226,"estimatedTokens":1324}}94{"id":"stack-53078554","source":"stackoverflow","questionId":53078554,"title":"How to implement isTypeOf method?","tags":["node.js","typescript","express","graphql","express-graphql"],"text":"Title: How to implement isTypeOf method?\nTags: node.js, typescript, express, graphql, express-graphql\nSource: Stack Overflow\n\nQuestion:\nGiven this schema:\n\n```\ninterface INode {\n id: ID\n}\n\ntype Todo implements INode {\n id: ID\n title: String!\n}\n\ntype Query {\n node(id: ID!): INode\n}\n```\n\nGiven this class:\n\n```\nexport default class Todo {\n constructor (public id: string, public title: string) { }\n\n isTypeOf(value: any): Boolean {\n return value instanceof Todo;\n }\n}\n```\n\nGiven this resolver:\n\n```\ntype NodeArgs = {\n id: string\n}\nexport const resolver = {\n node: ({ id }: NodeArgs) => {\n return new Todo('1', 'Todo 1');\n }\n}\n```\n\nWhen I call the query: \n\n```\nquery {\n node(id: \"1\") {\n id\n ... on Todo {\n title\n }\n }\n}\n```\n\nThen I get the return below:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Abstract type INode must resolve to an Object type at runtime for field Query.node with value { id: \\\"1\\\", title: \\\"Todo 1\\\" }, received \\\"undefined\\\". Either the INode type should provide a \\\"resolveType\\\" function or each possible type should provide an \\\"isTypeOf\\\" function.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"node\"\n ]\n }\n ],\n \"data\": {\n \"node\": null\n }\n}\n```\n\nAs you can see, I've implemented the `isTypeOf` function but I am still getting the error message.\n\nWhat am I doing wrong?\n\nNotes:\n\n- I am using Typescript, express and express-graphql;\n\n========================================\n\nCode:\n```text\ninterface INode {\n id: ID\n}\n\ntype Todo implements INode {\n id: ID\n title: String!\n}\n\ntype Query {\n node(id: ID!): INode\n}\n```\n\n```text\nexport default class Todo {\n constructor (public id: string, public title: string) { }\n\n isTypeOf(value: any): Boolean {\n return value instanceof Todo;\n }\n}\n```\n\n```text\ntype NodeArgs = {\n id: string\n}\nexport const resolver = {\n node: ({ id }: NodeArgs) => {\n return new Todo('1', 'Todo 1');\n }\n}\n```\n\n```text\nquery {\n node(id: \"1\") {\n id\n ... on Todo {\n title\n }\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Abstract type INode must resolve to an Object type at runtime for field Query.node with value { id: \\\"1\\\", title: \\\"Todo 1\\\" }, received \\\"undefined\\\". Either the INode type should provide a \\\"resolveType\\\" function or each possible type should provide an \\\"isTypeOf\\\" function.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"node\"\n ]\n }\n ],\n \"data\": {\n \"node\": null\n }\n}\n```\n\n```text\nisTypeOf\n```\n\n```text\nexport default class Todo {\n get __typename() {\n return 'Todo'\n }\n}\n```\n\n```text\nconst resolvers = {\n Query: {\n node: (obj, args, context, info) => {\n return new Todo('1', 'Todo 1')\n }\n },\n INode: {\n __resolveType: (obj, context, info) => {\n if (obj instanceof Todo) return 'Todo'\n },\n }\n}\n```\n\n```text\nconst resolvers = {\n Query: {\n node: (obj, args, context, info) => {\n return new Todo('1', 'Todo 1')\n }\n },\n Todo: {\n __isTypeOf: (obj, context, info) => {\n return obj instanceof Todo\n },\n }\n}\n```\n\n```text\nisTypeOf\n```\n\n```text\nresolveType\n```\n\n```text\nbuildSchema\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nresolveType\n```\n\n```text\n__typename\n```\n\n```text\nisTypeOf\n```\n\n```text\nbuildSchema\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\ngraphql-tools\n```\n\n```text\nresolveType\n```\n\n```text\nisTypeOf\n```\n\n```text\nisTypeOf\n```\n\n```text\nresolveType\n```\n\n```text\nbuildSchema\n```\n\n```text\nisTypeOf\n```\n\n```text\nresolveType\n```\n\n```text\nresolveType\n```\n\n```text\nisTypeOf\n```\n\n========================================\n\nComments:\n- Daniel, Thank you for your time. I've tried the first suggestion and it doesn't work, so now I'm considering proceed with your second suggestion: use `makeExecutableSchema`. However I have one concern. I'm trying to create a Relay Server and `makeExecutableSchema` is from Apollo. So far I know, Relay is a \"pattern\" and Apollo is a \"framework\" with different implementation. So my question is: Wouldn't be incorrect use both in the same solution?\n- If you're looking to integrate `graphql-relay-js` to make a relay-compliant server, I believe that forces you generate a schema programatically using vanilla GraphQL.js -- building a schema from SDL using either `buildSchema` or `makeExecutableSchema` probably won't let you incorporate all the various helper methods included with the relay library. Otherwise, it's possible to have a relay-compliant server built with graphql-tools or even apollo-server.\n- I'm curious what about the first approach \"doesn't work\"? What errors or behavior were you seeing? Here's a working example using Launchpad that demonstrates what I was suggesting: launchpad.graphql.com/07wkrx5qj5 (Launchpad uses makeExecutableSchema, but the concept is still the same)\n- \"If you're looking to integrate graphql-relay-js to make a relay-compliant server, I believe that forces you generate a schema programatically using vanilla GraphQL.js\" - That's exactly what I am trying to do! =)\n- Regarding the error, it's my fault: I've changed just the implementation of todo class and I kept it using buildSchema from 'graphql.js' (not makeExecutableSchema from 'graphql-tools'). I'll keep trying understand how to implement the relay server with vanilla GraphQL!\n- Can the answer be updated to include an isTypeOf implementation? That was the original question but it doesn't seem to actually explain that way.\n- I wonder in the future if I won't be able to type my keyboard because the type of my fingers wont' work with the expected type of my keys. You want absurd. welcome to GQL and TS. Were you endlessly code code for the sake of coding code and everything has a type but no one stops to ask why. Good luck.\n- remember when our lives were easy and we didnt have to do anything of this extra typing crap.","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":297,"estimatedTokens":1459}}95{"id":"stack-61575312","source":"stackoverflow","questionId":61575312,"title":"sequelize migrations not running","tags":["node.js","orm","graphql","migration","sequelize.js"],"text":"Title: sequelize migrations not running\nTags: node.js, orm, graphql, migration, sequelize.js\nSource: Stack Overflow\n\nQuestion:\nI'm having a weird issue with Sequelize I haven't encountered before, when I try to run my migrations nothing happens. I get the following output:\n\n```\nLoaded configuration file \"config\\config.json\"\nUsing environment \"development\"\n```\n\nAnd the program just exists back.\n\nI've checked my code multiple times over and everything checks out.\n\nModel code:\n\n```\nmodule.exports = {\nup: (queryInterface, Sequelize) => {\n return queryInterface.createTable(\"users\", {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n username: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false,\n validate: {\n notEmpty: true\n }\n },\n email: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false,\n validate: {\n notEmpty: true,\n isEmail: true\n }\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false,\n validate: {\n notEmpty: true,\n len: [7, 42]\n }\n },\n createdAt: {\n type: Sequelize.DATE\n },\n updatedAt: {\n type: Sequelize.DATE\n }\n })\n},\ndown: (queryInterface, Sequelize) => {\n return queryInterface.dropTable(\"users\")\n}\n```\n\n}\n\nAnd here is a snippet from my model/index.js:\n\n```\nconst fs = require(\"fs\")\nconst path = require(\"path\")\nconst Sequelize = require(\"sequelize\")\n\nconst basename = path.basename(__filename)\nconst env = process.env.TEST_ENV || \"development\"\nconst config = require(`${__dirname}/../config/config.js`)[env]\nconst db = {}\n\nconsole.log('config', config)\n\nlet sequelize\nif (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable], config)\n} else {\n sequelize = new Sequelize(\n config.database,\n config.username,\n config.password,\n config\n )\n}\n```\n\nIt's almost like sequelize just isn't picking up any of migrations file. I'm not sure how I should troubleshoot this. Any help on this would be much appreciated.\n\n========================================\n\nTop Answer:\nUpdating `pg` fixed the issue on my end.\n\n```\nnpm install --save pg@latest\n```\n\n========================================\n\nCode:\n```text\nLoaded configuration file \"config\\config.json\"\nUsing environment \"development\"\n```\n\n```text\nmodule.exports = {\nup: (queryInterface, Sequelize) => {\n return queryInterface.createTable(\"users\", {\n id: {\n allowNull: false,\n autoIncrement: true,\n primaryKey: true,\n type: Sequelize.INTEGER\n },\n username: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false,\n validate: {\n notEmpty: true\n }\n },\n email: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: false,\n validate: {\n notEmpty: true,\n isEmail: true\n }\n },\n password: {\n type: Sequelize.STRING,\n allowNull: false,\n validate: {\n notEmpty: true,\n len: [7, 42]\n }\n },\n createdAt: {\n type: Sequelize.DATE\n },\n updatedAt: {\n type: Sequelize.DATE\n }\n })\n},\ndown: (queryInterface, Sequelize) => {\n return queryInterface.dropTable(\"users\")\n}\n```\n\n```text\nconst fs = require(\"fs\")\nconst path = require(\"path\")\nconst Sequelize = require(\"sequelize\")\n\nconst basename = path.basename(__filename)\nconst env = process.env.TEST_ENV || \"development\"\nconst config = require(`${__dirname}/../config/config.js`)[env]\nconst db = {}\n\nconsole.log('config', config)\n\nlet sequelize\nif (config.use_env_variable) {\n sequelize = new Sequelize(process.env[config.use_env_variable], config)\n} else {\n sequelize = new Sequelize(\n config.database,\n config.username,\n config.password,\n config\n )\n}\n```\n\n```text\nsequelize db:migrate:all\n```\n\n```text\nnpm install --save pg@latest\n```\n\n```text\npg\n```\n\n```text\nnpm install pg@latest\n```\n\n========================================\n\nComments:\n- Did you ever figure out why version 14 doesn't work (and possible file an issue)?\n- No, nothing concrete but I think the issue was that the migrations were initially setup with Node 10.13.0 so when I tried to run them with 14 there was some sort of compatibility issue.\n- It seems like this was a compatibility issue between Node 14 and the pg library. Updating to pg@8.0.3 fixed the issue without needing to downgrade Node.\n- @bradley2w1dl Thanks,, having the same issue and npm install --save pg@latest fixed it for me.\n- that command doesn't exist at least in my CLI version 5.5.1\n- does not exist in verion 5 `sequelize db:migrate Run pending migrations`\n- Life saver. Thank you so much.","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":213,"estimatedTokens":1190}}96{"id":"stack-41424728","source":"stackoverflow","questionId":41424728,"title":"How to execute GraphQL query from server","tags":["javascript","graphql","graphql-js"],"text":"Title: How to execute GraphQL query from server\nTags: javascript, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am using graphql-express to create an endpoint where I can execute graphql queries in. Although I am using Sequelize with a SQL database it feels wrong to use it directly from the server outside of my graphql `resolve` functions. How do I go about querying my graphql API from the same server as it was defined in?\n\nThis is how I set up my graphql endpoint:\n\n```\nconst express = require('express');\nconst router = express.Router();\nconst graphqlHTTP = require('express-graphql');\nconst gqlOptions = {\n schema: require('./schema')\n};\nrouter.use('/', graphqlHTTP(gqlOptions));\n\nmodules.exports = router;\n```\n\nBasically what I want is to be able to do something like this:\n\n```\nquery(`\n {\n user(id: ${id}) {\n name\n }\n }\n`)\n```\n\nHow would I create this `query` function?\n\n========================================\n\nTop Answer:\nI would like to complete the answer from @aα΄ΙͺΚ by providing the pattern for properly doing a query / mutation with parameters:\n\n```\nconst params = {\n username: 'john',\n password: 'hello, world!',\n userData: {\n ...\n }\n}\n\nquery(`mutation createUser(\n $username: String!,\n $password: String!,\n $userData: UserInput) {\n createUserWithPassword(\n username: $username,\n password: $password,\n userData: $userData) {\n id\n name {\n familyName\n givenName\n }\n }\n}`, params)\n```\n\nThis way, you don't have to deal with the string construction bits `\"` or `'` here and there.\n\n========================================\n\nCode:\n```text\nconst express = require('express');\nconst router = express.Router();\nconst graphqlHTTP = require('express-graphql');\nconst gqlOptions = {\n schema: require('./schema')\n};\nrouter.use('/', graphqlHTTP(gqlOptions));\n\nmodules.exports = router;\n```\n\n```text\nquery(`\n {\n user(id: ${id}) {\n name\n }\n }\n`)\n```\n\n```text\nresolve\n```\n\n```text\nquery\n```\n\n```text\ngraphql({schema, requestString}).then(result => {\n console.log(result);\n});\n```\n\n```text\nconst {graphql} = require('graphql');\nconst schema = require('./schema');\nfunction query (requestString) {\n return graphql({schema, requestString});\n}\n\nquery(`\n {\n user(id: ${id}) {\n name\n }\n }\n`).then(data => {\n console.log(data);\n})\n```\n\n```text\ngraphql\n```\n\n```text\nconst params = {\n username: 'john',\n password: 'hello, world!',\n userData: {\n ...\n }\n}\n\nquery(`mutation createUser(\n $username: String!,\n $password: String!,\n $userData: UserInput) {\n createUserWithPassword(\n username: $username,\n password: $password,\n userData: $userData) {\n id\n name {\n familyName\n givenName\n }\n }\n}`, params)\n```\n\n```text\n\"\n```\n\n```text\n'\n```\n\n```text\nimport {MongoClient} from \"mongodb\"\n\nexport const connectToDatabase = async() => {\n const client = new MongoClient(process.env.MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true})\n let cachedConnection\n if(cachedConnection) return cachedConnection\n try {\n const connection = await client.connect()\n cachedConnection = connection\n return connection\n } catch(error) {\n console.error(error)\n }\n}\n\nexport const mongoServer = async() => {\n const connect = await connectToDatabase()\n return connect.db(process.env.DB_NAME)\n}\n```\n\n```text\nimport {graphql} from 'graphql'\nimport {schema} from '@/plugin/zSchema/schema'\nimport {mongoServer} from '@/plugin/zDb/index'\nasync function query(source, variableValues) {\n return graphql({schema, source, contextValue: {mongo: await mongoServer()}, variableValues})\n}\nexport async function getServerSideProps(ctx) {\n const listingCurrent = await query(`query($keyField: String, $keyValue: String) {\n ListingRQlistingListKeyValue(keyField: $keyField, keyValue: $keyValue) {\n address\n urlSlug\n imageFeature {\n photoName\n }\n }\n }`, {\n keyField: 'offerStatus'\n , keyValue: 'CURRENT'\n })\n return {props: {\n listingCurrent: listingCurrent.data.ListingRQlistingListKeyValue\n }\n}\n}\n```\n\n```text\nexport type GraphQLArgs = {|\n schema: GraphQLSchema,\n source: string | Source,\n rootValue?: mixed,\n contextValue?: mixed,\n variableValues?: ?ObjMap<mixed>,\n operationName?: ?string,\n fieldResolver?: ?GraphQLFieldResolver<any, any>,\n|};\n```\n\n```text\nimport { makeExecutableSchema } from '@graphql-tools/schema'\nimport {resolvers} from '@/plugin/zSchema/resolvers'\nimport {typeDefs} from '@/plugin/zSchema/typeDefs'\n\nexport const schema = makeExecutableSchema({resolvers, typeDefs})\n```\n\n```text\n{\n \"compilerOptions\": {\n \"baseUrl\": \".\"\n , \"paths\": {\n \"@/*\": [\"./*\"]\n }\n }\n}\n```\n\n========================================\n\nComments:\n- To get more options, see the source code at github.com/graphql/graphql-js/blob/…\n- Also here is the official documentation page for the graphql function: graphql.org/graphql-js/graphql/#graphql\n- graphql 16 dropped support for positional arguments\n- Doesn't the query function have to change as well? Your call passes 2 parameters and not one.","metadata":{"transformedAt":"2026-08-18T18:32:36.026Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":250,"estimatedTokens":1260}}97{"id":"stack-67659937","source":"stackoverflow","questionId":67659937,"title":"What are differences between GraphQL Subscription and WebSocket protocol?","tags":["websocket","socket.io","graphql","graphql-subscriptions"],"text":"Title: What are differences between GraphQL Subscription and WebSocket protocol?\nTags: websocket, socket.io, graphql, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nI have two sides.\n\nIn one side I have direct usage of WebSocket protocol by using libraries/packages like ws (a Node.js WebSocket library) or Socket.io. Here I can use test tools to subscribe against and address starting with `ws` or `wss` like `ws://localhost:8080` and receive updates.\n\nIn other side, I use GraphQL Subscription by using components like `ApolloGraphQL`. It seems that this way I should use something embedded in GraphQL. Projects developed with this way can not be accessed via `ws://` or `wss://` addresses, or at least I am not aware of.\n\nMy questions is what are differences between two? Are GraphQL Subscription is built on top of WebSocket? If yes, how? How can I access a GraphQL Subscription via `ws://` or `wss://` urls?\n\nUPDATE:\nI have read this and this question before, but they did not helped a lot.\n\n========================================\n\nCode:\n```text\nws\n```\n\n```text\nwss\n```\n\n```text\nws://localhost:8080\n```\n\n```text\nApolloGraphQL\n```\n\n```text\nws://\n```\n\n```text\nwss://\n```\n\n```text\nws://\n```\n\n```text\nwss://\n```\n\n```text\nsubscriptions-transport-ws\n```\n\n```text\ngraphql-ws\n```\n\n========================================\n\nComments:\n- What about tooling? How can I see traffic of GraphQL Subscription?\n- You can see the websocket GraphQL traffic in the browser developer console under the network tab.","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":64,"estimatedTokens":378}}98{"id":"stack-65717505","source":"stackoverflow","questionId":65717505,"title":"How can I print the schema in HotChocolate as GraphQL SDL","tags":["graphql","relay","hotchocolate"],"text":"Title: How can I print the schema in HotChocolate as GraphQL SDL\nTags: graphql, relay, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nIt would be great for development with Relay to print the GraphQL SDL directly with the Hot Chocolate GraphQL server. Is there a way to do this?\n\n```\nschema {\n query: Query\n}\n\ntype Query {\n sayHello: String\n}\n```\n\n========================================\n\nTop Answer:\nIf you want to generate the schema in CI/CD, you can add a CLI argument that generates the schema and doesn't start the app. Something like:\n\nIn Program.cs:\n\n```\nif (args.Any(c => c == \"--generate-schema\"))\n{\n builder.Services.AddGraphQL().InitializeOnStartup();\n var app = builder.Build();\n var executor = app.Services.GetRequiredService().GetRequestExecutorAsync().Result;\n var schema = executor.Schema.Print();\n File.WriteAllText(\"schema.graphql\", schema);\n return;\n}\n```\n\n========================================\n\nCode:\n```text\nschema {\n query: Query\n}\n\ntype Query {\n sayHello: String\n}\n```\n\n```text\nToString\n```\n\n```text\nISchema\n```\n\n```text\nToString\n```\n\n```text\nhttp://localhost:5000/graphql/schema\n```\n\n```text\nhttp://localhost:5000/graphql?sdl\n```\n\n```text\ngraphql\n```\n\n```cs\nHostInstance = builder.Build();\nif(Debugger.IsAttached)\n{\n var resolver = HostInstance.Services.GetService<IRequestExecutorResolver>();\n if (resolver != null)\n {\n var executor = resolver.GetRequestExecutorAsync().Result;\n if (executor != null)\n {\n var schemaFile = Path.Combine(ProjectPathInfo.ProjectPath, \"Apps\\\\src\\\\lib\\\\com\\\\GraphQL\\\\schema.graphql\");\n var newSchema = executor.Schema.ToString();\n var oldSchema = File.ReadAllText(schemaFile);\n if (newSchema != oldSchema)\n File.WriteAllText(schemaFile, newSchema);\n }\n }\n\n}\n```\n\n```cs\ninternal static class ProjectPathInfo\n{\n public static string CSharpClassFileName = nameof(ProjectPathInfo) + \".cs\";\n public static string CSharpClassPath;\n public static string ProjectPath;\n public static string SolutionPath;\n\n static ProjectPathInfo()\n {\n CSharpClassPath = GetSourceFilePathName();\n ProjectPath = Directory.GetParent(CSharpClassPath)!.FullName;\n SolutionPath = Directory.GetParent(ProjectPath)!.FullName;\n }\n\n private static string GetSourceFilePathName([CallerFilePath] string callerFilePath = null) => callerFilePath ?? \"\";\n}\n```\n\n```text\nProgram.cs\n```\n\n```text\nschema.graphql\n```\n\n```text\nif (args.Any(c => c == \"--generate-schema\"))\n{\n builder.Services.AddGraphQL().InitializeOnStartup();\n var app = builder.Build();\n var executor = app.Services.GetRequiredService<IRequestExecutorResolver>().GetRequestExecutorAsync().Result;\n var schema = executor.Schema.Print();\n File.WriteAllText(\"schema.graphql\", schema);\n return;\n}\n```\n\n========================================\n\nComments:\n- Does hotchocolate provide a built-in means to extract the SDL without running the server?\n- Would be useful for CI/CD systems to be able to get this at build time without running the server.. though maybe thats just my dinosaur brain\n- With HC 13, where do you get ISchema from?\n- Should that read `var executor = app.Services...` instead of `host.Services`?","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":140,"estimatedTokens":811}}99{"id":"stack-33323894","source":"stackoverflow","questionId":33323894,"title":"Why are edges required in a Relay/GraphQL Connection?","tags":["graphql","relayjs"],"text":"Title: Why are edges required in a Relay/GraphQL Connection?\nTags: graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nIn a Relay/GraphQL schema configuration, one-to-many relationships (with pagination) are specified as in the tutorial example\n\n```\ntype ShipConnection {\n edges: [ShipEdge]\n pageInfo: PageInfo!\n}\ntype ShipEdge {\n cursor: String!\n node: Ship\n}\n```\n\nHowever, the one-to-one connection made by `ShipEdge` seems redundant. Why can't we move the cursor to `ShipConnection` and store an array of `Ship` IDs as edges?\n\n```\ntype ShipConnection {\n edges: [Ship]\n pageInfo: PageInfo!\n cursor: String!\n}\n```\n\nWhat were the design decisions to require one extra object for every `edge` in a one-to-many relationship?\n\n========================================\n\nTop Answer:\n(Updated with more explanations)\n\nThere are 3 ways to represent an array of data in GraphQL:\n\n- List: Use when you have a finite list of associated objects that you're fine fetching all at once. In GraphQL SDL, this is represented as `[Ship]`.\n\n- Nodes: Use when you need to paginate over a list, usually because there can be thousands of items. Note that this is not part of the Relay specification and as such is not supported by the Relay client (instead, you'd wrap the item in an edge as described in #3), but some other clients such as Apollo are more flexible and support this construct (but you need to provide more boilerplate). In GraphQL, this would be represented as `type ShipConnection { nodes: [Ship], pageInfo: PageInfo! }`.\n\n- Edges: Use when, in addition to pagination, you also need to provide extra information for each edge in the connection (read below for more details). In GraphQL, you'd write it as `type ShipConnection { edges: [ShipEdge], pageInfo: PageInfo! }`.\n\nNote that your GraphQL server might support all three options for a specific association, and the client then selects which field they want. Here's how they'd all look together:\n\n```\ntype Query {\n ships: [Ship] // #1\n shipsConnection: [ShipConnection]\n}\n\ntype ShipConnection {\n nodes: [Ship] // #2\n edges: [ShipEdge] // #3\n pageInfo: PageInfo!\n}\n\ntype PageInfo {\n endCursor // page-based pagination\n hasNextPage\n}\n\ntype ShipEdge {\n cursor: String! // edge-based pagination\n node: Ship\n // ... edge attributes\n}\n\ntype Ship {\n // ... ship attributes\n}\n```\n\nLists (#1) should only ever be used when you know that the number of items won't grow (for example, if you have a `Post`, you may want to return `tags` as a List, but you shouldn't do that with `comments`). To decide between #2 and #3, there are two reasons for using edges over just plain nodes:\n\nIt's a place for edge-specific attributes. For example, if you have a `User` that belongs to many `Group`s, in a relational database you'd have a UserGroup table with `user_id` and `group_id`. This table can have additional attributes like `role`, `joined_at` etc. The `GroupUserEdge` would then be the place where you could access these attributes.\n\nHave a place for the cursor. Relay, in addition to page-based pagination (using `pageInfo`) supports edge-based pagination. Why does Relay need a cursor for each edge? Because Relay intelligently merges data requirements from your entire app, it may already have a connection with the same parameters you're requesting but not enough records in it. To fetch the missing data, it can ask for data in the connection after some edge's cursor.\n\nI understand it may be confusing, considering databases have cursors, too, and there is only one cursor per query. A Relay connection is not a query really, it's rather a set of parameters that identify a query. A cursor of connection's edge is a set of parameters that identify a position within a connection. This is a higher abstraction level than a pure query cursor (remember that edges need to be able to identify a position even over a connection that might not be a DB query, or be hidden by a 3rd party system). Because of this required flexibility, one cursor for a connection would not be enough.\n\n========================================\n\nCode:\n```text\ntype ShipConnection {\n edges: [ShipEdge]\n pageInfo: PageInfo!\n}\ntype ShipEdge {\n cursor: String!\n node: Ship\n}\n```\n\n```text\ntype ShipConnection {\n edges: [Ship]\n pageInfo: PageInfo!\n cursor: String!\n}\n```\n\n```text\nShipEdge\n```\n\n```text\nShipConnection\n```\n\n```text\nShip\n```\n\n```text\nedge\n```\n\n```text\nedges\n```\n\n```text\ncreator\n```\n\n```text\npriority\n```\n\n```text\nGraphQLList\n```\n\n```text\ntype Query {\n ships: [Ship] // #1\n shipsConnection: [ShipConnection]\n}\n\ntype ShipConnection {\n nodes: [Ship] // #2\n edges: [ShipEdge] // #3\n pageInfo: PageInfo!\n}\n\ntype PageInfo {\n endCursor // page-based pagination\n hasNextPage\n}\n\ntype ShipEdge {\n cursor: String! // edge-based pagination\n node: Ship\n // ... edge attributes\n}\n\ntype Ship {\n // ... ship attributes\n}\n```\n\n```text\n[Ship]\n```\n\n```text\ntype ShipConnection { nodes: [Ship], pageInfo: PageInfo! }\n```\n\n```text\ntype ShipConnection { edges: [ShipEdge], pageInfo: PageInfo! }\n```\n\n```text\nPost\n```\n\n```text\ntags\n```\n\n```text\ncomments\n```\n\n```text\nUser\n```\n\n```text\nGroup\n```\n\n```text\nuser_id\n```\n\n```text\ngroup_id\n```\n\n```text\nrole\n```\n\n```text\njoined_at\n```\n\n```text\nGroupUserEdge\n```\n\n```text\npageInfo\n```\n\n========================================\n\nComments:\n- Yes, in the \"ship\" scenario you might want `createdAt` and `color` on the ship itself; I was just giving those as abstract examples of field names. Note that in some domains you could have multiple edges pointing to the same node, and you might want to know when each edge (in the graph sense) was added and so would use `createdAt`. I was using `color` as a generic property name, but you could think of other things that might describe the nature of the edge. such as `weight` (how important the edge is) or `creator` (who established the link) etc. I'll edit my answer to avoid this confusion.\n- This is a helpful answer but I still can't imagine when relay would need to fetch data using a cursor from the middle of a connection. In the situation where you have a \"connection with the same parameters you're requesting but not enough records in it\" a cursor for the last edge would suffice.\n- An example off the top of my head: You fetch a list of comments but then the last comment is deleted. So to fetch next batch of comments, you need to start from the currently-last cursor. I'm sure there are many more use cases. The point is, Relay tries to be as generic as possible and robust enough to manage whatever happens to the data.\n- @PetrBela When you do keyset pagination you are not affected by a deleted record. I don't see why you would need the previous comments cursor in order to fetch the next page.\n- @MassimoFazzolari Yeah I guess my previous example wasn't the best. However, the point of having a cursor (for both offset and keyset pagination) is still the same. The question is why does Relay mandate that each node has a cursor when the whole connection already has a cursor? Perhaps to account for using the same connection in two different components, one paginating by 3 and the other by 10 items? Might be an edge case but Relay would still be able to handle it. (This is probably used in Facebook comments which initially show like top 3 but then you expand it, it adds 8 or so etc.)\n- @PetrBela As far as I understand it you get a slight optimisation when you have a component asking for 3 items but you already loaded the first 10. But your Facebook example wouldn't benefit of that because you don't want to load 10 items in cache if you only need to show 3 in most cases. I still don't see any real use case where edges are useful.\n- @MassimoFazzolari If you see 3 comments on the news feed and then go to the detail page which shows 10, then Relay can just fetch the 7 new ones. I probably can't explain any more than that since I didn't author it but this is how I understand it. FB has a lot of specific use cases and optimizations that are probably not worth the complexity in most projects, and this seems to be one of those. (You may note that Apollo doesn't deal with this at all as they didn't deem it common enough.)\n- @MassimoFazzolari Edges are still useful, though, since you can attach edge-specific data, which I've hopefully explained in my answer. Edge cursors, on the other hand, have more of a theoretical value which might not be strictly needed in most projects but since the Relay client works that way, it still requires them.\n- @PetrBela Could you point any real-world API that attach edge-specific data? Shopify and Github don't use that. Also attaching data to edges means that you need to have different Connection Types for each model, which in my opinion makes your code less reusable. Edges and cursors for each node look to me like a classic example of over-engineering.\n- @MassimoFazzolari I don't have a list of who uses edge data in their APIs. I was just trying to explain what they can be used for and why Relay requires this structure. And yes, in practice, in 95% of cases you won't need edges, but the authors of Relay decided to cover the theoretical 5% by writing a spec that covers them (and, most likely, that 5% is used in the FB codebase). I'd end the discussion here since I'm not an author of the spec and don't have any more info beyond what I've just speculated.\n- On the last note, I'd add that I did use edge data in one of my APIs. However, I found that in practice it's easier to convert \"relationship tables\" to standalone entities, as they're nicer to work with. In other words, instead of orgs -> org_users -> users tables, where the `Org` type has a users connection with the org_user being the edge, it's better to have orgs -> members -> users tables, where the `Org` type has a members connection, and each `Member` has an associated `User`.","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":233,"estimatedTokens":2466}}100{"id":"stack-60747549","source":"stackoverflow","questionId":60747549,"title":"How to split type definitions and resolvers into separate files in Apollo Server","tags":["typescript","graphql","graphql-js","apollo-server"],"text":"Title: How to split type definitions and resolvers into separate files in Apollo Server\nTags: typescript, graphql, graphql-js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nindex.ts:\n\n```\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n context: ({ req, res }: any) => ({ req, res })\n });\n```\n\nUserSchema.ts\n\n```\nexport const typeDefs = gql`\n scalar TimeStamp\n type Query {\n getUser(id: Int!): User\n }\n type Mutation {\n addUser(\n name: String!\n email: String\n age: Int\n register_at: TimeStamp!\n ): Boolean!\n }\n type User {\n id: Int!\n name: String!\n email: String!\n age: Int!\n register_at: TimeStamp!\n }\n`;\n```\n\nUserResolver.ts\n\n```\nexport const resolvers = {\n TimeStamp: timeStamp,\n Query: {\n getUser: async (_: any, args: any) => {\n const { id } = args;\n\n return await User.findOne({ where: { id: id } });\n }\n },\n Mutation: {\n addUser: async (_: any, args: any) => {\n const { name, email, age, register_at } = args;\n try {\n const user = User.create({\n name,\n email,\n age,\n register_at\n });\n\n await user.save();\n\n return true;\n } catch (error) {\n return false;\n }\n }\n }\n};\n```\n\nI would like to know how I would initialize my Apollo Server instance if I had additional type definitions and resolvers, for example `BookSchema.ts` and `BookResolver.ts`.\n\n========================================\n\nTop Answer:\nI dont know, if it is good way of doing this, but you can do it like this.\n\n```\nconst typeDefA = `\n name: String!\n email: String!\n phone: String!\n`\n\nconst RootTypeDef = gql`\n ${typeDefA}\n\n type Query {\n users: [User]\n }\n`;\n```\n\nyou can just take out user schema or any other schema and store it in normal variable, then add it like a variable in root schema.\n\nPlease let me know, whether it is good practice or not.\n\n========================================\n\nCode:\n```text\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n context: ({ req, res }: any) => ({ req, res })\n });\n```\n\n```text\nexport const typeDefs = gql`\n scalar TimeStamp\n type Query {\n getUser(id: Int!): User\n }\n type Mutation {\n addUser(\n name: String!\n email: String\n age: Int\n register_at: TimeStamp!\n ): Boolean!\n }\n type User {\n id: Int!\n name: String!\n email: String!\n age: Int!\n register_at: TimeStamp!\n }\n`;\n```\n\n```text\nexport const resolvers = {\n TimeStamp: timeStamp,\n Query: {\n getUser: async (_: any, args: any) => {\n const { id } = args;\n\n return await User.findOne({ where: { id: id } });\n }\n },\n Mutation: {\n addUser: async (_: any, args: any) => {\n const { name, email, age, register_at } = args;\n try {\n const user = User.create({\n name,\n email,\n age,\n register_at\n });\n\n await user.save();\n\n return true;\n } catch (error) {\n return false;\n }\n }\n }\n};\n```\n\n```text\nBookSchema.ts\n```\n\n```text\nBookResolver.ts\n```\n\n```text\nconst server = new ApolloServer({\n typeDefs: [userTypeDefs, bookTypeDefs],\n resolvers,\n})\n```\n\n```text\nconst typeDefsA = gql`\n type Query {\n users: [User!]!\n }\n`\nconst typeDefsB = gql`\n extend type Query {\n books: [Book!]!\n }\n`\nconst typeDefsC = gql`\n extend type Query {\n posts: [Post!]!\n }\n`\n```\n\n```text\ntype Query\n\ntype Mutation\n```\n\n```text\nconst resolversA = {\n Query: {\n users: () => {...},\n }\n}\n\nconst resolversB = {\n Query: {\n books: () => {...},\n }\n}\n```\n\n```text\nconst resolvers = {\n ...resolversA,\n ...resolversB,\n}\n```\n\n```text\nconst resolvers = _.merge({}, resolversA, resolversB)\n```\n\n```text\nexport default gql`\ntype User {\n id: ID!\n username: String!\n books: [Book!]!\n}\n\nextend type Query {\n users: [User!]!\n}\n`\n```\n\n```text\nexport default gql`\ntype Book {\n id: ID!\n title: String!\n author: User!\n}\n\nextend type Query {\n books: [Book!]!\n}\n`\n```\n\n```text\nexport default {\n Query: {\n users: () => {...},\n },\n User: {\n books: () => {...},\n },\n}\n```\n\n```text\nexport default {\n Query: {\n books: () => {...},\n },\n Book: {\n author: () => {...},\n },\n}\n```\n\n```text\nimport userTypeDefs from '...'\nimport userResolvers from '...'\nimport bookTypeDefs from '...'\nimport bookResolvers from '...'\n\n// Note: This is also a good place to put any types that are common to each \"module\"\nconst baseTypeDefs = gql`\n type Query\n`\n\nconst apollo = new ApolloServer({\n typeDefs: [baseTypeDefs, userTypeDefs, bookTypeDefs],\n resolvers: _.merge({}, userResolvers, bookResolvers)\n})\n```\n\n```text\nApolloServer\n```\n\n```text\nDocumentNode\n```\n\n```text\nQuery\n```\n\n```text\nextend type Query\n```\n\n```text\nObject.assign\n```\n\n```text\nQuery\n```\n\n```text\nlodash\n```\n\n```text\nconst typeDefA = `\n name: String!\n email: String!\n phone: String!\n`\n\nconst RootTypeDef = gql`\n ${typeDefA}\n\n type Query {\n users: [User]\n }\n`;\n```\n\n========================================\n\nComments:\n- I didn't quite understand the extension part, could you show me how i could by types and solve on same file ?\n- Not sure I understand what you're asking. What exactly do you still have questions about?\n- basically i wanted to try to put my resolvers and types in a file that is userschema: types and resolvers: bookschema: types and resolvers but I was a little confused about extends\n- Type extensions are only necessary if you want to take a single type like `Query` or `Mutation` and split it across multiple files. You can't define `Query` more than once, but you can add the `extend` keyword to turn a definition into an extension.\n- Here's the spec for reference.\n- in case if I want to separate the typedefs do I need to use extend?\n- I think you understand, you could just give me an example of this: I usually create a \"base\" set of type definitions like:\n- That is the example already. It's just `type Query` with no fields -- that way you can use `extend type Query` in all other files. I updated the final example with additional details. Hopefully that helps.\n- Thank you so freaking much, Daniel! This is THE definitive answer to this problem as of today (2022-05-28)","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":356,"estimatedTokens":1507}}101{"id":"stack-64701308","source":"stackoverflow","questionId":64701308,"title":"GraphQL ERESOLVE unable to resolve dependency tree when building my docker container","tags":["docker","docker-compose","graphql","dockerfile"],"text":"Title: GraphQL ERESOLVE unable to resolve dependency tree when building my docker container\nTags: docker, docker-compose, graphql, dockerfile\nSource: Stack Overflow\n\nQuestion:\nHere are my files.\n\nHere is I think the core of the problem.\n\n```\nCould not resolve dependency:\nnpm ERR! peer graphql@\"^0.12.0 || ^0.13.0 || ^14.0.0\" from graphql-middleware@4.0.2\n```\n\n### docker-compose.yml\n\n```\nversion: '3.7'\n\nservices:\n apollo:\n container_name: apollo\n build:\n context: .\n dockerfile: Dockerfile\n environment:\n - NODE_ENV=development\n volumes:\n - '.:/app'\n - '/app/node_modules'\n\n ports:\n - 4000:4000\n\n restart: always\n```\n\n### Dockerfile\n\n```\n# Use the official image as a parent image.\nFROM node:current-slim\n\n# Set the working directory.\nWORKDIR /app\n\n# Setting environment path.\nENV PATH=/app/node_modules/.bin:$PATH\n\n# Copy the file from your host to your current location.\nCOPY package.json .\n\n# Run the command inside your image filesystem.\nRUN npm init --yes\nRUN npm install --save cors apollo-server-express express graphql reflect-metadata type-graphql apollo-datasource-rest soap jsonwebtoken --yes\nRUN npm install nodemon -g --yes\n\n# Add metadata to the image to describe which port the container is listening on at runtime.\nEXPOSE 4000\n\n# Copy the rest of your app's source code from your host to your image filesystem.\nCOPY . .\nCMD [ \"nodemon\", \"index.js\" ]\n```\n\n### Dependency Error\n\n```\n$ docker-compose up --build\nBuilding apollo\nStep 1/10 : FROM node:current-slim\n ---> f3f62dfcc735\nStep 2/10 : WORKDIR /app\n ---> Using cache\n ---> 33088e65c748\nStep 3/10 : ENV PATH=/app/node_modules/.bin:$PATH\n ---> Using cache\n ---> c7f742267b26\nStep 4/10 : COPY package.json .\n ---> Using cache\n ---> 76285ea4a8ca\nStep 5/10 : RUN npm init --yes\n ---> Using cache\n ---> 29a3d715136b\nStep 6/10 : RUN npm install --save cors apollo-server-express express graphql reflect-metadata type-graphql apollo-datasource-rest soap jsonwebtoken --yes\n ---> Running in 1e4472bcd901\nnpm ERR! code ERESOLVE\nnpm ERR! ERESOLVE unable to resolve dependency tree\nnpm ERR! \nnpm ERR! While resolving: apollo-express-server@1.0.0\nnpm ERR! Found: graphql@15.4.0\nnpm ERR! node_modules/graphql\nnpm ERR! graphql@\"^15.3.0\" from the root project\nnpm ERR! \nnpm ERR! Could not resolve dependency:\nnpm ERR! peer graphql@\"^0.12.0 || ^0.13.0 || ^14.0.0\" from graphql-middleware@4.0.2\nnpm ERR! node_modules/graphql-middleware\nnpm ERR! graphql-middleware@\"^4.0.2\" from the root project\nnpm ERR! \nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force, or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\nnpm ERR! \nnpm ERR! See /root/.npm/eresolve-report.txt for a full report.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /root/.npm/_logs/2020-11-05T16_19_42_605Z-debug.log\nERROR: Service 'apollo' failed to build : The command '/bin/sh -c npm install --save cors apollo-server-express express graphql reflect-metadata type-graphql apollo-datasource-rest soap jsonwebtoken --yes' returned a non-zero code: 1\n```\n\n========================================\n\nTop Answer:\nThere is not need to downgrade to npm 6.\nIndeed npm 7 can still be used with option --legacy-peer-deps.\n\n```\nnpm install --legacy-peer-deps\n```\n\n========================================\n\nCode:\n```text\nCould not resolve dependency:\nnpm ERR! peer graphql@\"^0.12.0 || ^0.13.0 || ^14.0.0\" from graphql-middleware@4.0.2\n```\n\n```text\nversion: '3.7'\n\nservices:\n apollo:\n container_name: apollo\n build:\n context: .\n dockerfile: Dockerfile\n environment:\n - NODE_ENV=development\n volumes:\n - '.:/app'\n - '/app/node_modules'\n\n ports:\n - 4000:4000\n\n restart: always\n```\n\n```text\n# Use the official image as a parent image.\nFROM node:current-slim\n\n# Set the working directory.\nWORKDIR /app\n\n# Setting environment path.\nENV PATH=/app/node_modules/.bin:$PATH\n\n# Copy the file from your host to your current location.\nCOPY package.json .\n\n# Run the command inside your image filesystem.\nRUN npm init --yes\nRUN npm install --save cors apollo-server-express express graphql reflect-metadata type-graphql apollo-datasource-rest soap jsonwebtoken --yes\nRUN npm install nodemon -g --yes\n\n# Add metadata to the image to describe which port the container is listening on at runtime.\nEXPOSE 4000\n\n# Copy the rest of your app's source code from your host to your image filesystem.\nCOPY . .\nCMD [ \"nodemon\", \"index.js\" ]\n```\n\n```text\n$ docker-compose up --build\nBuilding apollo\nStep 1/10 : FROM node:current-slim\n ---> f3f62dfcc735\nStep 2/10 : WORKDIR /app\n ---> Using cache\n ---> 33088e65c748\nStep 3/10 : ENV PATH=/app/node_modules/.bin:$PATH\n ---> Using cache\n ---> c7f742267b26\nStep 4/10 : COPY package.json .\n ---> Using cache\n ---> 76285ea4a8ca\nStep 5/10 : RUN npm init --yes\n ---> Using cache\n ---> 29a3d715136b\nStep 6/10 : RUN npm install --save cors apollo-server-express express graphql reflect-metadata type-graphql apollo-datasource-rest soap jsonwebtoken --yes\n ---> Running in 1e4472bcd901\nnpm ERR! code ERESOLVE\nnpm ERR! ERESOLVE unable to resolve dependency tree\nnpm ERR! \nnpm ERR! While resolving: apollo-express-server@1.0.0\nnpm ERR! Found: graphql@15.4.0\nnpm ERR! node_modules/graphql\nnpm ERR! graphql@\"^15.3.0\" from the root project\nnpm ERR! \nnpm ERR! Could not resolve dependency:\nnpm ERR! peer graphql@\"^0.12.0 || ^0.13.0 || ^14.0.0\" from graphql-middleware@4.0.2\nnpm ERR! node_modules/graphql-middleware\nnpm ERR! graphql-middleware@\"^4.0.2\" from the root project\nnpm ERR! \nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force, or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\nnpm ERR! \nnpm ERR! See /root/.npm/eresolve-report.txt for a full report.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /root/.npm/_logs/2020-11-05T16_19_42_605Z-debug.log\nERROR: Service 'apollo' failed to build : The command '/bin/sh -c npm install --save cors apollo-server-express express graphql reflect-metadata type-graphql apollo-datasource-rest soap jsonwebtoken --yes' returned a non-zero code: 1\n```\n\n```text\nnpm install --save cors apollo-server-express express graphql@14 reflect-metadata type-graphql@0 apollo-datasource-rest soap jsonwebtoken\n```\n\n```text\nnode:current\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql\n```\n\n```text\ntype-graphql\n```\n\n```text\napollo-server-express\n```\n\n```text\ngraphql\n```\n\n```text\napollo-server-express\n```\n\n```text\ngraphql\n```\n\n```text\nnpm install\n```\n\n```text\ngraphql@14\n```\n\n```text\ntype-graphql@0\n```\n\n```text\ngraphql\n```\n\n```text\nnpm install --save express\nnpm install --save express-graphql\nnpm install --save graphql\nnpm install --save mongoose\n```\n\n```text\nnpm install --legacy-peer-deps\n```\n\n```text\nnpm install package_name --legacy-peer-deps\n```\n\n```text\nnpm install package_name --force\n```\n\n```text\npackage.json\n```\n\n```text\nnode:16-alpine3.11\n```\n\n```text\nnode:12-alpine3.11\n```\n\n```text\nnpm install --save --legacy-peer-deps\n```\n\n========================================\n\nComments:\n- Thank you. I had a similar issue with `express-grahql` after upgrading from Gatsby 2.x to 3.3.1. express-graphql was not on the main package.json so installing it added it to the package.json and fixed the warning. With similar warnings I guess looking for the package in the package.json and not seeing it is the first thing to fix.\n- This solution still work with npm 8.","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":310,"estimatedTokens":1871}}102{"id":"stack-51285621","source":"stackoverflow","questionId":51285621,"title":"GraphQL project structure","tags":["javascript","node.js","graphql"],"text":"Title: GraphQL project structure\nTags: javascript, node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nWhat is the best way to structure a graphQL project/server side? \nthis is my current structure \n\n- src\nconfig\n\nmodels\n\n- setup\nschema\n\nqueries\n\n- index\n\n- userQuery\n\nresolvers\n\n- index\n\n- userResolver\n\ntypes\n\n- index\n\n- userType\n\n========================================\n\nTop Answer:\n```\nsrc\n schema\n Product\n model.js\n query.js\n mutation.js\n type.js\n resolvers.js\n index.js\n Order\n query.js\n mutation.js\n model.js\n types.js\n resolvers.js\n index.js\n index.js\n```\n\n***let's explore what's inside the Product directory***\n\n**query.js**: all the query resolvers related to the Product\n\n**mutations.js**: all the mutation resolvers related to the Product\n\n**types.js**: all the Product related GraphQL types also query and mutation included (export a string containing GraphQL types).\n\n**mode.js**: the Product database schema.\n\n**resolvers.js**: all the resolvers related to the Product type.\ne.g:\n\n```\nlet Product = {\n comments: (user: id) => {\n // whatever\n }\n}\n```\n\n**Product/index.js**: combine all the files and export them as *Query*, *Mutation*, *types*, *Product* (Product type fields resolvers).\n\n***Note:*** you can also convert query.js or any one of them to a folder and then write each query and mutation resolver in its own file.\n\n**schema/index.js**: combine all the exported *Query*, *Mutation*, *type* inside index.js and export them as *resolvers* and *typeDefs*\n\ne.g\n\n```\nexport const resolvers = {\n Query: {\n ...ProductQueries,\n ...OrderQueries,\n },\n Mutation: {\n ...ProductQueries,\n ...OrderMutations,\n },\n // schema/Proudct/resolvers.js\n Product,\n Order\n}\n```\n\nFor a complete description this link\nhttps://theehsansarshar.hashnode.dev/scalable-graphql-architecture\n\n========================================\n\nCode:\n```text\nsrc/\nβββ user/\nβ βββ data.ts\nβ βββ mutation.ts\nβ βββ query.ts\nβ βββ type.ts\nβββ bananas/\nβ βββ data.ts\nβ βββ mutation.ts\nβ βββ query.ts\nβ βββ type.ts\nβββ utils/\nβ βββ database.ts\nβ βββ config.ts\nβββ index.ts\nβββ schema.ts\n```\n\n```text\nsrc\n schema\n Product\n model.js\n query.js\n mutation.js\n type.js\n resolvers.js\n index.js\n Order\n query.js\n mutation.js\n model.js\n types.js\n resolvers.js\n index.js\n index.js\n```\n\n```text\nlet Product = {\n comments: (user: id) => {\n // whatever\n }\n}\n```\n\n```text\nexport const resolvers = {\n Query: {\n ...ProductQueries,\n ...OrderQueries,\n },\n Mutation: {\n ...ProductQueries,\n ...OrderMutations,\n },\n // schema/Proudct/resolvers.js\n Product,\n Order\n}\n```\n\n========================================\n\nComments:\n- Looks good! And, here's another example that's similar, I think π€\n- What do you handle in `data.ts` files?\n- @jastor_007 it is just functions to handle data request/response from database.\n- @MarcoDaniel Hi, how you connect all mutation and queries in single file?\n- π @Dan, I connect them all in the `schema.ts` file. Here I have a very old example I made, it still shows the idea: github.com/MarcoDaniels/graphql-demo/blob/master/services/AP‌​I/…\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":180,"estimatedTokens":861}}103{"id":"stack-58497740","source":"stackoverflow","questionId":58497740,"title":"nestjs context.swithToHttp().getRequest() returns undefined","tags":["graphql","nestjs"],"text":"Title: nestjs context.swithToHttp().getRequest() returns undefined\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to create RolesGuard for Graphql\n\nI create Roles decorator like following\n\n```\nexport const Roles = (...roles: string[]) => SetMetadata('roles', roles);\n```\n\nAnd I create GqlAuthGuard and RolesGuard like following\n\n```\ngql-gurad.ts\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n getRequest(context: ExecutionContext){\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req;\n }\n}\n\nrole-guard.ts\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\nconstructor(private readonly reflector: Reflector) {}\n\n canActivate(context: ExecutionContext): boolean {\n const roles = this.reflector.get('roles', context.getHandler());\n if (!roles) {\n return true;\n }\n const request = context.switchToHttp().getRequest();\n const user = request.user;\n\n ...\n }\n}\n```\n\nbut line `const request = context.switchToHttp().getRequest();` returns undefined.\n\nand i'm using two guards like following\n\n```\n@AuthGuard(GqlAuthGuard, RolesGuard)\n@Mutation(...)\n```\n\nWhat did I miss??\n\n========================================\n\nCode:\n```text\nexport const Roles = (...roles: string[]) => SetMetadata('roles', roles);\n```\n\n```text\ngql-gurad.ts\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n getRequest(context: ExecutionContext){\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req;\n }\n}\n\nrole-guard.ts\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\nconstructor(private readonly reflector: Reflector) {}\n\n canActivate(context: ExecutionContext): boolean {\n const roles = this.reflector.get<string[]>('roles', context.getHandler());\n if (!roles) {\n return true;\n }\n const request = context.switchToHttp().getRequest();\n const user = request.user;\n\n ...\n }\n}\n```\n\n```text\n@AuthGuard(GqlAuthGuard, RolesGuard)\n@Mutation(...)\n```\n\n```text\nconst request = context.switchToHttp().getRequest();\n```\n\n```text\nconst request = context.switchToHttp().getRequest();\nconst user = request.user;\n\nto\n\nconst ctx = GqlExecutionContext.create(context);\nconst user = ctx.getContext().req.user;\n```\n\n========================================\n\nComments:\n- Where does the `user` property come from? In what I'm making I have the concept of an organization instead of a user, but the `.getRequest()` still returns the `user` property but with my organization on it. I mean it works fine, it's just an odd forced naming convention that doesn't apply to me. I'd like to change it if possible.\n- @ChrisBarr when you use passport, the user property will be dynamically attached to your object of value extracted from Req decorator with req user is the value returned from your validate() method in your defined Strategy, for example: import {Strategy} from passport-local, localStrategy extends passport(Strategy). Maybe too late but hope it helps you in the foreseeable future !\n- Another usecase where `context.switchToHttp().getRequest()` returns undefined is with websocket. I met the case with a global guard + adding websocket (through graphql). Such guard has to be reimagined for websocket if, for example, relying on HTTP headers.\n- You must check context type before using it. `if (context.getType() === 'http') { const req = context.switchToHttp().getRequest(); }`","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":119,"estimatedTokens":862}}104{"id":"stack-66241844","source":"stackoverflow","questionId":66241844,"title":"Using gRPC and/or GraphQL for microservice architecture","tags":["architecture","graphql","microservices","grpc","rpc"],"text":"Title: Using gRPC and/or GraphQL for microservice architecture\nTags: architecture, graphql, microservices, grpc, rpc\nSource: Stack Overflow\n\nQuestion:\nAt my company we're about to set up a new microservice architecture, but we're still trying to decide which protocol would be best for our use case.\n\nIn our case we have some services that are called internally by other services, but are also exposed via a GraphQL API gateway towards our clients.\n\n### Option 1: gRPC\n\ngRPC seems to be a popular choice for microservice internal communication because of its performance and efficiency.\n\nHowever, gRPC makes it more difficult to query relational data and requires more work to hook up to our API gateway.\n\n### Option 2: GraphQL\n\nAnother option is for each microservice to implement their own GraphQL schema so they can be easily stitched together using Apollo Federation in the API gateway.\n\nThis approach will make queries more flexible, but internal requests become less performant because of the lack of protocol buffers.\n\n### Option 3: Both?\n\nPerhaps another alternative is to use the best of both worlds by implementing mutations in gRPC and queries in GraphQL. Or just creating two APIs, one facing the gateway clients and one for communication between services.\n\n### Questions\n\n- How do we decide which approach to use?\n\n- Are there any significant (dis)advantages we should consider? E.g. in terms of ease of use, maintainability, scalability, performance, etc?\n\n- Are there better alternatives for this use case?\n\n========================================\n\nTop Answer:\nI would suggest that you should go with gRPC for internal services communication as it is fast. Now comes what should you use for external communication, you may use REST or Graph QL. Graph QL is good option if different type of Client needs different amount of data otherwise REST will be easier to implement.\n\nIn one of my project, we have used the gRPC for internal communication (services are in Go language) & for external communication, we have used REST. Go have some packages which help to develop service expose using REST and internally communicating with other service using gRPC. So, in our scenario, it was working fine.\n\n========================================\n\nComments:\n- There is nothing wrong with your question. Somebody is not just feeling right!\n- It is not a good choice. In real life REST or GRPC tend to make hard to change contract between back and front. REST and GRPC just not flexible enough.","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":45,"estimatedTokens":625}}105{"id":"stack-52772836","source":"stackoverflow","questionId":52772836,"title":"How to return an array of objects in GraphQL, possibly using the same endpoint as the one that returns a single object?","tags":["javascript","node.js","graphql","graphql-js","express-graphql"],"text":"Title: How to return an array of objects in GraphQL, possibly using the same endpoint as the one that returns a single object?\nTags: javascript, node.js, graphql, graphql-js, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI am making a GraphQL API where I would be able to retrieve a car object by its id or retrieve all the cars when no parameter is provided. \n\nUsing the code below, I am successfully able to retrieve a single car object by supplying id as a parameter.\n\n**However, in the case where I would expect an array of objects i.e. when I supply no parameter at all, I get no result on GraphiQL.**\n\nschema.js\n\n```\nlet cars = [\n { name: \"Honda\", id: \"1\" },\n { name: \"Toyota\", id: \"2\" },\n { name: \"BMW\", id: \"3\" }\n];\n\nconst CarType = new GraphQLObjectType({\n name: \"Car\",\n fields: () => ({\n id: { type: GraphQLString },\n name: { type: GraphQLString }\n })\n});\n\nconst RootQuery = new GraphQLObjectType({\n name: \"RootQueryType\",\n fields: {\n cars: {\n type: CarType,\n args: {\n id: { type: GraphQLString }\n },\n resolve(parent, args) {\n if (args.id) {\n console.log(cars.find(car => car.id == args.id));\n return cars.find(car => car.id == args.id);\n }\n console.log(cars);\n //***Problem Here***\n return cars;\n }\n }\n }\n});\n```\n\nTest queries and their respective results:\n\nQuery 1\n\n```\n{\n cars(id:\"1\"){\n name\n }\n}\n```\n\nQuery 1 Response (Success) \n\n```\n{\n \"data\": {\n \"cars\": {\n \"name\": \"Honda\"\n }\n }\n}\n```\n\nQuery 2 \n\n```\n{\n cars{\n name\n }\n}\n```\n\nQuery 2 Response (Fail)\n\n```\n{\n \"data\": {\n \"cars\": {\n \"name\": null\n }\n }\n}\n```\n\nAny help would be much appreciated.\n\n========================================\n\nCode:\n```text\nlet cars = [\n { name: \"Honda\", id: \"1\" },\n { name: \"Toyota\", id: \"2\" },\n { name: \"BMW\", id: \"3\" }\n];\n\nconst CarType = new GraphQLObjectType({\n name: \"Car\",\n fields: () => ({\n id: { type: GraphQLString },\n name: { type: GraphQLString }\n })\n});\n\nconst RootQuery = new GraphQLObjectType({\n name: \"RootQueryType\",\n fields: {\n cars: {\n type: CarType,\n args: {\n id: { type: GraphQLString }\n },\n resolve(parent, args) {\n if (args.id) {\n console.log(cars.find(car => car.id == args.id));\n return cars.find(car => car.id == args.id);\n }\n console.log(cars);\n //***Problem Here***\n return cars;\n }\n }\n }\n});\n```\n\n```text\n{\n cars(id:\"1\"){\n name\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"cars\": {\n \"name\": \"Honda\"\n }\n }\n}\n```\n\n```text\n{\n cars{\n name\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"cars\": {\n \"name\": null\n }\n }\n}\n```\n\n```text\ncars: {\n type: new GraphQLList(CarType), // note the change here\n args: {\n id: {\n type: GraphQLString\n },\n },\n resolve: (parent, args) => {\n if (args.id) {\n return cars.filter(car => car.id === args.id);\n }\n return cars;\n }\n}\n```\n\n```text\ncars: {\n type: new GraphQLList(CarType),\n resolve: (parent, args) => cars,\n},\ncar: {\n type: CarType,\n args: {\n id: {\n // example of using GraphQLNonNull to make the id required\n type: new GraphQLNonNull(GraphQLString)\n },\n },\n resolve: (parent, args) => cars.find(car => car.id === args.id),\n}\n```\n\n```text\nname\n```\n\n```text\ncars\n```\n\n```text\nname\n```\n\n```text\nfilter\n```\n\n```text\nfind\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":227,"estimatedTokens":812}}106{"id":"stack-62122523","source":"stackoverflow","questionId":62122523,"title":"Wait for useLazyQuery response","tags":["reactjs","graphql","apollo-client"],"text":"Title: Wait for useLazyQuery response\nTags: reactjs, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI need to call a query when submit button is pressed and then handle the response.\n\nI need something like this:\n\n```\nconst [checkEmail] = useLazyQuery(CHECK_EMAIL)\nconst handleSubmit = async () => {\n const res = await checkEmail({ variables: { email: values.email }})\n console.log(res) // handle response\n}\n```\n\nTry #1: \n\n```\nconst [checkEmail, { data }] = useLazyQuery(CHECK_EMAIL)\nconst handleSubmit = async () => {\n const res = await checkEmail({ variables: { email: values.email }})\n console.log(data) // undefined the first time\n}\n```\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nThis works for me:\n\n```\nconst { refetch } = useQuery(CHECK_EMAIL, {\n skip: !values.email\n})\n\nconst handleSubmit = async () => {\n const res = await refetch({ variables: { email: values.email }})\n console.log(res)\n}\n```\n\n========================================\n\nCode:\n```text\nconst [checkEmail] = useLazyQuery(CHECK_EMAIL)\nconst handleSubmit = async () => {\n const res = await checkEmail({ variables: { email: values.email }})\n console.log(res) // handle response\n}\n```\n\n```text\nconst [checkEmail, { data }] = useLazyQuery(CHECK_EMAIL)\nconst handleSubmit = async () => {\n const res = await checkEmail({ variables: { email: values.email }})\n console.log(data) // undefined the first time\n}\n```\n\n```text\nexport function useLazyQuery<TData = any, TVariables = OperationVariables>(query: DocumentNode) {\n const client = useApolloClient()\n return React.useCallback(\n (variables: TVariables) =>\n client.query<TData, TVariables>({\n query: query,\n variables: variables,\n }),\n [client]\n )\n}\n```\n\n```text\nconst { refetch } = useQuery(CHECK_EMAIL, {\n skip: !values.email\n})\n\nconst handleSubmit = async () => {\n const res = await refetch({ variables: { email: values.email }})\n console.log(res)\n}\n```\n\n```text\nconst [checkEmail] = useLazyQuery(CHECK_EMAIL, {\n onCompleted: (data) => {\n console.log(data);\n }\n});\n\nconst handleSubmit = () => {\n checkEmail({ variables: { email: values.email }});\n}\n```\n\n```text\nonCompleted\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nimport { useLazyQuery } from \"@apollo/client\";\nimport { useState, useEffect } from \"react\";\nimport { GET_DOGS } from \"../../utils/apiUtils\";\n \nconst DisplayDogsLazy = () => {\n const [getDogs] = useLazyQuery(GET_DOGS);\n const [data, setData] = useState([]);\n \n useEffect(() => {\n getAllData();\n }, []);\n\n const getAllData = async () => {\n const response = await getDogs();\n console.log(\"Awaited response >\", response);\n };\n \n const handleGetDogsClick = async () => {\n const response = await getDogs();\n setData(response.data.dogs);\n };\n \n return (\n <>\n <button onClick={handleGetDogsClick}>Get Dogs</button>\n \n {data?.length > 0 && (\n <ul>\n {data?.map((dog) => (\n <li key={dog.id} value={dog.breed}>\n {dog.breed}\n </li>\n ))}\n </ul>\n )}\n </>\n );\n };\n \nexport default DisplayDogsLazy;\n```\n\n```text\nimport { useLazyQuery } from '@apollo/client';\n\nconst [myQuery] = useLazyQuery(MY_GQL_QUERY)\n\nconst result = await myQuery({ variables: { some: 'variable' }})\nconsole.log(result.data)\n```\n\n========================================\n\nComments:\n- Is this just a closure of client / apollo client so response is held in the closure - won't it be immediately invoked? UseLazy is supposed to be at call- but i guess that doesn't matter for the client, so i guess this is really good! Big brain stuff! Confused and interested, would love some more detail.\n- in @apollo/react-hooks@4.0.0, refetch accept the parameter as variable (no need to put inside variables properties. So it's `refetch({ email: values.email })`","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":166,"estimatedTokens":986}}107{"id":"stack-35968581","source":"stackoverflow","questionId":35968581,"title":"The significance of the string immediately after query type (query / mutation) GraphQL","tags":["graphql","graphql-js"],"text":"Title: The significance of the string immediately after query type (query / mutation) GraphQL\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI was wondering what the significance of the string that follows the query type, in this case \"ProvisionQueues\", it seems removing this from the string doesn't affect anything - is it just for logging or something. meta data?\n\n```\nmutation ProvisionQueues {\n createQueue(name: \"new-queue\") {\n url\n }\n}\n```\n\n========================================\n\nTop Answer:\nAdding to @Eric's answer with another example.\n\n```\nquery allNotifications {\n notifications {\n success\n errors\n notifications {\n id\n title\n description\n attachment\n createdAt\n }\n }\n} β\nβ\nquery {\n users {\n errors\n success\n users {\n id\n fullName\n }\n }\n}\n```\n\nNotice above that the users query has no **operation name**. This can be resolved as below.\nβ\n\n```\nquery allUsers {\n users {\n errors\n success\n users {\n id\n fullName\n mohalla\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nmutation ProvisionQueues {\n createQueue(name: \"new-queue\") {\n url\n }\n}\n```\n\n```text\nquery {\n user(id: 1) {\n name\n }\n}\n\nquery {\n user(id: 2) {\n name\n }\n}\n```\n\n```text\n\"message\": \"This anonymous operation must be the only defined operation.\"\n```\n\n```text\nquery allNotifications {\n notifications {\n success\n errors\n notifications {\n id\n title\n description\n attachment\n createdAt\n }\n }\n} β\nβ\nquery {\n users {\n errors\n success\n users {\n id\n fullName\n }\n }\n}\n```\n\n```text\nquery allUsers {\n users {\n errors\n success\n users {\n id\n fullName\n mohalla\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":133,"estimatedTokens":419}}108{"id":"stack-52347310","source":"stackoverflow","questionId":52347310,"title":"GraphQL Conditional Queries","tags":["node.js","express","graphql","graphiql"],"text":"Title: GraphQL Conditional Queries\nTags: node.js, express, graphql, graphiql\nSource: Stack Overflow\n\nQuestion:\nI'm a newbie in GraphQL and I was wondering if there is a easy way to query with \"dynamic conditions\".\n\nFor exemple, on GraphiQL I can query for :\n\n```\nquery {\n users{\n name\n age\n }\n}\n```\n\nAnd It will bring me a list of all users\n\n```\n{\n \"data\": {\n \"users\": [\n {\n \"name\": \"Luis Coimbra\",\n \"age\": 15\n },\n {\n \"name\": \"SebastiΓ£o Campagnucci\",\n \"age\": 50\n },\n {\n \"name\": \"Giovana Ribeiro\",\n \"age\": 30\n }\n ]\n }\n}\n```\n\nBut is there an easy way for me to bring only, for example, users who are above 18 or any other age ?\n\nAn expected solution would be:\n\n```\nquery {\n users{\n name\n age > 18\n }\n }\n```\n\nHaven't found anything like that on documentation...\n\n========================================\n\nTop Answer:\nYou should send your age filter as a parameter.You might try the following one:\n\nIn your graphql file\n\n```\ntype users {\n name: String,\n age: Int,\n ...\n}\n\nusersQuery(ageLimit: Int): [users]\n```\n\nalso you can send '>' , 'and you should configure your resolver where statement with these operators. hope it helps you.\n\n========================================\n\nCode:\n```text\nquery {\n users{\n name\n age\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"users\": [\n {\n \"name\": \"Luis Coimbra\",\n \"age\": 15\n },\n {\n \"name\": \"SebastiΓ£o Campagnucci\",\n \"age\": 50\n },\n {\n \"name\": \"Giovana Ribeiro\",\n \"age\": 30\n }\n ]\n }\n}\n```\n\n```text\nquery {\n users{\n name\n age > 18\n }\n }\n```\n\n```text\n{\n users(where: {age: { $gt: 18 }}){ #inspired by mongoDB query api\n name\n age\n }\n }\n```\n\n```text\n{\n users(where: {age: \">18\"}}){\n name\n age\n }\n }\n```\n\n```text\nwhere\n```\n\n```text\nusers\n```\n\n```text\ntype users {\n name: String,\n age: Int,\n ...\n}\n\nusersQuery(ageLimit: Int): [users]\n```\n\n```text\nusersQuery(ageLimit: Int, ageOperator: String): [users]\n```\n\n========================================\n\nComments:\n- Simplest - by parameters/variables like `minAge`, `maxAge` - it's resolver role to 'react' (use) conditionally when this optional parameters are defined.\n- good question. it's not elegant, judging from the answers","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":162,"estimatedTokens":564}}109{"id":"stack-63362483","source":"stackoverflow","questionId":63362483,"title":"Apollo client fragments not embedding data","tags":["graphql","apollo-client"],"text":"Title: Apollo client fragments not embedding data\nTags: graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nThis is the first time I've ventured into fragments and I can't see where I'm screwing up, but it definitely isn't working! In GraphiQL it's working fine:\n\n```\nquery Tasks($taskIds: [String]!) {\n tasks(taskIds: $taskIds) {\n ...taskDisplay\n }\n}\nfragment taskDisplay on Task {\n _id\n name\n description\n status\n children {\n _id\n }\n}\n```\n\nHere's what's in my client app:\n\n```\nimport { gql } from \"@apollo/client\";\n\nexport const TASK_FRAGMENT = gql`\n fragment taskDisplay on Task {\n _id\n name\n description\n status\n children {\n _id\n }\n }\n`;\n\nexport const TASKS = gql`\n query Tasks($taskIds: [String]!) {\n tasks(taskIds: $taskIds) {\n ...taskDisplay\n }\n }\n ${TASK_FRAGMENT}\n`;\n```\n\nSo, the server returns the data correct as I can see in the *Network* tab of Chrome, but the data received by the `useQuery` result is an empty object. What gives?\n\nUsing `@apollo/client@3.2.0-beta.2` (I have downgraded to 3.1.0 with same results)\n\n### EDIT:\n\nAdding more info. My code is about as simple as it could be using a hook. Here's what's happening:\n\n```\nimport { useQuery, gql } from \"@apollo/client\";\nimport { TASK_FRAGMENT } from \"../pages/task/queries\";\n\nconst ROOT_TASK_QUERY = gql`\n query Project($projectId: String!) {\n rootTask(projectId: $projectId) {\n ...taskDisplay\n }\n }\n ${TASK_FRAGMENT}\n`;\n\nconst useProject = ({ variables }) => {\n return useQuery(ROOT_TASK_QUERY, {\n variables,\n });\n};\nexport default useProject;\n```\n\nAnd this is just logging the query itself:\n\nhttps://i.sstatic.net/iueps.png\n\n========================================\n\nTop Answer:\nIn my case, I was using a fragment of an interface but returning back objects implementing that interface. In order to resolve this, you need to add `possibleTypes`:\n\n```\ncache: new InMemoryCache({\n possibleTypes: {\n GenericInterface: [\n 'TypeA',\n 'TypeB',\n 'TypeC',\n ],\n },\n}),\n```\n\nalso see here: https://github.com/apollographql/apollo-client/issues/7648\n\n========================================\n\nCode:\n```text\nquery Tasks($taskIds: [String]!) {\n tasks(taskIds: $taskIds) {\n ...taskDisplay\n }\n}\nfragment taskDisplay on Task {\n _id\n name\n description\n status\n children {\n _id\n }\n}\n```\n\n```text\nimport { gql } from \"@apollo/client\";\n\nexport const TASK_FRAGMENT = gql`\n fragment taskDisplay on Task {\n _id\n name\n description\n status\n children {\n _id\n }\n }\n`;\n\nexport const TASKS = gql`\n query Tasks($taskIds: [String]!) {\n tasks(taskIds: $taskIds) {\n ...taskDisplay\n }\n }\n ${TASK_FRAGMENT}\n`;\n```\n\n```text\nimport { useQuery, gql } from \"@apollo/client\";\nimport { TASK_FRAGMENT } from \"../pages/task/queries\";\n\nconst ROOT_TASK_QUERY = gql`\n query Project($projectId: String!) {\n rootTask(projectId: $projectId) {\n ...taskDisplay\n }\n }\n ${TASK_FRAGMENT}\n`;\n\nconst useProject = ({ variables }) => {\n return useQuery(ROOT_TASK_QUERY, {\n variables,\n });\n};\nexport default useProject;\n```\n\n```text\nuseQuery\n```\n\n```text\n@apollo/client@3.2.0-beta.2\n```\n\n```text\n__typename\n```\n\n```js\ncache: new InMemoryCache({\n possibleTypes: {\n GenericInterface: [\n 'TypeA',\n 'TypeB',\n 'TypeC',\n ],\n },\n}),\n```\n\n```text\npossibleTypes\n```\n\n========================================\n\nComments:\n- your returned data is missing the `__typename` field, might this be the cause?\n- OMG that's awesome. I had turned that off when I was learning Apollo 'cause I didn't see it's utility for what I was doing. That's exactly what it was. `const cache = new InMemoryCache({ addTypename: false });`\n- Post it as an answer and I'll mark it!\n- My pleasure, will do\n- Why does __typename need to be present for fragments to be embedded?\n- 1.5 years later, you fixed my issue too! Much appreciated\n- Also 1.5 years later, and you solved my issue! Thanks!\n- It can also be that you've set `addTypename` in the Apollo options to `false`.\n- Can anybody explain why this is the case?\n- 3 years later for me!\n- 4 years here to me","metadata":{"transformedAt":"2026-08-18T18:32:36.027Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":211,"estimatedTokens":1037}}110{"id":"stack-68356207","source":"stackoverflow","questionId":68356207,"title":"How to define an empty Object Type in a GraphQL schema?","tags":["graphql"],"text":"Title: How to define an empty Object Type in a GraphQL schema?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI want to specify my GraphQL API in a schema, but I also want to spread my schema out among multiple files. I want to be able to use `extend type Query` or `extend type Mutation` to add queries or mutations to the overall schema. For example, my `user.graphql` file is as follows:\n\n```\ntype User {\n id: ID!\n name: String!\n email: String!\n}\n\ntype UserResult {\n success: Boolean!\n errors: [String]\n user: User\n}\n\nextend type Query {\n user(userId: ID!): UserResult!\n}\n```\n\nThe `Query` Object Type is defined in a different file, `schema.graphql`:\n\n```\nschema {\n query: Query\n mutation: Mutation\n}\n\ntype Query {\n dummyField: Boolean\n}\n```\n\nThese files are combined when my application launches to produce the full API schema.\n\nFor `type Query` I have included a `dummyField` because I can't define an empty Object Type (one without fields) without getting an error. The following lines:\n\n```\ntype Query {}\n```\n\nand\n\n```\ntype Query {\n}\n```\n\nThrow errors like:\n\nline 988, in expect_token f\"Expected {get_token_kind_desc(kind)},\nfound {get_token_desc(token)}.\",\ngraphql.error.syntax_error.GraphQLSyntaxError: Syntax Error: Expected\nName, found '}'.\n\nI would prefer for these Object Types to be empty to avoid the `dummyField` polluting my code and to make it clear that the intention is for `Query` and `Mutation` to be extended in other files.\n\nI am using Flask with ariadne (0.13.0), which relies on graphql-core (3.1.5). I could not find anything in the most recent GraphQL specification about empty Object Types. Is it possible to declare empty Object Types in the schema, without using a placeholder field? If so, what is the correct syntax?\n\n========================================\n\nCode:\n```text\ntype User {\n id: ID!\n name: String!\n email: String!\n}\n\ntype UserResult {\n success: Boolean!\n errors: [String]\n user: User\n}\n\nextend type Query {\n user(userId: ID!): UserResult!\n}\n```\n\n```text\nschema {\n query: Query\n mutation: Mutation\n}\n\ntype Query {\n dummyField: Boolean\n}\n```\n\n```text\ntype Query {}\n```\n\n```text\ntype Query {\n}\n```\n\n```text\nextend type Query\n```\n\n```text\nextend type Mutation\n```\n\n```text\nuser.graphql\n```\n\n```text\nQuery\n```\n\n```text\nschema.graphql\n```\n\n```text\ntype Query\n```\n\n```text\ndummyField\n```\n\n```text\ndummyField\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\ntype Query\n\nextend type Query {\n a: Boolean;\n}\n```\n\n```text\n{ ... }\n```\n\n```text\nObjectTypeDefinition\n```\n\n```text\nFieldsDefinition\n```\n\n========================================\n\nComments:\n- Just to clarify for future readers, there seems to be a bit of confusion in the spec around this, as there are other Type Validation sections that require types to define at least one field (spec.graphql.org/October2021/#sel-FAHZhCFDBAACDA4qe). Also, other libraries such as `sangria` and `graphql-java` don't support empty types like shown in this example.","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":169,"estimatedTokens":745}}111{"id":"stack-48067366","source":"stackoverflow","questionId":48067366,"title":"Best practices for refetching part of a GraphQL query with Apollo?","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: Best practices for refetching part of a GraphQL query with Apollo?\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have the following `react-apollo`-wrapped GraphQL query:\n\n```\nuser(id: 1) {\n name\n friends {\n id\n name\n }\n}\n```\n\nAs semantically represented, it fetches the user with ID 1, returns its `name`, and returns the `id` and `name` of all of its friends.\n\nI then render this in a component structure like the following:\n\n```\ngraphql(ParentComponent)\n -> UserInfo\n -> ListOfFriends (with the list of friends passed in)\n```\n\nThis is all working for me. However, I wish to be able to refetch the list of friends for the current user.\n\nI can do `this.props.data.refetch()` on the parent component and updates will be propagated; however, I'm not sure this is the best practice, given that my GraphQL query looks something more like this,\n\n```\nuser(id: 1) {\n name\n foo1\n foo2\n foo3\n foo4\n foo5\n ...\n friends {\n id\n name\n }\n}\n```\n\nWhilst the only thing I wish to refetch is the list of friends.\n\nWhat is the best way to cleanly architect this? I'm thinking along the lines of binding an initially skipped GraphQL fetcher to the `ListOfFriends` component, which can be triggered as necessary, but would like some guidance on how this should be best done.\n\nThanks in advance.\n\n========================================\n\nCode:\n```text\nuser(id: 1) {\n name\n friends {\n id\n name\n }\n}\n```\n\n```text\ngraphql(ParentComponent)\n -> UserInfo\n -> ListOfFriends (with the list of friends passed in)\n```\n\n```text\nuser(id: 1) {\n name\n foo1\n foo2\n foo3\n foo4\n foo5\n ...\n friends {\n id\n name\n }\n}\n```\n\n```text\nreact-apollo\n```\n\n```text\nname\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\nthis.props.data.refetch()\n```\n\n```text\nListOfFriends\n```\n\n```text\nrefetch\n```\n\n```text\nUserInfo\n```\n\n```text\nListOfFriends\n```\n\n```text\nwithApollo()\n```\n\n```text\nthis.client.query\n```\n\n```text\nwithApollo\n```\n\n```text\nApolloClient\n```\n\n```text\nthis.client.query()\n```\n\n```text\n{ user(id: 1) { friendlist { ... } } }\n```\n\n========================================\n\nComments:\n- i believe apollo does provide caching out of the box\n- @mehulmpt Yes I understand that; however, I do not wish to cache; I wish to refetch a subsection of a query.\n- I think the question \"What is the **best** way to **cleanly** architect this\" is too subjective. Can you rephrase so it's less subjective?\n- Amazing. Thank you so much for your depth of insight.","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":155,"estimatedTokens":621}}112{"id":"stack-55904192","source":"stackoverflow","questionId":55904192,"title":"React Apollo Error: No more mocked responses for the query: mutation","tags":["reactjs","unit-testing","testing","graphql","apollo"],"text":"Title: React Apollo Error: No more mocked responses for the query: mutation\nTags: reactjs, unit-testing, testing, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\n**Intended outcome:**\n\nMockedProvider should mock my createPost mutation.\n\n**Actual outcome:**\n\n```\nError: No more mocked responses for the query: mutation...\n```\n\n**How to reproduce the issue:**\n\nI have a very simple repository. I also created a separate branch with example commit which is breaking the apollo mock provider.\n\n1) Mutation definition is here: https://github.com/developer239/react-apollo-graphql/blob/create-post-integration-tests/src/modules/blog/gql.js#L23\n\n```\nexport const CREATE_POST = gql`\n mutation createPost($title: String!, $text: String!) {\n createPost(title: $title, text: $text) {\n id\n title\n text\n }\n }\n`\n```\n\n2) The fake request is here: https://github.com/developer239/react-apollo-graphql/blob/create-post-integration-tests/test/utils/gql-posts.js#L68\n\n```\nexport const fakeCreatePostSuccess = {\n request: {\n query: CREATE_POST,\n variables: {\n title: 'Mock Title',\n text: 'Mock lorem ipsum text. And another paragraph.',\n }\n },\n result: {\n data: {\n createPost: {\n id: '1',\n title: 'Mock Title',\n text: 'Mock lorem ipsum text. And another paragraph.',\n },\n },\n },\n```\n\n3) The component that I am testing lives here: https://github.com/developer239/react-apollo-graphql/blob/create-post-integration-tests/src/pages/Blog/PostCreate/index.js#L24\n\n```\n push(`/posts/${id}`)}\n >\n {mutate => (\n <>\n \n\n### Create New Post\n\n mutate({ variables: values })} />\n \n )}\n \n```\n\n4) The failing test case lives here: https://github.com/developer239/react-apollo-graphql/blob/create-post-integration-tests/src/pages/Blog/PostCreate/index.test.js#L33\n\n```\ndescribe('on form submit', () => {\n it('should handle success', async () => {\n const renderer = renderApp(, ROUTE_PATHS.createPost, [\n fakeCreatePostSuccess,\n ])\n const { formSubmitButton } = fillCreatePostForm(renderer)\n fireEvent.click(formSubmitButton)\n await waitForElement(() => renderer.getByTestId(POST_DETAIL_TEST_ID))\n expect(renderer.getByTestId(POST_DETAIL_TEST_ID)).toBeTruthy()\n })\n })\n```\n\nIt seems that I followed all steps from the official documentation but I still can't make this work. Do you have any suggestions? π\n\n========================================\n\nCode:\n```text\nError: No more mocked responses for the query: mutation...\n```\n\n```text\nexport const CREATE_POST = gql`\n mutation createPost($title: String!, $text: String!) {\n createPost(title: $title, text: $text) {\n id\n title\n text\n }\n }\n`\n```\n\n```text\nexport const fakeCreatePostSuccess = {\n request: {\n query: CREATE_POST,\n variables: {\n title: 'Mock Title',\n text: 'Mock lorem ipsum text. And another paragraph.',\n }\n },\n result: {\n data: {\n createPost: {\n id: '1',\n title: 'Mock Title',\n text: 'Mock lorem ipsum text. And another paragraph.',\n },\n },\n },\n```\n\n```text\n<Mutation\n mutation={CREATE_POST}\n update={updatePostCache}\n onCompleted={({ createPost: { id } }) => push(`/posts/${id}`)}\n >\n {mutate => (\n <>\n <H2>Create New Post</H2>\n <PostForm submit={values => mutate({ variables: values })} />\n </>\n )}\n </Mutation>\n```\n\n```text\ndescribe('on form submit', () => {\n it('should handle success', async () => {\n const renderer = renderApp(<App />, ROUTE_PATHS.createPost, [\n fakeCreatePostSuccess,\n ])\n const { formSubmitButton } = fillCreatePostForm(renderer)\n fireEvent.click(formSubmitButton)\n await waitForElement(() => renderer.getByTestId(POST_DETAIL_TEST_ID))\n expect(renderer.getByTestId(POST_DETAIL_TEST_ID)).toBeTruthy()\n })\n })\n```\n\n```text\n{ Error: Network error: No more mocked responses for the query: query getDog($dogId: ID!) {\n dog(dogId: $dogId) {\n name\n __typename\n }\n}\n```\n\n```text\nMissing field __typename in {\n \"name\": \"dog\"\n}\n```\n\n```text\nconst mocks = [\n {\n request: {\n query: dogQuery,\n variables: {\n dogId: 1,\n },\n },\n result: {\n data: {\n dog: {\n name: 'dog',\n __typename: 'Dog',\n },\n },\n },\n },\n];\n```\n\n```text\naddTypename={false}\n```\n\n```text\n<MockedProvider>\n```\n\n```text\n__typename\n```\n\n```text\naddTypename={false}\n```\n\n```text\n__typename\n```\n\n========================================\n\nComments:\n- I will investigate that and approve the answer if it works. ππ","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":218,"estimatedTokens":1124}}113{"id":"stack-56932295","source":"stackoverflow","questionId":56932295,"title":"How to access final GraphQL-Reponse in nest.js with interceptor","tags":["node.js","graphql","nestjs"],"text":"Title: How to access final GraphQL-Reponse in nest.js with interceptor\nTags: node.js, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have implemented a `LoggingInterceptor` which should be able to access the final GraphQL-Response with its data- and error properties + the original request body and the authenticated user, which has been added to the request by `AuthGuard` before.*(EDIT: Partially solved by @jay-mcdoniel: `user` and `body` are accessible through `GqlExecutionContext.create(context).getContext()`)*\n\nIndeed the Interceptor just provides one fully resolved GraphQL-Object.\n\n```\n@Injectable()\nexport class LoggingInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable {\n return next.handle().pipe(tap(\n (allData) => console.log(allData),\n (error)=> console.log(error)));\n }\n}\n```\n\nThis is my Interceptor-Class. It's just calling the RxJS-Operator `tap` to log the current values of the observable.\n\nIf I run the following GraphQL-Request...\n\n```\nmutation {\n login(data: { username: \"admin\", password: \"123456\" }) {\n id\n username\n token\n }\n}\n```\n\n... my server answers correctly with the following response-body:\n\n```\n{\n \"data\": {\n \"login\": {\n \"id\": \"6f40be3b-cda9-4e6d-97ce-ced3787e9974\",\n \"username\": \"admin\",\n \"token\": \"someToken\"\n }\n }\n}\n```\n\nBut the content of `allData` which get's logged to console by my interceptor is the following:\n\n```\n{\n id: '6f40be3b-cda9-4e6d-97ce-ced3787e9974',\n isAdmin: true,\n username: 'admin',\n firstname: null,\n lastname: null,\n email: null,\n created: 2019-07-05T15:11:31.606Z,\n token: 'someToken'\n}\n```\n\nInstead I would like to see the information of the real response-body.\n\nI have additionally tried to access the HttpResponse by `context.switchToHttp().getResponse()`. But this only contains the parameters of the mutation-login-method:\n\n```\n{\n data: [Object: null prototype] { username: 'admin', password: '123456' }\n}\n```\n\n**EDIT**:\n\n`console.log(GqlExecutionContext.create(context).getContext());`\nprints (still no GraphQL-ResponseBody):\n\n```\n{\n headers: {\n /*...*/\n },\n user: /*...*/,\n body: {\n operationName: null,\n variables: {},\n query: 'mutation {\\n login(data: {username: \"admin\", password: ' +\n '\"123456\"}) {\\n token\\n id\\n username\\n isAdmin\\n }\\n' +\n '}\\n'\n },\n res: ServerResponse {\n _events: [Object: null prototype] { finish: [Function: bound resOnFinish] },\n _eventsCount: 1,\n _maxListeners: undefined,\n outputData: [],\n outputSize: 0,\n writable: true,\n _last: false,\n chunkedEncoding: false,\n shouldKeepAlive: true,\n useChunkedEncodingByDefault: true,\n sendDate: true,\n _removedConnection: false,\n _removedContLen: false,\n _removedTE: false,\n _contentLength: null,\n _hasBody: true,\n _trailer: '',\n finished: false,\n _headerSent: false,\n socket: Socket {\n connecting: false,\n _hadError: false,\n _parent: null,\n _host: null,\n _readableState: [ReadableState],\n readable: true,\n _events: [Object],\n _eventsCount: 8,\n _maxListeners: undefined,\n _writableState: [WritableState],\n writable: true,\n allowHalfOpen: true,\n _sockname: null,\n _pendingData: null,\n _pendingEncoding: '',\n server: [Server],\n _server: [Server],\n timeout: 120000,\n parser: [HTTPParser],\n on: [Function: socketOnWrap],\n _paused: false,\n _httpMessage: [Circular],\n [Symbol(asyncId)]: 566,\n [Symbol(kHandle)]: [TCP],\n [Symbol(lastWriteQueueSize)]: 0,\n [Symbol(timeout)]: Timeout {\n /*...*/\n },\n [Symbol(kBytesRead)]: 0,\n [Symbol(kBytesWritten)]: 0\n },\n connection: Socket {\n connecting: false,\n _hadError: false,\n _parent: null,\n _host: null,\n _readableState: [ReadableState],\n readable: true,\n _events: [Object],\n _eventsCount: 8,\n _maxListeners: undefined,\n _writableState: [WritableState],\n writable: true,\n allowHalfOpen: true,\n _sockname: null,\n _pendingData: null,\n _pendingEncoding: '',\n server: [Server],\n _server: [Server],\n timeout: 120000,\n parser: [HTTPParser],\n on: [Function: socketOnWrap],\n _paused: false,\n _httpMessage: [Circular],\n [Symbol(asyncId)]: 566,\n [Symbol(kHandle)]: [TCP],\n [Symbol(lastWriteQueueSize)]: 0,\n [Symbol(timeout)]: Timeout {\n _idleTimeout: 120000,\n _idlePrev: [TimersList],\n _idleNext: [TimersList],\n _idleStart: 3273,\n _onTimeout: [Function: bound ],\n _timerArgs: undefined,\n _repeat: null,\n _destroyed: false,\n [Symbol(refed)]: false,\n [Symbol(asyncId)]: 567,\n [Symbol(triggerId)]: 566\n },\n [Symbol(kBytesRead)]: 0,\n [Symbol(kBytesWritten)]: 0\n },\n _header: null,\n _onPendingData: [Function: bound updateOutgoingData],\n _sent100: false,\n _expect_continue: false,\n req: IncomingMessage {\n /*...*/\n },\n locals: [Object: null prototype] {},\n [Symbol(isCorked)]: false,\n [Symbol(outHeadersKey)]: [Object: null prototype] {\n 'x-powered-by': [Array],\n 'access-control-allow-origin': [Array]\n }\n },\n _extensionStack: GraphQLExtensionStack { extensions: [ [CacheControlExtension] ] }\n}\n```\n\n========================================\n\nTop Answer:\nThe interceptor is actually called before and after the response, or it should be at least, so that you can have pre-request logic (request in) and post-request logic (response out). You should be able to do all pre-request processing before you call `next.hanlde()` and then you should be able to use the `RxJS Observable operators` such as `tap` or `map` after a `pipe()` call. Your `allData` variable should have all the information from the request/response, and you can even use the `context` variable for getting even more information.\n\nWhat does `allData` currently print for you? Have you tried `GqlExecutionContext.create(context).getContext().req` or `GqlExecutionContext.create(context).getContext().res`? These are shown being used in the `Guards` documentation to get the request and response objects like you would with a normal HTTP call.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class LoggingInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n return next.handle().pipe(tap(\n (allData) => console.log(allData),\n (error)=> console.log(error)));\n }\n}\n```\n\n```text\nmutation {\n login(data: { username: \"admin\", password: \"123456\" }) {\n id\n username\n token\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"login\": {\n \"id\": \"6f40be3b-cda9-4e6d-97ce-ced3787e9974\",\n \"username\": \"admin\",\n \"token\": \"someToken\"\n }\n }\n}\n```\n\n```text\n{\n id: '6f40be3b-cda9-4e6d-97ce-ced3787e9974',\n isAdmin: true,\n username: 'admin',\n firstname: null,\n lastname: null,\n email: null,\n created: 2019-07-05T15:11:31.606Z,\n token: 'someToken'\n}\n```\n\n```text\n{\n data: [Object: null prototype] { username: 'admin', password: '123456' }\n}\n```\n\n```text\n{\n headers: {\n /*...*/\n },\n user: /*...*/,\n body: {\n operationName: null,\n variables: {},\n query: 'mutation {\\n login(data: {username: \"admin\", password: ' +\n '\"123456\"}) {\\n token\\n id\\n username\\n isAdmin\\n }\\n' +\n '}\\n'\n },\n res: ServerResponse {\n _events: [Object: null prototype] { finish: [Function: bound resOnFinish] },\n _eventsCount: 1,\n _maxListeners: undefined,\n outputData: [],\n outputSize: 0,\n writable: true,\n _last: false,\n chunkedEncoding: false,\n shouldKeepAlive: true,\n useChunkedEncodingByDefault: true,\n sendDate: true,\n _removedConnection: false,\n _removedContLen: false,\n _removedTE: false,\n _contentLength: null,\n _hasBody: true,\n _trailer: '',\n finished: false,\n _headerSent: false,\n socket: Socket {\n connecting: false,\n _hadError: false,\n _parent: null,\n _host: null,\n _readableState: [ReadableState],\n readable: true,\n _events: [Object],\n _eventsCount: 8,\n _maxListeners: undefined,\n _writableState: [WritableState],\n writable: true,\n allowHalfOpen: true,\n _sockname: null,\n _pendingData: null,\n _pendingEncoding: '',\n server: [Server],\n _server: [Server],\n timeout: 120000,\n parser: [HTTPParser],\n on: [Function: socketOnWrap],\n _paused: false,\n _httpMessage: [Circular],\n [Symbol(asyncId)]: 566,\n [Symbol(kHandle)]: [TCP],\n [Symbol(lastWriteQueueSize)]: 0,\n [Symbol(timeout)]: Timeout {\n /*...*/\n },\n [Symbol(kBytesRead)]: 0,\n [Symbol(kBytesWritten)]: 0\n },\n connection: Socket {\n connecting: false,\n _hadError: false,\n _parent: null,\n _host: null,\n _readableState: [ReadableState],\n readable: true,\n _events: [Object],\n _eventsCount: 8,\n _maxListeners: undefined,\n _writableState: [WritableState],\n writable: true,\n allowHalfOpen: true,\n _sockname: null,\n _pendingData: null,\n _pendingEncoding: '',\n server: [Server],\n _server: [Server],\n timeout: 120000,\n parser: [HTTPParser],\n on: [Function: socketOnWrap],\n _paused: false,\n _httpMessage: [Circular],\n [Symbol(asyncId)]: 566,\n [Symbol(kHandle)]: [TCP],\n [Symbol(lastWriteQueueSize)]: 0,\n [Symbol(timeout)]: Timeout {\n _idleTimeout: 120000,\n _idlePrev: [TimersList],\n _idleNext: [TimersList],\n _idleStart: 3273,\n _onTimeout: [Function: bound ],\n _timerArgs: undefined,\n _repeat: null,\n _destroyed: false,\n [Symbol(refed)]: false,\n [Symbol(asyncId)]: 567,\n [Symbol(triggerId)]: 566\n },\n [Symbol(kBytesRead)]: 0,\n [Symbol(kBytesWritten)]: 0\n },\n _header: null,\n _onPendingData: [Function: bound updateOutgoingData],\n _sent100: false,\n _expect_continue: false,\n req: IncomingMessage {\n /*...*/\n },\n locals: [Object: null prototype] {},\n [Symbol(isCorked)]: false,\n [Symbol(outHeadersKey)]: [Object: null prototype] {\n 'x-powered-by': [Array],\n 'access-control-allow-origin': [Array]\n }\n },\n _extensionStack: GraphQLExtensionStack { extensions: [ [CacheControlExtension] ] }\n}\n```\n\n```text\nLoggingInterceptor\n```\n\n```text\nAuthGuard\n```\n\n```text\nuser\n```\n\n```text\nbody\n```\n\n```text\nGqlExecutionContext.create(context).getContext()\n```\n\n```text\ntap\n```\n\n```text\nallData\n```\n\n```text\ncontext.switchToHttp().getResponse()\n```\n\n```text\nconsole.log(GqlExecutionContext.create(context).getContext());\n```\n\n```text\n@Injectable()\nexport class LoggingInterceptor implements NestInterceptor {\n constructor(private readonly logger: Logger) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n // default REST Api\n if (context.getType() === 'http') {\n ...\n ...\n }\n\n // Graphql\n if (context.getType<GqlContextType>() === 'graphql') {\n const gqlContext = GqlExecutionContext.create(context);\n const info = gqlContext.getInfo();\n const res: Response = gqlContext.getContext().res;\n // Get user that sent request\n const userId = context.getArgByIndex(2).req.user.userId;\n const parentType = info.parentType.name;\n const fieldName = info.fieldName;\n const body = info.fieldNodes[0]?.loc?.source?.body;\n const message = `GraphQL - ${parentType} - ${fieldName}`;\n\n // Add request ID,so it can be tracked with response\n const requestId = uuidv4();\n // Put to header, so can attach it to response as well\n res.set('requestId', requestId);\n\n const trace = {\n userId,\n body\n };\n\n this.logger.info(`requestId: ${requestId}`, {\n context: message,\n trace\n });\n \n return next.handle().pipe(\n tap({\n next: (val: unknown): void => {\n this.logNext(val, context);\n }\n })\n );\n }\n return next.handle();\n }\n\n /**\n * Method to log response message\n */\n private logNext(body: unknown, context: ExecutionContext): void {\n // default REST Api\n if (context.getType() === 'http') {\n ...\n ...\n }\n\n if (context.getType<GqlContextType>() === 'graphql') {\n const gqlContext = GqlExecutionContext.create(context);\n const info = gqlContext.getInfo();\n const parentType = info.parentType.name;\n const fieldName = info.fieldName;\n const res: Response = gqlContext.getContext().res;\n const message = `GraphQL - ${parentType} - ${fieldName}`;\n\n // Remove secure fields from request body and headers\n const secureBody = secureReqBody(body);\n\n const requestId = res.getHeader('requestId');\n\n // Log trace message\n const trace = {\n body: { ...secureBody }\n };\n this.logger.info(`requestId: ${requestId}`, {\n context: message,\n trace\n });\n }\n }\n}\n```\n\n```text\nnext.hanlde()\n```\n\n```text\nRxJS Observable operators\n```\n\n```text\ntap\n```\n\n```text\nmap\n```\n\n```text\npipe()\n```\n\n```text\nallData\n```\n\n```text\ncontext\n```\n\n```text\nallData\n```\n\n```text\nGqlExecutionContext.create(context).getContext().req\n```\n\n```text\nGqlExecutionContext.create(context).getContext().res\n```\n\n```text\nGuards\n```\n\n========================================\n\nComments:\n- I'm not even able to print anything with this in case of graphql query, however this is working fine with regular controller calls.\n- Thx so far! `allData` contains the requested data you would find inside the data property of the graphql reponse plus all properties that got resolved by typeorm relations (even that ones which aren't present in the graphql request). That's why I called it `allData`. It's not a partial object. `GqlExecutionContext.create(context).getContext()` works for reading `context.body.query` and `context.user`. But it is still not possible to access `graphqlResponse` because it is not part of the context.\n- I have added some more examples to my question and removed unnecessary information.\n- To be honest, I think the response body you are looking for is something that Nest handles under the hood and isn't quite exposed to us without really getting into the internals. I'm trying to read through the source code, but I can't promise much will come out of it\n- I have totally forgot to post the log of `GqlExecutionContext.create(context).getContext()`. I have updated my question with the information.\n- Yeah, I was doing some digging both with my GraphQL code and with the source code, and I'm pretty sure the `GraphQLRespnse` you are looking for is taken care of under the hood and not exposed, but without 100% understanding it I couldn't say.\n- Hello there, This **GqlExecutionContext.create(context).getContext().req** works fine and returns whole request, But **GqlExecutionContext.create(context).getContext().res** returns undefined, Any Solution for it?\n- @AmmarAhmed do you have the `context` set correctly to set up the `req` and `res` in your `GraphqlModule.forRoot/Async`?\n- HI @JayMcDoniel I am setting **context** like this `GraphQLModule.forRoot({ autoSchemaFile: true, context: ({ req }) => ({ req }), }),`. How I can add res there?\n- `context: ({ req, res }) => ({ req, res })`","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":569,"estimatedTokens":3735}}114{"id":"stack-50770217","source":"stackoverflow","questionId":50770217,"title":"How to give Gatsby a GraphQL schema","tags":["javascript","reactjs","graphql","gatsby"],"text":"Title: How to give Gatsby a GraphQL schema\nTags: javascript, reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nWe're bringing in some posts from a Wordpress backend, some have pictures (in an ACF field) and some don't. The problem is that Gatsby infers the schema based off of the first node it receives. If it receives a node without a picture, then the schema is wrong.\n\n Where does Gatsbyβs GraphQL schema come from?\n With Gatsby, we use plugins which fetch data from different sources. We then use that data to automatically infer a GraphQL schema.\n\nHow can we dictate a schema to GraphQL/Gatsby that always includes a picture, with 'null' as the default value if it's blank?\n\n```\n{\n allWordpressWpTestimonial {\n edges {\n node {\n id\n title\n acf {\n photo_fields {\n photo {\n id\n localFile {\n childImageSharp {\n sizes {\n src\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\nIn the example above, sometimes 'photo' doesn't exist and it breaks everything...\n\n**Gatsby config:**\n\n```\nconst innertext = require('innertext')\nconst url = require('url')\n\nmodule.exports = {\n siteMetadata: {\n title: 'Test',\n googleMapsAPIKey: 'xxxxxx',\n adminBaseUrl: '123.123.123',\n adminProtocol: 'http',\n },\n pathPrefix: '/web/beta',\n plugins: [\n 'gatsby-plugin-react-next',\n 'gatsby-plugin-react-helmet',\n 'gatsby-plugin-sharp',\n 'gatsby-plugin-svgr',\n {\n resolve: 'gatsby-plugin-google-analytics',\n options: {\n trackingId: 'GOOGLE_ANALYTICS_TRACKING_ID',\n },\n },\n {\n resolve: 'gatsby-plugin-bugherd',\n options: {\n key: 'xxxxxx',\n showInProduction: true,\n },\n },\n {\n resolve: '@andrew-codes/gatsby-plugin-elasticlunr-search',\n options: {\n fields: ['title', 'url', 'textContent', 'urlSearchable'],\n resolvers: {\n wordpress__PAGE: {\n title: node => node.title,\n textContent: node => innertext(node.content),\n url: node => url.parse(node.link).path,\n urlSearchable: node =>\n url\n .parse(node.link)\n .path.split('/')\n .join(' '),\n },\n wordpress__POST: {\n title: node => node.title,\n textContent: node => innertext(node.content),\n url: node => `/news/${node.slug}`,\n urlSearchable: node =>\n url\n .parse(node.link)\n .path.split('/')\n .join(' '),\n },\n wordpress__wp_industry: {\n title: node => node.title,\n textContent: node => innertext(node.content),\n url: node => `/business/industries/${node.slug}`,\n urlSearchable: node =>\n url\n .parse(node.link)\n .path.split('/')\n .join(' '),\n },\n },\n },\n },\n {\n resolve: 'gatsby-source-wordpress',\n options: {\n baseUrl: 'xxxxxx',\n protocol: 'http',\n hostingWPCOM: false,\n useACF: true,\n auth: {\n htaccess_user: 'admin',\n htaccess_pass: 'xxxxxx',\n htaccess_sendImmediately: false,\n },\n verboseOutput: false,\n },\n },\n 'gatsby-transformer-sharp',\n ],\n}\n```\n\n========================================\n\nTop Answer:\nFirst are you using Gatsby-plugin-sharp, Gatsby-transform-sharp & Gatsby-source-WordPress Plugins ?\n\nMy site uses Gatsby-source-Wordpress Plugin plus the sharp library as well as Bluebird for returning promises etc.\nDefine the ImageURL on your Post.js or Page.js. The Source URL is produced when loaded in my Media Library but is offloaded to a S3 bucket because my WordPress site is built \"programmatically\".\nThe source URL is typically defined by you and can be chosen in ACF field types when build a post of page template.\n\n```\nexport const pageQuery = graphql`\n query homePageQuery {\n site {\n siteMetadata {\n title\n subtitle\n description\n }\n }\n\n allWordpressPost(sort: { fields: [date] }) {\n edges {\n node {\n title\n excerpt\n slug\n type\n _image{\n source_url\n }\n categories {\n slug\n name\n }\n }\n }\n }\n }\n```\n\nQuerying the data in the exact order is a must for each post type or GraphQL will not return the scheme correctly which will produce an error.\nAs simple as it sounds and duplicative, there will have to be two different GraphQL schemes at times and two post.js example post1.js and post2.js files defining the different post categories.\n1.Query for the return with Images URL.\n2.Query for the return with no Images. to equal null or non-existant\nThat is a downfall of GraphQL it expects to receive X and when Y happens it gets unhappy and fails.\n\nYou could also try this when you receive the image transform it with sharp to href= and transform it from https to size it on receiving.But in your case scheme it to be null.\nWe did this for a employee bio page that was return from an old WordPress site.\n\n```\n/**\n * Transform internal absolute link to relative.\n * \n * @param {string} string The HTML to run link replacemnt on\n */\n linkReplace(string) {\n // console.log(string)\n const formatted = string.replace(\n /(href=\"https?:\\/\\/dev-your-image-api\\.pantheonsite\\.io\\/)/g,\n `href=\"/`\n )\n\n return formatted\n }\n\n render() {\n const post = { ...this.props.data.wordpressPost }\n const headshot = { ...this.props.data.file.childImageSharp.resolutions }\n const { percentScrolled } = { ...this.state }\n const contentFormatted = this.linkReplace(post.content)\n\n return (\n (this.post = el)}>\n \n \n \n\n \n \n\n \n\n \n \n \n )\n }\n}\n\nPost.propTypes = {\n data: PropTypes.object.isRequired,\n}\n\nexport default Post\n\nexport const postQuery = graphql`\n query currentPostQuery($id: String!) {\n wordpressPost(id: { eq: $id }) {\n wordpress_id\n title\n content\n slug\n }\n file(relativePath: { eq: \"your-image-headshot.jpg\" }) {\n childImageSharp {\n resolutions(width: 300, height: 300) {\n ...GatsbyImageSharpResolutions\n }\n }\n }\n }\n```\n\n`\n\nHope this helps feel free to message me.\n\n========================================\n\nCode:\n```text\n{\n allWordpressWpTestimonial {\n edges {\n node {\n id\n title\n acf {\n photo_fields {\n photo {\n id\n localFile {\n childImageSharp {\n sizes {\n src\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nconst innertext = require('innertext')\nconst url = require('url')\n\nmodule.exports = {\n siteMetadata: {\n title: 'Test',\n googleMapsAPIKey: 'xxxxxx',\n adminBaseUrl: '123.123.123',\n adminProtocol: 'http',\n },\n pathPrefix: '/web/beta',\n plugins: [\n 'gatsby-plugin-react-next',\n 'gatsby-plugin-react-helmet',\n 'gatsby-plugin-sharp',\n 'gatsby-plugin-svgr',\n {\n resolve: 'gatsby-plugin-google-analytics',\n options: {\n trackingId: 'GOOGLE_ANALYTICS_TRACKING_ID',\n },\n },\n {\n resolve: 'gatsby-plugin-bugherd',\n options: {\n key: 'xxxxxx',\n showInProduction: true,\n },\n },\n {\n resolve: '@andrew-codes/gatsby-plugin-elasticlunr-search',\n options: {\n fields: ['title', 'url', 'textContent', 'urlSearchable'],\n resolvers: {\n wordpress__PAGE: {\n title: node => node.title,\n textContent: node => innertext(node.content),\n url: node => url.parse(node.link).path,\n urlSearchable: node =>\n url\n .parse(node.link)\n .path.split('/')\n .join(' '),\n },\n wordpress__POST: {\n title: node => node.title,\n textContent: node => innertext(node.content),\n url: node => `/news/${node.slug}`,\n urlSearchable: node =>\n url\n .parse(node.link)\n .path.split('/')\n .join(' '),\n },\n wordpress__wp_industry: {\n title: node => node.title,\n textContent: node => innertext(node.content),\n url: node => `/business/industries/${node.slug}`,\n urlSearchable: node =>\n url\n .parse(node.link)\n .path.split('/')\n .join(' '),\n },\n },\n },\n },\n {\n resolve: 'gatsby-source-wordpress',\n options: {\n baseUrl: 'xxxxxx',\n protocol: 'http',\n hostingWPCOM: false,\n useACF: true,\n auth: {\n htaccess_user: 'admin',\n htaccess_pass: 'xxxxxx',\n htaccess_sendImmediately: false,\n },\n verboseOutput: false,\n },\n },\n 'gatsby-transformer-sharp',\n ],\n}\n```\n\n```text\n---\ntitle: \"Screen title\"\nimage: \"./hero-image.png\" <--- sometimes it's an empty string, \"\"\ncategory: \"Cat\"\n---\n\n...content...\n```\n\n```text\nexports.sourceNodes = ({ actions, schema }) => {\n const { createTypes } = actions\n createTypes(`\n type MarkdownRemarkFrontmatter {\n image: File\n }\n\n type MarkdownRemark implements Node {\n frontmatter: MarkdownRemarkFrontmatter\n }\n `)\n}\n```\n\n```text\ngatsby-transformer-remark\n```\n\n```text\n.md\n```\n\n```text\n.md\n```\n\n```text\nString\n```\n\n```text\nFile\n```\n\n```text\ngatsby-node.js\n```\n\n```text\nimage\n```\n\n```text\nnull\n```\n\n```text\nMarkdownRemark\n```\n\n```text\nNode\n```\n\n```text\nMarkdownRemarkFrontmatter\n```\n\n```text\nfrontmatter\n```\n\n```text\nMarkdownRemark\n```\n\n```text\ncategory\n```\n\n```text\nMarkdownRemarkFrontmatter\n```\n\n```text\nMarkdownRemark\n```\n\n```text\nMarkdownRemarkFrontmatter\n```\n\n```text\nlocalhost:8000/___graphql\n```\n\n```text\nexport const pageQuery = graphql`\n query homePageQuery {\n site {\n siteMetadata {\n title\n subtitle\n description\n }\n }\n\n allWordpressPost(sort: { fields: [date] }) {\n edges {\n node {\n title\n excerpt\n slug\n type\n _image{\n source_url\n }\n categories {\n slug\n name\n }\n }\n }\n }\n }\n```\n\n```text\n/**\n * Transform internal absolute link to relative.\n * \n * @param {string} string The HTML to run link replacemnt on\n */\n linkReplace(string) {\n // console.log(string)\n const formatted = string.replace(\n /(href=\"https?:\\/\\/dev-your-image-api\\.pantheonsite\\.io\\/)/g,\n `href=\"/`\n )\n\n return formatted\n }\n\n render() {\n const post = { ...this.props.data.wordpressPost }\n const headshot = { ...this.props.data.file.childImageSharp.resolutions }\n const { percentScrolled } = { ...this.state }\n const contentFormatted = this.linkReplace(post.content)\n\n return (\n <div ref={el => (this.post = el)}>\n <div className={styles.progressBarWrapper}>\n <div\n style={{ width: `${percentScrolled}%` }}\n className={styles.progressBar}\n />\n </div>\n\n <div className={styles.post}>\n <h1\n className={styles.title}\n dangerouslySetInnerHTML={{ __html: post.title }}\n />\n\n <div\n className={styles.content}\n dangerouslySetInnerHTML={{ __html: contentFormatted }}\n />\n\n <Bio headshot={headshot} horizontal={true} />\n </div>\n </div>\n )\n }\n}\n\nPost.propTypes = {\n data: PropTypes.object.isRequired,\n}\n\nexport default Post\n\nexport const postQuery = graphql`\n query currentPostQuery($id: String!) {\n wordpressPost(id: { eq: $id }) {\n wordpress_id\n title\n content\n slug\n }\n file(relativePath: { eq: \"your-image-headshot.jpg\" }) {\n childImageSharp {\n resolutions(width: 300, height: 300) {\n ...GatsbyImageSharpResolutions\n }\n }\n }\n }\n```\n\n========================================\n\nComments:\n- Which plugin to extract the source from Wordpress are you using? Could you your gatsby config file?\n- gatsby-source-wordpress, will update with gatsby config\n- I'm struggling to get this to work with wordpress and acf. Each node has an ACF object, within that a repeater object, with that an array for a Link with 3 strings (title, url, target). I've tried creating a series of functions as above to mine all the way down to the 3 strings, this doesn't work for me. { allWordpressPost { edges { node { title acf { project_students partners { partner_link { title url target } } } } } } }","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":573,"estimatedTokens":3036}}115{"id":"stack-45242250","source":"stackoverflow","questionId":45242250,"title":"GraphQL use field value as variable for another query","tags":["javascript","reactjs","graphql","apollo"],"text":"Title: GraphQL use field value as variable for another query\nTags: javascript, reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm querying for 2 objects which are both needed in the same component. The problem is that one of the queries have to wait on the other and use its `id` field as an argument for the other. Not sure how to implement this.\n\n```\nconst PlayerQuery = gql`query PlayerQuery($trackId: Int!, $duration: Int!, $language: String!) {\n subtitle(trackId: $trackId, duration: $duration) {\n id,\n lines {\n text\n time\n }\n }\n translation(trackId: $trackId, language: $language, subtitleId: ???) {\n lines {\n translation\n original\n }\n }\n}`;\n```\n\nSo in the query above `translation` needs `subtitleId` as an argument which is returned by the `subtitle` query.\n\nI'm using Apollo both on the client and on the server.\n\n========================================\n\nCode:\n```text\nconst PlayerQuery = gql`query PlayerQuery($trackId: Int!, $duration: Int!, $language: String!) {\n subtitle(trackId: $trackId, duration: $duration) {\n id,\n lines {\n text\n time\n }\n }\n translation(trackId: $trackId, language: $language, subtitleId: ???) {\n lines {\n translation\n original\n }\n }\n}`;\n```\n\n```text\nid\n```\n\n```text\ntranslation\n```\n\n```text\nsubtitleId\n```\n\n```text\nsubtitle\n```\n\n```text\nconst Translation = new GraphQLObjectType({\n name: \"Translation\",\n fields: {\n id: { type: GraphQLInt },\n lines: { type: Lines }\n }\n});\n\nconst SubTitle = new GraphQLObjectType({\n name: \"SubTitle\",\n fields: {\n lines: { type: Lines }\n }\n});\n\nconst RootQuery = new GraphQLObjectType({\n name: \"RootQuery\",\n fields: {\n subtitle: { type: SubTitle },\n translation: { type: Translation }\n }\n});\n\nmodule.exports = new GraphQLSchema({\n query: RootQuery\n});\n```\n\n```text\nconst Translation = new GraphQLObjectType({\n name: \"Translation\",\n fields: {\n id: { type: GraphQLInt },\n lines: { type: Lines }\n }\n});\n\nconst SubTitle = new GraphQLObjectType({\n name: \"SubTitle\",\n fields: {\n lines: { type: Lines }\n translations: {\n type: Translation,\n resolve: () => {\n // Inside this resolver you should have access to the id you need\n return { /*...*/ }\n }\n }\n }\n});\n\nconst RootQuery = new GraphQLObjectType({\n name: \"RootQuery\",\n fields: {\n subtitle: { type: SubTitle }\n }\n});\n\nmodule.exports = new GraphQLSchema({\n query: RootQuery\n});\n```\n\n```text\nsubtitle\n```\n\n```text\ntranslation\n```\n\n```text\nschema\n```\n\n```text\ntranslation\n```\n\n```text\nsubtitle\n```\n\n========================================\n\nComments:\n- I only just started with GraphQL, but from what I understand, that's not possible. If `translation` was referenced from the `subtitle` or `lines` types in the schema, it probably *would* be possible, because the resolver would receive the `subtitle` object.\n- Thanks for confirming my suspicion, and providing a proper answer :)\n- If you wouldn't mind, can you click the checkmark to confirm that this is a correct answer? You just upvoted it (which I also appreciate) :).\n- I can't as I wasn't the one asking the question :)\n- @Baer yeah, I was thinking that this is the only way to pull it off, and after all it makes sense. I'll give it a try!\n- I was looking for this same question, what if we don't have access to the schema to modify it? I'm looking for something like result of query as input to another query...","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":159,"estimatedTokens":854}}116{"id":"stack-71400221","source":"stackoverflow","questionId":71400221,"title":"SyntaxError: Named export 'ApolloClient' not found","tags":["javascript","graphql","apollo-client"],"text":"Title: SyntaxError: Named export 'ApolloClient' not found\nTags: javascript, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create server with ApolloClient and GraphQL but got the following error:\n\nSyntaxError: Named export 'ApolloClient' not found. The requested\nmodule '@apollo/client' is a CommonJS module, which may not support\nall module.exports as named exports.\n\nmy code looks like this:\n\n```\nimport { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'\n\nconst httpLink = createHttpLink({\n uri: 'http://localhost:4000/graphql',\n})\n\nconst createApolloClient = () => {\n return new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n })\n}\n\nexport default createApolloClient\n```\n\nI tried\n\n```\nimport pkg from '@apollo/client'\nconst { ApolloClient, InMemoryCache, createHttpLink } = pkg\n```\n\nbut it didn't help\n\n========================================\n\nTop Answer:\nSolution for me:\n\n```\nimport { default as pkg } from '@apollo/client'\nconst { ApolloClient, ApolloProvider, InMemoryCache, createHttpLink } = pkg\n```\n\n========================================\n\nCode:\n```text\nimport { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'\n\nconst httpLink = createHttpLink({\n uri: 'http://localhost:4000/graphql',\n})\n\nconst createApolloClient = () => {\n return new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n })\n}\n\nexport default createApolloClient\n```\n\n```text\nimport pkg from '@apollo/client'\nconst { ApolloClient, InMemoryCache, createHttpLink } = pkg\n```\n\n```text\nimport { ApolloClient, InMemoryCache } from \"@apollo/client/core/core.cjs\";\nimport { HttpLink } from \"@apollo/client/link/http/http.cjs\";\n```\n\n```text\n{\n \"extends\": \"astro/tsconfigs/strict\",\n \"compilerOptions\": {\n \"strictNullChecks\": true,\n \"jsx\": \"react-jsx\",\n \"jsxImportSource\": \"react\",\n \"moduleResolution\": \"Bundler\"\n }\n}\n```\n\n```text\nimport { default as pkg } from '@apollo/client'\nconst { ApolloClient, ApolloProvider, InMemoryCache, createHttpLink } = pkg\n```\n\n========================================\n\nComments:\n- What version of Apollo Client?\n- @HumbleDeveloper01 I created new project but result is same\n- @DaveNewton Version is - 3.5.10\n- try to update last version and remove old version\n- @HumbleDeveloper01 That's the latest non-beta version.\n- Could you some detail about your use case where the Apollo Client is needing to be exported? Typically a component is used to query data from the client which appears to be the opposite of the pattern being used here.\n- How are you running ES modules? Where is this code executed (in the browser, in nodejs, something else)? Are you using any transpilation or bundling tools? What exactly is throwing that error, is there a stack trace?","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":106,"estimatedTokens":692}}117{"id":"stack-39379943","source":"stackoverflow","questionId":39379943,"title":"How to determine mutation loading state with react-apollo graphql","tags":["reactjs","graphql","apollostack"],"text":"Title: How to determine mutation loading state with react-apollo graphql\nTags: reactjs, graphql, apollostack\nSource: Stack Overflow\n\nQuestion:\n**2018 Update:** Apollo Client 2.1 added a new Mutation component that adds the loading property back. See @robin-wieruch's answer below and the announcement here https://dev-blog.apollodata.com/introducing-react-apollo-2-1-c837cc23d926 Read on for the original question which now only applies to earlier versions of Apollo.\n\nUsing the current version of the `graphql` higher-order-component in `react-apollo` (v0.5.2), I don't see a documented way to inform my UI that a mutation is awaiting server response. I can see that earlier versions of the package would send a property indicating loading.\n\nQueries still receive a loading property as documented here: http://dev.apollodata.com/react/queries.html#default-result-props\n\nMy application is also using redux, so I think one way to do it is to connect my component to redux and pass down a function property that will put my UI into a loading state. Then when rewriting my graphql mutation to a property, I can make calls to update the redux store.\n\nSomething roughly like this:\n\n```\nfunction Form({ handleSubmit, loading, handleChange, value }) {\n return (\n \n \n \n {loading ? 'Loading...' : 'Submit'}\n \n \n );\n}\n\nconst withSubmit = graphql(\n gql`\n mutation submit($something : String) {\n submit(something : $something) {\n id\n something\n }\n }\n `, \n {\n props: ({ ownProps, mutate }) => ({\n async handleSubmit() {\n ownProps.setLoading(true);\n try {\n const result = await mutate();\n } catch (err) {\n // @todo handle error here\n }\n ownProps.setLoading(false);\n },\n }),\n }\n);\n\nconst withLoading = connect(\n (state) => ({ loading: state.loading }),\n (dispatch) => ({\n setLoading(loading) {\n dispatch(loadingAction(loading));\n },\n })\n);\n\nexport default withLoading(withSubmit(Form));\n```\n\nI'm curious if there is a more idiomatic approach to informing the UI that the mutation is \"in-flight.\" Thanks.\n\n========================================\n\nTop Answer:\nAnyone who stumbles across this question, since Apollo Client 2.1 you have access to those properties in the Query and Mutation component's render props function.\n\n```\nimport React from \"react\";\nimport { Mutation } from \"react-apollo\";\nimport gql from \"graphql-tag\";\n\nconst TOGGLE_TODO = gql`\n mutation ToggleTodo($id: Int!) {\n toggleTodo(id: $id) {\n id\n completed\n }\n }\n`;\n\nconst Todo = ({ id, text }) => (\n \n {(toggleTodo, { loading, error, data }) => (\n \n \n {text}\n \n\n {loading && Loading...\n\n}\n {error && Error :( Please try again\n\n}\n \n )}\n \n);\n```\n\nNote: Example code taken from the Apollo Client 2.1 release blog post.\n\n========================================\n\nCode:\n```text\nfunction Form({ handleSubmit, loading, handleChange, value }) {\n return (\n <form onSubmit={handleSubmit}>\n <input\n name=\"something\"\n value={value}\n onChange={handleChange}\n disabled={loading}\n />\n <button type=\"submit\" disabled={loading}>\n {loading ? 'Loading...' : 'Submit'}\n </button>\n </form>\n );\n}\n\nconst withSubmit = graphql(\n gql`\n mutation submit($something : String) {\n submit(something : $something) {\n id\n something\n }\n }\n `, \n {\n props: ({ ownProps, mutate }) => ({\n async handleSubmit() {\n ownProps.setLoading(true);\n try {\n const result = await mutate();\n } catch (err) {\n // @todo handle error here\n }\n ownProps.setLoading(false);\n },\n }),\n }\n);\n\nconst withLoading = connect(\n (state) => ({ loading: state.loading }),\n (dispatch) => ({\n setLoading(loading) {\n dispatch(loadingAction(loading));\n },\n })\n);\n\nexport default withLoading(withSubmit(Form));\n```\n\n```text\ngraphql\n```\n\n```text\nreact-apollo\n```\n\n```text\nimport React from \"react\";\nimport { Mutation } from \"react-apollo\";\nimport gql from \"graphql-tag\";\n\nconst TOGGLE_TODO = gql`\n mutation ToggleTodo($id: Int!) {\n toggleTodo(id: $id) {\n id\n completed\n }\n }\n`;\n\nconst Todo = ({ id, text }) => (\n <Mutation mutation={TOGGLE_TODO} variables={{ id }}>\n {(toggleTodo, { loading, error, data }) => (\n <div>\n <p onClick={toggleTodo}>\n {text}\n </p>\n {loading && <p>Loading...</p>}\n {error && <p>Error :( Please try again</p>}\n </div>\n )}\n </Mutation>\n);\n```\n\n========================================\n\nComments:\n- Asking myself the exact same question (*redux + apollo client: mutation loading state*). Nowadays (*few weeks later*) I did not find any more clue about it. I still use the same approach as yours...\n- Mutations are called from within the component itself. What speaks against setting your custom loading state to true before running the mutation, and after the mutation has returned setting it to false again?\n- Thanks, @marktani. Yeah, this was of doing it is ok. With react-apollo, queries automatically set the loading property when the request is in-flight, so I wanted to make sure I wasn't missing a built-in way to do the same thing for mutations.\n- Tom's explanation about being able to send multiple mutations makes sense. And +1 for an alternate HOC solution in your gist. I'll mark this as accepted.\n- Can I know the progress (%) of the loading?\n- Since it is a HTTP request, you don't know the progress of it. You send a request and wait for the response to come back.\n- HTTP requests can provide a progress status. I've used it before with the axios library. This is the API, note the \"onprogress\" event: developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/uplo‌​ad","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":209,"estimatedTokens":1413}}118{"id":"stack-39481691","source":"stackoverflow","questionId":39481691,"title":"GraphQL readiness for .net development","tags":["c#","asp.net-web-api","graphql"],"text":"Title: GraphQL readiness for .net development\nTags: c#, asp.net-web-api, graphql\nSource: Stack Overflow\n\nQuestion:\nI found GraphQL as an enticing option to decouple front-end development from APIs (potentially a great fit for our company, which does lots of API customization for each customer). However, I can't quite work out if it's ready for a .NET development environment, or whether it's still considered an early technology? I also can't tell if it has bigger problems under the covers (e.g. N+1 issue). Any experience and guidance for GraphQL with a .NET implementation?\n\n========================================\n\nTop Answer:\nIt's now 2019, I stumbled upon this question and I thought I'd this cool GraphQL library for .NET\n\nhttps://github.com/graphql-dotnet/graphql-dotnet\n\nDon't forget to `dotnet add package GraphQL.Server.Ui.Playground` to get the very sweet ui playground:\nhttps://i.sstatic.net/y1chQ.png\n\n========================================\n\nCode:\n```text\ndotnet add package GraphQL.Server.Ui.Playground\n```\n\n========================================\n\nComments:\n- The library was available also in 2016 when my answer was made, but has matured a lot since then. Thanks for pointing this out!\n- Bananacake pop from hotchocolate library is also very fun to use.","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":29,"estimatedTokens":320}}119{"id":"stack-48213151","source":"stackoverflow","questionId":48213151,"title":"Is it possible to deprecate a mutation on GraphQL?","tags":["migration","graphql","deprecated"],"text":"Title: Is it possible to deprecate a mutation on GraphQL?\nTags: migration, graphql, deprecated\nSource: Stack Overflow\n\nQuestion:\nI have a mutation that we want to deprecate:\n\n```\nupdateObject(\n id: String!\n object: ObjectInput!\n): Object!\n```\n\nWe'd like to change it to:\n\n```\nupdateObject(\n object: UpdateObjectInput!\n): Object!\n```\n\nWhere ObjectInput and UpdateObjectInput are:\n\n```\ninput ObjectInput {\n product: String!\n isPercentage: Boolean\n amount: Float!\n visibility: ObjectVisibility\n isDiscontinued: Boolean\n expiresAt: String\n}\n```\n\nand\n\n```\ninput UpdateObjectInput {\n id: String!\n visibility: ObjectVisibility\n isDiscontinued: Boolean\n expiresAt: String\n}\n```\n\nBasically, ObjectInput is great for creating Object, but not ideal for updating it. \n\nWe've tried overloading the mutation or marking the mutation as deprecated, but neither works. \n\nThe only other solutions we've come up with is to rename the new updateObject mutation to something else, like \"newUpdateObject\", or to make the id and object fields deprecated and optional and then add a field \"updateObject\" or something that would take in the new UpdateObjectInput. However, neither of those is optimal. \n\nIs there another way to accomplish the migration?\n\n========================================\n\nCode:\n```text\nupdateObject(\n id: String!\n object: ObjectInput!\n): Object!\n```\n\n```text\nupdateObject(\n object: UpdateObjectInput!\n): Object!\n```\n\n```text\ninput ObjectInput {\n product: String!\n isPercentage: Boolean\n amount: Float!\n visibility: ObjectVisibility\n isDiscontinued: Boolean\n expiresAt: String\n}\n```\n\n```text\ninput UpdateObjectInput {\n id: String!\n visibility: ObjectVisibility\n isDiscontinued: Boolean\n expiresAt: String\n}\n```\n\n```text\nupdateObject(\n id: String!\n object: ObjectInput!\n): Object! @deprecated(\"Use updateObject2 instead\")\nupdateObject2(\n object: UpdateObjectInput!\n): Object!\n```\n\n```text\nupdateObject(\n \"\"\"Don't use. Use object2 instead\"\"\"\n id: String!\n\n \"\"\"Don't use. Use object2 instead\"\"\"\n object: ObjectInput!\n\n object2: UpdateObjectInput!\n): Object!\n```\n\n```text\n@deprecated\n```\n\n========================================\n\nComments:\n- The default reason didn't work for me. Had to include as `@deprecated(reason: \"Use updateObject2 instead\")`\n- Current state regarding \"ONly fields and enum values can be deprecated\" seems to be: introspection was missing some deprecation filtering support github.com/graphql-java/graphql-java/pull/2825","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":121,"estimatedTokens":616}}120{"id":"stack-52512011","source":"stackoverflow","questionId":52512011,"title":"AWS AppSync: pass arguments from parent resolver to children","tags":["graphql","aws-appsync","appsync-apollo-client"],"text":"Title: AWS AppSync: pass arguments from parent resolver to children\nTags: graphql, aws-appsync, appsync-apollo-client\nSource: Stack Overflow\n\nQuestion:\nIn AWS AppSync, arguments send on the main query don't seem to be forwarded to all children resolvers.\n\n```\ntype Query {\n article(id: String!, consistentRead: Boolean): Article\n book(id: String!, consistentRead: Boolean): Book\n}\n\ntype Article {\n title: String!\n id: String!\n}\n\ntype Book {\n articleIds: [String]!\n articles: [Article]!\n id: String!\n}\n```\n\nwhen I call:\n\n```\nquery GetBook {\n book(id: 123, consistentRead: true) {\n articles {\n title\n }\n }\n}\n```\n\nthe first query to get the book receives the `consistentRead` param in `$context.arguments`, but the subsequent query to retrieve the article does not. (`$context.arguments` is empty)\n\nI also tried `articles(consistentRead: Boolean): [Article]!` inside `book` but no luck.\n\nDoes anyone know if it's possible in AppSync to pass arguments to all queries part of the same request?\n\n========================================\n\nTop Answer:\nTo achieve availability across all related resolvers (nested or those collection-entity related) for me was fine **Workaround 2** (tnx Max for such a good answer) but just for child resolvers. \nIn another case when I needed to resolve entities from collection query (contains other fields besides entity) property added to response mapping template wasn't available anymore.\nSo my solution was to set it to request headers:\n\n```\n##Set parent query profile parameter to headers to achieve availability accross related resolvers.\n#set( $headers = $context.request.headers )\n$util.qr($headers.put(\"profile\", $util.defaultIfNullOrBlank($context.args.profile, \"default\")))\n```\n\nAnd read this value from your nested/other request mapping templates:\n\n```\n#set($profile = $ctx.request.headers.profile)\n```\n\nThis makes the parent argument available wherever I need it between related resolvers. In your case, it would be 'device' and some default value or without that part if not needed.\n\n========================================\n\nCode:\n```none\ntype Query {\n article(id: String!, consistentRead: Boolean): Article\n book(id: String!, consistentRead: Boolean): Book\n}\n\ntype Article {\n title: String!\n id: String!\n}\n\ntype Book {\n articleIds: [String]!\n articles: [Article]!\n id: String!\n}\n```\n\n```none\nquery GetBook {\n book(id: 123, consistentRead: true) {\n articles {\n title\n }\n }\n}\n```\n\n```text\nconsistentRead\n```\n\n```text\n$context.arguments\n```\n\n```text\n$context.arguments\n```\n\n```text\narticles(consistentRead: Boolean): [Article]!\n```\n\n```text\nbook\n```\n\n```json\n{\n \"errors\": [],\n \"mappingTemplateType\": \"After Mapping\",\n \"path\": \"[getLatestDeviceState]\",\n \"resolverArn\": \"arn:aws:appsync:us-east-1:xxx:apis/yyy/types/Query/fields/getLatestDeviceState\",\n \"context\": {\n \"arguments\": {\n \"device\": \"ddddd\"\n },\n \"prev\": {\n \"result\": {\n \"items\": [{\n \"version\": \"849\",\n \"device\": \"ddddd\",\n \"timestamp\": \"2019-01-29T12:18:34.504+13:00\"\n }]\n }\n },\n \"stash\": {\"testKey\": \"testValue\"},\n \"outErrors\": []\n },\n \"fieldInError\": false\n}\n```\n\n```json\n{\n \"errors\": [],\n \"mappingTemplateType\": \"Before Mapping\",\n \"path\": \"[getLatestDeviceState, media]\",\n \"resolverArn\": \"arn:aws:appsync:us-east-1:yyy:apis/xxx/types/DeviceStatePRODConnection/fields/media\",\n \"context\": {\n \"arguments\": {},\n \"source\": {\n \"items\": [{\n \"version\": \"849\",\n \"device\": \"ddddd\",\n \"timestamp\": \"2019-01-29T12:18:34.504+13:00\"\n }]\n },\n \"stash\": {},\n \"outErrors\": []\n },\n \"fieldInError\": false\n}\n```\n\n```none\n#set($device = $util.defaultIfNullOrBlank($ctx.args.device, $ctx.source.items[0].device))\n```\n\n```none\n{\n \"items\": $utils.toJson($context.result.items),\n \"device\": \"${ctx.args.device}\"\n}\n```\n\n```text\n$context\n```\n\n```text\narguments\n```\n\n```text\nstash\n```\n\n```text\nsource\n```\n\n```text\narguments\n```\n\n```text\nstash\n```\n\n```text\narguments\n```\n\n```text\nstash\n```\n\n```text\narguments\n```\n\n```text\nstash\n```\n\n```text\ndevice\n```\n\n```text\ntype Author {\n # parent's id\n bookID: ID!\n # author id\n id: ID!\n name: String!\n}\n\ntype Book {\n id: ID!\n title: String!\n author: [Author]!\n}\n\ntype Mutation {\n insertAuthor(bookID: ID!, id: ID!, name: String!): Author\n insertBook(id: ID!, title: String!): Book\n}\n\ntype Query {\n getBook(id: ID!): Book\n}\n```\n\n```text\n{\n \"version\" : \"2017-02-28\",\n \"operation\" : \"PutItem\",\n \"key\" : {\n \"bookID\" : $util.dynamodb.toDynamoDBJson($ctx.args.bookID),\n \"id\" : $util.dynamodb.toDynamoDBJson($ctx.args.id)\n },\n \"attributeValues\" : {\n \"name\" : $util.dynamodb.toDynamoDBJson($ctx.args.name)\n }\n}\n```\n\n```text\nAuthor\n```\n\n```text\nBook\n```\n\n```text\nAuthor.bookID\n```\n\n```text\nAuthor.id\n```\n\n```text\nBook.id\n```\n\n```text\nBook.author\n```\n\n```text\ninsertAuthor\n```\n\n```text\ngetBook\n```\n\n```text\n$ctx.source.id\n```\n\n```text\nid\n```\n\n```text\n##Set parent query profile parameter to headers to achieve availability accross related resolvers.\n#set( $headers = $context.request.headers )\n$util.qr($headers.put(\"profile\", $util.defaultIfNullOrBlank($context.args.profile, \"default\")))\n```\n\n```text\n#set($profile = $ctx.request.headers.profile)\n```\n\n```text\n#set( $book = $ctx.result )\n#set($Articles = []);\n#foreach($article in $book.articles)\n #set( $newArticle = $article )\n $util.qr($newArticle.put(\"bookID\", $book.id))\n $util.qr($Articles.add($newArticle))\n#end\n$util.qr($book.put(\"articles\", $Articles))\n$util.toJson($book)\n```\n\n```text\nconsistentRead\n```\n\n```text\n$context.info.variables\n```\n\n```text\n$context.info.variables.consistentRead\n```\n\n========================================\n\nComments:\n- This workaround using request headers work with or without pipeline stackoverflow.com/a/58093410/1480391 it's ugly but it's the only solution I know that allows passing information to ALL sub-resolvers\n- @joshblour - What solution did you find? Please, check this as the correct answer if you agree. This area is still very badly documented in AWS. This may help others save time.\n- To add to this, by default cloudwatch logs aren't activated on appsync. Once you've activated it and \"Field resolver log level\" is set to ALL, you can clearly see the contents of the context object that the documents fail to address in detail. From there you can do many other things.\n- Good find! But it looks like a hack.. I'm not sure modifying request headers is an intended AWS feature.. But thanks to this workaround I can propagate values to sub-resolvers\n- See github.com/aws/aws-appsync-community/issues/…\n- Glad it helps. I was desperate to achieve this but couldn't find better workaround yet, so hope AWS will implement appropriate way to handle it soon.\n- Beauty of this answer is that it will work not only for Children but for Grand Children as well :) .. And that too without passing arguments from One layer to other. Just brilliant!","metadata":{"transformedAt":"2026-08-18T18:32:36.028Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":40,"totalLines":341,"estimatedTokens":1790}}121{"id":"stack-38904499","source":"stackoverflow","questionId":38904499,"title":"Take result from one query / mutation and pipe to another","tags":["graphql"],"text":"Title: Take result from one query / mutation and pipe to another\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI'm wondering if there's a way in GraphiQL that will let me pipe the result from one query / mutation into another query / mutation. Here's an example where the `login` mutation is used to get a `viewer` and the `viewer` would be used to query the `addresses` for that user. Is this possible with GraphQL / GraphiQL.\n\n```\nmutation {\n login(credentials: {\n email: \"me@me.com\",\n password: \"password123\",\n passwordConfirmation: \"password123\"\n }) {\n viewer\n }\n}\n\nquery {\n addresses(viewer:viewer) {\n city\n }\n}\n```\n\n========================================\n\nCode:\n```text\nmutation {\n login(credentials: {\n email: \"me@me.com\",\n password: \"password123\",\n passwordConfirmation: \"password123\"\n }) {\n viewer\n }\n}\n\nquery {\n addresses(viewer:viewer) {\n city\n }\n}\n```\n\n```text\nlogin\n```\n\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\naddresses\n```\n\n```text\ntype Address {\n city: String\n}\ntype User {\n addresses: [Address]\n}\n```\n\n```text\nmutation {\n login(credentials: {\n email: \"me@me.com\",\n password: \"password123\",\n passwordConfirmation: \"password123\"\n }) {\n viewer {\n addresses {\n city\n }\n }\n }\n}\n```\n\n```text\nlogin\n```\n\n```text\nviewer\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- There's an experimental batchOperations feature but I don't think it's landed in graphql-js yet. I opened a issue here. github.com/graphql/graphql-js/issues/462\n- In the case above the viewer is an id or token that allows you to access other pieces of the API. What your saying makes sense, but it doesn't help me. I need to still make one request get the viewer (token) then copy and paste it in as an argument for other mutations, which is a bummer.\n- I think for queries, you need a \"User\" type that represents the logged in user and add the fields related to the user in that type. Then you can add a reference to `User` in the mutation result type, so you can query it. For mutations, as you said, it's true that you can't batch mutations that depend on a result of a previous mutation inside GraphQL, but it should be possible to build a batch endpoint that does this at outside the query language, in your HTTP server.\n- I think It's coming, just not ready yet. github.com/graphql/graphql-js/issues/462","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":110,"estimatedTokens":601}}122{"id":"stack-56879288","source":"stackoverflow","questionId":56879288,"title":"How to approach a GraphQL query that returns a boolean value?","tags":["graphql","apollo-client"],"text":"Title: How to approach a GraphQL query that returns a boolean value?\nTags: graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nNeed to check whether an email is available or taken during the user sign-up process. The goal is to quickly query, using GraphQL, the API server and have it tell us if the email is available or taken. \n\nWhat is the general best practice on a simple boolean-ish type of situation using GraphQL?\n\nBelow is what I have come up with but I am unsure if this is a good practice or not and want to hear feedback on a better practice on queries like this.\n\nRequest:\n\n```\nquery {\n emailExists(email:\"jane@doe.com\") {\n is\n }\n}\n```\n\nResponse:\n\n```\n{\n \"data\": {\n \"emailExists\": {\n \"is\": true\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n emailExists(email:\"jane@doe.com\") {\n is\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"emailExists\": {\n \"is\": true\n }\n }\n}\n```\n\n```text\ntype Query {\n emailExists(email: String!): Boolean!\n}\n```\n\n```text\nQuery\n```\n\n```text\nis\n```\n\n========================================\n\nComments:\n- Exactly what I am looking for!! Thanks so much.\n- Just for the records, with this solution the request would be this (no field selection is needed): `graphql query { emailExists(email:\"jane@doe.com\") }`\n- @Marco eslint crashes if i use a query without selection","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":74,"estimatedTokens":336}}123{"id":"stack-55341558","source":"stackoverflow","questionId":55341558,"title":"refetching a query with react-apollo: why is `loading` not true?","tags":["reactjs","graphql","apollo","react-apollo","apollo-client"],"text":"Title: refetching a query with react-apollo: why is `loading` not true?\nTags: reactjs, graphql, apollo, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm trying Apollo and using the following relevant code:\n\n```\nconst withQuery = graphql(gql`\nquery ApolloQuery {\n apolloQuery {\n data\n }\n}\n`);\n\nexport default withQuery(props => {\n const {\n data: { refetch, loading, apolloQuery },\n } = props;\n\n return (\n \n { await refetch(); }}\n >\n Refresh\n \n {loading ? 'Loading...' : apolloQuery.data}\n \n\n );\n});\n```\n\nThe server delays for 500ms before sending a response with `{ data: `Hello ${new Date()}` }` as the payload. When I'm clicking the button, I expect to see `Loading...`, but instead the component still says `Hello [date]` and rerenders half a second later.\n\nAccording to this, the `networkStatus` should be 4 (`refetch`), and thus `loading` should be true. Is my expectation wrong? Or is something regarding caching going on that is not mentioned in the React Apollo docs?\n\nThe project template I'm using uses SSR, so the initial query happens on the server; only refetching happens in the browser - just if that could make a difference.\n\n========================================\n\nCode:\n```text\nconst withQuery = graphql(gql`\nquery ApolloQuery {\n apolloQuery {\n data\n }\n}\n`);\n\nexport default withQuery(props => {\n const {\n data: { refetch, loading, apolloQuery },\n } = props;\n\n return (\n <p>\n <Button\n variant=\"contained\"\n color=\"primary\"\n onClick={async () => { await refetch(); }}\n >\n Refresh\n </Button>\n {loading ? 'Loading...' : apolloQuery.data}\n </p>\n );\n});\n```\n\n```text\n{ data: `Hello ${new Date()}` }\n```\n\n```text\nLoading...\n```\n\n```text\nHello [date]\n```\n\n```text\nnetworkStatus\n```\n\n```text\nrefetch\n```\n\n```text\nloading\n```\n\n```text\nnotifyOnNetworkStatusChange: true\n```\n\n```text\nfalse\n```\n\n========================================\n\nComments:\n- where to set this option?\n- @BryanLumbantobing you set this option here: const { data, loading, refetch } = useQuery( UsersQuery({ activeUser }), { notifyOnNetworkStatusChange: true } );\n- Also if `skip` is true then even though `refetch` will be run explicitly, loading will remain false.","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":110,"estimatedTokens":567}}124{"id":"stack-40360936","source":"stackoverflow","questionId":40360936,"title":"graphql-go : Use an Object as Input Argument to a Query","tags":["go","graphql"],"text":"Title: graphql-go : Use an Object as Input Argument to a Query\nTags: go, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to pass an object as an argument to a query (rather than a scalar). From the docs it seems that this should be possible, but I can't figure out how to make it work.\n\nI'm using graphql-go, here is the test schema:\n\n```\nvar fileDocumentType = graphql.NewObject(graphql.ObjectConfig{\nName: \"FileDocument\",\nFields: graphql.Fields{\n \"id\": &graphql.Field{\n Type: graphql.String,\n Resolve: func(p graphql.ResolveParams) (interface{}, error) {\n if fileDoc, ok := p.Source.(data_format.FileDocument); ok {\n return fileDoc.Id, nil\n }\n return \"\", nil\n },\n },\n \"tags\": &graphql.Field{\n Type: graphql.NewList(tagsDataType),\n Args: graphql.FieldConfigArgument{\n \"tags\": &graphql.ArgumentConfig{\n Type: tagsInputType,\n },\n },\n Resolve: func(p graphql.ResolveParams) (interface{}, error) {\n fmt.Println(p.Source)\n fmt.Println(p.Args)\n if fileDoc, ok := p.Source.(data_format.FileDocument); ok {\n return fileDoc.Tags, nil\n }\n return nil, nil\n },\n },\n\n},\n})\n```\n\nAnd the inputtype I'm attempting to use (I've tried both an InputObject and a standard Object)\n\n```\nvar tagsInputType = graphql.NewInputObject(graphql.InputObjectConfig{\nName: \"tagsInput\",\nFields: graphql.Fields{\n \"keyt\": &graphql.Field{\n Type: graphql.String,\n },\n \"valuet\": &graphql.Field{\n Type: graphql.String,\n },\n},\n})\n```\n\nAnd here is the graphql query I'm using to test:\n\n```\n{\n list(location:\"blah\",rule:\"blah\")\n {\n id,tags(tags:{keyt:\"test\",valuet:\"test\"})\n {\n key,\n value\n },\n {\n datacentre,\n handlerData\n {\n key,\n value\n }\n }\n }\n }\n```\n\nI'm getting the following error:\n\n```\nwrong result, unexpected errors: [Argument \"tags\" has invalid value {keyt: \"test\", valuet: \"test\"}.\nIn field \"keyt\": Unknown field.\nIn field \"valuet\": Unknown field.]\n```\n\nThe thing is, when I change the type to a string, it works fine. How do I use an object as an input arg?\n\nThanks!\n\n========================================\n\nCode:\n```text\nvar fileDocumentType = graphql.NewObject(graphql.ObjectConfig{\nName: \"FileDocument\",\nFields: graphql.Fields{\n \"id\": &graphql.Field{\n Type: graphql.String,\n Resolve: func(p graphql.ResolveParams) (interface{}, error) {\n if fileDoc, ok := p.Source.(data_format.FileDocument); ok {\n return fileDoc.Id, nil\n }\n return \"\", nil\n },\n },\n \"tags\": &graphql.Field{\n Type: graphql.NewList(tagsDataType),\n Args: graphql.FieldConfigArgument{\n \"tags\": &graphql.ArgumentConfig{\n Type: tagsInputType,\n },\n },\n Resolve: func(p graphql.ResolveParams) (interface{}, error) {\n fmt.Println(p.Source)\n fmt.Println(p.Args)\n if fileDoc, ok := p.Source.(data_format.FileDocument); ok {\n return fileDoc.Tags, nil\n }\n return nil, nil\n },\n },\n\n},\n})\n```\n\n```text\nvar tagsInputType = graphql.NewInputObject(graphql.InputObjectConfig{\nName: \"tagsInput\",\nFields: graphql.Fields{\n \"keyt\": &graphql.Field{\n Type: graphql.String,\n },\n \"valuet\": &graphql.Field{\n Type: graphql.String,\n },\n},\n})\n```\n\n```text\n{\n list(location:\"blah\",rule:\"blah\")\n {\n id,tags(tags:{keyt:\"test\",valuet:\"test\"})\n {\n key,\n value\n },\n {\n datacentre,\n handlerData\n {\n key,\n value\n }\n }\n }\n }\n```\n\n```text\nwrong result, unexpected errors: [Argument \"tags\" has invalid value {keyt: \"test\", valuet: \"test\"}.\nIn field \"keyt\": Unknown field.\nIn field \"valuet\": Unknown field.]\n```\n\n```text\nvar inputType = graphql.NewInputObject(\n graphql.InputObjectConfig{\n Name: \"MyInputType\",\n Fields: graphql.InputObjectConfigFieldMap{\n \"key\": &graphql.InputObjectFieldConfig{\n Type: graphql.String,\n },\n },\n },\n)\n```\n\n```text\npackage main\n\nimport (\n \"encoding/json\"\n \"fmt\"\n \"log\"\n\n \"github.com/graphql-go/graphql\"\n)\n\nfunc main() {\n // Schema\n\n var inputType = graphql.NewInputObject(\n graphql.InputObjectConfig{\n Name: \"MyInputType\",\n Fields: graphql.InputObjectConfigFieldMap{\n \"key\": &graphql.InputObjectFieldConfig{\n Type: graphql.String,\n },\n },\n },\n )\n\n args := graphql.FieldConfigArgument{\n \"foo\": &graphql.ArgumentConfig{\n Type: inputType,\n },\n }\n\n fields := graphql.Fields{\n \"hello\": &graphql.Field{\n Type: graphql.String,\n Args: args,\n Resolve: func(p graphql.ResolveParams) (interface{}, error) {\n fmt.Println(p.Args)\n return \"world\", nil\n },\n },\n }\n rootQuery := graphql.ObjectConfig{\n Name: \"RootQuery\",\n Fields: fields,\n }\n\n schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}\n schema, err := graphql.NewSchema(schemaConfig)\n if err != nil {\n log.Fatalf(\"failed to create new schema, error: %v\", err)\n }\n\n // Query\n query := `\n {\n hello(foo:{key:\"blah\"})\n }\n `\n params := graphql.Params{Schema: schema, RequestString: query}\n r := graphql.Do(params)\n if len(r.Errors) > 0 {\n log.Fatalf(\"failed to execute graphql operation, errors: %+v\", r.Errors)\n }\n rJSON, _ := json.Marshal(r)\n fmt.Printf(\"%s \\n\", rJSON) // {βdataβ:{βhelloβ:βworldβ}}\n}\n```\n\n```text\nFields\n```\n\n```text\nInputObject\n```\n\n```text\nInputObjectConfigFieldMap\n```\n\n```text\nInputObjectConfigFieldMapThunk\n```\n\n```text\nInputObject\n```\n\n```text\nInput Object\n```\n\n========================================\n\nComments:\n- You deserve a medal for this. That project really needs documentation. Like the other implementation of it.","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":281,"estimatedTokens":1503}}125{"id":"stack-48277651","source":"stackoverflow","questionId":48277651,"title":"GraphQL how to avoid duplicate code between input and output types","tags":["interface","graphql","apollo"],"text":"Title: GraphQL how to avoid duplicate code between input and output types\nTags: interface, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'am new to GraphQL but I really like it. Now that I'am playing with interfaces and unions, I'am facing a problem with mutations.\n\nSuppose that I have this schema :\n\n```\ninterface FoodType {\n id: String\n type: String\n composition: [Ingredient]\n }\n\n type Pizza implements FoodType {\n id: String\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n composition: [Ingredient]\n }\n\n type Salad implements FoodType {\n id: String\n type: String\n vegetarian: Boolean\n dressing: Boolean\n composition: [Ingredient]\n }\n\n type BasicFood implements FoodType {\n id: String\n type: String\n composition: [Ingredient]\n }\n\n type Ingredient {\n name: String\n qty: Float\n units: String\n }\n```\n\nNow, I'd like to create new food items, so I started doing something like this :\n\n```\ntype Mutation {\n addPizza(input:Pizza):FoodType\n addSalad(input:Salad):FoodType\n addBasic(input:BasicFood):FoodType\n}\n```\n\nThis did not work for 2 reasons :\n\n- If I want to pass an object as parameter, this one must be an \"input\" type. But \"Pizza\", \"Salad\" and \"BasicFood\" are just \"type\".\n\n- An input type cannot implement an interface.\n\nSo, I need to modify my previous schema like this :\n\n```\ninterface FoodType {\n id: String\n type: String\n composition: [Ingredient]\n}\n\ntype Pizza implements FoodType {\n id: String\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n composition: [Ingredient]\n}\n\ntype Salad implements FoodType {\n id: String\n type: String\n vegetarian: Boolean\n dressing: Boolean\n composition: [Ingredient]\n}\n\ntype BasicFood implements FoodType {\n id: String\n type: String\n composition: [Ingredient]\n}\n\ntype Ingredient {\n name: String\n qty: Float\n units: String\n}\n\ntype Mutation {\n addPizza(input: PizzaInput): FoodType\n addSalad(input: SaladInput): FoodType\n addBasic(input: BasicInput): FoodType \n}\n\ninput PizzaInput {\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n composition: [IngredientInput]\n}\n\ninput SaladInput {\n type: String\n vegetarian: Boolean\n dressing: Boolean\n composition: [IngredientInput]\n}\n\ninput BasicFoodInput {\n type: String\n composition: [IngredientInput]\n}\n\ninput IngredientInput {\n name: String\n qty: Float\n units: String\n}\n```\n\nSo, here I defined my 3 creation methods for Pizza, Salad and Basic food.\nI need to define 3 input types (one for each food)\nAnd I also need to define a new input type for Ingredients.\n\nIt makes lot of duplication. Are you ok with that? Or there is a better way to deal with this?\n\nThank you\n\n========================================\n\nTop Answer:\nI was using Dgraph and it solved the same problem.\nHave a look: https://dgraph.io/docs/graphql/schema/types/#interfaces\nBasically if using dgraph, you can just write minimal amount of code and it will generate rest.\nAlso with webstorm you can write:\n\n`# noinspection GraphQLInterfaceImplementation` on top of file, it will disable inspection for interfaces and then use some kind of transpiler to fullfill fields on types that use interfaces.\n\n========================================\n\nCode:\n```text\ninterface FoodType {\n id: String\n type: String\n composition: [Ingredient]\n }\n\n type Pizza implements FoodType {\n id: String\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n composition: [Ingredient]\n }\n\n type Salad implements FoodType {\n id: String\n type: String\n vegetarian: Boolean\n dressing: Boolean\n composition: [Ingredient]\n }\n\n type BasicFood implements FoodType {\n id: String\n type: String\n composition: [Ingredient]\n }\n\n type Ingredient {\n name: String\n qty: Float\n units: String\n }\n```\n\n```text\ntype Mutation {\n addPizza(input:Pizza):FoodType\n addSalad(input:Salad):FoodType\n addBasic(input:BasicFood):FoodType\n}\n```\n\n```text\ninterface FoodType {\n id: String\n type: String\n composition: [Ingredient]\n}\n\ntype Pizza implements FoodType {\n id: String\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n composition: [Ingredient]\n}\n\ntype Salad implements FoodType {\n id: String\n type: String\n vegetarian: Boolean\n dressing: Boolean\n composition: [Ingredient]\n}\n\ntype BasicFood implements FoodType {\n id: String\n type: String\n composition: [Ingredient]\n}\n\ntype Ingredient {\n name: String\n qty: Float\n units: String\n}\n\ntype Mutation {\n addPizza(input: PizzaInput): FoodType\n addSalad(input: SaladInput): FoodType\n addBasic(input: BasicInput): FoodType \n}\n\ninput PizzaInput {\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n composition: [IngredientInput]\n}\n\ninput SaladInput {\n type: String\n vegetarian: Boolean\n dressing: Boolean\n composition: [IngredientInput]\n}\n\ninput BasicFoodInput {\n type: String\n composition: [IngredientInput]\n}\n\ninput IngredientInput {\n name: String\n qty: Float\n units: String\n}\n```\n\n```text\nconst getPizzaFields = (isInput = false) => {\n const fields = {\n type: { type: GraphQLString }\n pizzaType: { type: GraphQLString }\n toppings: { type: new GraphQLList(GraphQLString) }\n size: { type: GraphQLString }\n composition: {\n type: isInput ? new GraphQLList(IngredientInput) : new GraphQLList(Ingredient)\n }\n }\n if (!isInput) fields.id = { type: GraphQLString }\n return fields\n}\n\nconst Pizza = new GraphQLObjectType({\n name: 'Pizza',\n fields: () => getFields()\n})\n\nconst PizzaInput = new GraphQLObjectType({\n name: 'Pizza',\n fields: () => getFields(true)\n})\n```\n\n```text\nconst transformObject = (type) => {\n const input = Object.assign({}, type)\n input.fields.composition.type = new GraphQLList(IngredientInput)\n delete input.fields.id\n return input\n}\n```\n\n```text\nconst commonPizzaFields = `\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n`\n\nconst schema = `\n type Pizza {\n id: String\n ${commonPizzaFields}\n composition: [Ingredient]\n }\n\n input PizzaInput {\n ${commonPizzaFields}\n composition: [IngredientInput]\n }\n`\n```\n\n```text\ntype Pizza {\n toppings(filter: ToppingTypeEnum): [String]\n}\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\ntoppings\n```\n\n```text\nPizza\n```\n\n```text\nPizzaInput\n```\n\n```text\n# noinspection GraphQLInterfaceImplementation\n```\n\n========================================\n\nComments:\n- `commonPizzaFields` like a `fragment` conception. But graphql `fragment` is only used in \"graphql client\"","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":355,"estimatedTokens":1643}}126{"id":"stack-58016672","source":"stackoverflow","questionId":58016672,"title":"Gatsby and Graphql - How to filter allMarkdownRemark by folder","tags":["reactjs","regex","graphql","gatsby","remarkjs"],"text":"Title: Gatsby and Graphql - How to filter allMarkdownRemark by folder\nTags: reactjs, regex, graphql, gatsby, remarkjs\nSource: Stack Overflow\n\nQuestion:\nI'm using Gatsby and MarkdownRemark.\n\nI want to query the markdown files and then filter them down to the files contained within a sub-directory. My folder structure looks like this:\n\n```\n- src\n - pages\n -index.md\n -about.md\n - team\n - team_member_1.md\n - team_member_2.md\n - team_member_3.md\n```\n\nSo far I can query all the markdown pages in the directory but I'm having trouble trying to filter down path. There must be a way to do it with a graphQL query. \n\nInstead what I do is map all the results and then check if the slug string includes 'team' this tells me that its in the 'team' folder. And then it makes the component.\n\n```\nimport React from 'react'\nimport { useStaticQuery, graphql } from 'gatsby'\nimport TeamMember from '../components/TeamMember.js'\nconst Team = () => {\n const data = useStaticQuery(graphql`\n query {\n allMarkdownRemark {\n edges {\n node {\n fields{\n slug\n }\n frontmatter {\n name\n position\n image\n }\n }\n }\n }\n }\n `)\n\n return (\n \n {data.allMarkdownRemark.edges.map( (item, index) => {\n if(item.node.fields.slug.includes('team')){\n return \n }\n } )}\n \n )\n}\nexport default Team\n```\n\nThis works fine. But I thought the whole point of graphQl is to query and filter to return the exact data I need. Instead I'm back at writing my own filter code in javascript:\n\n```\nif(item.node.fields.slug.includes('team'))\n```\n\nIs there a Gatsby plugin or a way to filter a query to contain items in a folder?\n\n========================================\n\nTop Answer:\n@ksav's answer works but it is important to note that `regex: \"/(team)/\"` also matches `C:\\user\\gatsby\\src\\team2\\other.md`.\n\nSo I recommend using `allMarkdownRemark(filter: {fileAbsolutePath: {regex: \"/(/team/)/\" }}) {` instead.\n\n========================================\n\nCode:\n```text\n- src\n - pages\n -index.md\n -about.md\n - team\n - team_member_1.md\n - team_member_2.md\n - team_member_3.md\n```\n\n```text\nimport React from 'react'\nimport { useStaticQuery, graphql } from 'gatsby'\nimport TeamMember from '../components/TeamMember.js'\nconst Team = () => {\n const data = useStaticQuery(graphql`\n query {\n allMarkdownRemark {\n edges {\n node {\n fields{\n slug\n }\n frontmatter {\n name\n position\n image\n }\n }\n }\n }\n }\n `)\n\n return (\n <div>\n {data.allMarkdownRemark.edges.map( (item, index) => {\n if(item.node.fields.slug.includes('team')){\n return <TeamMember key={`team_member_${index}`}{...item.node.frontmatter}/>\n }\n } )}\n </div>\n )\n}\nexport default Team\n```\n\n```text\nif(item.node.fields.slug.includes('team'))\n```\n\n```text\nquery MyQuery {\n allMarkdownRemark(filter: {fileAbsolutePath: {regex: \"/(team)/\" }}) {\n nodes {\n id\n }\n }\n}\n```\n\n```text\nregex: \"/(team)/\"\n```\n\n```text\nC:\\user\\gatsby\\src\\team2\\other.md\n```\n\n```text\nallMarkdownRemark(filter: {fileAbsolutePath: {regex: \"/(/team/)/\" }}) {\n```\n\n========================================\n\nComments:\n- Thank you ksav, This is exactly what I was looking for. I knew there had to be a way to do it. I'm going to read through that filter documentation that you linked. I was having trouble articulating my searches to find this. Thanks.\n- For new people, and since no one here has mentioned it: filtering with `regex` and `fileAbsolutePath` is really, really slow. So if you can help it, filter with `eq` and `frontmatter` instead. My build times went from 11β12 minutes down to 3β4 minutes after changing. Read more about it here.","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":158,"estimatedTokens":930}}127{"id":"stack-74453995","source":"stackoverflow","questionId":74453995,"title":"Clean Gatsby 5.2 Install throwing `NPM WARN` flags for `react-server-dom-webpack`","tags":["npm","graphql"],"text":"Title: Clean Gatsby 5.2 Install throwing `NPM WARN` flags for `react-server-dom-webpack`\nTags: npm, graphql\nSource: Stack Overflow\n\nQuestion:\nAfter a clean Gatsby 5.2 install using the `Gatsby CLI`, I need help understanding my terminal output, which shows a multitude of `NPM WARN` flags.\n\n**I have three questions;**\n\n- What is the cause of these errors?\n\n- Why are these errors happening with a clean install?\n\n- What is the preferred method for resolving issues like these?\n\nI'm asking these questions here on S.O. because I'd like to pre-emptively learn how to understand and deal with them correctly.\n\nI read up on some similar questions here on S.O., and some recommend using the `--legacy-peer-deps` flag.\n\nI understand why someone might use the `--legacy-peer-deps` flag in general, but I'm struggling to understand why a new release, I.e. (Gatsby 5.0), needs to use the `--legacy-peer-deps`.\n\nNPM errors are still a pain point for me, so **I'm looking for easy-to-understand reading material**. Or **a well-rounded explanation** if possible.\n\n**After running: `gatsby info --clipboard`**\n\n```\n% gatsby info --clipboard\n\n System:\n OS: macOS 13.0.1\n CPU: (16) x64 Intel(R) Xeon(R) W-2140B CPU @ 3.20GHz\n Shell: 5.8.1 - /bin/zsh\n Binaries:\n Node: 18.12.1 - ~/.nvm/versions/node/v18.12.1/bin/node\n npm: 8.19.2 - ~/.nvm/versions/node/v18.12.1/bin/npm\n Browsers:\n Chrome: 108.0.5359.98\n Safari: 16.1\n npmPackages:\n gatsby: ^5.2.0 => 5.2.0\n gatsby-plugin-image: ^3.2.0 => 3.2.0\n gatsby-plugin-manifest: ^5.2.0 => 5.2.0\n gatsby-plugin-sharp: ^5.2.0 => 5.2.0\n gatsby-source-filesystem: ^5.2.0 => 5.2.0\n gatsby-transformer-sharp: ^5.2.0 => 5.2.0\n npmGlobalPackages:\n gatsby-cli: 5.2.0\n\n%\n```\n\n**The expected result after running: `npm i`**\n\n```\n% npm i\n\nremoved 1505 packages, and audited 83 packages in 8s\n\n20 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities\n%\n```\n\n**Actual result after running: `npm i`**\n\n```\n% npm i\nnpm WARN ERESOLVE overriding peer dependency\nnpm WARN While resolving: react-server-dom-webpack@0.0.0-experimental-c8b778b7f-20220825\nnpm WARN Found: react@18.2.0\nnpm WARN node_modules/react\nnpm WARN react@\"^18.2.0\" from the root project\nnpm WARN 10 more (react-dom, gatsby, gatsby-plugin-image, ...)\nnpm WARN \nnpm WARN Could not resolve dependency:\nnpm WARN peer react@\"0.0.0-experimental-c8b778b7f-20220825\" from react-server-dom-webpack@0.0.0-experimental-c8b778b7f-20220825\nnpm WARN node_modules/react-server-dom-webpack\nnpm WARN react-server-dom-webpack@\"0.0.0-experimental-c8b778b7f-20220825\" from gatsby@5.2.0\nnpm WARN node_modules/gatsby\nnpm WARN \nnpm WARN Conflicting peer dependency: react@0.0.0-experimental-c8b778b7f-20220825\nnpm WARN node_modules/react\nnpm WARN peer react@\"0.0.0-experimental-c8b778b7f-20220825\" from react-server-dom-webpack@0.0.0-experimental-c8b778b7f-20220825\nnpm WARN node_modules/react-server-dom-webpack\nnpm WARN react-server-dom-webpack@\"0.0.0-experimental-c8b778b7f-20220825\" from gatsby@5.2.0\nnpm WARN node_modules/gatsby\nnpm WARN deprecated async-cache@1.1.0: No longer maintained. Use [lru-cache](http://npm.im/lru-cache) version 7.6 or higher, and provide an asynchronous `fetchMethod` option.\nnpm WARN deprecated stable@0.1.8: Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility\nnpm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.\n\nadded 1505 packages, and audited 1588 packages in 1m\n\n325 packages are looking for funding\n run `npm fund` for details\n\n15 moderate severity vulnerabilities\n\nTo address issues that do not require attention, run:\n npm audit fix\n\nTo address all issues (including breaking changes), run:\n npm audit fix --force\n\nRun `npm audit` for details.\n%\n```\n\n========================================\n\nTop Answer:\nUntil Gatsby has fixed this and you want to remove this warning you can add this to your package.json to tell npm which dependency version to use:\n\n```\n\"overrides\": {\n \"react-server-dom-webpack@0.0.0-experimental-c8b778b7f-20220825\": {\n \"react\": \"^18.2.0\"\n }\n}\n```\n\nLink to comment in github where I found this fix.\n\n========================================\n\nCode:\n```bash\n% gatsby info --clipboard\n\n System:\n OS: macOS 13.0.1\n CPU: (16) x64 Intel(R) Xeon(R) W-2140B CPU @ 3.20GHz\n Shell: 5.8.1 - /bin/zsh\n Binaries:\n Node: 18.12.1 - ~/.nvm/versions/node/v18.12.1/bin/node\n npm: 8.19.2 - ~/.nvm/versions/node/v18.12.1/bin/npm\n Browsers:\n Chrome: 108.0.5359.98\n Safari: 16.1\n npmPackages:\n gatsby: ^5.2.0 => 5.2.0\n gatsby-plugin-image: ^3.2.0 => 3.2.0\n gatsby-plugin-manifest: ^5.2.0 => 5.2.0\n gatsby-plugin-sharp: ^5.2.0 => 5.2.0\n gatsby-source-filesystem: ^5.2.0 => 5.2.0\n gatsby-transformer-sharp: ^5.2.0 => 5.2.0\n npmGlobalPackages:\n gatsby-cli: 5.2.0\n\n%\n```\n\n```bash\n% npm i\n\nremoved 1505 packages, and audited 83 packages in 8s\n\n20 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities\n%\n```\n\n```bash\n% npm i\nnpm WARN ERESOLVE overriding peer dependency\nnpm WARN While resolving: react-server-dom-webpack@0.0.0-experimental-c8b778b7f-20220825\nnpm WARN Found: react@18.2.0\nnpm WARN node_modules/react\nnpm WARN react@\"^18.2.0\" from the root project\nnpm WARN 10 more (react-dom, gatsby, gatsby-plugin-image, ...)\nnpm WARN \nnpm WARN Could not resolve dependency:\nnpm WARN peer react@\"0.0.0-experimental-c8b778b7f-20220825\" from react-server-dom-webpack@0.0.0-experimental-c8b778b7f-20220825\nnpm WARN node_modules/react-server-dom-webpack\nnpm WARN react-server-dom-webpack@\"0.0.0-experimental-c8b778b7f-20220825\" from gatsby@5.2.0\nnpm WARN node_modules/gatsby\nnpm WARN \nnpm WARN Conflicting peer dependency: react@0.0.0-experimental-c8b778b7f-20220825\nnpm WARN node_modules/react\nnpm WARN peer react@\"0.0.0-experimental-c8b778b7f-20220825\" from react-server-dom-webpack@0.0.0-experimental-c8b778b7f-20220825\nnpm WARN node_modules/react-server-dom-webpack\nnpm WARN react-server-dom-webpack@\"0.0.0-experimental-c8b778b7f-20220825\" from gatsby@5.2.0\nnpm WARN node_modules/gatsby\nnpm WARN deprecated async-cache@1.1.0: No longer maintained. Use [lru-cache](http://npm.im/lru-cache) version 7.6 or higher, and provide an asynchronous `fetchMethod` option.\nnpm WARN deprecated stable@0.1.8: Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility\nnpm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.\n\nadded 1505 packages, and audited 1588 packages in 1m\n\n325 packages are looking for funding\n run `npm fund` for details\n\n15 moderate severity vulnerabilities\n\nTo address issues that do not require attention, run:\n npm audit fix\n\nTo address all issues (including breaking changes), run:\n npm audit fix --force\n\nRun `npm audit` for details.\n%\n```\n\n```text\nGatsby CLI\n```\n\n```text\nNPM WARN\n```\n\n```text\n--legacy-peer-deps\n```\n\n```text\n--legacy-peer-deps\n```\n\n```text\n--legacy-peer-deps\n```\n\n```text\ngatsby info --clipboard\n```\n\n```text\nnpm i\n```\n\n```text\nnpm i\n```\n\n```text\nreact-server-dom-webpack\n```\n\n```text\npackage.json\n```\n\n```text\nnode_modules/react-server-dom-webpack\n```\n\n```text\npackage.json\n```\n\n```text\nreact-server-dom-webpack\n```\n\n```json\n\"overrides\": {\n \"react-server-dom-webpack@0.0.0-experimental-c8b778b7f-20220825\": {\n \"react\": \"^18.2.0\"\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":266,"estimatedTokens":1931}}128{"id":"stack-42938472","source":"stackoverflow","questionId":42938472,"title":"What is the reason for having edges and nodes in a connection in your graphql schema?","tags":["facebook","graphql","relay"],"text":"Title: What is the reason for having edges and nodes in a connection in your graphql schema?\nTags: facebook, graphql, relay\nSource: Stack Overflow\n\nQuestion:\nI am trying to understand more complex graphql apis that implement the Relay Cursor Connections Specification\n\nIf you look at the query below that I run on the github graphql api explorer\n\n```\n{\n repository(owner: \"getsmarter\", name: \"moodle-api\") {\n id\n issues(first:2 ) {\n edges {\n node {\n id\n body\n }\n }\n nodes {\n body\n }\n pageInfo {\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n totalCount\n } \n }\n}\n```\n\nNotice it has the fields **edges** and **nodes**.\n\nWhy does github have an additional field called nodes in their api? Why donβt they just use the edges field since you can get the same data from edges? Is this just for convenience?\n\n========================================\n\nTop Answer:\nA node is always the same, regardless of how you get to it. The edge is metadata about that node in the context of the connection, usually just the cursor, but you could also add things like a relevancy score if your connection represented a search query. This data shouldn't exist on the node itself, because it makes no sense in a different context.\n\n**Terminology**:\n\n- **Node**, represents an entity. In a diagram of circles connected by lines, these would be the circles.\n\n- **Edge**, connects two nodes together, may include metadata. In the diagram, these would be the lines.\n\n- **Connection**, a paginated list of nodes. In the diagram, this would be a collection of lines.\n\n========================================\n\nCode:\n```text\n{\n repository(owner: \"getsmarter\", name: \"moodle-api\") {\n id\n issues(first:2 ) {\n edges {\n node {\n id\n body\n }\n }\n nodes {\n body\n }\n pageInfo {\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n totalCount\n } \n }\n}\n```\n\n```text\nA -> connection -> edges -> B\n```\n\n```text\n{\n repository(owner: \"getsmarter\", name: \"moodle-api\") {\n issues(first:2 ) {\n edges {\n cursor\n node {\n id\n }\n }\n }\n }\n}\n```\n\n```text\ntypeBConnection\n```\n\n```text\nedges\n```\n\n```text\nnode\n```\n\n```text\ncursor\n```\n\n```text\ncursor\n```\n\n```text\nedge\n```\n\n```text\nedges\n```\n\n```text\nnodes\n```\n\n```text\nA->conn->edge->B\n```\n\n```text\nA->conn->B\n```\n\n```text\ncursor\n```\n\n```text\nnode\n```\n\n```text\nnode\n```\n\n========================================\n\nComments:\n- this might be helpful stackoverflow.com/questions/42622912/…\n- Some background information: graph.cool/blog/connections-edges-nodes-relay-tioghei9go\n- Thanks for the detailed answer, but this doesn't actually answer the question. I want to know why nodes are included at the same level as edges. Specifically Github's api. Is it just a convenience? I have read the spec already and understand that an edge has a cursor and a node, but why is there a nodes collection at the same level as edges on the github api? I am leaning towards @griffith_joel's answer\n- I thought the statement \"They also have a field which bypasses the edge type in the case you don't need the cursors. This is why you see both edges and nodes fields directly off the connection type.\" would be sufficient and I apologize if that wasn't clear. I edited my answer to provide what I hope expands this for clarity.\n- I'm late, but after reviewing this answer I'm left with a question. The difference between using node or edge, beyond possible extra fields in the relationship that edge could provide, is: Node will always return all the data of the connection, while edge will additionally provide a cursor to work the \"paging\" of the related node on that connection (thus having a pagination of the connection and another independent of the edge-node)?","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":160,"estimatedTokens":957}}129{"id":"stack-40671105","source":"stackoverflow","questionId":40671105,"title":"Projects where REST is more suitable over GraphQL?","tags":["rest","web-applications","architecture","graphql"],"text":"Title: Projects where REST is more suitable over GraphQL?\nTags: rest, web-applications, architecture, graphql\nSource: Stack Overflow\n\nQuestion:\nBased on the articles I read, GraphQL is more resource-efficient in terms of roundtrips and it can also do what REST can provide. What are the reasons why software architect & developers might decide to stay with REST over GraphQL given that the web application will just be started from scratch? Also given that this is a continuous project, will be consumed from web and mobile and openID connect is a requirement.\n\n========================================\n\nTop Answer:\nThis is a rather broad question but I'll try answer speaking from my own experience.\n\nREST provides access to a specific resource, e.g. a user or a product. The result from a request will likely be an *assumption* of what data you will want or use, i.e. it's probably everything about that resource regardless of whether you use all the data or not.\n\nThere is also the problem of N+1. As an example, take the user has and belongs to many relationships scenario; with a RESTful API you would make a request to the user, e.g. `/users/:id` then make a request to all their relationships, e.g. `/users/:id/relationships`, so that's two requests already. There could be an *assumption* of the relationships endpoint to include both the relationship (friend, family member, etc.) and the user in the resulting array, but if the API doesn't make that *assumption*, you're going to have to make a request to each user endpoint to get the data on each user in each relationship.\n\nThis example can go deeper too; what if you want all second tier relationships (friends of friends for instance)?\n\nGraphQL solves this by allowing you to ask for specifically what you need. You can construct a query to return the data at depth:\n\n```\nquery myQuery($userId: ID!) {\n user(id: $userID) {\n id\n name\n relationships {\n id\n type\n user {\n id\n name\n relationships {\n id\n type\n user {\n id\n name\n }\n }\n }\n }\n }\n}\n```\n\nFragments could clean this up a bit and there may be recursive issues, but you should get the idea; one request gets you all the nested data you need.\n\nIf you don't have much need for such nested or inter-connected result sets, GraphQL may not offer much in a trade between benefit and complexity.\n\nHowever, one of the greatest benefits I have found with GraphQL is its extensibility and self-documentation.\n\n========================================\n\nCode:\n```text\nquery myQuery($userId: ID!) {\n user(id: $userID) {\n id\n name\n relationships {\n id\n type\n user {\n id\n name\n relationships {\n id\n type\n user {\n id\n name\n }\n }\n }\n }\n }\n}\n```\n\n```text\n/users/:id\n```\n\n```text\n/users/:id/relationships\n```\n\n========================================\n\nComments:\n- my thoughts on this are stackoverflow.com/questions/41141577/graphql-or-rest/… so it boils down to the question where the business logic should reside.\n- my blog post on that blog.ditectrev.com/blog/software-development/web-services/…\n- Graphql if we have time and we are after performance? BTW, oauth2.0/openID connect is the same for both right?\n- Well, sort of yes. You could get performance increases with GraphQL. Further more, GraphQL do not specify any methods of authentication so do what you would normally do.\n- I forgot to mention that openID connect is a must, will this be a factor for deciding which one to choose? For REST, we can restrict the endpoints accessible for a certain access_token, how's this in graphql?\n- @lem There are two ways: First is authentication on the GraphQL endpoint like you would normally do with any RESTful endpoint. The second is to pass the authenticated user into each query/mutation as a context and ensure the user has access to a given resource. This is an inside out approach to authentication where you first load the resource then check if the user is allowed to read/write to said resource. It's much easier with REST/CRUD because you can authenticate based on the operation rather than the resource itself.\n- general question: given that spring has getting started codes for oauth2(authorization & resource server) + hateoas, client code will be on react... rest is still faster to develop than with graphql?\n- For us, GraphQL is much faster when developing than traditional REST solutions like WebAPI in .NET or Spring. But this is still much subjective to each developer.\n- See also stackoverflow.com/questions/40689858/…","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":99,"estimatedTokens":1146}}130{"id":"stack-45959234","source":"stackoverflow","questionId":45959234,"title":"authentication in spring boot using graphql","tags":["authentication","spring-boot","spring-security","graphql","graphql-java"],"text":"Title: authentication in spring boot using graphql\nTags: authentication, spring-boot, spring-security, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nIβm working on a spring boot project with GraphQL. I'm using graphql-java-tools and graphql-spring-boot-starter. I managed to configure security and session management with spring security as you can see in the java config files below. \n\nNow the β/graphqlβ path is secured (it can be accessed only sending the βbasic http authenticationβ or a session token (`x-auth-token`) in a http header of the request). Authenticating with βbasic http authenticationβ on any GraphQL operation will start a new session and send back the new session token in a header, and that token can be used further to continue that session.\n\nHow to give access to anonymous users to some GraphQL queries/mutations keeping the above behavior?\n\nIf I change `antMatchers(\"/graphql\").authenticated()` to `antMatchers(\"/graphql\").permitAll()` in order to allow anonymous access, then my custom `AuthenticationProvider` is not called anymore even when I try to authenticate with βbasic http authenticationβ.\n\nThanks!\n\nHere are my configs:\n\n```\n@Configuration\n@EnableWebSecurity\n@EnableGlobalMethodSecurity(prePostEnabled = true)\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\n\n @Autowired\n private AuthenticationProvider authenticationProvider;\n\n @Override\n public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) {\n authenticationManagerBuilder.authenticationProvider(authenticationProvider);\n }\n\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http\n .csrf().disable()\n .authorizeRequests()\n .antMatchers(\"/graphql\").authenticated()\n .and()\n .requestCache()\n .requestCache(new NullRequestCache())\n .and()\n .httpBasic()\n .and()\n .headers()\n .frameOptions().sameOrigin() // needed for H2 web console\n .and()\n .sessionManagement()\n .maximumSessions(1)\n .maxSessionsPreventsLogin(true)\n .sessionRegistry(sessionRegistry());\n }\n\n @Bean\n public SessionRegistry sessionRegistry() {\n return new SessionRegistryImpl();\n }\n\n @Bean\n public HttpSessionEventPublisher httpSessionEventPublisher() {\n return new HttpSessionEventPublisher();\n }\n}\n```\n\n```\n@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 180)\npublic class HttpSessionConfig {\n\n @Bean\n public HttpSessionStrategy httpSessionStrategy() {\n return new HeaderHttpSessionStrategy();\n }\n\n}\n```\n\n========================================\n\nTop Answer:\nEven though you need to use `permitAll()` you can still create reasonable default for your resolver methods using AOP.\n\nYou can create your custom security aspect that will require authentication by default.\n\nUnsecured methods may be marked for example using annotation.\n\nSee my blog post for details: https://michalgebauer.github.io/spring-graphql-security\n\n========================================\n\nCode:\n```java\n@Configuration\n@EnableWebSecurity\n@EnableGlobalMethodSecurity(prePostEnabled = true)\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\n\n @Autowired\n private AuthenticationProvider authenticationProvider;\n\n @Override\n public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) {\n authenticationManagerBuilder.authenticationProvider(authenticationProvider);\n }\n\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http\n .csrf().disable()\n .authorizeRequests()\n .antMatchers(\"/graphql\").authenticated()\n .and()\n .requestCache()\n .requestCache(new NullRequestCache())\n .and()\n .httpBasic()\n .and()\n .headers()\n .frameOptions().sameOrigin() // needed for H2 web console\n .and()\n .sessionManagement()\n .maximumSessions(1)\n .maxSessionsPreventsLogin(true)\n .sessionRegistry(sessionRegistry());\n }\n\n @Bean\n public SessionRegistry sessionRegistry() {\n return new SessionRegistryImpl();\n }\n\n @Bean\n public HttpSessionEventPublisher httpSessionEventPublisher() {\n return new HttpSessionEventPublisher();\n }\n}\n```\n\n```java\n@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 180)\npublic class HttpSessionConfig {\n\n @Bean\n public HttpSessionStrategy httpSessionStrategy() {\n return new HeaderHttpSessionStrategy();\n }\n\n}\n```\n\n```text\nx-auth-token\n```\n\n```text\nantMatchers(\"/graphql\").authenticated()\n```\n\n```text\nantMatchers(\"/graphql\").permitAll()\n```\n\n```text\nAuthenticationProvider\n```\n\n```java\n@Configuration\n@EnableWebSecurity\n@EnableGlobalMethodSecurity(prePostEnabled = true)\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\n\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http\n .csrf().disable()\n .authorizeRequests()\n .antMatchers(\"/graphql\").permitAll()\n .and()\n .requestCache()\n .requestCache(new NullRequestCache())\n .and()\n .headers()\n .frameOptions().sameOrigin() // needed for H2 web console\n .and()\n .sessionManagement()\n .maximumSessions(1)\n .maxSessionsPreventsLogin(true)\n .sessionRegistry(sessionRegistry());\n }\n\n @Bean\n public SessionRegistry sessionRegistry() {\n return new SessionRegistryImpl();\n }\n\n @Bean\n public HttpSessionEventPublisher httpSessionEventPublisher() {\n return new HttpSessionEventPublisher();\n }\n}\n```\n\n```text\nlogin(credentials: CredentialsInputDto!): String\n\ninput CredentialsInputDto {\n username: String!\n password: String!\n}\n```\n\n```java\npublic String login(CredentialsInputDto credentials) {\n String username = credentials.getUsername();\n String password = credentials.getPassword();\n\n UserDetails userDetails = userDetailsService.loadUserByUsername(username);\n\n ... credential checks and third party authentication ...\n\n Authentication authentication = new UsernamePasswordAuthenticationToken(username, password, userDetails.getAuthorities());\n SecurityContextHolder.getContext().setAuthentication(authentication);\n httpSession.setAttribute(\"SPRING_SECURITY_CONTEXT\", SecurityContextHolder.getContext());\n return httpSession.getId();\n}\n```\n\n```text\n.antMatchers(\"/graphql\").authenticated()\n```\n\n```text\n.antMatchers(\"/graphql\").permitAll()\n```\n\n```text\n.httpBasic()\n```\n\n```text\nAuthenticationProvider\n```\n\n```text\n.antMatchers(\"/graphql\").permitAll()\n```\n\n```text\n@Preauthorize(\"isAnonymous()\n```\n\n```text\nhasRole(\"USER\")\")\n```\n\n```text\npermitAll()\n```\n\n========================================\n\nComments:\n- Blog post assisted me tremendously regarding this issue, great work!\n- I just wanted to say I spent the whole day searching for a solution until I found your blog post, thanks a lot!","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":264,"estimatedTokens":1738}}131{"id":"stack-50408657","source":"stackoverflow","questionId":50408657,"title":"How to use the loading property in a watchQuery when using the Apollo client for GraphQl","tags":["angular","graphql","apollo-client"],"text":"Title: How to use the loading property in a watchQuery when using the Apollo client for GraphQl\nTags: angular, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nSo when i get the response from my query, i can see there is a loading property. But i don't really get why they would pass it along. Because when you get the response it means that the loading is finished, hence the loading will always be false.\n\nIs there a way that i can use this loading property so that i can for example make a loading icon appear when the call is still loading?\n\nI have the following code in an Angular 2 environment:\n\n```\npublic apolloQuery = gql`\n query {\n apolloQuery \n }`;\n\nconst sub = this.apollo.watchQuery({\n query: this.apolloQuery \n}).subscribe(data => {\n console.log(data);\n sub.unsubscribe();\n});\n```\n\nAnd the log from the data object contains the loading property i was talking about, which is always false.\n\nI know i can make my own boolean property and check this way, but i was just wondering if i could use the built-in loading property that Apollo provides?\n\n========================================\n\nTop Answer:\nIt is posible, you need to set the option **notifyOnNetworkStatusChange: true**, it is explained in this documentation and then use the loading prop:\n\n```\nthis.querySubscription = this.apollo.watchQuery({\n query: CurrentUserForProfile\n ,notifyOnNetworkStatusChange: true {\n this.loading = loading; <-- now this will change to false at the start of the request\n this.currentUser = data.currentUser;\n });\n```\n\n========================================\n\nCode:\n```text\npublic apolloQuery = gql`\n query {\n apolloQuery \n }`;\n\nconst sub = this.apollo.watchQuery<QueryResponse>({\n query: this.apolloQuery \n}).subscribe(data => {\n console.log(data);\n sub.unsubscribe();\n});\n```\n\n```text\nimport { Component, OnInit } from '@angular/core';\nimport { Apollo } from 'apollo-angular';\nimport gql from 'graphql-tag';\n\n// We use the gql tag to parse our query string into a query document\nconst CurrentUserForProfile = gql`\n query CurrentUserForProfile {\n currentUser {\n login\n avatar_url\n}\n }\n`;\n\n@Component({ ... })\nclass ProfileComponent implements OnInit, OnDestroy {\n loading: boolean;\n currentUser: any;\n\n private querySubscription: Subscription;\n\n constructor(private apollo: Apollo) {}\n\n ngOnInit() {\n this.querySubscription = this.apollo.watchQuery<any>({\n query: CurrentUserForProfile\n })\n .valueChanges\n .subscribe(({ data, loading }) => {\n this.loading = loading;\n this.currentUser = data.currentUser;\n });\n }\n\n ngOnDestroy() {\n this.querySubscription.unsubscribe();\n }\n}\n```\n\n```text\nloading\n```\n\n```text\nthis.querySubscription = this.apollo.watchQuery<any>({\n query: CurrentUserForProfile\n ,notifyOnNetworkStatusChange: true <-- This will make the trick\n})\n .valueChanges\n .subscribe(({ data, loading }) => {\n this.loading = loading; <-- now this will change to false at the start of the request\n this.currentUser = data.currentUser;\n });\n```\n\n```text\nexport interface WatchQueryOptions<TVariables> extends CoreWatchQueryOptions<TVariables> {\n /**\n * Observable starts with `{ loading: true }`.\n * There's a big chance the next major version will enable that by default.\n *\n * Disabled by default\n */\n useInitialLoading?: boolean;\n}\n```\n\n```text\nconst variables = {};\nreturn apollo\n .watch(variables, { useInitialLoading: true })\n .valueChanges\n .subscribe(({data, loading})=> console.log(loading)));\n```\n\n```text\nuseInitialLoading: true\n```\n\n========================================\n\nComments:\n- I understand that, but what use does it have and more importantly how can i use it? I cant see the importance of it because i can do it myself much easier: When making a call i set a boolean 'loading' to true, when i receive the call i set it back to false. The boolean parameter provided bu GraphQL is only available to me when the call is already done, right?\n- The watchQuery method returns a QueryRef object which has the valueChanges property that is an Observable. We can see that the result object contains loading, a Boolean indicating if the query is \"in-flight.\": github.com/apollographql/apollo-angular/blob/master/docs/sou‌​rce/…\n- With this comment i understand the loading parameter is available in the moment of execute the subscription, not when the call is allready done\n- @MartijnvandenBergh : why did you mark this as the correct answer? It doesn't answer your question - the correct answer is provided by nanitohb below.\n- Can you please update the reference link in apollo angular website","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":149,"estimatedTokens":1166}}132{"id":"stack-41630743","source":"stackoverflow","questionId":41630743,"title":"How to resolve union/interface fields with GraphQL and ApolloStack","tags":["node.js","graphql","apollostack"],"text":"Title: How to resolve union/interface fields with GraphQL and ApolloStack\nTags: node.js, graphql, apollostack\nSource: Stack Overflow\n\nQuestion:\nI am making use of interfaces with my GraphQL instance, but this question perhaps applies to unions as well.\nThere are 2 common fields across all types which implement the interface, however there are multiple additional fields on each type.\n\nGiven the following schema\n\n```\ninterface FoodType {\n id: String\n type: String\n}\n\ntype Pizza implements FoodType {\n id: String\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n}\n\ntype Salad implements FoodType {\n id: String\n type: String\n vegetarian: Boolean\n dressing: Boolean\n}\n\ntype BasicFood implements FoodType {\n id: String\n type: String\n}\n```\n\nand the following resolvers\n\n```\n{\n Query: {\n GetAllFood(root) {\n return fetchFromAllFoodsEndpoint()\n .then((items) => {\n return mergeExtraFieldsByType(items);\n });\n },\n },\n FoodType: {\n __resolveType(food) {\n switch (food.type) {\n case 'pizza': return 'Pizza';\n case 'salad': return 'Salad';\n default: return 'BasicFood';\n }\n },\n },\n Pizza: {\n toppings({pizzaType}) {\n return fetchFromPizzaEndpoint(pizzaType);\n }\n }\n}\n```\n\nHow do I obtain the additional fields for each type?\n\nCurrently, I have the `allFood` fetching all foods to obtain the basic fields of `id` and `type`. After this I am looping over the results, and if any of found of the type `Pizza`, I make a calling to `fetchFromPizzaEndpoint`, obtaining the additional fields and merging those onto the original basic type. I repeat this for each type.\n\nI am also able to manually resolve specific fields, one at a type, such as the `Pizza.toppings`, as seen above.\n\nNow my solution is not ideal, I would much rather be able to resolve multiple fields for each type, much the same way I do with the single field `toppings`. Is this possible with GraphQL? There must be a better way to achieve this, seeing as it's quite a common use case.\n\nIdeally, I would like to be able to know in my resolver, what fragments my query is asking for, so I can only make calls to endpoints which are asked for (one endpoint per fragment).\n\n```\n{\n Query: {\n GetAllFood(root) {\n return fetchFromAllFoodsEndpoint();\n },\n },\n FoodType: {\n __resolveType(food) {\n switch (food.type) {\n case 'pizza': return 'Pizza';\n case 'salad': return 'Salad';\n default: return 'BasicFood';\n }\n },\n },\n Pizza: {\n __resolveMissingFields(food) {\n return fetchFromPizzaEndpoint(food.id);\n }\n },\n Salad: {\n __resolveMissingFields(food) {\n return fetchFromSaladEndpoint(food.id);\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\ninterface FoodType {\n id: String\n type: String\n}\n\ntype Pizza implements FoodType {\n id: String\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n}\n\ntype Salad implements FoodType {\n id: String\n type: String\n vegetarian: Boolean\n dressing: Boolean\n}\n\ntype BasicFood implements FoodType {\n id: String\n type: String\n}\n```\n\n```text\n{\n Query: {\n GetAllFood(root) {\n return fetchFromAllFoodsEndpoint()\n .then((items) => {\n return mergeExtraFieldsByType(items);\n });\n },\n },\n FoodType: {\n __resolveType(food) {\n switch (food.type) {\n case 'pizza': return 'Pizza';\n case 'salad': return 'Salad';\n default: return 'BasicFood';\n }\n },\n },\n Pizza: {\n toppings({pizzaType}) {\n return fetchFromPizzaEndpoint(pizzaType);\n }\n }\n}\n```\n\n```text\n{\n Query: {\n GetAllFood(root) {\n return fetchFromAllFoodsEndpoint();\n },\n },\n FoodType: {\n __resolveType(food) {\n switch (food.type) {\n case 'pizza': return 'Pizza';\n case 'salad': return 'Salad';\n default: return 'BasicFood';\n }\n },\n },\n Pizza: {\n __resolveMissingFields(food) {\n return fetchFromPizzaEndpoint(food.id);\n }\n },\n Salad: {\n __resolveMissingFields(food) {\n return fetchFromSaladEndpoint(food.id);\n }\n }\n}\n```\n\n```text\nallFood\n```\n\n```text\nid\n```\n\n```text\ntype\n```\n\n```text\nPizza\n```\n\n```text\nfetchFromPizzaEndpoint\n```\n\n```text\nPizza.toppings\n```\n\n```text\ntoppings\n```\n\n```text\n{\n Query: {\n GetAllFood(root) {\n return fetchFromAllFoodsEndpoint()\n .then((items) => {\n return mergeExtraFieldsByType(items);\n });\n },\n },\n FoodType: {\n __resolveType(food) {\n switch (food.type) {\n case 'pizza': return 'Pizza';\n case 'salad': return 'Salad';\n default: return 'BasicFood';\n }\n },\n },\n Pizza: {\n toppings({pizzaType}) {\n return fetchFromPizzaEndpoint(pizzaType);\n }\n }\n}\n```\n\n```text\n{\n Query: {\n GetAllFood(root) {\n return fetchFromAllFoodsEndpoint()\n .then((items) => {\n return mergeExtraFieldsByType(items);\n });\n },\n },\n FoodType: {\n __resolveType(data, ctx, info) {\n return whatIsTheType(data, ctx, info)\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Can you elaborate on what is returned by each dataLoader? This use-case looks quite foreign to me, although we do have several cases of union types in our server implementation. For us, we grab whatever data the union contains from the DB (at which point we already *have* all the data without needing to load more) and then decide which type GraphQL should return the data as (in its type resolver).\n- The DataLoaders are simply the Facebook DataLoaders which fetch data, the source of the data is unimportant. Currently, I am doing exactly as you mentioned however it is inefficient as I have to fetch more data than I am going to use. Example, if I only fragment \"Pizza\" I should not pull \"Salad\" properties down. It would be great to have fragment level resolvers, but after speaking with the GraphQL devs, it seems it's a future feature and not currently supported.\n- That's the bit that I don't understand. How would you get Salad properties if your data is actually a Pizza? That's why it matters which data are returned by the DataLoaders. We load data from MongoDB, for example. If you query a document from MongoDB, it contains what it contains (i.e. only the \"Pizza\" data for a Pizza document) and nothing else. There is no inefficiency there. If you mean there is an inefficiency in the data being returned from GraphQL, that's what the union type handles for you perfectly. If that's the inefficiency you're concerned about, I will write a more detailed answer\n- You have the benefit of calling a database directly and structuring your query as you see fit (in this case, MongoDb), whilst in my instance I am speaking to a number of REST web services. So I call Query.GetAllFood - this hits on service to get everything. However if I do a fragment of \"... on Pizza { toppings }\", I want to at that point know about the fragment and call another web service endpoint to get the pizza data and merge it on my result. Currently I call all services and merge everything which isn't a great solution.\n- Can you update your question to include that information? I personally found it hard to understand without it. When I get a moment I will write an answer to your question if I have one. In fact, it'd be better if you remove all mentions of `dataLoader` entirely and just use something like `fetchFromPizzaEndpoint()`, `fetchFromAllFoodsEndpoint()` etc.\n- I actually re-wrote it completely a few weeks ago doing exactly as you mentioned above. Almost forgot I had this question on here :)\n- So what was the problem and how your answer resolved it?\n- Does anyone know how to solve it when you build your schema with a string an `buildSchema`?\n- To answer my comment. Functionality was added here and can be done by returning `__typename` on your object.","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":276,"estimatedTokens":1961}}133{"id":"stack-44980989","source":"stackoverflow","questionId":44980989,"title":"GraphQL: Query.type field type must be Output Type but got: undefined","tags":["javascript","node.js","graphql","express-graphql"],"text":"Title: GraphQL: Query.type field type must be Output Type but got: undefined\nTags: javascript, node.js, graphql, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying my first GraphQL approach. Here is the code:\n\n**schema.js:**\n\n```\nimport {\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLInputObjectType,\n GraphQLNonNull,\n GraphQLString,\n GraphQLBoolean,\n GraphQLInt,\n GraphQLID,\n GraphQLList\n} from 'graphql';\n\nimport Company from '../../models/Company';\n\nconst CompanyType = new GraphQLObjectType({\n name: 'Company',\n description: 'Company',\n fields: {\n _id: {\n type: new GraphQLNonNull(GraphQLID)\n },\n name: {\n type: GraphQLString\n }\n }\n})\n\nconst Companies = {\n type: CompanyType,\n args: {\n id: {\n name: 'ID',\n type: new GraphQLNonNull(GraphQLID)\n }\n },\n resolve(root, params) {\n return Company.find(params.id).exec();\n }\n}\n\nexport default new GraphQLSchema({\n\n query: new GraphQLObjectType({\n name: 'Query',\n fields: Companies\n })\n});\n```\n\nThen on my **server.js**: \n\n```\nimport express from 'express';\nimport bodyParser from 'body-parser';\nimport mongoose from 'mongoose';\nimport morgan from 'morgan';\nimport graphqlHTTP from 'express-graphql';\n\nimport schema from './schema';\n\nmongoose.Promise = global.Promise;\n\n// set up example server\nconst app = express();\napp.set('port', (process.env.API_PORT || 3001));\n\n // logger\n app.use(morgan('dev')); \n\n// parse body\napp.use(bodyParser.json());\n\n// redirect all requests to /graphql\napp.use(function redirect(req, res) {\n res.redirect('/graphql');\n});\n\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n graphqli: true,\n pretty: true\n}));\n```\n\nI'm getting the following errror:\n\n```\nD:\\test\\node_modules\\graphql\\jsutils\\invariant.js:19\n throw new Error(message);\n ^\n\nError: Query.type field type must be Output Type but got: undefined.\n at invariant (D:\\test\\node_modules\\graphql\\jsutils\\invariant.js:19:11)\n at D:\\test\\node_modules\\graphql\\type\\definition.js:361:29\n at Array.forEach (native)\n at defineFieldMap (D:\\test\\node_modules\\graphql\\type\\definition.js:352:14)\n at GraphQLObjectType.getFields (D:\\test\\node_modules\\graphql\\type\\definition.js:306:44)\n at typeMapReducer (D:\\test\\node_modules\\graphql\\type\\schema.js:206:25)\n at Array.reduce (native)\n at new GraphQLSchema (D:\\test\\node_modules\\graphql\\type\\schema.js:95:34)\n at Object. (D:/9. DEV/WORKSPACE/mom/client/graphql/index.js:62:16)\n at Module._compile (module.js:570:32)\n at loader (D:\\test\\node_modules\\babel-register\\lib\\node.js:144:5)\n at Object.require.extensions.(anonymous function) [as .js] (D:\\test\\node_modules\\babel-register\\lib\\node.js:154:7)\n at Module.load (module.js:487:32)\n at tryModuleLoad (module.js:446:12)\n at Function.Module._load (module.js:438:3)\n at Module.require (module.js:497:17)\n```\n\n========================================\n\nTop Answer:\nFor me, the problem was that I defined a graphql type and input type with the same name in my graphql schema file.\n\nI changed this:\n\n```\ntype InternalAttribute {\n name: String\n}\n\ninput InternalAttribute {\n name: String\n}\n```\n\nto this:\n\n```\ntype InternalAttribute {\n name: String\n}\n\ninput InternalAttributeInput {\n name: String\n}\n```\n\n========================================\n\nCode:\n```text\nimport {\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLInputObjectType,\n GraphQLNonNull,\n GraphQLString,\n GraphQLBoolean,\n GraphQLInt,\n GraphQLID,\n GraphQLList\n} from 'graphql';\n\nimport Company from '../../models/Company';\n\nconst CompanyType = new GraphQLObjectType({\n name: 'Company',\n description: 'Company',\n fields: {\n _id: {\n type: new GraphQLNonNull(GraphQLID)\n },\n name: {\n type: GraphQLString\n }\n }\n})\n\n\nconst Companies = {\n type: CompanyType,\n args: {\n id: {\n name: 'ID',\n type: new GraphQLNonNull(GraphQLID)\n }\n },\n resolve(root, params) {\n return Company.find(params.id).exec();\n }\n}\n\n\nexport default new GraphQLSchema({\n\n query: new GraphQLObjectType({\n name: 'Query',\n fields: Companies\n })\n});\n```\n\n```text\nimport express from 'express';\nimport bodyParser from 'body-parser';\nimport mongoose from 'mongoose';\nimport morgan from 'morgan';\nimport graphqlHTTP from 'express-graphql';\n\nimport schema from './schema';\n\nmongoose.Promise = global.Promise;\n\n// set up example server\nconst app = express();\napp.set('port', (process.env.API_PORT || 3001));\n\n\n // logger\n app.use(morgan('dev')); \n\n// parse body\napp.use(bodyParser.json());\n\n// redirect all requests to /graphql\napp.use(function redirect(req, res) {\n res.redirect('/graphql');\n});\n\n\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n graphqli: true,\n pretty: true\n}));\n```\n\n```text\nD:\\test\\node_modules\\graphql\\jsutils\\invariant.js:19\n throw new Error(message);\n ^\n\nError: Query.type field type must be Output Type but got: undefined.\n at invariant (D:\\test\\node_modules\\graphql\\jsutils\\invariant.js:19:11)\n at D:\\test\\node_modules\\graphql\\type\\definition.js:361:29\n at Array.forEach (native)\n at defineFieldMap (D:\\test\\node_modules\\graphql\\type\\definition.js:352:14)\n at GraphQLObjectType.getFields (D:\\test\\node_modules\\graphql\\type\\definition.js:306:44)\n at typeMapReducer (D:\\test\\node_modules\\graphql\\type\\schema.js:206:25)\n at Array.reduce (native)\n at new GraphQLSchema (D:\\test\\node_modules\\graphql\\type\\schema.js:95:34)\n at Object.<anonymous> (D:/9. DEV/WORKSPACE/mom/client/graphql/index.js:62:16)\n at Module._compile (module.js:570:32)\n at loader (D:\\test\\node_modules\\babel-register\\lib\\node.js:144:5)\n at Object.require.extensions.(anonymous function) [as .js] (D:\\test\\node_modules\\babel-register\\lib\\node.js:154:7)\n at Module.load (module.js:487:32)\n at tryModuleLoad (module.js:446:12)\n at Function.Module._load (module.js:438:3)\n at Module.require (module.js:497:17)\n```\n\n```text\nfields: Companies\n```\n\n```text\nfields: { Companies }\n```\n\n```text\nfields: {\n name: {type: String} \n }\n```\n\n```text\nfields: {Companies}\n```\n\n```js\ntype InternalAttribute {\n name: String\n}\n\ninput InternalAttribute {\n name: String\n}\n```\n\n```js\ntype InternalAttribute {\n name: String\n}\n\ninput InternalAttributeInput {\n name: String\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.029Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":300,"estimatedTokens":1559}}134{"id":"stack-58550958","source":"stackoverflow","questionId":58550958,"title":"Get list of requested keys in NestJS/GraphQL request","tags":["graphql","nestjs"],"text":"Title: Get list of requested keys in NestJS/GraphQL request\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am just fiddling around trying to understand, thus my types are not exact.\n\n```\n@Resolver()\nexport class ProductsResolver {\n @Query(() => [Product])\n async products() {\n return [{\n id: 55,\n name: 'Moonshine',\n storeSupplies: {\n London: 25,\n Berlin: 0,\n Monaco: 3,\n },\n }];\n }\n}\n```\n\nIf I request data with query bellow\n\n```\n{\n products{\n id,\n name,\n }\n}\n```\n\nI want `async carriers()` to receive `['id', 'name']`. I want to skip getting of `storeSupplies` as it might be an expensive SQL call.\n\nI am new to GraphQL, I might have missed something obvious, or even whole patterns. Thanks in advance.\n\n========================================\n\nTop Answer:\nBasically you can seperate `StoreSupplies` queries, to make sure not to get them when query on the products.\n\nYou can also get the requested keys in your resolver, then query based on them. In order to do that, you can define a parameter decorator like this:\n\n```\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const Info = createParamDecorator(\n (data, [root, args, ctx, info]) => info,\n);\n```\n\nThen use it in your resolver like this:\n\n```\n@UseGuards(GqlAuthGuard)\n @Query(returns => UserType)\n async getMe(@CurrentUser() user: User, @Info() info): Promise {\n console.log(\n info.fieldNodes[0].selectionSet.selections.map(item => item.name.value),\n );\n return user;\n }\n```\n\nFor example, when you run this query\n\n```\n{\n getMe{\n id\n email\n roles\n }\n}\n```\n\nThe `console.log` output is:\n\n```\n[ 'id', 'email', 'roles' ]\n```\n\n========================================\n\nCode:\n```js\n@Resolver()\nexport class ProductsResolver {\n @Query(() => [Product])\n async products() {\n return [{\n id: 55,\n name: 'Moonshine',\n storeSupplies: {\n London: 25,\n Berlin: 0,\n Monaco: 3,\n },\n }];\n }\n}\n```\n\n```query\n{\n products{\n id,\n name,\n }\n}\n```\n\n```text\nasync carriers()\n```\n\n```text\n['id', 'name']\n```\n\n```text\nstoreSupplies\n```\n\n```js\n@Resolver()\nexport class ProductsResolver {\n @Query(() => [Product])\n async products(\n @Info() info\n ) {\n // Method 1 thanks to @pooya-haratian.\n // Update: use this method; read below article to understand why.\n let keys = info.fieldNodes[0].selectionSet.selections.map(item => item.name.value);\n // Method 2 by me, but I'm not sure which method is best.\n // Update: don't use this; read below article to understand why.\n let keys = info.operation.selectionSet.selections[0].selectionSet.selections.map(field => field.name.value);\n return keys;\n }\n}\n```\n\n```text\nfieldNodes[0]\n```\n\n```text\n@Info\n```\n\n```js\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const Info = createParamDecorator(\n (data, [root, args, ctx, info]) => info,\n);\n```\n\n```js\n@UseGuards(GqlAuthGuard)\n @Query(returns => UserType)\n async getMe(@CurrentUser() user: User, @Info() info): Promise<User> {\n console.log(\n info.fieldNodes[0].selectionSet.selections.map(item => item.name.value),\n );\n return user;\n }\n```\n\n```text\n{\n getMe{\n id\n email\n roles\n }\n}\n```\n\n```text\n[ 'id', 'email', 'roles' ]\n```\n\n```text\nStoreSupplies\n```\n\n```text\nconsole.log\n```\n\n```text\n@Query(() => [PostObject])\nasync posts(\n @FieldMap() fieldMap: FieldMap,\n) {\n console.log(fieldMap);\n}\n```\n\n```text\n{\n \"posts\": {\n \"id\": {},\n \"title\": {},\n \"body\": {},\n \"author\": {\n \"id\": {},\n \"username\": {},\n \"firstName\": {},\n \"lastName\": {}\n },\n \"comments\": {\n \"id\": {},\n \"body\": {},\n \"author\": {\n \"id\": {},\n \"username\": {},\n \"firstName\": {},\n \"lastName\": {}\n }\n }\n }\n}\n```\n\n```text\n{\n post { # post: [Post]\n id\n author: {\n id\n firstName\n lastName\n }\n }\n}\n```\n\n```text\nimport { fieldsList, fieldsMap } from 'graphql-fields-list';\nimport { Query, Info } from '@nestjs/graphql';\n\n@Query(() => [Post])\nasync post(\n @Info() info,\n) {\n console.log(fieldsList(info)); // [ 'id', 'firstName', 'lastName' ]\n console.log(fieldsMap(info)); // { id: false, firstName: false, lastName: false }\n console.log(fieldsProjection(info)); // { id: 1, firstName: 1, lastName: 1 };\n}\n```\n\n```text\ninfo\n```\n\n```js\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\nconst getNodeData = (node) => {\n const { selectionSet } = node || {};\n\n let fields = null;\n if (!!selectionSet) {\n fields = {};\n selectionSet.selections.forEach((selection) => {\n const name = selection.name.value;\n fields[name] = getNodeData(selection);\n });\n }\n\n return fields;\n};\n\nexport const FieldMap = createParamDecorator((_, ctx: ExecutionContext) => {\n const gqlCtx = GqlExecutionContext.create(ctx);\n const info = gqlCtx.getInfo();\n\n const node = info.fieldNodes[0];\n return getNodeData(node);\n});\n```\n\n```js\n@Resolver()\nexport class ExampleResolver {\n @Query()\n example(@FieldMap() fieldMap) {\n console.log(fieldMap);\n }\n}\n```\n\n```text\nexample {\n id\n name\n description\n child1 {\n id\n name\n }\n child2 {\n id\n name\n value\n }\n}\n```\n\n```text\n{\n id: null,\n name: null,\n description: null,\n child1: { id: null, name: null },\n child2: { id: null, name: null, value: null }\n}\n```\n\n```text\nexport const RequestedFields = createParamDecorator((data: undefined | string | string[], ctx: ExecutionContext) => {\n const info = GqlExecutionContext.create(ctx).getInfo<GraphQLResolveInfo>()\n const parsedInfo = parse(info) as ResolveTree\n const { returnType } = info\n const simplifiedInfo = simplify(parsedInfo, returnType)\n if (typeof data === 'undefined') return Object.keys(simplifiedInfo.fields)\n\n const result: string[] = []\n\n const getFields = (node: ResolveTree) => {\n Object.keys(node.fieldsByTypeName).forEach((key) => {\n const type = node.fieldsByTypeName[key]\n // check if the key is the requested field\n if (key === data) {\n Object.keys(type).forEach((field) => {\n result.push(type[field].name)\n })\n return\n }\n // check if the key is a nested field\n Object.keys(type).forEach((field) => {\n getFields(type[field])\n })\n })\n }\n getFields(simplifiedInfo)\n return result\n})\n```\n\n```text\n@Query(() => [Product])\n async products(\n @RequiredFields() fields : string[]\n) {\n console.log(fields) // return ['id','name','storeSupplies']\n return [{\n id: 55,\n name: 'Moonshine',\n storeSupplies: {\n London: 25,\n Berlin: 0,\n Monaco: 3,\n },\n }];\n }\n```\n\n```text\n@RequiredFields('Product') fields : string[]\n```\n\n========================================\n\nComments:\n- Why should `fieldNodes` be used instead of `operation.selectionSet.selections`? Is this the best way of doing so? I'm attempting to do the same, but only to use `projections` for mongodb's native driver to optimize requests.\n- @yaharga actually I'm not sure about the best way, but I guess for most cases, like the question above, we can simply use `@ResolvePropert`. I didn't notice that till now :D\n- I was attempting to get the keys in order to use them with the MongoDB `projection` parameter in the `find()` function. `@ResolveProperty` would be useless there, right?\n- Yeah I agree with you. @yaharga\n- My question was a little off topic, but it turns out I was looking for @CurrentUser()\n- To test which is better try some nested queries to see what gives correct list of fields back.\n- Added reference to the article. Hopefully it helps better clear things up.\n- this map only work with one level of selection set. If the schema comes with a nested selections sets possibilities it won't work\n- this code snipe looks like working for nest objects const keys = []; function getKeys(selections) { selections.map((item) => { if (keys.indexOf(item.name.value)) { keys.push(item.name.value); } if (item?.selectionSet) { getKeys(item.selectionSet.selections); } }); } const infoKeys = (info) => { keys.splice(0, keys.length); getKeys(info.fieldNodes[0].selectionSet.selections); return keys; }; export default infoKeys;\n- Do not deconstruct an object that could be `null` or `undefined`. Either use `const { } = obj || {}`, or simply use assignment. Other than that, this looks good :)","metadata":{"transformedAt":"2026-08-18T18:32:36.030Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":392,"estimatedTokens":2133}}135{"id":"stack-56781756","source":"stackoverflow","questionId":56781756,"title":"What is the proper way to unit test Service with NestJS/Elastic","tags":["elasticsearch","graphql","nestjs","typegraphql"],"text":"Title: What is the proper way to unit test Service with NestJS/Elastic\nTags: elasticsearch, graphql, nestjs, typegraphql\nSource: Stack Overflow\n\nQuestion:\nIm trying to unit test a Service that uses elastic search. I want to make sure I am using the right techniques.\n\nI am new user to many areas of this problem, so most of my attempts have been from reading other problems similar to this and trying out the ones that make sense in my use case. I believe I am missing a field within the createTestingModule. Also sometimes I see `providers: [Service]` and others `components: [Service]`. \n\n```\nconst module: TestingModule = await Test.createTestingModule({\n providers: [PoolJobService],\n }).compile()\n```\n\n**This is the current error I have:**\n\n```\nNest can't resolve dependencies of the PoolJobService (?). \n Please make sure that the argument at index [0] \n is available in the _RootTestModule context.\n```\n\n**Here is my code:**\n\n**PoolJobService**\n\n```\nimport { Injectable } from '@nestjs/common'\nimport { ElasticSearchService } from '../ElasticSearch/ElasticSearchService'\n\n@Injectable()\nexport class PoolJobService {\n constructor(private readonly esService: ElasticSearchService) {}\n\n async getPoolJobs() {\n return this.esService.getElasticSearchData('pool/job')\n }\n}\n```\n\n***PoolJobService.spec.ts***\n\n```\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PoolJobService } from './PoolJobService'\n\ndescribe('PoolJobService', () => {\n let poolJobService: PoolJobService\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [PoolJobService],\n }).compile()\n\n poolJobService = module.get(PoolJobService)\n })\n\n it('should be defined', () => {\n expect(poolJobService).toBeDefined()\n })\n```\n\nI could also use some insight on this, but haven't been able to properly test this because of the current issue\n\n```\nit('should return all PoolJobs', async () => {\n jest\n .spyOn(poolJobService, 'getPoolJobs')\n .mockImplementation(() => Promise.resolve([]))\n\n expect(await poolJobService.getPoolJobs()).resolves.toEqual([])\n })\n})\n```\n\n========================================\n\nCode:\n```js\nconst module: TestingModule = await Test.createTestingModule({\n providers: [PoolJobService],\n }).compile()\n```\n\n```text\nNest can't resolve dependencies of the PoolJobService (?). \n Please make sure that the argument at index [0] \n is available in the _RootTestModule context.\n```\n\n```js\nimport { Injectable } from '@nestjs/common'\nimport { ElasticSearchService } from '../ElasticSearch/ElasticSearchService'\n\n@Injectable()\nexport class PoolJobService {\n constructor(private readonly esService: ElasticSearchService) {}\n\n async getPoolJobs() {\n return this.esService.getElasticSearchData('pool/job')\n }\n}\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PoolJobService } from './PoolJobService'\n\ndescribe('PoolJobService', () => {\n let poolJobService: PoolJobService\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [PoolJobService],\n }).compile()\n\n poolJobService = module.get<PoolJobService>(PoolJobService)\n })\n\n it('should be defined', () => {\n expect(poolJobService).toBeDefined()\n })\n```\n\n```js\nit('should return all PoolJobs', async () => {\n jest\n .spyOn(poolJobService, 'getPoolJobs')\n .mockImplementation(() => Promise.resolve([]))\n\n expect(await poolJobService.getPoolJobs()).resolves.toEqual([])\n })\n})\n```\n\n```text\nproviders: [Service]\n```\n\n```text\ncomponents: [Service]\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { PoolJobService } from './PoolJobService'\nimport { ElasticSearchService } from '../ElasticSearch/ElasticSearchService'\n\ndescribe('PoolJobService', () => {\n let poolJobService: PoolJobService\n let elasticService: ElasticSearchService // this line is optional, but I find it useful when overriding mocking functionality\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n PoolJobService,\n {\n provide: ElasticSearchService,\n useValue: {\n getElasticSearchData: jest.fn()\n }\n }\n ],\n }).compile()\n\n poolJobService = module.get<PoolJobService>(PoolJobService)\n elasticService = module.get<ElasticSearchService>(ElasticSearchService)\n })\n\n it('should be defined', () => {\n expect(poolJobService).toBeDefined()\n })\n it('should give the expected return', async () => {\n elasticService.getElasticSearchData = jest.fn().mockReturnValue({data: 'your object here'})\n const poolJobs = await poolJobService.getPoolJobs()\n expect(poolJobs).toEqual({data: 'your object here'})\n })\n```\n\n```js\nexport class PoolJobService {\n\n constructor(private readonly elasticSearchService: ElasticSearchService) {}\n\n getPoolJobs(data: any): string {\n const returnData = this.elasticSearchService.getElasticSearchData(data);\n return returnData.toUpperCase();\n }\n}\n```\n\n```text\nproviders\n```\n\n```text\nComponents\n```\n\n```text\nAngular\n```\n\n```text\ncontrollers\n```\n\n```text\nElasticSearchServices\n```\n\n```text\njest.mock\n```\n\n```text\nPoolJobService\n```\n\n```text\nTest.createTestingModule\n```\n\n```text\njest.spy\n```\n\n```text\nmock\n```\n\n```text\nElasticSearchService\n```\n\n```text\ngetPoolJobs\n```\n\n```text\nPoolJobService\n```\n\n```text\nElasticSearchService\n```\n\n```text\ngetPoolJobs\n```\n\n```text\nElasticSearchService\n```\n\n```text\ngetElasticSearchData\n```\n\n```text\ngetPoolJobs\n```\n\n```text\ngetElasticSearchData\n```\n\n```text\ngetPoolJobs\n```\n\n```text\ngetElasticSearchData\n```\n\n```text\nintegration\n```\n\n```text\ne2e\n```\n\n========================================\n\nComments:\n- Awesome! This seems like the right solution. I need clarification though.. My ElasticSearchService also has an injected service in its constructor BUT we don't care about it because this solution has completely mocked the ElasticSearchService. Is this correct? Also i came up with a solution like this ``` const module: TestingModule = await Test.createTestingModule({ providers: [PoolJobService, ElasticSearchService, APIService], }).compile() ``` before reading this solution. I theory was that the createTestingModule was doing all the mocking for us. is this wrong?\n- Correct, we don't care about `ElasticSearchService`'s dependencies because the Service itself is mocked. If you instead go with the proposed `providers: [PoolJobService, ElasticSearchService, APIService]` you will need to provide all dependencies of `ElasticSearchService` and `APIService` as Nest otherwise will just instantiate the default class (i.e. what is running when you run your server) and will need access to all the dependencies to correctly instantiate these classes. The `createTestingModule` does not mock anything for you, but allows you to use mocks in place of full classes.\n- I see! That makes sense. I have another question outside the scope of this question but regarding the test `'should give the expected return'`. Both yours and mine are trying to accomplish the same test but I cant help but feel this is not a helpful test. It seems like to me we are mocking a function and then expecting that mocked function to return the value that WE set it to. Again this is a seperate question, and lack of testing knowledge on my part, but could you explain why this is a useful/useless test?\n- Sure, I'll edit my answer so it goes more in depth as to why I mock the way I showed.\n- Thank you so much for all the details. You've been super helpful!! @Jay McDoniel","metadata":{"transformedAt":"2026-08-18T18:32:36.030Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":32,"totalLines":292,"estimatedTokens":1894}}136{"id":"stack-67066619","source":"stackoverflow","questionId":67066619,"title":"Python requests post a query to graphql with variables","tags":["python","web-scraping","python-requests","graphql"],"text":"Title: Python requests post a query to graphql with variables\nTags: python, web-scraping, python-requests, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get a list of offers for an item sold on opensea.io\n\n```\ndef getHighestOffer(self):\n query = \"\"\"query OrdersQuery(\\n $cursor: String\\n $count: Int = 10\\n $excludeMaker: IdentityInputType\\n $isExpired: Boolean\\n $isFilled: Boolean\\n $isValid: Boolean\\n $maker: IdentityInputType\\n $makerArchetype: ArchetypeInputType\\n $makerAssetIsPayment: Boolean\\n $takerArchetype: ArchetypeInputType\\n $takerAssetCategories: [CollectionSlug!]\\n $takerAssetCollections: [CollectionSlug!]\\n $takerAssetIsOwnedBy: IdentityInputType\\n $takerAssetIsPayment: Boolean\\n $sortAscending: Boolean\\n $sortBy: OrderSortOption\\n $makerAssetBundle: BundleSlug\\n $takerAssetBundle: BundleSlug\\n) {\\n ...Orders_data_2g7x2d\\n}\\n\\nfragment AccountLink_data on AccountType {\\n address\\n chain {\\n identifier\\n id\\n }\\n user {\\n publicUsername\\n id\\n }\\n ...ProfileImage_data\\n ...wallet_accountKey\\n}\\n\\nfragment AskPrice_data on OrderV2Type {\\n dutchAuctionFinalPrice\\n openedAt\\n priceFnEndedAt\\n makerAssetBundle {\\n assetQuantities(first: 30) {\\n edges {\\n node {\\n ...quantity_data\\n id\\n }\\n }\\n }\\n id\\n }\\n takerAssetBundle {\\n assetQuantities(first: 1) {\\n edges {\\n node {\\n ...AssetQuantity_data\\n id\\n }\\n }\\n }\\n id\\n }\\n}\\n\\nfragment AssetCell_assetBundle on AssetBundleType {\\n assetQuantities(first: 2) {\\n edges {\\n node {\\n asset {\\n collection {\\n name\\n id\\n }\\n name\\n ...AssetMedia_asset\\n ...asset_url\\n id\\n }\\n relayId\\n id\\n }\\n }\\n }\\n name\\n slug\\n}\\n\\nfragment AssetMedia_asset on AssetType {\\n animationUrl\\n backgroundColor\\n collection {\\n description\\n displayData {\\n cardDisplayStyle\\n }\\n imageUrl\\n hidden\\n name\\n slug\\n id\\n }\\n description\\n name\\n tokenId\\n imageUrl\\n}\\n\\nfragment AssetQuantity_data on AssetQuantityType {\\n asset {\\n ...Price_data\\n id\\n }\\n quantity\\n}\\n\\nfragment Orders_data_2g7x2d on Query {\\n orders(after: $cursor, excludeMaker: $excludeMaker, first: $count, isExpired: $isExpired, isFilled: $isFilled, isValid: $isValid, maker: $maker, makerArchetype: $makerArchetype, makerAssetIsPayment: $makerAssetIsPayment, takerArchetype: $takerArchetype, takerAssetCategories: $takerAssetCategories, takerAssetCollections: $takerAssetCollections, takerAssetIsOwnedBy: $takerAssetIsOwnedBy, takerAssetIsPayment: $takerAssetIsPayment, sortAscending: $sortAscending, sortBy: $sortBy, makerAssetBundle: $makerAssetBundle, takerAssetBundle: $takerAssetBundle) {\\n edges {\\n node {\\n closedAt\\n isFulfillable\\n isValid\\n oldOrder\\n openedAt\\n orderType\\n maker {\\n address\\n ...AccountLink_data\\n ...wallet_accountKey\\n id\\n }\\n makerAsset: makerAssetBundle {\\n assetQuantities(first: 1) {\\n edges {\\n node {\\n asset {\\n assetContract {\\n account {\\n address\\n chain {\\n identifier\\n id\\n }\\n id\\n }\\n id\\n }\\n id\\n }\\n id\\n }\\n }\\n }\\n id\\n }\\n makerAssetBundle {\\n assetQuantities(first: 30) {\\n edges {\\n node {\\n ...AssetQuantity_data\\n ...quantity_data\\n id\\n }\\n }\\n }\\n id\\n }\\n relayId\\n side\\n taker {\\n ...AccountLink_data\\n ...wallet_accountKey\\n id\\n address\\n }\\n takerAssetBundle {\\n assetQuantities(first: 1) {\\n edges {\\n node {\\n ...AssetQuantity_data\\n ...quantity_data\\n asset {\\n ownedQuantity(identity: {})\\n decimals\\n symbol\\n relayId\\n assetContract {\\n account {\\n address\\n id\\n }\\n id\\n }\\n id\\n }\\n quantity\\n id\\n }\\n }\\n }\\n id\\n }\\n ...AskPrice_data\\n ...orderLink_data\\n makerAssetBundleDisplay: makerAssetBundle {\\n ...AssetCell_assetBundle\\n id\\n }\\n takerAssetBundleDisplay: takerAssetBundle {\\n ...AssetCell_assetBundle\\n id\\n }\\n id\\n __typename\\n }\\n cursor\\n }\\n pageInfo {\\n endCursor\\n hasNextPage\\n }\\n }\\n}\\n\\nfragment Price_data on AssetType {\\n decimals\\n imageUrl\\n symbol\\n usdSpotPrice\\n assetContract {\\n blockExplorerLink\\n id\\n }\\n}\\n\\nfragment ProfileImage_data on AccountType {\\n imageUrl\\n address\\n chain {\\n identifier\\n id\\n }\\n}\\n\\nfragment asset_url on AssetType {\\n assetContract {\\n account {\\n address\\n chain {\\n identifier\\n id\\n }\\n id\\n }\\n id\\n }\\n tokenId\\n}\\n\\nfragment orderLink_data on OrderV2Type {\\n makerAssetBundle {\\n assetQuantities(first: 30) {\\n edges {\\n node {\\n asset {\\n externalLink\\n collection {\\n externalUrl\\n id\\n }\\n id\\n }\\n id\\n }\\n }\\n }\\n id\\n }\\n}\\n\\nfragment quantity_data on AssetQuantityType {\\n asset {\\n decimals\\n id\\n }\\n quantity\\n}\\n\\nfragment wallet_accountKey on AccountType {\\n address\\n chain {\\n identifier\\n id\\n }\\n}\\n\"\"\"\n variables = {\"cursor\":None,\"count\":10,\"excludeMaker\":None,\"isExpired\":False,\"isFilled\":None,\"isValid\":True,\"maker\":None,\"makerArchetype\":None,\"makerAssetIsPayment\":True,\"takerArchetype\":{\"assetContractAddress\":\"0x7c40c393dc0f283f318791d746d894ddd3693572\",\"tokenId\":\"7722\"},\"takerAssetCategories\":None,\"takerAssetCollections\":None,\"takerAssetIsOwnedBy\":None,\"takerAssetIsPayment\":None,\"sortAscending\":None,\"sortBy\":\"MAKER_ASSETS_USD_PRICE\",\"makerAssetBundle\":None,\"takerAssetBundle\":None}\n response = requests.post('https://api.opensea.io/graphql/', json={'query': query},data=variables)\n print(response.text)\n```\n\n(In variables the \"assetContractAddress\" and \"tokenId\" are unique to the item.\n\nHowever when I run this I get:\n\n{\"errors\":[{\"message\":\"Must provide query string.\"}]}\n\nAnd if I don't use `data=variables` in `requests.post` I get:\n\n{\"errors\":[{\"message\":\"[400] One of taker_asset_categories, taker_asset_collections, maker, taker, maker, include_maker_assets, include_taker_assets, maker_assets, taker_assets, maker_asset_is_owned_by, taker_asset_is_owned_by, exclude_maker, maker_asset_bundle, taker_asset_bundle needs to be defined.\",\"locations\":[{\"line\":118,\"column\":3}],\"path\":[\"orders\"]}],\"data\":{\"orders\":null}}\n\nHow can I use `requests.post` with the query and variables to get the proper response?\n\nThanks!\n\n========================================\n\nCode:\n```text\ndef getHighestOffer(self):\n query = \"\"\"query OrdersQuery(\\n $cursor: String\\n $count: Int = 10\\n $excludeMaker: IdentityInputType\\n $isExpired: Boolean\\n $isFilled: Boolean\\n $isValid: Boolean\\n $maker: IdentityInputType\\n $makerArchetype: ArchetypeInputType\\n $makerAssetIsPayment: Boolean\\n $takerArchetype: ArchetypeInputType\\n $takerAssetCategories: [CollectionSlug!]\\n $takerAssetCollections: [CollectionSlug!]\\n $takerAssetIsOwnedBy: IdentityInputType\\n $takerAssetIsPayment: Boolean\\n $sortAscending: Boolean\\n $sortBy: OrderSortOption\\n $makerAssetBundle: BundleSlug\\n $takerAssetBundle: BundleSlug\\n) {\\n ...Orders_data_2g7x2d\\n}\\n\\nfragment AccountLink_data on AccountType {\\n address\\n chain {\\n identifier\\n id\\n }\\n user {\\n publicUsername\\n id\\n }\\n ...ProfileImage_data\\n ...wallet_accountKey\\n}\\n\\nfragment AskPrice_data on OrderV2Type {\\n dutchAuctionFinalPrice\\n openedAt\\n priceFnEndedAt\\n makerAssetBundle {\\n assetQuantities(first: 30) {\\n edges {\\n node {\\n ...quantity_data\\n id\\n }\\n }\\n }\\n id\\n }\\n takerAssetBundle {\\n assetQuantities(first: 1) {\\n edges {\\n node {\\n ...AssetQuantity_data\\n id\\n }\\n }\\n }\\n id\\n }\\n}\\n\\nfragment AssetCell_assetBundle on AssetBundleType {\\n assetQuantities(first: 2) {\\n edges {\\n node {\\n asset {\\n collection {\\n name\\n id\\n }\\n name\\n ...AssetMedia_asset\\n ...asset_url\\n id\\n }\\n relayId\\n id\\n }\\n }\\n }\\n name\\n slug\\n}\\n\\nfragment AssetMedia_asset on AssetType {\\n animationUrl\\n backgroundColor\\n collection {\\n description\\n displayData {\\n cardDisplayStyle\\n }\\n imageUrl\\n hidden\\n name\\n slug\\n id\\n }\\n description\\n name\\n tokenId\\n imageUrl\\n}\\n\\nfragment AssetQuantity_data on AssetQuantityType {\\n asset {\\n ...Price_data\\n id\\n }\\n quantity\\n}\\n\\nfragment Orders_data_2g7x2d on Query {\\n orders(after: $cursor, excludeMaker: $excludeMaker, first: $count, isExpired: $isExpired, isFilled: $isFilled, isValid: $isValid, maker: $maker, makerArchetype: $makerArchetype, makerAssetIsPayment: $makerAssetIsPayment, takerArchetype: $takerArchetype, takerAssetCategories: $takerAssetCategories, takerAssetCollections: $takerAssetCollections, takerAssetIsOwnedBy: $takerAssetIsOwnedBy, takerAssetIsPayment: $takerAssetIsPayment, sortAscending: $sortAscending, sortBy: $sortBy, makerAssetBundle: $makerAssetBundle, takerAssetBundle: $takerAssetBundle) {\\n edges {\\n node {\\n closedAt\\n isFulfillable\\n isValid\\n oldOrder\\n openedAt\\n orderType\\n maker {\\n address\\n ...AccountLink_data\\n ...wallet_accountKey\\n id\\n }\\n makerAsset: makerAssetBundle {\\n assetQuantities(first: 1) {\\n edges {\\n node {\\n asset {\\n assetContract {\\n account {\\n address\\n chain {\\n identifier\\n id\\n }\\n id\\n }\\n id\\n }\\n id\\n }\\n id\\n }\\n }\\n }\\n id\\n }\\n makerAssetBundle {\\n assetQuantities(first: 30) {\\n edges {\\n node {\\n ...AssetQuantity_data\\n ...quantity_data\\n id\\n }\\n }\\n }\\n id\\n }\\n relayId\\n side\\n taker {\\n ...AccountLink_data\\n ...wallet_accountKey\\n id\\n address\\n }\\n takerAssetBundle {\\n assetQuantities(first: 1) {\\n edges {\\n node {\\n ...AssetQuantity_data\\n ...quantity_data\\n asset {\\n ownedQuantity(identity: {})\\n decimals\\n symbol\\n relayId\\n assetContract {\\n account {\\n address\\n id\\n }\\n id\\n }\\n id\\n }\\n quantity\\n id\\n }\\n }\\n }\\n id\\n }\\n ...AskPrice_data\\n ...orderLink_data\\n makerAssetBundleDisplay: makerAssetBundle {\\n ...AssetCell_assetBundle\\n id\\n }\\n takerAssetBundleDisplay: takerAssetBundle {\\n ...AssetCell_assetBundle\\n id\\n }\\n id\\n __typename\\n }\\n cursor\\n }\\n pageInfo {\\n endCursor\\n hasNextPage\\n }\\n }\\n}\\n\\nfragment Price_data on AssetType {\\n decimals\\n imageUrl\\n symbol\\n usdSpotPrice\\n assetContract {\\n blockExplorerLink\\n id\\n }\\n}\\n\\nfragment ProfileImage_data on AccountType {\\n imageUrl\\n address\\n chain {\\n identifier\\n id\\n }\\n}\\n\\nfragment asset_url on AssetType {\\n assetContract {\\n account {\\n address\\n chain {\\n identifier\\n id\\n }\\n id\\n }\\n id\\n }\\n tokenId\\n}\\n\\nfragment orderLink_data on OrderV2Type {\\n makerAssetBundle {\\n assetQuantities(first: 30) {\\n edges {\\n node {\\n asset {\\n externalLink\\n collection {\\n externalUrl\\n id\\n }\\n id\\n }\\n id\\n }\\n }\\n }\\n id\\n }\\n}\\n\\nfragment quantity_data on AssetQuantityType {\\n asset {\\n decimals\\n id\\n }\\n quantity\\n}\\n\\nfragment wallet_accountKey on AccountType {\\n address\\n chain {\\n identifier\\n id\\n }\\n}\\n\"\"\"\n variables = {\"cursor\":None,\"count\":10,\"excludeMaker\":None,\"isExpired\":False,\"isFilled\":None,\"isValid\":True,\"maker\":None,\"makerArchetype\":None,\"makerAssetIsPayment\":True,\"takerArchetype\":{\"assetContractAddress\":\"0x7c40c393dc0f283f318791d746d894ddd3693572\",\"tokenId\":\"7722\"},\"takerAssetCategories\":None,\"takerAssetCollections\":None,\"takerAssetIsOwnedBy\":None,\"takerAssetIsPayment\":None,\"sortAscending\":None,\"sortBy\":\"MAKER_ASSETS_USD_PRICE\",\"makerAssetBundle\":None,\"takerAssetBundle\":None}\n response = requests.post('https://api.opensea.io/graphql/', json={'query': query},data=variables)\n print(response.text)\n```\n\n```text\ndata=variables\n```\n\n```text\nrequests.post\n```\n\n```text\nrequests.post\n```\n\n```json\n{\n \"query\": \"your query\",\n \"variables\": {\n \"var1\": \"value1\"\n }\n}\n```\n\n```py\nimport requests\n\nquery = \"\"\"query OrdersQuery(\\n $cursor: String\\n $count: Int = 10\\n $excludeMaker: IdentityInputType\\n $isExpired: Boolean\\n $isFilled: Boolean\\n $isValid: Boolean\\n $maker: IdentityInputType\\n $makerArchetype: ArchetypeInputType\\n $makerAssetIsPayment: Boolean\\n $takerArchetype: ArchetypeInputType\\n $takerAssetCategories: [CollectionSlug!]\\n $takerAssetCollections: [CollectionSlug!]\\n $takerAssetIsOwnedBy: IdentityInputType\\n $takerAssetIsPayment: Boolean\\n $sortAscending: Boolean\\n $sortBy: OrderSortOption\\n $makerAssetBundle: BundleSlug\\n $takerAssetBundle: BundleSlug\\n) {\\n ...Orders_data_2g7x2d\\n}\\n\\nfragment AccountLink_data on AccountType {\\n address\\n chain {\\n identifier\\n id\\n }\\n user {\\n publicUsername\\n id\\n }\\n ...ProfileImage_data\\n ...wallet_accountKey\\n}\\n\\nfragment AskPrice_data on OrderV2Type {\\n dutchAuctionFinalPrice\\n openedAt\\n priceFnEndedAt\\n makerAssetBundle {\\n assetQuantities(first: 30) {\\n edges {\\n node {\\n ...quantity_data\\n id\\n }\\n }\\n }\\n id\\n }\\n takerAssetBundle {\\n assetQuantities(first: 1) {\\n edges {\\n node {\\n ...AssetQuantity_data\\n id\\n }\\n }\\n }\\n id\\n }\\n}\\n\\nfragment AssetCell_assetBundle on AssetBundleType {\\n assetQuantities(first: 2) {\\n edges {\\n node {\\n asset {\\n collection {\\n name\\n id\\n }\\n name\\n ...AssetMedia_asset\\n ...asset_url\\n id\\n }\\n relayId\\n id\\n }\\n }\\n }\\n name\\n slug\\n}\\n\\nfragment AssetMedia_asset on AssetType {\\n animationUrl\\n backgroundColor\\n collection {\\n description\\n displayData {\\n cardDisplayStyle\\n }\\n imageUrl\\n hidden\\n name\\n slug\\n id\\n }\\n description\\n name\\n tokenId\\n imageUrl\\n}\\n\\nfragment AssetQuantity_data on AssetQuantityType {\\n asset {\\n ...Price_data\\n id\\n }\\n quantity\\n}\\n\\nfragment Orders_data_2g7x2d on Query {\\n orders(after: $cursor, excludeMaker: $excludeMaker, first: $count, isExpired: $isExpired, isFilled: $isFilled, isValid: $isValid, maker: $maker, makerArchetype: $makerArchetype, makerAssetIsPayment: $makerAssetIsPayment, takerArchetype: $takerArchetype, takerAssetCategories: $takerAssetCategories, takerAssetCollections: $takerAssetCollections, takerAssetIsOwnedBy: $takerAssetIsOwnedBy, takerAssetIsPayment: $takerAssetIsPayment, sortAscending: $sortAscending, sortBy: $sortBy, makerAssetBundle: $makerAssetBundle, takerAssetBundle: $takerAssetBundle) {\\n edges {\\n node {\\n closedAt\\n isFulfillable\\n isValid\\n oldOrder\\n openedAt\\n orderType\\n maker {\\n address\\n ...AccountLink_data\\n ...wallet_accountKey\\n id\\n }\\n makerAsset: makerAssetBundle {\\n assetQuantities(first: 1) {\\n edges {\\n node {\\n asset {\\n assetContract {\\n account {\\n address\\n chain {\\n identifier\\n id\\n }\\n id\\n }\\n id\\n }\\n id\\n }\\n id\\n }\\n }\\n }\\n id\\n }\\n makerAssetBundle {\\n assetQuantities(first: 30) {\\n edges {\\n node {\\n ...AssetQuantity_data\\n ...quantity_data\\n id\\n }\\n }\\n }\\n id\\n }\\n relayId\\n side\\n taker {\\n ...AccountLink_data\\n ...wallet_accountKey\\n id\\n address\\n }\\n takerAssetBundle {\\n assetQuantities(first: 1) {\\n edges {\\n node {\\n ...AssetQuantity_data\\n ...quantity_data\\n asset {\\n ownedQuantity(identity: {})\\n decimals\\n symbol\\n relayId\\n assetContract {\\n account {\\n address\\n id\\n }\\n id\\n }\\n id\\n }\\n quantity\\n id\\n }\\n }\\n }\\n id\\n }\\n ...AskPrice_data\\n ...orderLink_data\\n makerAssetBundleDisplay: makerAssetBundle {\\n ...AssetCell_assetBundle\\n id\\n }\\n takerAssetBundleDisplay: takerAssetBundle {\\n ...AssetCell_assetBundle\\n id\\n }\\n id\\n __typename\\n }\\n cursor\\n }\\n pageInfo {\\n endCursor\\n hasNextPage\\n }\\n }\\n}\\n\\nfragment Price_data on AssetType {\\n decimals\\n imageUrl\\n symbol\\n usdSpotPrice\\n assetContract {\\n blockExplorerLink\\n id\\n }\\n}\\n\\nfragment ProfileImage_data on AccountType {\\n imageUrl\\n address\\n chain {\\n identifier\\n id\\n }\\n}\\n\\nfragment asset_url on AssetType {\\n assetContract {\\n account {\\n address\\n chain {\\n identifier\\n id\\n }\\n id\\n }\\n id\\n }\\n tokenId\\n}\\n\\nfragment orderLink_data on OrderV2Type {\\n makerAssetBundle {\\n assetQuantities(first: 30) {\\n edges {\\n node {\\n asset {\\n externalLink\\n collection {\\n externalUrl\\n id\\n }\\n id\\n }\\n id\\n }\\n }\\n }\\n id\\n }\\n}\\n\\nfragment quantity_data on AssetQuantityType {\\n asset {\\n decimals\\n id\\n }\\n quantity\\n}\\n\\nfragment wallet_accountKey on AccountType {\\n address\\n chain {\\n identifier\\n id\\n }\\n}\\n\"\"\"\nvariables = {\"cursor\": None, \"count\": 10, \"excludeMaker\": None, \"isExpired\": False, \"isFilled\": None, \"isValid\": True, \"maker\": None, \"makerArchetype\": None, \"makerAssetIsPayment\": True, \"takerArchetype\": {\"assetContractAddress\": \"0x7c40c393dc0f283f318791d746d894ddd3693572\",\n \"tokenId\": \"7722\"}, \"takerAssetCategories\": None, \"takerAssetCollections\": None, \"takerAssetIsOwnedBy\": None, \"takerAssetIsPayment\": None, \"sortAscending\": None, \"sortBy\": \"MAKER_ASSETS_USD_PRICE\", \"makerAssetBundle\": None, \"takerAssetBundle\": None}\nresponse = requests.post('https://api.opensea.io/graphql/',\n json={\"query\": query, \"variables\": variables}\n)\nprint(response.text)\n```\n\n========================================\n\nComments:\n- 1. You should provide `data` or `json`, but not both, to `requests.post()`. 2. Read the documentation for the API you are trying to use to determine the correct data to pass to it. The error message gives you a hint about what is missing.\n- 1. Thanks that's nice to know. 2. The documentation at api.opensea.io/graphql is not helping at all. I've got the query and the values of its variables but I can't see how I can link them with the query.\n- seems not to be working. Looks like Cloudflare has been set in as a protection layer.","metadata":{"transformedAt":"2026-08-18T18:32:36.031Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":79,"estimatedTokens":5048}}137{"id":"stack-55243969","source":"stackoverflow","questionId":55243969,"title":"AWS Appsync $ctx vs $context in resolvers","tags":["amazon-web-services","graphql","aws-appsync","appsync-apollo-client","aws-appsync-ios"],"text":"Title: AWS Appsync $ctx vs $context in resolvers\nTags: amazon-web-services, graphql, aws-appsync, appsync-apollo-client, aws-appsync-ios\nSource: Stack Overflow\n\nQuestion:\nI understand that context is what ever name you define in your Lambda functions but when it comes to Appsync resolvers I'm a bit confused. I've seen both `$ctx` and `$context` being used in AppSync resolvers including in AWS docs. Some of AWS's own code generation tools like AWS Amplify CLI create resolvers that use both in the same code! I can't find anything in the docs explaining this. What's going on here?\n\n========================================\n\nCode:\n```text\n$ctx\n```\n\n```text\n$context\n```\n\n```text\n$ctx\n```\n\n```text\n$context\n```\n\n```text\n$ctx\n```\n\n```text\n$context\n```\n\n```text\n$ctx\n```\n\n```text\n$context\n```\n\n```text\n$context\n```\n\n```text\n$ctx\n```\n\n```text\n$ctx\n```\n\n========================================\n\nComments:\n- I'm in the process of scrubbing our docs and replacing `$context` with `$ctx` for consistency. I'll add a note to the Resolver Mapping page explaining that `$ctx` is an alias. Sorry for the confusion.\n- thank you for the answer. Does the same apply to arguments? I've seen some place use $ctx.args... ?Any other helpful aliases?\n- $ctx.* and $context.* refer to the same thing.\n- Just a minor note, $ctx is not allowed when referencing cache keys. Caching keys need to start with $context.args, $context.arguments, $context.identity, or $context.source, otherwise AppSync fails with 400\n- Why not `$c`? 85% less to type.","metadata":{"transformedAt":"2026-08-18T18:32:36.031Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":62,"estimatedTokens":382}}138{"id":"stack-39732223","source":"stackoverflow","questionId":39732223,"title":"GraphQL pass args to sub resolve","tags":["graphql","graphql-js"],"text":"Title: GraphQL pass args to sub resolve\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have a relationship between User and Post. This is how I query the User Posts.\n\n```\nconst UserType = new GraphQLObjectType({\n name: 'User'\n fields: () => ({\n name: {\n type: GraphQLString\n },\n posts: {\n type: new GraphQLList(PostType),\n resolve(parent, args , { db }) {\n // I want to get here the args.someBooleanArg\n return someLogicToGetUserPosts();\n }\n }\n })\n});\n```\n\nThe main query is:\n\n```\nconst queryType = new GraphQLObjectType({\n name: 'RootQuery',\n fields: {\n users: {\n type: new GraphQLList(UserType),\n args: {\n id: {\n type: GraphQLInt\n },\n someBooleanArg: {\n type: GraphQLInt\n }\n },\n resolve: (root, { id, someBooleanArg }, { db }) => {\n return someLogicToGetUsers();\n }\n }\n }\n});\n```\n\nThe problem is the args in the resolve function of the UserType posts is empty object, how do i pass the args from the main query to sub resolves functions?\n\n========================================\n\nTop Answer:\nYou can use the resolver fouth argument, **`info`**, to receive the desired variable - from Apollo docs:\n\n Every resolver in a GraphQL.js schema accepts four positional arguments:\n\n \n **fieldName(obj, args, context, info)** \n **{ result }** \n\n \n These arguments have\n the following meanings and conventional names:\n\n \n **obj**: The object that contains the result returned from the resolver on\n the parent field, or, in the case of a top-level Query field, the\n rootValue passed from the server configuration. This argument enables\n the nested nature of GraphQL queries. \n\n \n **args**: An object with the\n arguments passed into the field in the query. For example, if the\n field was called with author(name: \"Ada\"), the args object would be: {\n \"name\": \"Ada\" }. \n\n \n **context**: This is an object shared by all resolvers in\n a particular query, and is used to contain per-request state,\n including authentication information, dataloader instances, and\n anything else that should be taken into account when resolving the\n query. If you're using Apollo Server, read about how to set the\n context in the setup documentation. \n\n \n **info**: This argument should only be\n used in advanced cases, but it contains information about the\n execution state of the query, including the field name, path to the\n field from the root, and more. It's only documented in the GraphQL.js\n source code.\n\nThe **`info`** seems to be a very undocumented feature, but I'm using it now with no problems (at least until somebody decide to change it).\n\nHere is the trick:\n\n```\nconst UserType = new GraphQLObjectType({\n name: 'User'\n fields: () => ({\n name: {\n type: GraphQLString\n },\n posts: {\n type: new GraphQLList(PostType),\n resolve(parent, args , { db }, info) {\n // I want to get here the args.someBooleanArg\n\n console.log(\"BINGO!\");\n console.log(info.variableValues.someBooleanArg);\n\n return someLogicToGetUserPosts();\n }\n }\n })\n});\n```\n\n========================================\n\nCode:\n```text\nconst UserType = new GraphQLObjectType({\n name: 'User'\n fields: () => ({\n name: {\n type: GraphQLString\n },\n posts: {\n type: new GraphQLList(PostType),\n resolve(parent, args , { db }) {\n // I want to get here the args.someBooleanArg\n return someLogicToGetUserPosts();\n }\n }\n })\n});\n```\n\n```text\nconst queryType = new GraphQLObjectType({\n name: 'RootQuery',\n fields: {\n users: {\n type: new GraphQLList(UserType),\n args: {\n id: {\n type: GraphQLInt\n },\n someBooleanArg: {\n type: GraphQLInt\n }\n },\n resolve: (root, { id, someBooleanArg }, { db }) => {\n return someLogicToGetUsers();\n }\n }\n }\n});\n```\n\n```js\nconst queryType = new GraphQLObjectType({\n name: 'RootQuery',\n fields: {\n users: {\n type: new GraphQLList(UserType),\n args: {\n id: {\n type: GraphQLInt\n },\n someBooleanArg: {\n type: GraphQLInt\n }\n },\n resolve: (root, { id, someBooleanArg }, { db }) => {\n return Promise.resolve(someLogicToGetUsers()).then(v => {\n return Object.assign({}, v, {\n someBooleanArg\n });\n });\n }\n }\n }\n});\n\nconst UserType = new GraphQLObjectType({\n name: 'User'\n fields: () => ({\n name: {\n type: GraphQLString\n },\n posts: {\n type: new GraphQLList(PostType),\n resolve(parent, args , { db }) {\n console.log(parent.someBooleanArg);\n return someLogicToGetUserPosts();\n }\n }\n })\n});\n```\n\n```text\nconst UserType = new GraphQLObjectType({\n name: 'User'\n fields: () => ({\n name: {\n type: GraphQLString\n },\n posts: {\n type: new GraphQLList(PostType),\n resolve(parent, args , { db }, info) {\n // I want to get here the args.someBooleanArg\n\n console.log(\"BINGO!\");\n console.log(info.variableValues.someBooleanArg);\n\n return someLogicToGetUserPosts();\n }\n }\n })\n});\n```\n\n```text\ninfo\n```\n\n```text\ninfo\n```\n\n========================================\n\nComments:\n- Is there no native way to pass it as \"args\" to the sub query instead of altering the response object?\n- This is not correct, the `args` of the field are not the same as the `variables` of your query. You could have, for example ``` query($variableId: ID) { user(id: $variableId){ posts { // here you get info. variableValues.variableId, not user args.id } } ```\n- this only works for *named* variables, if you use hard coded ones they dont show up","metadata":{"transformedAt":"2026-08-18T18:32:36.031Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":240,"estimatedTokens":1385}}139{"id":"stack-53910519","source":"stackoverflow","questionId":53910519,"title":"Field \\\"createUaction\\\" of type \\\"CreateUaction\\\" must have a sub selection.\"","tags":["django","graphql","graphene-python","graphene-django"],"text":"Title: Field \\\"createUaction\\\" of type \\\"CreateUaction\\\" must have a sub selection.\"\nTags: django, graphql, graphene-python, graphene-django\nSource: Stack Overflow\n\nQuestion:\nThis is the first time I am using graphene, ain't have a good grasp over it.\nSo basically making a blog, where the user can like posts, comments and add posts to his favourite, and each other. \n\nI have made a separate model for all user actions \n\n```\nclass user_actions(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n liked_post = models.ForeignKey(Post, related_name='post_likes', \n on_delete=models.CASCADE)\n liked_comments = models.ForeignKey(Comment, \n related_name='comment_likes', on_delete=models.CASCADE)\n fav = models.ForeignKey(Post, related_name='fav_post', \n on_delete=models.CASCADE)\n target = models.ForeignKey(User, related_name='followers', \n on_delete=models.CASCADE, null=True, blank = True)\n follower = models.ForeignKey(User, related_name='targets', \n on_delete=models.CASCADE, null = True, blank = True)\n\n def __str__(self):\n return self.user.username\n```\n\nSo I have made a mutation for all the actions, I am trying to the DRY Principe and sum them all in one, I might be doing something wrong here, New coder trying my best :D\n\n```\nclass UactionInput(InputObjectType):\n liked_post_id = graphene.Int()\n fav_post_id = graphene.Int()\n comment_id = graphene.Int()\n target_id = graphene.Int()\n follower_id = graphene.Int()\n\n class CreateUaction(graphene.Mutation):\n user = graphene.Field(UactionType)\n\n class Arguments:\n input = UactionInput()\n\n def mutate(self, info, input):\n user = info.context.user\n if not user.is_authenticated:\n return CreateUaction(errors=json.dumps('Please Login '))\n\n if input.liked_post_id:\n\n post = Post.objects.get(id=input.liked_post_id)\n user_action = user_actions.objects.create(\n liked_post = post,\n user = user \n )\n\n return CreateUaction( user = user )\n\n if input.liked_comment_id:\n\n comment = Comment.objects.get(id=input.liked_comment_id)\n user_action = user_actions.objects.create(\n liked_comment = comment,\n user = user \n )\n\n return CreateUaction(user = user )\n\n if input.fav_post_id:\n\n post = Post.objects.get(id=input.fav_post_id)\n user_action = user_actions.objects.create(\n fav = post,\n user = user \n )\n\n return CreateUaction(user = user )\n\n if input.target_id:\n\n user = User.objects.get(id=input.target_id)\n user_action = user_actions.objects.create(\n target = user,\n user = user \n )\n\n return CreateUaction(user = user )\n\n if input.follower_id:\n\n user = User.objects.get(id=input.follower_id)\n user_action = user_actions.objects.create(\n follower= user,\n user = user \n )\n\n return CreateUaction(user = user )\n```\n\nSorry for the indentation in the question, but it's completely fine in my code.\n\nThe createUaction mutation gives me this error \n\n```\n\"message\": \"Field \\\"createUaction\\\" of type \\\"CreateUaction\\\" must have a sub selection.\",\n```\n\nAny help is appreciated. Do let me know if I need to post the resolvers too.\n\n========================================\n\nCode:\n```text\nclass user_actions(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n liked_post = models.ForeignKey(Post, related_name='post_likes', \n on_delete=models.CASCADE)\n liked_comments = models.ForeignKey(Comment, \n related_name='comment_likes', on_delete=models.CASCADE)\n fav = models.ForeignKey(Post, related_name='fav_post', \n on_delete=models.CASCADE)\n target = models.ForeignKey(User, related_name='followers', \n on_delete=models.CASCADE, null=True, blank = True)\n follower = models.ForeignKey(User, related_name='targets', \n on_delete=models.CASCADE, null = True, blank = True)\n\n def __str__(self):\n return self.user.username\n```\n\n```text\nclass UactionInput(InputObjectType):\n liked_post_id = graphene.Int()\n fav_post_id = graphene.Int()\n comment_id = graphene.Int()\n target_id = graphene.Int()\n follower_id = graphene.Int()\n\n class CreateUaction(graphene.Mutation):\n user = graphene.Field(UactionType)\n\n class Arguments:\n input = UactionInput()\n\n\n def mutate(self, info, input):\n user = info.context.user\n if not user.is_authenticated:\n return CreateUaction(errors=json.dumps('Please Login '))\n\n\n if input.liked_post_id:\n\n post = Post.objects.get(id=input.liked_post_id)\n user_action = user_actions.objects.create(\n liked_post = post,\n user = user \n )\n\n return CreateUaction( user = user )\n\n if input.liked_comment_id:\n\n comment = Comment.objects.get(id=input.liked_comment_id)\n user_action = user_actions.objects.create(\n liked_comment = comment,\n user = user \n )\n\n return CreateUaction(user = user )\n\n if input.fav_post_id:\n\n post = Post.objects.get(id=input.fav_post_id)\n user_action = user_actions.objects.create(\n fav = post,\n user = user \n )\n\n return CreateUaction(user = user )\n\n if input.target_id:\n\n user = User.objects.get(id=input.target_id)\n user_action = user_actions.objects.create(\n target = user,\n user = user \n )\n\n return CreateUaction(user = user )\n\n if input.follower_id:\n\n user = User.objects.get(id=input.follower_id)\n user_action = user_actions.objects.create(\n follower= user,\n user = user \n )\n\n return CreateUaction(user = user )\n```\n\n```text\n\"message\": \"Field \\\"createUaction\\\" of type \\\"CreateUaction\\\" must have a sub selection.\",\n```\n\n```text\nmutation SomeOperationName {\n createUaction {\n user {\n # one or more user fields\n }\n }\n}\n```\n\n```text\nCreateUaction\n```\n\n========================================\n\nComments:\n- adding a doc link to this answer if you don't mind docs.graphene-python.org/projects/django/en/latest/…","metadata":{"transformedAt":"2026-08-18T18:32:36.031Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":225,"estimatedTokens":1493}}140{"id":"stack-41407620","source":"stackoverflow","questionId":41407620,"title":"Why is DataFetcher not called in this GraphQL setup?","tags":["java","graphql","graphql-java"],"text":"Title: Why is DataFetcher not called in this GraphQL setup?\nTags: java, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI want to write a piece of code, which will handle GraphQL queries like these:\n\n```\nquery {\n group(id: \"com.graphql-java\")\n name(name: \"graphql-java\")\n version(id: \"2.3.0\")\n }\n```\n\nI've created a data fetcher and put a breakpoint inside the `get` method:\n\n```\nimport graphql.schema.DataFetcher;\n import graphql.schema.DataFetchingEnvironment;\n\n public class TestDataFetcher implements DataFetcher {\n public Object get(final DataFetchingEnvironment dataFetchingEnvironment) {\n return null;\n }\n }\n```\n\nThen I wrote the following code:\n\n```\npublic class Example02 {\n public static void main(final String[] args) throws IOException {\n final Example02 app = new Example02();\n app.run();\n }\n void run() throws IOException {\n final TestDataFetcher testDataFetcher = new TestDataFetcher();\n\n final List fields = Lists.newArrayList(\n createGroupField(testDataFetcher),\n createNameField(),\n createVersionField());\n\n final GraphQLObjectType queryType = newObject()\n .name(\"query\")\n .fields(fields)\n .build();\n final GraphQLSchema schema = GraphQLSchema.newSchema()\n .query(queryType)\n .build();\n final String query = FileUtils.readFileToString(\n new File(\"src/main/resources/query1.txt\"),\n \"UTF-8\"\n );\n final Map result = (Map) new GraphQL(schema).execute(query).getData();\n System.out.println(result);\n }\n\n private GraphQLFieldDefinition createVersionField() {\n return newFieldDefinition().type(GraphQLString).name(\"version\").build();\n }\n\n private GraphQLFieldDefinition createNameField() {\n return newFieldDefinition().type(GraphQLString).name(\"name\").build();\n }\n\n private GraphQLFieldDefinition createGroupField(TestDataFetcher testDataFetcher) {\n final GraphQLArgument idArg = newArgument().name(\"id\").type(GraphQLString).build();\n return newFieldDefinition()\n .type(GraphQLString)\n .name(\"group\")\n .dataFetcher(testDataFetcher)\n .argument(idArg)\n .build();\n }\n }\n```\n\nWhen I run the `main` method in debug mode, the breakpoint is not activated.\n\nWhy? How can I fix it?\n\n========================================\n\nTop Answer:\nYour problem is your query. If you debug the variable `query` it is `query {\\n group(id: \"com.graphql-java\")\\n name(name: \"graphql-java\")\\n version(id: \"2.3.0\")\\n}`. \nThe problem is the '\\n' in the query.\n\nIf you change your query to `query{group(id: \"com.graphql-java\")}` your breakpoint will be executed.\n\nTo execute your query I had to update the GraphQlFiledDefinitions first to receive the argument.\n\n```\nprivate GraphQLFieldDefinition createVersionField(TestDataFetcher testDataFetcher) {\n final GraphQLArgument idArg = newArgument().name(\"id\").type(GraphQLString).build();\n return newFieldDefinition().type(GraphQLString).name(\"version\").staticValue(\"id value\").argument(idArg).build();\n}\n\nprivate GraphQLFieldDefinition createNameField(TestDataFetcher testDataFetcher) {\n final GraphQLArgument nameArg = newArgument().name(\"name\").type(GraphQLString).build();\n return newFieldDefinition().type(GraphQLString).name(\"name\").staticValue(\"name Value\").argument(nameArg).build();\n}\n\nprivate GraphQLFieldDefinition createGroupField(TestDataFetcher testDataFetcher) {\n final GraphQLArgument idArg = newArgument().name(\"id\").type(GraphQLString).build();\n return newFieldDefinition()\n .type(GraphQLString)\n .name(\"group\")\n .dataFetcher(testDataFetcher)\n .argument(idArg)\n .build();\n}\n```\n\nAnd then I can use the query without line breaks `query {group(id: \"com.graphql-java\"),name(name:\"graphql-java\"),version(id: \"2.3.0\")}`\n\n========================================\n\nCode:\n```text\nquery {\n group(id: \"com.graphql-java\")\n name(name: \"graphql-java\")\n version(id: \"2.3.0\")\n }\n```\n\n```text\nimport graphql.schema.DataFetcher;\n import graphql.schema.DataFetchingEnvironment;\n\n public class TestDataFetcher implements DataFetcher {\n public Object get(final DataFetchingEnvironment dataFetchingEnvironment) {\n return null;\n }\n }\n```\n\n```text\npublic class Example02 {\n public static void main(final String[] args) throws IOException {\n final Example02 app = new Example02();\n app.run();\n }\n void run() throws IOException {\n final TestDataFetcher testDataFetcher = new TestDataFetcher();\n\n final List<GraphQLFieldDefinition> fields = Lists.newArrayList(\n createGroupField(testDataFetcher),\n createNameField(),\n createVersionField());\n\n final GraphQLObjectType queryType = newObject()\n .name(\"query\")\n .fields(fields)\n .build();\n final GraphQLSchema schema = GraphQLSchema.newSchema()\n .query(queryType)\n .build();\n final String query = FileUtils.readFileToString(\n new File(\"src/main/resources/query1.txt\"),\n \"UTF-8\"\n );\n final Map<String, Object> result = (Map<String, Object>) new GraphQL(schema).execute(query).getData();\n System.out.println(result);\n }\n\n private GraphQLFieldDefinition createVersionField() {\n return newFieldDefinition().type(GraphQLString).name(\"version\").build();\n }\n\n private GraphQLFieldDefinition createNameField() {\n return newFieldDefinition().type(GraphQLString).name(\"name\").build();\n }\n\n private GraphQLFieldDefinition createGroupField(TestDataFetcher testDataFetcher) {\n final GraphQLArgument idArg = newArgument().name(\"id\").type(GraphQLString).build();\n return newFieldDefinition()\n .type(GraphQLString)\n .name(\"group\")\n .dataFetcher(testDataFetcher)\n .argument(idArg)\n .build();\n }\n }\n```\n\n```text\nget\n```\n\n```text\nmain\n```\n\n```text\nimport graphql.GraphQL;\nimport graphql.schema.*;\nimport org.apache.commons.io.FileUtils;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport static graphql.Scalars.GraphQLString;\nimport static graphql.schema.GraphQLArgument.newArgument;\nimport static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;\nimport static graphql.schema.GraphQLObjectType.newObject;\n\npublic class Example2 {\n\n\n public class TestDataFetcher implements DataFetcher {\n public Object get(DataFetchingEnvironment environment) {\n String id = (String)environment.getArgument(\"id\");\n return id;\n }\n }\n\n public static void main(final String[] args) {\n Example2 app = new Example2();\n app.run();\n }\n void run() {\n TestDataFetcher testDataFetcher = new TestDataFetcher(); \n\n List<GraphQLFieldDefinition> fields = new ArrayList<GraphQLFieldDefinition>();\n\n fields.add(createGroupField(testDataFetcher));\n fields.add(createNameField());\n fields.add(createVersionField());\n\n GraphQLObjectType queryType = newObject()\n .name(\"query\")\n .fields(fields)\n .build();\n\n GraphQLSchema schema = GraphQLSchema.newSchema()\n .query(queryType)\n .build();\n String query = null;\n try {\n query = FileUtils.readFileToString(\n new File(\"src/main/resources/query1.txt\"),\n \"UTF-8\"\n );\n }catch(IOException ioe){\n ioe.printStackTrace();\n }\n\n if(query!=null) {\n Map<String, Object> result = (Map<String, Object>) new GraphQL(schema).execute(query).getData();\n System.out.println(result);\n }\n }\n\n private GraphQLFieldDefinition createVersionField() {\n GraphQLArgument arg = newArgument().name(\"id\").type(GraphQLString).build();\n return newFieldDefinition().type(GraphQLString).name(\"version\").argument(arg).build();\n }\n\n private GraphQLFieldDefinition createNameField() {\n GraphQLArgument arg = newArgument().name(\"name\").type(GraphQLString).build();\n return newFieldDefinition().type(GraphQLString).name(\"name\").argument(arg).build();\n }\n\n private GraphQLFieldDefinition createGroupField(TestDataFetcher testDataFetcher) {\n final GraphQLArgument idArg = newArgument().name(\"id\").type(GraphQLString).build();\n return newFieldDefinition()\n .type(GraphQLString)\n .name(\"group\")\n .dataFetcher(testDataFetcher)\n .argument(idArg)\n .build();\n }\n}\n```\n\n```text\nnew GraphQL(schema).execute(query)\n```\n\n```text\nerrors\n```\n\n```text\nprivate GraphQLFieldDefinition createVersionField(TestDataFetcher testDataFetcher) {\n final GraphQLArgument idArg = newArgument().name(\"id\").type(GraphQLString).build();\n return newFieldDefinition().type(GraphQLString).name(\"version\").staticValue(\"id value\").argument(idArg).build();\n}\n\nprivate GraphQLFieldDefinition createNameField(TestDataFetcher testDataFetcher) {\n final GraphQLArgument nameArg = newArgument().name(\"name\").type(GraphQLString).build();\n return newFieldDefinition().type(GraphQLString).name(\"name\").staticValue(\"name Value\").argument(nameArg).build();\n}\n\nprivate GraphQLFieldDefinition createGroupField(TestDataFetcher testDataFetcher) {\n final GraphQLArgument idArg = newArgument().name(\"id\").type(GraphQLString).build();\n return newFieldDefinition()\n .type(GraphQLString)\n .name(\"group\")\n .dataFetcher(testDataFetcher)\n .argument(idArg)\n .build();\n}\n```\n\n```text\nquery\n```\n\n```text\nquery {\\n group(id: \"com.graphql-java\")\\n name(name: \"graphql-java\")\\n version(id: \"2.3.0\")\\n}\n```\n\n```text\nquery{group(id: \"com.graphql-java\")}\n```\n\n```text\nquery {group(id: \"com.graphql-java\"),name(name:\"graphql-java\"),version(id: \"2.3.0\")}\n```\n\n========================================\n\nComments:\n- \\n is simply whitespace. It's a new line.","metadata":{"transformedAt":"2026-08-18T18:32:36.031Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":331,"estimatedTokens":2511}}141{"id":"stack-33550843","source":"stackoverflow","questionId":33550843,"title":"Authentication and Access Control with Relay","tags":["javascript","graphql","relayjs","graphql-js"],"text":"Title: Authentication and Access Control with Relay\nTags: javascript, graphql, relayjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nThe official line from Facebook is that Relay is \"intentionally agnostic about authentication mechanisms.\" In all the examples in the Relay repository, authentication and access control are a separate concern. In practice, I have not found a simple way to implement this separation.\n\nThe examples provided in the Relay repository all have root schemas with a `viewer` field that assumes there is one user. And that user has access to everything.\n\nHowever, in reality, an application has has many users and each user has different degrees of access to each node.\n\nSuppose I have this schema in JavaScript:\n\n```\nexport const Schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n user: {\n type: new GraphQLObjectType({\n name: 'User',\n args: {\n // The `id` of the user being queried for\n id: { type: new GraphQLNonNull(GraphQLID) },\n // Identity the user who is querying\n session: { type: new GraphQLInputObjectType({ ... }) },\n },\n resolve: (_, { id, session }) => {\n // Given `session, get user with `id`\n return data.getUser({ id, session });\n }\n fields: () => ({\n name: {\n type: GraphQLString,\n resolve: user => {\n // Does `session` have access to this user's\n // name?\n user.name\n }\n }\n })\n })\n }\n })\n })\n});\n```\n\nSome users are entirely private from the perspective of the querying user. Other users might only expose certain fields to the querying user. So to get a user, the client must not only provide the user ID they are querying for, but they must also identify themselves so that access control can occur.\n\nThis seems to quickly get complicated as the need to control access trickles down the graph. \n\nFurthermore, I need to control access for every root query, like `nodeField`. I need to make sure that every node implementing `nodeInterface`.\n\nAll of this seems like a lot of repetitive work. Are there any known patterns for simplifying this? Am I thinking about this incorrectly?\n\n========================================\n\nTop Answer:\nDifferent applications have very different requirements for the form of access control, so baking something into the basic Relay framework or GraphQL reference implementation probably doesn't make sense.\n\nAn approach that I have seen pretty successful is to bake the privacy/access control into the data model/data loader framework. Every time you load an object, you wouldn't just load it by id, but also provide the context of the viewer. If the viewer cannot see the object, it would fail to load *as if it doesn't exist* to prevent even leaking the existence of the object. The object also retains the viewer context and certain fields might have restricted access that are checked before being returned from the object. Baking this in the lower level data loading mechanism helps to ensure that bugs in higher level product / GraphQL code doesn't leak private data.\n\nIn a concrete example, I might not be allowed to see some User, because he has blocked me. You might be allowed to see him in general, but no his email, since you're not friends with him.\n\nIn code something like this:\n\n```\nvar viewer = new Viewer(getLoggedInUser());\nUser.load(id, viewer).then(\n (user) => console.log(\"User name:\", user.name),\n (error) => console.log(\"User does not exist or you don't have access.\")\n)\n```\n\nTrying to implement the visibility on GraphQL level has lots of potential to leak information. Think of the many way to access a user in GraphQL implementation for Facebook:\n\n```\nnode($userID) { name }\nnode($postID) { author { name } }\nnode($postID) { likers { name } }\nnode($otherUserID) { friends { name } }\n```\n\nAll of these queries could load a user's name and if the user has blocked you, none of them should return the user or it's name. Having the access control on all these fields and not forgetting the check anywhere is a recipe for missing the check *somewhere*.\n\n========================================\n\nCode:\n```js\nexport const Schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n user: {\n type: new GraphQLObjectType({\n name: 'User',\n args: {\n // The `id` of the user being queried for\n id: { type: new GraphQLNonNull(GraphQLID) },\n // Identity the user who is querying\n session: { type: new GraphQLInputObjectType({ ... }) },\n },\n resolve: (_, { id, session }) => {\n // Given `session, get user with `id`\n return data.getUser({ id, session });\n }\n fields: () => ({\n name: {\n type: GraphQLString,\n resolve: user => {\n // Does `session` have access to this user's\n // name?\n user.name\n }\n }\n })\n })\n }\n })\n })\n});\n```\n\n```text\nviewer\n```\n\n```text\nnodeField\n```\n\n```text\nnodeInterface\n```\n\n```text\nfunction getSession(req, res, next) {\n loadSession(req).then(session => {\n req.session = session;\n next();\n }).catch(\n res.sendStatus(400);\n );\n}\n\napp.use('/graphql', getSession, graphqlHTTP(({ session }) => ({\n schema: schema,\n rootValue: { session }\n})));\n```\n\n```text\nnew GraphQLObjectType({\n name: 'MyType',\n fields: {\n myField: {\n type: GraphQLString,\n resolve(parentValue, _, { rootValue: { session } }) {\n // use `session` here\n }\n }\n }\n});\n```\n\n```text\nfunction createLoaders(authToken) {\n return {\n users: new DataLoader(ids => genUsers(authToken, ids)),\n cdnUrls: new DataLoader(rawUrls => genCdnUrls(authToken, rawUrls)),\n stories: new DataLoader(keys => genStories(authToken, keys)),\n };\n}\n```\n\n```text\nrootValue\n```\n\n```text\nvar viewer = new Viewer(getLoggedInUser());\nUser.load(id, viewer).then(\n (user) => console.log(\"User name:\", user.name),\n (error) => console.log(\"User does not exist or you don't have access.\")\n)\n```\n\n```text\nnode($userID) { name }\nnode($postID) { author { name } }\nnode($postID) { likers { name } }\nnode($otherUserID) { friends { name } }\n```\n\n========================================\n\nComments:\n- I think it would be really cool if there was some middleware in Relay that sat above the execution engine and rewrote queries AST based on session information.\n- Did you ever get a good example/answer? I am looking for information on token authentication (no session) with relay but it is hard to find anything\n- @GreenRails not here but I figured out how to do it. It's pretty nice! Basically the key for me was figuring out that you can put things into the GraphQL \"rootValue\", which is available at all levels of resolution. If you're using the express middleware, it's done like this: gist.github.com/dminkovsky/…. Same can be done for any implementation. Then, per the answer below, you can also take a 'viewer-oriented' approach to loading data to assist in ACL. github.com/facebook/dataloader is a good helper tool.\n- @GreenRails just added an answer\n- If anyone has problems with this topic: I made an example repo for Relay/GraphQL/express authentication based on dimadima's answer. It saves session data (userId and role) in a cookie using express middleware and a GraphQL Mutation\n- There should be a github repo demonstrating this.\n- That's not a concrete example. You've kinda answered access control (which is just adding some logic) but didn't touch authentication\n- How do you find this approach compares to rest?\n- @GreenRails I'm not very experienced. Maybe someone else can answer that?","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":209,"estimatedTokens":2000}}142{"id":"stack-52247877","source":"stackoverflow","questionId":52247877,"title":"Apollo-client returns \"400 (Bad Request) Error\" on sending mutation to server","tags":["django","vue.js","graphql","apollo","graphene-python"],"text":"Title: Apollo-client returns \"400 (Bad Request) Error\" on sending mutation to server\nTags: django, vue.js, graphql, apollo, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI am currently using the vue-apollo package for Apollo client with VueJs stack with django and graphene-python for my GraphQl API.\n\nI have a simple setup with vue-apollo below:\n\n```\nimport Vue from 'vue'\nimport { ApolloClient } from 'apollo-client'\nimport { HttpLink } from 'apollo-link-http'\nimport { InMemoryCache } from 'apollo-cache-inmemory'\nimport VueApollo from 'vue-apollo'\nimport Cookies from 'js-cookie'\n\nconst httpLink = new HttpLink({\n credentials: 'same-origin',\n uri: 'http://localhost:8000/api/',\n})\n\n// Create the apollo client\nconst apolloClient = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n connectToDevTools: true,\n})\n\nexport const apolloProvider = new VueApollo({\n defaultClient: apolloClient,\n})\n\n// Install the vue plugin\nVue.use(VueApollo)\n```\n\nI also have CORS setup on my Django `settings.py` with the django-cors-headers package. All queries and mutations resolve fine when I use graphiQL or the Insomnia API client for chrome, but trying the mutation below from my vue app:\n\n```\n'''\n\nimport gql from \"graphql-tag\";\nimport CREATE_USER from \"@/graphql/NewUser.gql\";\n\nexport default {\n data() {\n return {\n test: \"\"\n };\n },\n methods: {\n authenticateUser() {\n this.$apollo.mutate({\n mutation: CREATE_USER,\n variables: {\n email: \"test@example.com\",\n password: \"pa$$word\",\n username: \"testuser\"\n }\n }).then(data => {\n console.log(result)\n })\n }\n }\n};\n```\n\nNewUser.gql\n\n```\nmutation createUser($email: String!, $password: String!, $username: String!) {\n createUser (username: $name, password: $password, email: $email)\n user {\n id\n username\n email\n password\n }\n}\n```\n\nreturns with the error response below: \n\n```\nPOST http://localhost:8000/api/ 400 (Bad Request)\n\nApolloError.js?d4ec:37 Uncaught (in promise) Error: Network error: Response not successful: Received status code 400\n```\n\nRegular queries in my vue app, however, work fine resolving the right response, except mutations, so this has me really baffled\n\n========================================\n\nTop Answer:\nIn addition to graphiQL, I would like to add that apollo-link-error package would also had been of great help. \nBy importing its error handler { onError }, you can obtain great detail through the console about errors produced at network and application(graphql) level :\n\n```\nimport { onError } from 'apollo-link-error';\nimport { ApolloLink } from 'apollo-link';\n\nconst errorLink = onError(({ graphQLErrors, networkError }) => {\n if (graphQLErrors) {\n console.log('graphQLErrors', graphQLErrors);\n }\n if (networkError) {\n console.log('networkError', networkError);\n }\n});\n\nconst httpLink = ...\n\nconst link = ApolloLink.from([errorLink, httpLink]);\n\nconst client = new ApolloClient({\n ...,\n link,\n ...\n});\n```\n\nBy adding this configuration where you instantiate your Apollo Client, you would have obtained an error similar to this one:\n\nGraphQLError{message: \"Syntax Error: Expected {, found Name \"createUser\"\"}\n\nFurther information can be found in Apollo Doc - Error handling: https://www.apollographql.com/docs/react/features/error-handling.\nHope it helps in the future.\n\n========================================\n\nCode:\n```js\nimport Vue from 'vue'\nimport { ApolloClient } from 'apollo-client'\nimport { HttpLink } from 'apollo-link-http'\nimport { InMemoryCache } from 'apollo-cache-inmemory'\nimport VueApollo from 'vue-apollo'\nimport Cookies from 'js-cookie'\n\n\nconst httpLink = new HttpLink({\n credentials: 'same-origin',\n uri: 'http://localhost:8000/api/',\n})\n\n// Create the apollo client\nconst apolloClient = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n connectToDevTools: true,\n})\n\nexport const apolloProvider = new VueApollo({\n defaultClient: apolloClient,\n})\n\n// Install the vue plugin\nVue.use(VueApollo)\n```\n\n```js\n'''\n\nimport gql from \"graphql-tag\";\nimport CREATE_USER from \"@/graphql/NewUser.gql\";\n\nexport default {\n data() {\n return {\n test: \"\"\n };\n },\n methods: {\n authenticateUser() {\n this.$apollo.mutate({\n mutation: CREATE_USER,\n variables: {\n email: \"test@example.com\",\n password: \"pa$$word\",\n username: \"testuser\"\n }\n }).then(data => {\n console.log(result)\n })\n }\n }\n};\n```\n\n```text\nmutation createUser($email: String!, $password: String!, $username: String!) {\n createUser (username: $name, password: $password, email: $email)\n user {\n id\n username\n email\n password\n }\n}\n```\n\n```text\nPOST http://localhost:8000/api/ 400 (Bad Request)\n\nApolloError.js?d4ec:37 Uncaught (in promise) Error: Network error: Response not successful: Received status code 400\n```\n\n```text\nsettings.py\n```\n\n```text\n$username\n```\n\n```text\n$name\n```\n\n```text\nmutation createUser($email: String!, $password: String!, $username: String!) {\n createUser (username: $name, password: $password, email: $email) {\n user {\n id\n username\n email\n password\n }\n }\n}\n```\n\n```text\nimport { onError } from 'apollo-link-error';\nimport { ApolloLink } from 'apollo-link';\n\nconst errorLink = onError(({ graphQLErrors, networkError }) => {\n if (graphQLErrors) {\n console.log('graphQLErrors', graphQLErrors);\n }\n if (networkError) {\n console.log('networkError', networkError);\n }\n});\n\nconst httpLink = ...\n\nconst link = ApolloLink.from([errorLink, httpLink]);\n\nconst client = new ApolloClient({\n ...,\n link,\n ...\n});\n```\n\n```text\nconfig/cors.php\n```\n\n```text\n'paths' => ['api/*', 'sanctum/csrf-cookie'],\n```\n\n```text\n'paths' => ['api/*', 'graphql', 'sanctum/csrf-cookie'],\n```\n\n```text\nno-cors\n```\n\n```text\napollo config\n```\n\n========================================\n\nComments:\n- Oh wow, thanks! never saw that, but I have it changed now to the right variable and I still get the same error\n- So I finally figured this out, thank you so much for leading me in the right direction, Daniel! My mutation field was missing an outer curly brace after its arguments and I was able to discover this after pasting the query in graphiQL. Could have never thought just one curly brace would have me this stressed.\n- Yeahh, thanks Austio, I had to paste the mutation in graphiql to detect that.","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":283,"estimatedTokens":1578}}143{"id":"stack-60830193","source":"stackoverflow","questionId":60830193,"title":"How to run useQuery inside forEach?","tags":["javascript","graphql","hook","apollo"],"text":"Title: How to run useQuery inside forEach?\nTags: javascript, graphql, hook, apollo\nSource: Stack Overflow\n\nQuestion:\nI have loop - forEach - which find productId for every element of array. I want to fetch my database by productId using apollo query. \nHow to do it?\n\n```\nproducts.forEach(({ productId, quantity }) =>\n // fetch by 'productId'\n\n);\n```\n\n========================================\n\nTop Answer:\nIf you want to perform multiple calls to `useQuery` then you can't do that in a forEach, map etc. You need to use `useQueries` e.g.\n\n```\nfunction Products({ productIds }) {\n const productQueries = useQueries({\n queries: productIds.map(productId => {\n return {\n queryKey: ['productById', productId],\n queryFn: () => fetchProductById(productId),\n }\n })\n })\n```\n\nExample taken from: https://tanstack.com/query/latest/docs/framework/react/guides/parallel-queries#dynamic-parallel-queries-with-usequeries\n\n========================================\n\nCode:\n```text\nproducts.forEach(({ productId, quantity }) =>\n // fetch by 'productId'\n\n);\n```\n\n```text\nconst YourComponent = () => {\n ...\n return products.map(({ productId, quantity }) => (\n <Product key={productId} productId={productId} quantity={quantity} />\n ))\n}\n\nconst Product = () => {\n const { data, error, loading } = useQuery(...)\n // render your data accordingly\n}\n```\n\n```text\nforEach\n```\n\n```text\nuseQuery\n```\n\n```text\nmap\n```\n\n```text\nconst RefetchExample = () => {\n\nconst manualFetch = {\n refetchOnWindowFocus: false,\n enabled: false\n}\n\nconst GetAssetImage = async () => {\n const {data} = await axiosInstance.get(\"Your API\")\n return data\n}\n\nconst {assetImage, refetch} = useQuery('assetImage', GetAssetImage, manualFetch)\n\nconst imageFetch = () => {\n refetch();\n}\nreturn (\n <Button onClick={imageFetch}>Refetch</Button>\n)\n}\n\nexport default RefetchExample\n```\n\n```text\nfunction Products({ productIds }) {\n const productQueries = useQueries({\n queries: productIds.map(productId => {\n return {\n queryKey: ['productById', productId],\n queryFn: () => fetchProductById(productId),\n }\n })\n })\n```\n\n```text\nuseQuery\n```\n\n```text\nuseQueries\n```\n\n========================================\n\nComments:\n- Note that this potentially points to a bigger issue with your API. If you're getting the list of products from the API already, you should be able to just request the product details in that query and not have to make a separate, additional query for each product.\n- My app is microservice with different databases. And I think this is problem\n- I have services: api-gateway classifieds-app carts-service orders-service products-service users-service And this 4 services above has different databases. And this is reason to make separate, additional query for each product. But I don't know how to deal with it. Anyway, thank you for response. This really help me! Best wishes!\n- Thank you! But I have question ;) \"Separate component\" what this can look like? I don't have idea\n- Updated question with expanded example\n- Thanks, I was stuck with the same problem, you helped me a lot\n- This doesn't solve problem, when query needs to be ran to fetch dynamic amount of items, but data can't be split into individual components.\n- What if I need all the product details in the same component?\n- Thats one of hook drawbacks - you need to create NEW component just to be able run a hook in a loop... :(\n- refetch() - doesnt accept a query value to fetch data on dynamic IDs for example. So this unswer doesnt apply for this question. since he needs to fetch data based on different IDs in each loop.","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":129,"estimatedTokens":900}}144{"id":"stack-66368895","source":"stackoverflow","questionId":66368895,"title":"How to authenticate through Graphiql playground","tags":["authentication","graphql","request-headers","graphiql"],"text":"Title: How to authenticate through Graphiql playground\nTags: authentication, graphql, request-headers, graphiql\nSource: Stack Overflow\n\nQuestion:\nIt's my first time using GraphQL and I'm trying to access the content of a given query but I can't access this given query because of lack of permissions, in this case I have been given a username and a password to access this GraphQL API, and I'm able to get and verify the token using these credentials in GraphQL but my question is the following, how do I become authenticated in the API to be able to access the queries of the API?\n\nMy error is as follows.\n\n```\n\"errors\": [\n {\n \"message\": \"You do not have permission to perform this action\",\n```\n\nI believe this is something very basic, but I just not able to find a way to solve this issue.\n\n========================================\n\nTop Answer:\nThis is for **JWT authentication** in **REQUEST HEADERS** on **GraphiQL** below:\n\n```\n{\n \"Authorization\": \"JWT your_jwt_access_token_here\"\n}\n```\n\n========================================\n\nCode:\n```text\n\"errors\": [\n {\n \"message\": \"You do not have permission to perform this action\",\n```\n\n```text\n{\n \"Authorization\": \"Bearer YOUR_TOKEN_HERE\"\n}\n```\n\n```text\nlet token = req?.cookies?.token\n```\n\n```text\nlet token = req?.cookies?.token ?? req?.headers?.authorization\n```\n\n```text\n{\n \"Authorization\": \"JWT your_jwt_access_token_here\"\n}\n```\n\n```html\n<script type=\"module\">\n import { initializeApp } from \"https://www.gstatic.com/firebasejs/9.22.0/firebase-app.js\";\n import { getAuth } from \"https://www.gstatic.com/firebasejs/9.22.0/firebase-auth.js\";\n\n const app = initializeApp({\n projectId: \"example\",\n appId: \"xxxxx\",\n apiKey: \"xxxxx\",\n authDomain: \"example.com\"\n });\n\n function setAuthHeader(token) {\n const editor = document.querySelectorAll('.variable-editor .CodeMirror')[1].CodeMirror;\n const headers = JSON.parse(editor.getValue());\n headers.Authorization = token ? \"Bearer \" + token : undefined;\n editor.setValue(JSON.stringify(headers, null, 2));\n }\n\n getAuth(app).onIdTokenChanged((user) => {\n if (user) {\n user.getIdToken().then(token => setAuthHeader(token));\n } else {\n setAuthHeader(null);\n }\n });\n</script>\n```\n\n```text\nAuthorization: ...\n```\n\n```text\n{ \n \"Authorization\": \"Bearer k1kmcDKasVAKd......\" \n}\n```\n\n========================================\n\nComments:\n- thanks for your answer but I can see users have got the option to add HTTP Headers directly into they're Graphiql interface like you say, normally found next to 'Query Variables', but in my case I haven't got this option, it could be caused because the server uses an older version maybe. ¿Is there a way to add the authorization token without the HTTP Header Panel in Graphiql? Thank you for your time.\n- How does your answer differ from the accepted answer?","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":101,"estimatedTokens":713}}145{"id":"stack-45113394","source":"stackoverflow","questionId":45113394,"title":"How do I create a GraphQL subscription with Apollo Client in Vanilla JS","tags":["javascript","graphql","apollo","apollo-client"],"text":"Title: How do I create a GraphQL subscription with Apollo Client in Vanilla JS\nTags: javascript, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nRecently Apollo Client released a websocket subscription feature, but so far I've only seen it used by launching a query using subscribeToMore inside the componentWillMount lifecycle hook.\n\nHere is an example taken from https://dev-blog.apollodata.com/tutorial-graphql-subscriptions-client-side-40e185e4be76#0a8f\n\n```\nconst messagesSubscription = gql`\n subscription messageAdded($channelId: ID!) {\n messageAdded(channelId: $channelId) {\n id\n text\n }\n }\n`\n\ncomponentWillMount() {\n this.props.data.subscribeToMore({\n document: messagesSubscription,\n variables: {\n channelId: this.props.match.params.channelId,\n },\n updateQuery: (prev, {subscriptionData}) => {\n if (!subscriptionData.data) {\n return prev;\n }\n const newMessage = subscriptionData.data.messageAdded;\n // don't double add the message\n if (!prev.channel.messages.find((msg) => msg.id === newMessage.id)) {\n return Object.assign({}, prev, {\n channel: Object.assign({}, prev.channel, {\n messages: [...prev.channel.messages, newMessage],\n })\n });\n } else {\n return prev;\n }\n }\n });\n}\n```\n\nBut subscribeToMore is specific to Apollo Client React integration. In VanillaJS there is a watchQuery, but it's stated it should not be used for subscriptions. There is also a subscribe that might be what I'm searching for, but is not documented.\n\nIs there any way using Apollo GraphQL client to handle subscriptions, without being inside a React Component?\n\n========================================\n\nCode:\n```js\nconst messagesSubscription = gql`\n subscription messageAdded($channelId: ID!) {\n messageAdded(channelId: $channelId) {\n id\n text\n }\n }\n`\n\ncomponentWillMount() {\n this.props.data.subscribeToMore({\n document: messagesSubscription,\n variables: {\n channelId: this.props.match.params.channelId,\n },\n updateQuery: (prev, {subscriptionData}) => {\n if (!subscriptionData.data) {\n return prev;\n }\n const newMessage = subscriptionData.data.messageAdded;\n // don't double add the message\n if (!prev.channel.messages.find((msg) => msg.id === newMessage.id)) {\n return Object.assign({}, prev, {\n channel: Object.assign({}, prev.channel, {\n messages: [...prev.channel.messages, newMessage],\n })\n });\n } else {\n return prev;\n }\n }\n });\n}\n```\n\n```js\nsubscribe(repoName, updateQuery){\n // call the \"subscribe\" method on Apollo Client\n this.subscriptionObserver = this.props.client.subscribe({\n query: SUBSCRIPTION_QUERY,\n variables: { repoFullName: repoName },\n }).subscribe({\n next(data) {\n // ... call updateQuery to integrate the new comment\n // into the existing list of comments\n },\n error(err) { console.error('err', err); },\n });\n}\n```\n\n========================================\n\nComments:\n- The API for client subscriptions is really hard to find. I'm using react-apollo 2.5.5 and it seems the syntax has changed now to `next({ data })`. However, you're not getting any \"loading\" state, as you would with the `Subscription` component.\n- What is `data` here?","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":109,"estimatedTokens":808}}146{"id":"stack-57666539","source":"stackoverflow","questionId":57666539,"title":"GraphQL - Apollo Client without using hooks?","tags":["react-native","aws-lambda","graphql","apollo-client"],"text":"Title: GraphQL - Apollo Client without using hooks?\nTags: react-native, aws-lambda, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am attempting to use the Apollo GraphQL Client for React Native. However, in some parts of my app I need to do a mutation on the GraphQL data, in such a way that the interface should not be exposed to the user.\n\nFor instance, on my sign up page, I want to create a user in the database, but only after I have gone through and verified everything, created a uuid, etc. (things that require a class). If the call is sucessful, I want to imediately move on to the home page of the app. If not, I want to notify the user.\n\nAs such, I need access to do a GraphQL request, without hooks and just using callbacks to change the UI. Is this possible, and how could this be done?\n\n========================================\n\nTop Answer:\n```\n// clients/apollo.ts\n\nconst apolloClient = new ApolloClient({\n uri: \"/graphql\",\n cache: new InMemoryCache()\n})\n\n// queries/customer.ts\nconst GET_CUSTOMERS = gql`\n query {\n getCustomers() {\n name\n }\n }\n`\n\n// components/somewhere.ts \nconst result = await apolloClient.query({\n query: GET_CUSTOMERS ,\n variables: {}\n})\n```\n\n========================================\n\nCode:\n```text\nquery\n```\n\n```text\nmutation\n```\n\n```text\nfetch\n```\n\n```text\nPOST\n```\n\n```text\ncURL\n```\n\n```text\nPOST\n```\n\n```text\nquery\n```\n\n```text\nmutate\n```\n\n```text\nfetch\n```\n\n```text\n// clients/apollo.ts\n\nconst apolloClient = new ApolloClient({\n uri: \"/graphql\",\n cache: new InMemoryCache()\n})\n\n// queries/customer.ts\nconst GET_CUSTOMERS = gql`\n query {\n getCustomers() {\n name\n }\n }\n`\n\n\n// components/somewhere.ts \nconst result = await apolloClient.query({\n query: GET_CUSTOMERS ,\n variables: {}\n})\n```\n\n```text\nimport { client } from './config/connection';\nimport { ApolloProvider } from '@apollo/client';\n\n<ApolloProvider client={client}>\n <App/>\n</ApolloProvider>\n```\n\n```text\nimport { ApolloClient, ApolloLink, InMemoryCache } from '@apollo/client';\n\nexport const client = new ApolloClient({\n cache: new InMemoryCache(),\n uri: 'http://localhost:4000/graphql',\n});\n```\n\n```text\nimport { gql } from '@apollo/client';\n\nexport const Query_SignIn = gql`\n query Login($email: String!, $password: String!) {\n login(email: $email, password: $password) {\n name\n }\n }\n`;\n\nexport const Mutate_SignUp = gql`\n mutation SignUp($name: String!, $email: String!, $password: String!, $passwordConfirmation: String!) {\n signUp(name: $name, email: $email, password: $password, passwordConfirmation: $passwordConfirmation) {\n name\n }\n }\n`;\n```\n\n```text\nimport { Query_SignIn } from '../../../operations';\nclass login {\n constructor(client) {\n this._client = client;\n }\n\n async signIn(email, password) {\n const response = await this._client.query({\n query: Query_SignIn,\n variables: {\n email,\n password,\n },\n });\n\n return response;\n }\n}\n\nexport default login;\n```\n\n```text\nimport { Mutate_SignUp } from '../../../operations';\nclass register {\n constructor(client) {\n this._client = client;\n }\n\n async signUp(accountType, name, email, password, passwordConfirmation) {\n const response = await this._client.mutate({\n mutation: Mutate_SignUp,\n variables: {\n name,\n email,\n password,\n passwordConfirmation,\n },\n });\n\n return response;\n }\n}\n\nexport default register;\n```\n\n========================================\n\nComments:\n- Would this work for subscriptions as well?\n- Welcome to Stack Overflow, and Thank you for contributing an answer. Would you kindly edit your answer to to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts. That's especially important when there's already an accepted answer that's been validated by the community. Under what conditions might your approach be preferred? Are you taking advantage of new capabilities?","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":193,"estimatedTokens":1025}}147{"id":"stack-61887922","source":"stackoverflow","questionId":61887922,"title":"AWS AppSync Resolvers Lambda Function vs Velocity Template Language (VTL)","tags":["amazon-web-services","aws-lambda","graphql","aws-appsync"],"text":"Title: AWS AppSync Resolvers Lambda Function vs Velocity Template Language (VTL)\nTags: amazon-web-services, aws-lambda, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI have been looking into AWS AppSync to create a managed GraphQL API with DynamoDB as the datastore. I know AppSync can use Apache Velocity Template Language as a resolver to fetch data from dynamoDB. However, that means I have to introduce an extra language to the programming stack, so I would prefer to write the resolvers in Javascript/Node.js\n\nIs there any downside of using a lambda function to fetch data from DynamoDB? What reasons are there to use VTL instead of a lambda for resolvers?\n\n========================================\n\nCode:\n```text\nlong\n```\n\n```text\nlong\n```\n\n========================================\n\nComments:\n- Any idea of how much more costs it adds to the stack? @ben\n- @DiegoPonciano it depends on the frequency and complexity as AWS charges for lambdas based on a flat rate per invocation, plus per ms billing depending on how big an instance you need and how long it runs for. It also depends on how burstable you expect your load to be (more burstable means more cold starts or more cost keeping more lambdas warm). In general, if the complexity is there, the additional aws cost is going to be worth it compared to the pain (and time) you'll save yourself dealing with complex VTLs. See their pricing for current rates: aws.amazon.com/lambda/pricing","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":25,"estimatedTokens":364}}148{"id":"stack-51563960","source":"stackoverflow","questionId":51563960,"title":"How to add default values to input arguments in graphql","tags":["graphql","graphql-js"],"text":"Title: How to add default values to input arguments in graphql\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have this input type and I would like to add a default Value to one of the fields. I want to add 0 to the value field inside the ExampleInput.\n\n```\ntype ExampleType {\n value: Int\n another: String\n}\n\ntype Mutation {\n example(input: ExampleInput): ExampleType\n}\n\ninput ExampleInput {\n value: Int\n another: String\n}\n```\n\nAny ideas?\n\n========================================\n\nTop Answer:\nIn a programmatic/object-based (or code-first) approach, you can set a default value like this for the InputObjectType:\n\n```\nconst exampleInput = new GraphQLInputObjectType({\n name: \"ExampleInput\",\n fields: () => ({\n value: { type: graphql.GraphQLInt, defaultValue: 0 },\n another: { type: new GraphQLNonNull(graphql.GraphQLString) },\n isAvailable: { type: graphql.GraphQLBoolean, defaultValue: false },\n }),\n });\n```\n\nby using `defaultValue` keyword.\n\n========================================\n\nCode:\n```text\ntype ExampleType {\n value: Int\n another: String\n}\n\ntype Mutation {\n example(input: ExampleInput): ExampleType\n}\n\ninput ExampleInput {\n value: Int\n another: String\n}\n```\n\n```graphql\ninput ExampleInput {\n value: Int = 0\n another: String\n isAvailable: Boolean = false\n}\n```\n\n```js\nconst exampleInput = new GraphQLInputObjectType({\n name: \"ExampleInput\",\n fields: () => ({\n value: { type: graphql.GraphQLInt, defaultValue: 0 },\n another: { type: new GraphQLNonNull(graphql.GraphQLString) },\n isAvailable: { type: graphql.GraphQLBoolean, defaultValue: false },\n }),\n });\n```\n\n```text\ndefaultValue\n```\n\n========================================\n\nComments:\n- how to set default values in manual types declaration ? like new GraphQLObjectType({ args:{ isAdmin:{type:GraphQLBoolean} } }) how to set isAdmin to False by default?","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":89,"estimatedTokens":465}}149{"id":"stack-46446042","source":"stackoverflow","questionId":46446042,"title":"Passing Multiple Arguments to GraphQL Query","tags":["sparql","graphql"],"text":"Title: Passing Multiple Arguments to GraphQL Query\nTags: sparql, graphql\nSource: Stack Overflow\n\nQuestion:\n**First thing**\n\nAppreciate this may be a bit of a stupid question, but I'm working with GraphQL having come from the RDF/Linked Data world and having a lot of trouble getting my head around how I would return a set. Essentially I want something where I could select, let's say a list of `Characters` (using the examples from the GraphQL docs) via their `id`. In SPARQL I'd be using the `VALUES` clause and then binding, something like:\n\n```\nVALUES { }\n```\n\nI'd assume something like this would be what I'd want (pseudocode)\n\n```\n{\n human(id: [\"1\", \"2\", \"3\", \"4\", \"5\"]) {\n name\n height\n }\n}\n```\n\nAliases kind of do what I want, but I don't want to have to specify in advance or manually what the different named return values are - I want to say in my code pass a list of IDs:\n\n```\n[1 2 3 4 5]\n```\n\n...and have a query that could accept that array of IDs and return me results in a predictable non-scalar shape as per the pseudo-query above.\n\n**Second thing**\n\nI'm also assuming that it's in fact not possible to have a query resolve to either a `Human` or `[Human]` - that it has to be one or the other? No biggie if so, I'd just settle for the latter... but I think I'm just generally quite confused over this now.\n\n========================================\n\nTop Answer:\nYou can use GraphQL Aliases\n\n```\n{\n first: human(id: \"1\") {\n name\n height\n }\n second: human(id: \"2\") {\n name\n height\n }\n}\n```\n\n========================================\n\nCode:\n```text\nVALUES { <http://uri/id-1> <http://uri/id-2> <http://uri/id-3> }\n```\n\n```text\n{\n human(id: [\"1\", \"2\", \"3\", \"4\", \"5\"]) {\n name\n height\n }\n}\n```\n\n```text\n[1 2 3 4 5]\n```\n\n```text\nCharacters\n```\n\n```text\nid\n```\n\n```text\nVALUES\n```\n\n```text\nHuman\n```\n\n```text\n[Human]\n```\n\n```text\nextend type Query {\n humans(listId: [String!]): [Human!]\n human(id: ObjID!): Human\n}\n```\n\n```text\nQuery: {\n humans(root, {listId}, { Human }) {\n return Human.fillAllByListId(listId);\n },\n ...\n},\n```\n\n```text\nquery getConfigurationList($ids: [String!]!) {\n configuration (where: {id:{_in: $ids}}){\n id\n value\n }\n}\n```\n\n```text\n{\n first: human(id: \"1\") {\n name\n height\n }\n second: human(id: \"2\") {\n name\n height\n }\n}\n```\n\n========================================\n\nComments:\n- For example, am I thinking about this wrong, and I should define say a `Slice` type where I can define multiple arguments to chop up a hypothetical list into ranges? Even so, that kind of feels sub optimal for processing lists of resources.\n- And ideally I'd like to avoid having a string input like `\"[1 2 3 4 5]\"` so I don't have to worry about parsing, although I suppose that's a last ditch option.\n- works without adjusting the serverside, perfect!\n- You may want to use fragments so you don't have to repeat the fields.","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":139,"estimatedTokens":729}}150{"id":"stack-39504986","source":"stackoverflow","questionId":39504986,"title":"Document a GraphQL API","tags":["graphql","graphql-js"],"text":"Title: Document a GraphQL API\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nWith REST we can use Swagger, RAML or other technologies to document our API and generate an HTML documentation that our consumers can read without any need of interaction with the servers.\n\nDoes something similar exist for GraphQL? Is there any way to generate a documentation of resources and properties?\n\n========================================\n\nTop Answer:\nTo my knowledge there is no tool yet that automatically generates HTML documentation for a GraphQL API, but I've found GraphiQL to be even more useful than any API documentation in HTML that I've seen.\n\nGraphiQL lets you interactively explore the schema of a GraphQL server and run queries against it at the same time. It has syntax highlighting, autocompletion, and it even tells you when your query is invalid without executing it.\n\nIf you're looking for static documentation, I've found it pretty convenient to read the schema in GraphQL schema language. Thanks to another great feature of GraphQL - schema introspection - you can easily print the schema for any server you have access to. Simply run the introspection query against the server and then print the resulting introspection schema like so (using graphql-js):\n\n```\nvar graphql = require('graphql');\nvar introspectionSchema = {}; // paste schema here\nconsole.log(graphql.printSchema(graphql.buildClientSchema(introspectionSchema)));\n```\n\nThe result will look something like this:\n\n```\n# An author\ntype Author {\n id: ID!\n\n # First and last name of the author\n name: String\n}\n\n# The schema's root query type\ntype Query {\n\n # Find an author by name (must match exactly)\n author(name: String!): Author\n}\n```\n\n========================================\n\nCode:\n```text\nnpm install -g graphql-docs\ngraphql-docs-gen http://GRAPHQL_ENDPOINT documentation.html\n```\n\n```text\nvar graphql = require('graphql');\nvar introspectionSchema = {}; // paste schema here\nconsole.log(graphql.printSchema(graphql.buildClientSchema(introspectionSchema)));\n```\n\n```text\n# An author\ntype Author {\n id: ID!\n\n # First and last name of the author\n name: String\n}\n\n# The schema's root query type\ntype Query {\n\n # Find an author by name (must match exactly)\n author(name: String!): Author\n}\n```\n\n```text\ntype Query {\n eventSearch(\n # comma separated location IDs. (eg: '5,12,27')\n locationIds: String,\n # Date Time should be ISO 8601: 'YYYY-DD-MM HH:mm:ss'. (eg: '2018-04-23 00:00:00')\n startDateTime: String!,\n endDateTime: String!): [Event]\n }\n```\n\n```text\nGraphiql\n```\n\n```text\nAltair\n```\n\n```text\nspecific format\n```\n\n```text\narguments\n```\n\n========================================\n\nComments:\n- Thanks, helfer. The caveat of using the API as documentation is that sometimes the developer needs it before having access. For example: When deciding to buy some API service. You provided a nice alternative to this caveat. Thanks for the useful answer. I'll wait a little and mark it as accepted if none better come.\n- Would this work for an endpoint developed using Spring Boot (Java) ?\n- Note that this hasn't been updated since 2015 (although I haven't investigated more recent forks), and it cannot handle Unions so may not be able to parse your schema.\n- SpectaQL just released a big update, see the announcement blog post here useanvil.com/blog/engineering/spectaql-one-point-zero","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":108,"estimatedTokens":854}}151{"id":"stack-54551615","source":"stackoverflow","questionId":54551615,"title":"GraphQL syntax to access file by relativepath","tags":["graphql","gatsby"],"text":"Title: GraphQL syntax to access file by relativepath\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nGatsbyJS docs give this example for accessing a file by relativepath with GraphQL:\n\n```\nexport const query = graphql`\n query {\n fileName: file(relativePath: { eq: \"images/myimage.jpg\" }) {\n childImageSharp {\n fluid(maxWidth: 400, maxHeight: 250) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n`\n```\n\nI just can't get this working and I don't know why. I've tried all kinds of different syntaxes but the query always returns null for filename. This is my most recent attempt in Graph**i**QL:\n\n```\n{\n fileName: file(relativePath: { eq: \"./html.js\" }) {\n id\n } \n}\n```\n\nWhat am I missing? How can I access a file by relative path?\n\nEdit after reading the answer:\n\nIn my `gatsby-config.js` there are several paths set as queriable:\n\n```\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `images`,\n path: `${__dirname}/src/images/`\n }\n},\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/content/posts/`,\n name: \"posts\"\n }\n},\n....\n```\n\nWhen I make a query for `pic.jpg` (instead of `images/pic.jpg`), how does Gatsby know I want `images/pic.jpg` instead of `posts/pic.jpg`? How is this uniquely defining a path?\n\n========================================\n\nTop Answer:\nWhat caught me out is that per this issue you need to restart `gatsby develop` for the GraphQL data to refresh (i.e. after you adjust the `relativePath`).\n\nThis can be resolved by:\n\n- Starting Gatsby with `ENABLE_GATSBY_REFRESH_ENDPOINT=true gatsby develop`\n\n- Running `curl -X POST localhost:8000/__refresh` in a separate terminal each time you want to refresh the data\n\n========================================\n\nCode:\n```text\nexport const query = graphql`\n query {\n fileName: file(relativePath: { eq: \"images/myimage.jpg\" }) {\n childImageSharp {\n fluid(maxWidth: 400, maxHeight: 250) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n`\n```\n\n```text\n{\n fileName: file(relativePath: { eq: \"./html.js\" }) {\n id\n } \n}\n```\n\n```text\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `images`,\n path: `${__dirname}/src/images/`\n }\n},\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/content/posts/`,\n name: \"posts\"\n }\n},\n....\n```\n\n```text\ngatsby-config.js\n```\n\n```text\npic.jpg\n```\n\n```text\nimages/pic.jpg\n```\n\n```text\nimages/pic.jpg\n```\n\n```text\nposts/pic.jpg\n```\n\n```text\nroot\n |--gatsby-config.js\n `--dirA\n |--fileA.md\n `--dirB\n |--fileB.md\n `--dirC\n `--fileC.md\n```\n\n```js\n{\n resolve: `gatsby-source-filesystem`\n options: {\n path: `${__dirname}/dirA`, <---- root/dirA\n name: `dir`,\n },\n}\n```\n\n```text\nFile | relativePath\n---------------------------------\nfileA.md | 'fileA.md'\n---------------------------------\nfileB.md | 'dirB/fileB.md'\n---------------------------------\nfileC.md | 'dirB/dirC/fileC.md'\n```\n\n```text\nquery {\n fileName: file(relativePath: {\n eq: \"dirB/dirC/fileC.md\"\n }) {\n id\n }\n}\n```\n\n```text\nroot\n |--gatsby-config.js\n |--dirD\n | `--index.md\n `--dirE\n `--index.md\n```\n\n```text\nquery {\n fileName: file(relativePath: {\n eq: \"index.md\"\n }) {\n id\n }\n}\n```\n\n```text\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/dirE`,\n name: `dirE`,\n },\n},\n```\n\n```text\n{\n file(\n relativePath: {\n eq: \"index.md\"\n },\n sourceInstanceName: {\n eq: \"dirE\"\n }\n ) {\n id\n }\n}\n```\n\n```text\nquery {\n allFile(filter: {\n relativePath: { eq: \"index.md\" }\n }) {\n edges {\n node { \n id\n }\n } \n }\n}\n```\n\n```text\nrelativePath\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\ngatsby-config.js\n```\n\n```text\ndirA\n```\n\n```text\nrelativePath\n```\n\n```text\nfileC\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\nhtml.js\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\nrelativePath\n```\n\n```text\nindex.md\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\nname\n```\n\n```text\nname\n```\n\n```text\nsourceInstanceName\n```\n\n```text\nsourceInstanceName\n```\n\n```text\nrelativePath\n```\n\n```text\nabsolutePath\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\nrelativePath\n```\n\n```text\ngatsby develop\n```\n\n```text\nrelativePath\n```\n\n```text\nENABLE_GATSBY_REFRESH_ENDPOINT=true gatsby develop\n```\n\n```text\ncurl -X POST localhost:8000/__refresh\n```\n\n========================================\n\nComments:\n- Thanks a ton, again! This works, though I'm still wondering how is this uniquely defining a path? I edited OP to clarify what I mean by this question.\n- @AtteJuvonen Hi Atte! I've updated the answer to address the edited question. In short, if you only rely on `relativePath`, Gatsby won't know which file you want, and will just return the first one that it can find. You'd have to add additional filters to ensure the file is unique.\n- Alternatively, you can also query File node by its `absolutePath` field, in which case you won't need to pass in additional filters.\n- This is a seriously good answer requiring a comment, not just a vote. :-) This doesn't seem to be clearly stated on the Gatsby `gatsby-source-filesystem` plugin page or its GItHub repo. Thank you.\n- Excellent answer!","metadata":{"transformedAt":"2026-08-18T18:32:36.032Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":41,"totalLines":334,"estimatedTokens":1307}}152{"id":"stack-45806368","source":"stackoverflow","questionId":45806368,"title":"GraphQL Error field type must be Input Type but got:","tags":["javascript","graphql"],"text":"Title: GraphQL Error field type must be Input Type but got:\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nHere is the mutation:\n\n```\nconst createNotebook = mutationWithClientMutationId ({\n name: 'CreateNotebook',\n inputFields: {\n token: {\n type: GraphQLString,\n },\n\n details: {\n type: NotebookDetails,\n },\n },\n outputFields: {\n\n },\n async mutateCRNotebook(input, context) {\n const data = getJSONFromRelativeURL(input.token);\n\n },\n});\n```\n\nHere is the schema used in the details field of the mutation: \n\n```\nconst NotebookDetails = new GraphQLObjectType({\n name: 'NotebookDetails',\n interfaces: [nodeInterface],\n\n fields: () => ({\n id: globalIdField('NotebookDetails'),\n\n description: {\n type: GraphQLString,\n description: '...',\n resolve(obj) {\n return obj.description;\n },\n },\n\n language: {\n type: GraphQLString,\n description: '...',\n resolve(obj) {\n return obj.language;\n },\n },\n\n }),\n\n});\n```\n\nError I am getting on running this code is : \n\n```\napi_1 | Error: CreateNotebookInput.details field type must be Input Type but got: NotebookDetails.\napi_1 | at invariant (/usr/src/app/node_modules/graphql/jsutils/invariant.js:19:11)\napi_1 | at /usr/src/app/node_modules/graphql/type/definition.js:698:58\napi_1 | at Array.forEach (native)\napi_1 | at GraphQLInputObjectType._defineFieldMap (/usr/src/app/node_modules/graphql/type/definition.js:693:16)\napi_1 | at GraphQLInputObjectType.getFields (/usr/src/app/node_modules/graphql/type/definition.js:682:49)\napi_1 | at typeMapReducer (/usr/src/app/node_modules/graphql/type/schema.js:224:26)\napi_1 | at typeMapReducer (/usr/src/app/node_modules/graphql/type/schema.js:190:12)\napi_1 | at Array.reduce (native)\napi_1 | at /usr/src/app/node_modules/graphql/type/schema.js:217:36\napi_1 | at Array.forEach (native)\napi_1 | at typeMapReducer (/usr/src/app/node_modules/graphql/type/schema.js:210:27)\napi_1 | at Array.reduce (native)\napi_1 | at new GraphQLSchema (/usr/src/app/node_modules/graphql/type/schema.js:98:34)\napi_1 | at Object. (/usr/src/app/src/schema/index.js:39:16)\napi_1 | at Module._compile (module.js:569:30)\napi_1 | at Object.Module._extensions..js (module.js:580:10)\n```\n\nI have used this syntax with queries and they worked correctly. But, they are returning error with a mutation.\nWhat is incorrect in my code and how do I correct it?\n\n========================================\n\nTop Answer:\n**For those who are using `graphql-tools` and stumble accross this post, documentation is here at GraphQL's Website.**\n\n**My Example using graphQL tools** is here **below**: (this has an input inside of an input AKA an `ImageInput` inside the `SocialPostInput`)\n\n//mutation file\n\n```\nextend type Mutation {\n SchedulePost ( \n socialPost: SocialPostInput,\n schedule: ScheduleInput\n ): ScheduledPost\n}`\n```\n\n//Schedule and SocialPost file\n\n```\ntype Image {\n id: String\n url: String\n}\ntype SocialPost {\n id: String\n GCID: String\n message: String\n image: Image\n}\ninput ImageInput {\n url: String\n}\ninput SocialPostInput {\n GCID: String\n message: String\n image: ImageInput\n}\ntype Schedule {\n id: String\n month: Int\n date: Int\n hour: Int\n minute: Int\n}\ninput ScheduleInput {\n id: String\n month: Int\n date: Int\n hour: Int\n minute: Int\n}`\n```\n\n========================================\n\nCode:\n```text\nconst createNotebook = mutationWithClientMutationId ({\n name: 'CreateNotebook',\n inputFields: {\n token: {\n type: GraphQLString,\n },\n\n details: {\n type: NotebookDetails,\n },\n },\n outputFields: {\n\n },\n async mutateCRNotebook(input, context) {\n const data = getJSONFromRelativeURL(input.token);\n\n },\n});\n```\n\n```text\nconst NotebookDetails = new GraphQLObjectType({\n name: 'NotebookDetails',\n interfaces: [nodeInterface],\n\n fields: () => ({\n id: globalIdField('NotebookDetails'),\n\n description: {\n type: GraphQLString,\n description: '...',\n resolve(obj) {\n return obj.description;\n },\n },\n\n language: {\n type: GraphQLString,\n description: '...',\n resolve(obj) {\n return obj.language;\n },\n },\n\n }),\n\n});\n```\n\n```text\napi_1 | Error: CreateNotebookInput.details field type must be Input Type but got: NotebookDetails.\napi_1 | at invariant (/usr/src/app/node_modules/graphql/jsutils/invariant.js:19:11)\napi_1 | at /usr/src/app/node_modules/graphql/type/definition.js:698:58\napi_1 | at Array.forEach (native)\napi_1 | at GraphQLInputObjectType._defineFieldMap (/usr/src/app/node_modules/graphql/type/definition.js:693:16)\napi_1 | at GraphQLInputObjectType.getFields (/usr/src/app/node_modules/graphql/type/definition.js:682:49)\napi_1 | at typeMapReducer (/usr/src/app/node_modules/graphql/type/schema.js:224:26)\napi_1 | at typeMapReducer (/usr/src/app/node_modules/graphql/type/schema.js:190:12)\napi_1 | at Array.reduce (native)\napi_1 | at /usr/src/app/node_modules/graphql/type/schema.js:217:36\napi_1 | at Array.forEach (native)\napi_1 | at typeMapReducer (/usr/src/app/node_modules/graphql/type/schema.js:210:27)\napi_1 | at Array.reduce (native)\napi_1 | at new GraphQLSchema (/usr/src/app/node_modules/graphql/type/schema.js:98:34)\napi_1 | at Object.<anonymous> (/usr/src/app/src/schema/index.js:39:16)\napi_1 | at Module._compile (module.js:569:30)\napi_1 | at Object.Module._extensions..js (module.js:580:10)\n```\n\n```text\nconst NotebookDetailsInput = new GraphQLInputObjectType({\n name: 'NotebookDetailsInput',\n fields: () => ({\n id: { type: GraphQLID },\n description: { type: GraphQLString },\n language: { type: GraphQLString }, \n })\n});\n```\n\n```text\ninput {\n id: ID\n description: String\n language: String\n}\n```\n\n```text\ninput\n```\n\n```text\ntype\n```\n\n```text\ntype\n```\n\n```text\ninput\n```\n\n```text\nextend type Mutation {\n SchedulePost ( \n socialPost: SocialPostInput,\n schedule: ScheduleInput\n ): ScheduledPost\n}`\n```\n\n```text\ntype Image {\n id: String\n url: String\n}\ntype SocialPost {\n id: String\n GCID: String\n message: String\n image: Image\n}\ninput ImageInput {\n url: String\n}\ninput SocialPostInput {\n GCID: String\n message: String\n image: ImageInput\n}\ntype Schedule {\n id: String\n month: Int\n date: Int\n hour: Int\n minute: Int\n}\ninput ScheduleInput {\n id: String\n month: Int\n date: Int\n hour: Int\n minute: Int\n}`\n```\n\n```text\ngraphql-tools\n```\n\n```text\nImageInput\n```\n\n```text\nSocialPostInput\n```\n\n```text\nconst NotebookDetails = new GraphQLObjectType({\n name: 'NotebookDetails',\n fields: () => ({\n id: { type: GraphQLID },\n description: { type: GraphQLString },\n language: { type: GraphQLString },\n\n }),\n\n});\n```\n\n```text\ntype SomeData {\n someField: String!\n}\n```\n\n```text\ninput SomeData {\n someField: String!\n}\n```\n\n```text\ntype CreateNotebookInput\n```\n\n```text\ninput CreateNotebookInput\n```\n\n========================================\n\nComments:\n- This took me way too long to catch on to but seems quite \"obvious\" once you catch on!\n- your answer should be flashing on top of their website\n- I your answer @zemil, and it works for me. Thank you. My question is: I have a large schema language, and i have to clone the type to make it an input. Is there existing options that will minimize the redundancy of it because their only difference is the type/input code, the fields are all the same.\n- @JurP check stackoverflow.com/questions/52452982/…\n- And what would that do?\n- Because this bug showing need the input, not a type. Changing will fix this bug","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":347,"estimatedTokens":1927}}153{"id":"stack-46770501","source":"stackoverflow","questionId":46770501,"title":"GraphQL: Non-nullable array/list","tags":["javascript","graphql","graphql-js","apollo","express-graphql"],"text":"Title: GraphQL: Non-nullable array/list\nTags: javascript, graphql, graphql-js, apollo, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm learning GraphQL now and while walking through tutorial I met behavior that I can't understand.\nLet's say we have defined type in schema: \n\n```\ntype Link {\n id: ID!\n url: String!\n description: String!\n postedBy: User\n votes: [Vote!]!\n}\n```\n\nDue to docs `votes: [Vote!]!` means that that field should be a non-nullable and array itself should be non-nullable too. But just after that author of tutorial shows example of query and for some of links it returns empty array for `votes` field. Like this: \n\n```\n{\n \"url\": \"youtube.com\",\n \"votes\": []\n},\n{\n \"url\": \"agar.io\",\n \"votes\": []\n}\n```\n\nSo my question is: Doesn't \"non-nullable\" means \"empty\" in graphQL schema or it's just some kind of wrong behavior of graphQL server (I mean it returns array of nothing without warning that there should be something due to schema).\n\nThanks!\n\n========================================\n\nCode:\n```text\ntype Link {\n id: ID!\n url: String!\n description: String!\n postedBy: User\n votes: [Vote!]!\n}\n```\n\n```text\n{\n \"url\": \"youtube.com\",\n \"votes\": []\n},\n{\n \"url\": \"agar.io\",\n \"votes\": []\n}\n```\n\n```text\nvotes: [Vote!]!\n```\n\n```text\nvotes\n```\n\n```none\ndeclaration accepts: | null | [] | [null] | [{foo: 'BAR'}]\n------------------------------------------------------------------------\n[Vote!]! | no | yes | no | yes\n[Vote]! | no | yes | yes | yes\n[Vote!] | yes | yes | no | yes\n[Vote] | yes | yes | yes | yes\n```\n\n```text\n[Vote!]!\n```\n\n```text\nvotes\n```\n\n```text\nnull\n```\n\n```text\n[]\n```\n\n```text\n[{}]\n```\n\n```text\n[{foo: 'BAR'}]\n```\n\n```text\nfoo\n```\n\n```text\n[{foo: 'BAR'}, null]\n```\n\n```text\n[Vote]!\n```\n\n```text\n[Vote!]\n```\n\n```text\n[Vote]\n```\n\n========================================\n\nComments:\n- May I know the URL of the tutorial you are talking about?\n- Currently GraphQL do not allow to validate array length (github.com/graphql/graphql-js/issues/397).\n- Maybe I was confused because of paragraph in tutorial: *\"[Episode]! represents an array of Episode objects. Since it is also non-nullable, you can always expect an array (with zero or more items) when you query the appearsIn field.\"* For some reasons I though if absence of exclamation mark means *\"zero or more items\"* so presence of exclamation mark means there should be at least 1 item. Thanks for your answer!\n- @daniel-rearden thanks for your precise answer. But what for would I use an array with nulls inside? `[]` and `[null]` are pretty similar (no info inside), so why do we need both?\n- @VladimirAlexiev It could be useful for returning one array element for each requested element (example: request `[4, 1, 2, 6]` => response `[Vote, null, null, Vote]`)\n- I figured there is another reason: to report a particular element as erroneous. Say Vote has a mandatory field, but it's missing or a particular vote: then the error should be propagated and that whole Vote should be nulled out. AND if the array has type [Vote!] then the whole array should be nulled out!\n- Good point @VladimirAlexiev Errors will propagate differently depending on whether the list element is non-null or not. See this section of the spec for more details.","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":130,"estimatedTokens":827}}154{"id":"stack-40644296","source":"stackoverflow","questionId":40644296,"title":"How to query list of objects with array as an argument in GraphQL","tags":["graphql","graphql-js"],"text":"Title: How to query list of objects with array as an argument in GraphQL\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to query a list of objects having array of IDs. Something similar to following SQL query:\n\n```\nSELECT name FROM events WHERE id IN(1,2,3,...);\n```\n\nHow do I achieve this in GraphQL?\n\n========================================\n\nTop Answer:\nI just do this:\n\n```\nquery nameOfYourQuery {\n allEvents(filter: { id: { in: [1,2,3] } }) {\n nodes {\n name\n }\n }\n}\n```\n\nIf the array is a variable, then it would look like this (in Gatsby, at least):\n\n```\nquery nameOfYourQuery($arrayOfID: [String]) {\n allEvents(filter: { id: { in: $arrayOfID: [String] } }) {\n nodes {\n name\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nSELECT name FROM events WHERE id IN(1,2,3,...);\n```\n\n```text\n{\n events(containsId: [1,2,3]) {\n ...\n }\n}\n```\n\n```text\nconst eventsType = new GraphQLObjectType({\n name: 'events',\n type: // your type definition for events,\n args: {\n containsId: new GraphQLList(GraphQLID)\n },\n ...\n});\n```\n\n```text\n{\n query: `\n query events ($containsId: [Int]) {\n events(containsId: $containsId) {\n id\n name\n }\n }\n `,\n variables: {\n containsId: [1,2,3]\n }\n}\n```\n\n```text\nvehicleTypes: { name: [\"Small\", \"Minivan\"] }\n```\n\n```text\nvehicleTypes: VehicleTypesInput\n```\n\n```text\nInput VehicleTypesInput {\n name: [String]!\n}\n```\n\n```text\nquery nameOfYourQuery {\n allEvents(filter: { id: { in: [1,2,3] } }) {\n nodes {\n name\n }\n }\n}\n```\n\n```text\nquery nameOfYourQuery($arrayOfID: [String]) {\n allEvents(filter: { id: { in: $arrayOfID: [String] } }) {\n nodes {\n name\n }\n }\n}\n```\n\n========================================\n\nComments:\n- what would the schema look like?\n- what would the [1,2,3] look like when using query variables instead of hardcoding it directly in the query?\n- Why do you use an input type on a query?\n- allEvents has no argument named \\\"filter\\\"\". From what I understand the remote side needs to have this option implemented. I don't understand all the hype around graphQL, there is no magic, as api clients, we still need to ask api developper for new features when needed, or do multiples queries in case what we look for is not implemented....\n- @Tobbey the hype around graphql is mostly because with it you can query multiple services and have just one endpoint. Also when building frontends separately from the backend \"headless\" you can use that same endpoint for different frontends. With rest apis you have different endpoints for things like products, categories, etc","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":124,"estimatedTokens":655}}155{"id":"stack-34828418","source":"stackoverflow","questionId":34828418,"title":"What do 3 dots/periods/ellipsis in a relay/graphql query mean?","tags":["relayjs","graphql"],"text":"Title: What do 3 dots/periods/ellipsis in a relay/graphql query mean?\nTags: relayjs, graphql\nSource: Stack Overflow\n\nQuestion:\nThe relay docs contain this fragment:\n\n```\nquery RebelsRefetchQuery {\n node(id: \"RmFjdGlvbjox\") {\n id\n ... on Faction {\n name\n }\n }\n}\n```\n\nWhat does this `... on Faction` on syntax mean?\n\n========================================\n\nTop Answer:\nAh. It's explained here:\n\n Fragments are consumed by using the spread operator (...). All fields\n selected by the fragment will be added to the query field selection at\n the same level as the fragment invocation. This happens through\n multiple levels of fragment spreads.\n\n========================================\n\nCode:\n```text\nquery RebelsRefetchQuery {\n node(id: \"RmFjdGlvbjox\") {\n id\n ... on Faction {\n name\n }\n }\n}\n```\n\n```text\n... on Faction\n```\n\n```text\nquery Foo {\n user(id: 4) {\n ...userFields\n }\n}\n\nfragment userFields on User {\n name\n}\n```\n\n```text\nquery Foo {\n user(id: 4) {\n name\n }\n}\n```\n\n```text\nquery Foo {\n profile(id: $id) {\n url\n ... on User {\n homeAddress\n }\n ... on Business {\n address\n }\n }\n}\n```\n\n```text\n...\n```\n\n```text\nhomeAddress\n```\n\n```text\naddress\n```\n\n```text\nUser\n```\n\n```text\nBusiness\n```\n\n========================================\n\nComments:\n- I'm having trouble iterating on queries that contain fragments. what do I do? I have no idea.\n- I only new of inline fragments before. Fragment syntax saves so many lines!","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":107,"estimatedTokens":368}}156{"id":"stack-39814853","source":"stackoverflow","questionId":39814853,"title":"Apollo GraphQL React - how to query on click?","tags":["reactjs","graphql","apollostack"],"text":"Title: Apollo GraphQL React - how to query on click?\nTags: reactjs, graphql, apollostack\nSource: Stack Overflow\n\nQuestion:\nIn the Apollo React docs http://dev.apollodata.com/react/queries.html#basics there are examples of fetching automatically when the component is shown, but I'd like to run a query when a button is clicked. I see an example to \"re\"fetch a query when a button is clicked, but I don't want it to query initially. I see there is a way to call mutations, but how do you call queries?\n\n========================================\n\nTop Answer:\nAs of version 3.0, you can do this in two ways now.\n\n### `client.query`\n\nThe first way is to call `ApolloClient`'s `query` method. This returns a Promise that will resolve to the query's result. You can get a reference to the client by using the withApollo HOC:\n\n```\nclass MyComponent extends React.Component {\n handleClick() {\n const { data } = await this.props.client.query({\n query: gql`...`,\n variables: { ... },\n })\n ...\n }\n ...\n}\n\nwithApollo(MyComponent)\n```\n\nAlternatively, you can also use ApolloConsumer to get the client:\n\n```\nconst MyComponent = () => (\n \n {client => {\n ...\n }\n \n)\n```\n\nor the useApolloClient hook:\n\n```\nconst MyComponent = () => {\n const client = useApolloClient()\n ...\n}\n```\n\n### `useLazyQuery`\n\nThe second way is to use the useLazyQuery hook:\n\n```\nconst MyComponent = () => {\n const [runQuery, { called, loading, data }] = useLazyQuery(gql`...`)\n const handleClick = () => runQuery({ variables: { ... } })\n ...\n}\n```\n\n========================================\n\nCode:\n```text\nclass MyComponent extends React.Component {\n runQuery() {\n this.props.client.query({\n query: gql`...`,\n variables: { ... },\n });\n }\n\n render() { ... }\n}\n\nwithApollo(MyComponent);\n```\n\n```text\nwithApollo\n```\n\n```text\nclient.query\n```\n\n```text\nclass MyComponent extends React.Component {\n handleClick() {\n const { data } = await this.props.client.query({\n query: gql`...`,\n variables: { ... },\n })\n ...\n }\n ...\n}\n\nwithApollo(MyComponent)\n```\n\n```text\nconst MyComponent = () => (\n <ApolloConsumer>\n {client => {\n ...\n }\n </ApolloConsumer>\n)\n```\n\n```text\nconst MyComponent = () => {\n const client = useApolloClient()\n ...\n}\n```\n\n```text\nconst MyComponent = () => {\n const [runQuery, { called, loading, data }] = useLazyQuery(gql`...`)\n const handleClick = () => runQuery({ variables: { ... } })\n ...\n}\n```\n\n```text\nclient.query\n```\n\n```text\nApolloClient\n```\n\n```text\nquery\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nimport React from 'react';\nimport { useLazyQuery } from '@apollo/client';\n\nfunction DelayedQuery() {\n const [getDog, { loading, error, data }] = useLazyQuery(GET_DOG_PHOTO);\n\n if (loading) return <p>Loading ...</p>;\n if (error) return `Error! ${error}`;\n\n return (\n <div>\n {data?.dog && <img src={data.dog.displayImage} />}\n <button onClick={() => getDog({ variables: { breed: 'bulldog' } })}>\n Click me!\n </button>\n </div>\n );\n}\n```\n\n```text\nuseLazyQuery\n```\n\n========================================\n\nComments:\n- any ideas on this one? stackoverflow.com/questions/49238490/…\n- i wanted to use this for a search bar\n- Im finding if I use this on a component which has the gql HOC on a parent, it triggers the parents componentWillReceiveProps. No idea why. Is there a better way? perhaps redux.\n- This does not update the props? Why? How can I update props after the result comes in successfully?\n- you can define an updateQuery function or updateQueries object in order to update the existing props\n- Why can be that shows this error: `Error: Network error: Could not find query inside query map.`?\n- Are you using some persisted queries library?\n- @stubailo Yes, I have disabled persisted queries and I can use it. Thanks.\n- @tahayk seems like updateQuery is not in client.query api, how we can archive that ?\n- Sounds like this should be a new question - I'm not quite sure what you're trying to do. You might be able to use `client.writeQuery` though: dev.apollodata.com/core/apollo-client-api.html#ApolloClient\\‌​.writeQuery\n- Shouldn't you just fire the submit event and pass the input as props to another component which utilizes them in a query?\n- is there a way to get `fetchMore()` from `this.props.client.query` like what `graphql()` has under `props.data.fetchMore()`?\n- any ideas on this one? stackoverflow.com/questions/49238490/…\n- In apollo 2.1 you can user component apollographql.com/docs/react/api/…... Also this ---> apollographql.com/docs/react/essentials/…\n- Hooks are headache when you need handle subscriptions. Potential of making mistakes and open too many subscription channels on the server is too high! `useMemo` will help but `subscribeToMore` is so dangerous :)))\n- useLazyQuery is just what we need for immediate load. Thanks.\n- I have to use `useApolloClient` because I have a list of posts and each row of the list has an edit button. I want to get post data by its id and show data in a modal when I click on edit button. I tested `useLazyQuery` it doesn't get a post data again. I mean For the second and third time, I can not do this without refresh the page.\n- @FullOfStack you should add argument `fetchPolicy: 'network-only'` in your `useLazyQuery`","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":192,"estimatedTokens":1323}}157{"id":"stack-59465864","source":"stackoverflow","questionId":59465864,"title":"Handling errors with react-apollo useMutation hook","tags":["reactjs","graphql","react-apollo","apollo-client"],"text":"Title: Handling errors with react-apollo useMutation hook\nTags: reactjs, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have been trying to get my head around this problem but haven't found a strong answer to it. I am trying to execute a login mutation using the `useMutation` hook.\n\n***TLDR; I want to know what exactly is the difference between the `onError` passed in `options` and `error` given to me by the `useMutation`***\n\nHere's my code snippet\n\n```\nconst [login, { data, loading, error }] = useMutation(LOGIN_QUERY, {\n variables: {\n email,\n password\n },\n onError(err) {\n console.log(err);\n },\n});\n```\n\nOn the server-side, I have a preset/hardcoded email used for login and I am not using Apollo or any other client. In the resolver of this Login Mutation, I simply throw an error if the email is not same using\n\n```\nthrow new Error('Invalid Email');\n```\n\nNow I want to handle this error on the client-side (React). But my concern is that if I use the 'error' returned from the `useMutation` hook and try to show the error in this way\n\n```\nrender() {\n ...\n {error && Error occurred }\n ...\n}\n```\n\nthe error is updated in the UI but then immediately React shows me a screen with:\n\n```\nUnhandled Rejection (Error): Graphql error: My-custom-error-message\n```\n\nBut, if I use `onError` passed in `options` to `useMutate` function, then it doesn't show me this screen and I can do whatever I want with the error.\n\nI want to know what exactly is the difference between the `onError` passed in `options` and `error` given to me by the `useMutation` and why does React show me that error screen when `onError` is **not** used.\n\nThanks!\n\n========================================\n\nTop Answer:\n```\nconst [mutationHandler, { data, loading }] = useMutation(YOUR_MUTATION, {\n onError: (err) => {\n setError(err);\n }\n});\n```\n\nWith this we can access data with loading status and proper error handling to avoid any error in console / unhandled promise rejection.\n\n========================================\n\nCode:\n```text\nconst [login, { data, loading, error }] = useMutation(LOGIN_QUERY, {\n variables: {\n email,\n password\n },\n onError(err) {\n console.log(err);\n },\n});\n```\n\n```text\nthrow new Error('Invalid Email');\n```\n\n```text\nrender() {\n ...\n {error && <div> Error occurred </div>}\n ...\n}\n```\n\n```text\nUnhandled Rejection (Error): Graphql error: My-custom-error-message\n```\n\n```text\nuseMutation\n```\n\n```text\nonError\n```\n\n```text\noptions\n```\n\n```text\nerror\n```\n\n```text\nuseMutation\n```\n\n```text\nuseMutation\n```\n\n```text\nonError\n```\n\n```text\noptions\n```\n\n```text\nuseMutate\n```\n\n```text\nonError\n```\n\n```text\noptions\n```\n\n```text\nerror\n```\n\n```text\nuseMutation\n```\n\n```text\nonError\n```\n\n```text\nlogin()\n .then(({ data }) => {\n // you can do something with the response here\n })\n .catch(e => {\n // you can do something with the error here\n })\n```\n\n```text\ntry {\n const { data } = await login()\n} catch (e) {\n // do something with the error here\n}\n```\n\n```text\nconst [mutate] = useMutation(YOUR_MUTATION)\nconst [data, setData] = useState()\nconst [error, setError] = useState()\nconst handleClick = async () => {\n try {\n const { data } = await mutate()\n setData(data)\n catch (e) {\n setError(e)\n }\n}\n```\n\n```text\nconst [mutate, { data, error }] = useMutation(YOUR_MUTATION)\n```\n\n```text\nerrors\n```\n\n```text\ndata\n```\n\n```text\nerrors\n```\n\n```text\nmutate\n```\n\n```text\ndata\n```\n\n```text\nignore\n```\n\n```text\nall\n```\n\n```text\nonError\n```\n\n```text\nonError\n```\n\n```text\nerrorPolicy\n```\n\n```text\nonError\n```\n\n```text\nerrorPolicy\n```\n\n```text\nnone\n```\n\n```text\nonError\n```\n\n```text\nmutate\n```\n\n```text\nmutate\n```\n\n```text\nuseMutation\n```\n\n```text\nerror\n```\n\n```text\nerror\n```\n\n```text\ndata\n```\n\n```text\nonError\n```\n\n```text\ncatch\n```\n\n```text\nconst [mutationHandler, { data, loading }] = useMutation(YOUR_MUTATION, {\n onError: (err) => {\n setError(err);\n }\n});\n```\n\n```text\nconst YOUR_COMPONENT = ({ setError }) => {\n // ... \n\n const [mutationHandler, { data, loading }] = useMutation(YOUR_MUTATION, { \n onError: (error) => {\n setError(error.graphQLErrors[0].message)\n }\n})\n```\n\n========================================\n\nComments:\n- This is really great, if I want to use the convenient `data` and `error` from `useMutation`, what do I do with the `data` and `error` when handling the Promise? Since I don't have to set them myself.\n- one note, looks like we would need to expose the `reset()` method hook, such that we can call in `onError` callback, so that the `loading` state gets reset correctly.","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":299,"estimatedTokens":1154}}158{"id":"stack-41515679","source":"stackoverflow","questionId":41515679,"title":"Can you make a graphql type both an input and output type?","tags":["graphql","graphql-js"],"text":"Title: Can you make a graphql type both an input and output type?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have some object types that I'd like to use as both input and output - for instance a currency type or a reservation type.\n\nHow do I define my schema to have a type that supports both input and output - I don't want to duplicate code if I don't have to. I'd also prefer not to create duplicate input types of things like currency and status enums.\n\n```\nexport const ReservationInputType = new InputObjectType({\n name: 'Reservation',\n fields: {\n hotelId: { type: IntType },\n rooms: { type: new List(RoomType) },\n totalCost: { type: new NonNull(CurrencyType) },\n status: { type: new NonNull(ReservationStatusType) },\n },\n});\n\nexport const ReservationType = new ObjectType({\n name: 'Reservation',\n fields: {\n hotelId: { type: IntType },\n rooms: { type: new List(RoomType) },\n totalCost: { type: new NonNull(CurrencyType) },\n status: { type: new NonNull(ReservationStatusType) },\n },\n});\n```\n\n========================================\n\nTop Answer:\nWhile working on a project I had a similar problem with code duplication between `input` and `type` objects. I did not find the `extend` keyword very helpful as it only extended the fields of that specific type. So the fields in `type` objects cannot not be inherited in `input` objects.\n\nIn the end I found this pattern using literal expressions helpful:\n\n```\nconst UserType = `\n name: String!,\n surname: String!\n`;\n\nconst schema = graphql.buildSchema(`\n type User {\n ${UserType}\n }\n input InputUser {\n ${UserType}\n }\n`)\n```\n\n========================================\n\nCode:\n```text\nexport const ReservationInputType = new InputObjectType({\n name: 'Reservation',\n fields: {\n hotelId: { type: IntType },\n rooms: { type: new List(RoomType) },\n totalCost: { type: new NonNull(CurrencyType) },\n status: { type: new NonNull(ReservationStatusType) },\n },\n});\n\nexport const ReservationType = new ObjectType({\n name: 'Reservation',\n fields: {\n hotelId: { type: IntType },\n rooms: { type: new List(RoomType) },\n totalCost: { type: new NonNull(CurrencyType) },\n status: { type: new NonNull(ReservationStatusType) },\n },\n});\n```\n\n```text\nReservation\n```\n\n```text\nReservationInput\n```\n\n```js\nexport const createTypes = ({name, fields}) => {\n return {\n inputType: new InputObjectType({name: `${name}InputType`, fields}),\n objectType: new ObjectType({name: `${name}ObjectType`, fields})\n };\n};\n\nconst reservation = createTypes({\n name: \"Reservation\",\n fields: () => ({\n hotelId: { type: IntType },\n rooms: { type: new List(RoomType) },\n totalCost: { type: new NonNull(CurrencyType) },\n status: { type: new NonNull(ReservationStatusType) }\n })\n});\n// now you can use:\n// reservation.inputType\n// reservation.objectType\n```\n\n```text\nconst RelativeTemplate = name => {\n return {\n name: name,\n fields: () => ({\n name: { type: GraphQLString },\n reference: { type: GraphQLString }\n })\n };\n};\nconst RelativeType = {\n input: new GraphQLInputObjectType(RelativeTemplate(\"RelativeInput\")),\n output: new GraphQLObjectType(RelativeTemplate(\"RelativeOutput\"))\n};\n```\n\n```text\nconst UserType = `\n name: String!,\n surname: String!\n`;\n\nconst schema = graphql.buildSchema(`\n type User {\n ${UserType}\n }\n input InputUser {\n ${UserType}\n }\n`)\n```\n\n```text\ninput\n```\n\n```text\ntype\n```\n\n```text\nextend\n```\n\n```text\ntype\n```\n\n```text\ninput\n```\n\n========================================\n\nComments:\n- where is it stated that about the separate names for type and input?\n- @4F2E4A2E: Well, the section of the specification that I quoted covers this (Object versus Input Object).\n- @4F2E4A2E: \"it is possible to have both definitions with the same name but with different types, right?\" -- not to the best of my knowledge. Symbols have to be unique in most programming languages.\n- Thanks, i've tested it out, it's clearly not possible. @MonkeyBonkey: don't forget to mark this as answered.\n- That this is not possible is a major flaw from a developer perspective. I hope they had a good reason to set it up like this. Leads to very WET code.\n- \"All types within a GraphQL schema must have unique names. No two provided types may have the same name.\" GraphQL / Schema\n- I upvoted for the idea, but very hacky in my opinion\n- won't work if the shared fields are non scalar fields :(\n- This is the best solution I think. Personally though I prefer to use a file.graphql because its distinctive and removes complication. I think the creators of graphql should be working on a solution to the data between type and input via a variable type.\n- @SteveTomlin do you know how to solve it in .graphql files? I can't find any reference\n- Sure. An example: import * as schemaGame from './_game.graphql';","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":175,"estimatedTokens":1209}}159{"id":"stack-62760975","source":"stackoverflow","questionId":62760975,"title":"graphqlHTTP is not a function","tags":["javascript","node.js","express","graphql","express-graphql"],"text":"Title: graphqlHTTP is not a function\nTags: javascript, node.js, express, graphql, express-graphql\nSource: Stack Overflow\n\nQuestion:\nHere is my simple graphql express app\n\n```\nconst express = require('express');\nconst graphqlHTTP = require('express-graphql');\n\nconst app = express();\napp.use(\n '/graphql',\n graphqlHTTP({\n graphiql: true,\n })\n );\n\napp.listen(4000, () => {\n console.log(\"listening for request!\");\n});\n```\n\nI'm getting the following errors when I run it:\n\n```\ngraphqlHTTP({\n ^\n\nTypeError: graphqlHTTP is not a function\n at Object. (D:\\PersonalProjects\\GraphQL\\server\\app.js:7:5)\n at Module._compile (internal/modules/cjs/loader.js:1138:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)\n at Module.load (internal/modules/cjs/loader.js:986:32)\n at Function.Module._load (internal/modules/cjs/loader.js:879:14)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) \n at internal/main/run_main_module.js:17:47\n```\n\nHow can I fix it\n\n========================================\n\nTop Answer:\nQuentin's answer was on spot. Apparently the npm documentation was updated but some of the tutorials on YouTube were not. That's why there's a certain degree of confusion for learners like myself.\nThere are still outdated versions of the code like\n\nThis one: https://github.com/iamshaunjp/graphql-playlist/blob/lesson-36/server/app.js\n\nThis one: https://github.com/WebDevSimplified/Learn-GraphQL/blob/master/server.js\n\nOr this one: https://github.com/bradtraversy/customerbase/blob/master/server.js\n\nThey should all be updated to\n\n```\nconst { graphqlHTTP } = require('express-graphql');\n```\n\nand then\n\n```\napp.use('/graphql', graphqlHTTP({\n schema:schema,\n graphiql:true\n}));\n```\n\n========================================\n\nCode:\n```text\nconst express = require('express');\nconst graphqlHTTP = require('express-graphql');\n\nconst app = express();\napp.use(\n '/graphql',\n graphqlHTTP({\n graphiql: true,\n })\n );\n\napp.listen(4000, () => {\n console.log(\"listening for request!\");\n});\n```\n\n```text\ngraphqlHTTP({\n ^\n\nTypeError: graphqlHTTP is not a function\n at Object.<anonymous> (D:\\PersonalProjects\\GraphQL\\server\\app.js:7:5)\n at Module._compile (internal/modules/cjs/loader.js:1138:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)\n at Module.load (internal/modules/cjs/loader.js:986:32)\n at Function.Module._load (internal/modules/cjs/loader.js:879:14)\n at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) \n at internal/main/run_main_module.js:17:47\n```\n\n```text\nconst { graphqlHTTP } = require('express-graphql');\n```\n\n```text\nconst graphqlHTTP = require('express-graphql').graphqlHTTP;\n```\n\n```text\nrequire('express-graphql')\n```\n\n```text\ngraphqlHTTP\n```\n\n```text\nconst { graphqlHTTP } = require('express-graphql');\n```\n\n```text\napp.use('/graphql', graphqlHTTP({\n schema:schema,\n graphiql:true\n}));\n```\n\n```text\nconst gqlHTTP = require('express-graphql');\n\napp.use('/graphql', gqlHTTP.graphqlHTTP({\n // something\n}))\n```\n\n```text\napp.use('/graphql', graphqlHTTP({\n // your config\n}));\n```\n\n```text\nconst graphqlServer = require('express-graphql');\n```\n\n```text\nconst { graphqlHTTP } = require('express-graphql');\n```\n\n```js\nconst express = require('express');\nconst { graphqlHTTP } = require('express-graphql');\n \nconst app = express();\n \napp.use(\n '/graphql',\n graphqlHTTP({\n schema: MyGraphQLSchema,\n graphiql: true,\n }),\n);\n \napp.listen(4000, () => {\n console.log('Server is running on port 4K')\n);\n```\n\n```text\nvar graphqlHTTP = require('express-graphql');\n```\n\n```text\nvar { graphqlHTTP } = require('express-graphql');\n```\n\n```text\nexpress-graphql\n```\n\n```js\nconst { graphqlHTTP } = require('express-graphql');\n```\n\n========================================\n\nComments:\n- Thanks. This was really helpful. I hit this error while following a GraphQL in 40 minutes video tutorial dated Mar 2, 2019.","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":191,"estimatedTokens":995}}160{"id":"stack-44564905","source":"stackoverflow","questionId":44564905,"title":"What is Over-Fetching or Under-fetching?","tags":["graphql","fetching-strategy"],"text":"Title: What is Over-Fetching or Under-fetching?\nTags: graphql, fetching-strategy\nSource: Stack Overflow\n\nQuestion:\nI've been playing sometimes with graphQL. Before graphQL, we normally use REST API. Many developers said that graphQL fixes some problems of the REST. (e.g. over-fetching & under-fetching). I confuses with this terms.\n\nCan somebody explain what is over and under fetching in this context? \n\nThanks,\n\n========================================\n\nTop Answer:\n**Over fetching** means you are fetching irrelevant variables that are useless at this point.\n**Under fetching** means you are fetching less variables that are required at this point\n\n========================================\n\nComments:\n- \"In a perfect world, these problems would never arise; you would have exactly the right endpoints to give exactly the right data to your products.\" These problems often appear when you scale and iterate on your products. Worth Highlighting.\n- GraphQL focuses talking points on not over-fetching from API perspective. \"Client gets exactly & only what they ask for\". Important to consider GraphQL \"handlers\" you've written to fetch from database. Typically we over-fetch from database, selecting all columns user might ask for, but gets trimmed down to 1 or 2 user actually requested. For \"joins\", or \"computed\" or lookup fields, we write resolvers that don't cause those database queries unless requested by the client. So GraphQL normally over-fetches by design from db. More traffic to/from db, but less back to client.\n- This question is regarding graphQL and REST, not Ruby.","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":23,"estimatedTokens":396}}161{"id":"stack-56847935","source":"stackoverflow","questionId":56847935,"title":"GraphQLError: Syntax Error: Expected Name, found","tags":["graphql","react-apollo","graphql-tag"],"text":"Title: GraphQLError: Syntax Error: Expected Name, found\nTags: graphql, react-apollo, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nI got the above error on a graphql query, I am using apollo-react by the way and using the Query component for rendering the data\n\nthis is my code\n\n```\nconst GET_VEHICLE_CHECKS = gql`\nquery getVehicleChecks($uuid: String!) {\n tripDetails(uuid: $uuid){\n departmentAssigned{\n vehicleChecks{\n conditions{\n id\n name\n standard\n valueType\n spinnerItems\n }\n }\n }\n }\n\n`;\n```\n\nand this is what my actual query looks like\n\n```\n{\n tripDetails(uuid: \"c0e7233093b14afa96f39e2b70c047d8\"){\n departmentAssigned{\n vehicleChecks{\n conditions{\n id\n name\n standard\n valueType\n spinnerItems\n }\n }\n }\n vehicleConditions{\n id\n condition{\n id\n standard\n }\n value\n }\n }\n}\n```\n\nI tried changing variable names, but that didn't work\n\n========================================\n\nTop Answer:\nThis error message is usually cause by a missing `{` or a missing `(` so look for that in your query also look for stray/missing `:`\n\nIt could be that your query is empty which will give you the EOF error as well\n\n========================================\n\nCode:\n```text\nconst GET_VEHICLE_CHECKS = gql`\nquery getVehicleChecks($uuid: String!) {\n tripDetails(uuid: $uuid){\n departmentAssigned{\n vehicleChecks{\n conditions{\n id\n name\n standard\n valueType\n spinnerItems\n }\n }\n }\n }\n\n`;\n```\n\n```text\n{\n tripDetails(uuid: \"c0e7233093b14afa96f39e2b70c047d8\"){\n departmentAssigned{\n vehicleChecks{\n conditions{\n id\n name\n standard\n valueType\n spinnerItems\n }\n }\n }\n vehicleConditions{\n id\n condition{\n id\n standard\n }\n value\n }\n }\n}\n```\n\n```text\nconst GET_VEHICLE_CHECKS = gql`\nquery getVehicleChecks($uuid: String!) {\n tripDetails(uuid: $uuid){\n departmentAssigned{\n vehicleChecks{\n conditions{\n id\n name\n standard\n valueType\n spinnerItems\n }\n }\n }\n }\n} <- THIS\n`;\n```\n\n```text\n}\n```\n\n```text\n{\n```\n\n```text\n(\n```\n\n```text\n:\n```\n\n========================================\n\nComments:\n- This was the answer for me. Too bad the person writing this error message didnt have the sense to make a descriptive message. EOF is vague and someone really shouldnt need to do look up what it means to understand.\n- @EricAya My answer is more general and applicable then the accepted. Plus it adds more information","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":156,"estimatedTokens":639}}162{"id":"stack-37337466","source":"stackoverflow","questionId":37337466,"title":"How do you prevent nested attack on GraphQL/Apollo server?","tags":["graphql","graphql-js","apollo"],"text":"Title: How do you prevent nested attack on GraphQL/Apollo server?\nTags: graphql, graphql-js, apollo\nSource: Stack Overflow\n\nQuestion:\nHow do you prevent a nested attack against an Apollo server with a query such as:\n\n```\n{\n authors {\n firstName\n posts {\n title\n author {\n firstName\n posts{\n title\n author {\n firstName\n posts {\n title\n [n author]\n [n post]\n }\n }\n }\n }\n }\n }\n}\n```\n\nIn other words, how can you limit the number of recursions being submitted in a query? This could be a potential server vulnerability.\n\n========================================\n\nTop Answer:\nTo supplement point (4) in stubailo's answer, here are some Node.js implementations that impose *cost and depth bounds* on incoming GraphQL documents.\n\n- graphql-depth-limit\n\n- graphql-validation-complexity\n\n- graphql-query-complexity\n\nThese are custom rules that supplement the validation phase.\n\n========================================\n\nCode:\n```text\n{\n authors {\n firstName\n posts {\n title\n author {\n firstName\n posts{\n title\n author {\n firstName\n posts {\n title\n [n author]\n [n post]\n }\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Excellent response. Do you know of any tooling that can detect circular dependencies in GraphQL? I would also stress that another big concern is memory exhaustion. Each level deeper in a Posts -> Author -> Post hierarchy is a multiplier (i.e. 1 author with 5 posts -> 5 authors with 25 posts -> 25 authors with 125 posts, etc) that compounds not just SQL/query to the underlying data source, but heap allocation to send back the response. A few levels deep can easily deplete a few GB of RAM and crash the server entirely. 1 query could take out V8!\n- I think this is where (2) and (3) would help. First, you can simply limit the amount of requests to the database a single query can do (kind of like a timeout). Second, you can have your server accept only pre-approved queries in production, see here for more details: dev-blog.apollodata.com/…\n- Note: GraphQL Ruby has built in analyzers for query depth and complexity. I'm not sure about the implementations for other languages. graphql-ruby.org/queries/analysis.html\n- Doesn't this kill the flexibility of GraphQL and sets it at the level of a regular HTTP request?\n- I don't think so, but if you elaborate on which flexibility you have in mind, others will be better able to answer your question.\n- I mean that you can choose what entities and properties you want to get.\n- I've expanded my answer to hopefully address your concerns.\n- But I don't mean dynamic interpolated queries, but a new client wants to use a new query and they have to report it to the API so it whitelists it?","metadata":{"transformedAt":"2026-08-18T18:32:36.033Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":86,"estimatedTokens":709}}163{"id":"stack-49693928","source":"stackoverflow","questionId":49693928,"title":"Date and Json in type definition for graphql","tags":["graphql","apollo"],"text":"Title: Date and Json in type definition for graphql\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nIs it possible to have a define a field as Date or JSON in my graphql schema ?\n\n```\ntype Individual {\n id: Int\n name: String\n birthDate: Date\n token: JSON\n}\n```\n\nactually the server is returning me an error saying : \n\n```\nType \"Date\" not found in document.\nat ASTDefinitionBuilder._resolveType (****node_modules\\graphql\\utilities\\buildASTSchema.js:134:11)\n```\n\nAnd same error for JSON...\n\nAny idea ?\n\n========================================\n\nTop Answer:\nPrimitive scalar types in GraphQL are `Int`, `Float`, `String`, `Boolean` and `ID`. For `JSON` and `Date` you need to define your own custom scalar types, the documentation is pretty clear on how to do this.\n\nIn your schema you have to add:\n\n```\nscalar Date\n\ntype MyType {\n created: Date\n}\n```\n\nThen, in your code you have to add the type implementation:\n\n```\nimport { GraphQLScalarType } from 'graphql';\n\nconst dateScalar = new GraphQLScalarType({\n name: 'Date',\n parseValue(value) {\n return new Date(value);\n },\n serialize(value) {\n return value.toISOString();\n },\n})\n```\n\nFinally, you have to include this custom scalar type in your resolvers:\n\n```\nconst server = new ApolloServer({\n typeDefs,\n resolvers: {\n Date: dateScalar,\n // Remaining resolvers..\n },\n});\n```\n\nThis `Date` implementation will parse any string accepted by the `Date` constructor, and will return the date as a string in ISO format.\n\nFor `JSON` you might use `graphql-type-json` and import it as shown here.\n\n========================================\n\nCode:\n```text\ntype Individual {\n id: Int\n name: String\n birthDate: Date\n token: JSON\n}\n```\n\n```text\nType \"Date\" not found in document.\nat ASTDefinitionBuilder._resolveType (****node_modules\\graphql\\utilities\\buildASTSchema.js:134:11)\n```\n\n```text\nscalar Date\n \ntype MyType {\n created: Date\n}\n```\n\n```js\nimport { GraphQLScalarType } from 'graphql';\nimport { Kind } from 'graphql/language';\n\nconst resolverMap = {\n Date: new GraphQLScalarType({\n name: 'Date',\n description: 'Date custom scalar type',\n parseValue(value) {\n return new Date(value); // value from the client\n },\n serialize(value) {\n return value.getTime(); // value sent to the client\n },\n parseLiteral(ast) {\n if (ast.kind === Kind.INT) {\n return parseInt(ast.value, 10); // ast value is always in string format\n }\n return null;\n },\n })\n};\n```\n\n```text\nscalar Date\n\ntype MyType {\n created: Date\n}\n```\n\n```js\nimport { GraphQLScalarType } from 'graphql';\n\nconst dateScalar = new GraphQLScalarType({\n name: 'Date',\n parseValue(value) {\n return new Date(value);\n },\n serialize(value) {\n return value.toISOString();\n },\n})\n```\n\n```js\nconst server = new ApolloServer({\n typeDefs,\n resolvers: {\n Date: dateScalar,\n // Remaining resolvers..\n },\n});\n```\n\n```text\nInt\n```\n\n```text\nFloat\n```\n\n```text\nString\n```\n\n```text\nBoolean\n```\n\n```text\nID\n```\n\n```text\nJSON\n```\n\n```text\nDate\n```\n\n```text\nDate\n```\n\n```text\nDate\n```\n\n```text\nJSON\n```\n\n```text\ngraphql-type-json\n```\n\n```text\nscalar DateTime\n```\n\n```text\nimport { DateTimeResolver} from 'graphql-scalars'\n\nexport const resolvers = {\n DateTime: DateTimeResolver,\n\n Query: {\n ...\n },\n ...\n};\n```\n\n```text\ntype Post {\n id: ID!\n title: String!\n content: String!\n createdAt: DateTime!\n updatedAt: DateTime!\n}\n```\n\n```text\ngraphql-scalars\n```\n\n```text\nresolvers\n```\n\n```text\nimport\n```\n\n```text\nDateTime\n```\n\n```text\nDateTime\n```\n\n========================================\n\nComments:\n- While the solutions given in this thread is appetizing and complete. I have seen that when you are using adapters like github.com/Soluto/graphql-to-mongodb - then we cannot create our own types - so in that situation I directly store dates as time in millis within DB and utilize float type. js had (new Date()).getTime() to assist and use resolver to have it convert to required date format as string wherever needed - new Date(1324339200000); date.toString(\"MMM dd\");\n- how is the query in that example?. 10.02.1993??\n- Just wanted to mentioned that this snippet only works when the date you pass is a number. \"2020-01-01\" for example, although a valid date, won't be parsed as it only does so expecting a number.","metadata":{"transformedAt":"2026-08-18T18:32:36.034Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":252,"estimatedTokens":1097}}164{"id":"stack-44403930","source":"stackoverflow","questionId":44403930,"title":"Error: Network error: Error writing result to store for query (Apollo Client)","tags":["javascript","graphql","react-apollo","apollo-client"],"text":"Title: Error: Network error: Error writing result to store for query (Apollo Client)\nTags: javascript, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am using Apollo Client to make an application to query my server using Graphql. I have a python server on which I execute my graphql queries which fetches data from the database and then returns it back to the client. \n\nI have created a custom NetworkInterface for the client that helps me to make make customized server request (by default ApolloClient makes a POST call to the URL we specify). The network interface only has to have a query() method wherein we return the promise for the result of form `Promise`. \n\nI am able to make the server call and fetch the requested data but still getting the following error.\n\n```\nError: Network error: Error writing result to store for query \n{\n query something{\n row{\n data\n }\n }\n}\nCannot read property 'row' of undefined\n at new ApolloError (ApolloError.js:32)\n at ObservableQuery.currentResult (ObservableQuery.js:76)\n at GraphQL.dataForChild (react-apollo.browser.umd.js:410)\n at GraphQL.render (react-apollo.browser.umd.js:448)\n at ReactCompositeComponent.js:796\n at measureLifeCyclePerf (ReactCompositeComponent.js:75)\n at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)\n at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)\n at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:746)\n at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)\n at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)\n at ReactCompositeComponentWrapper.performUpdateIfNecessary (ReactCompositeComponent.js:561)\n at Object.performUpdateIfNecessary (ReactReconciler.js:157)\n at runBatchedUpdates (ReactUpdates.js:150)\n at ReactReconcileTransaction.perform (Transaction.js:140)\n at ReactUpdatesFlushTransaction.perform (Transaction.js:140)\n at ReactUpdatesFlushTransaction.perform (ReactUpdates.js:89)\n at Object.flushBatchedUpdates (ReactUpdates.js:172)\n at ReactDefaultBatchingStrategyTransaction.closeAll (Transaction.js:206)\n at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:153)\n at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)\n at Object.enqueueUpdate (ReactUpdates.js:200)\n```\n\nI want to know the possible cause of the error and solution if possible.\n\n========================================\n\nTop Answer:\nwe need to include `id`,\notherwise it will cause the mentioned error.\n\n```\n{\n query something {\n id\n row {\n id\n data\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nError: Network error: Error writing result to store for query \n{\n query something{\n row{\n data\n }\n }\n}\nCannot read property 'row' of undefined\n at new ApolloError (ApolloError.js:32)\n at ObservableQuery.currentResult (ObservableQuery.js:76)\n at GraphQL.dataForChild (react-apollo.browser.umd.js:410)\n at GraphQL.render (react-apollo.browser.umd.js:448)\n at ReactCompositeComponent.js:796\n at measureLifeCyclePerf (ReactCompositeComponent.js:75)\n at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)\n at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)\n at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:746)\n at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)\n at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)\n at ReactCompositeComponentWrapper.performUpdateIfNecessary (ReactCompositeComponent.js:561)\n at Object.performUpdateIfNecessary (ReactReconciler.js:157)\n at runBatchedUpdates (ReactUpdates.js:150)\n at ReactReconcileTransaction.perform (Transaction.js:140)\n at ReactUpdatesFlushTransaction.perform (Transaction.js:140)\n at ReactUpdatesFlushTransaction.perform (ReactUpdates.js:89)\n at Object.flushBatchedUpdates (ReactUpdates.js:172)\n at ReactDefaultBatchingStrategyTransaction.closeAll (Transaction.js:206)\n at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:153)\n at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)\n at Object.enqueueUpdate (ReactUpdates.js:200)\n```\n\n```text\nPromise<ExecutionResult>\n```\n\n```text\nquery {\n service:me {\n productServices {\n id\n title\n }\n }\n}\n```\n\n```text\nquery {\n service:me {\n id // <-------\n productServices {\n id\n title\n }\n }\n}\n```\n\n```text\n// Apollo option object for `mutation AddPlayer`\nupdate: (store, response) => {\n const addr = { query: gql(QUERY_TEAM), variables: { _id } };\n const data = store.readQuery(addr);\n stored.teams.players.push(response.data.player));\n store.writeQuery({...addr, data});\n}\n```\n\n```text\n// Apollo option object for `mutation AddPlayer`\nupdate: (store, response) => {\n const addr = { query: gql(QUERY_TEAM), variables: { _id, meta: null } };\n const data = store.readQuery(addr);\n data.teams.players.push(response.data.player));\n store.writeQuery({...addr, data});\n}\n```\n\n```text\nexports.writeResultToStore = writeResultToStore;\nfunction writeSelectionSetToStore(_a) {\n\n var result = _a.result, dataId = _a.dataId, selectionSet = _a.selectionSet, context = _a.context;\n var variables = context.variables, store = context.store, fragmentMap = context.fragmentMap;\n\n +if (typeof result === 'undefined') {\n + debugger;\n +}\n```\n\n```text\nplayer\n```\n\n```text\nteam\n```\n\n```text\nQUERY_TEAM\n```\n\n```text\nmeta\n```\n\n```text\nnull\n```\n\n```text\naddr\n```\n\n```text\nundefined\n```\n\n```text\nnull\n```\n\n```text\nnode_modules/apollo-cache-inmemory/lib/writeToStore.js\n```\n\n```text\n_a\n```\n\n```text\napollo-cache-inmemory\n```\n\n```text\napollo-cache-hermes\n```\n\n```text\napollo-cache-inmemory\n```\n\n```text\napollo-cache-inmemory\n```\n\n```text\napollo-cache-inmemory\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\n{\n query something {\n id\n row {\n id\n data\n }\n }\n}\n```\n\n```text\nid\n```\n\n```text\nquery dog(){id, name}\nquery cat(){id, name }\n```\n\n========================================\n\nComments:\n- what is `{ query something{ row{ data } } }` supposed to be?\n- It is the graphql query that specifies the data required by the component\n- whenever you use \"fetchPolicy={\"cache-and-network\"}\", you must include \"id\" for each graphql object. { query something { id row { \" id\" data } } }\n- Thanks for explaining the root cause of the issue. Adding `id` to the query to make it consistent with other queries I have solved the problem for me.\n- Genius hermes did the job github.com/convoyinc/apollo-cache-hermes\n- It worked for me... This one saved me a lot","metadata":{"transformedAt":"2026-08-18T18:32:36.034Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":259,"estimatedTokens":1715}}165{"id":"stack-36691554","source":"stackoverflow","questionId":36691554,"title":"Graphql post body \"Must provide query string.\"","tags":["express","graphql","postman","graphql-js"],"text":"Title: Graphql post body \"Must provide query string.\"\nTags: express, graphql, postman, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI use Express-graphql middleware.\nI send the following request in the body line:\n\n```\nPOST /graphql HTTP/1.1\nHost: local:8083\nContent-Type: application/graphql\nCache-Control: no-cache\nPostman-Token: d71a7ea9-5502-d5fe-2e36-0ae49c635a29\n\n{\n testing {\n pass(id: 1) {\n idn\n }\n }\n}\n```\n\nand have error\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Must provide query string.\"\n }\n ]\n}\n```\n\nin graphql i can send update in URL.\n\nURL string is too short. i must send update model like\n\n```\nmutation {\n update(id: 2, x1: \"zazaza\", x2: \"zazaza\", x3: \"zazaza\" ...(more more fields)...) {\n idn\n }\n}\n```\n\nI think its must be in request body. How can I send 'update' query or that I'm doing wrong?\n\n========================================\n\nTop Answer:\nIf you are using graphql and want to test it using postman or any other HTTP client, you can do this.\n\nIn postman, select `POST` method and enter your `URL` and set `Content-Type` as `application/graphql` then pass your query in the body.\n\nExample:\n\n```\nhttp://localhost:8080/graphql\nMethod: POST\nContent-Type: application/graphql\nBody: \n query{\n FindAllGames{\n _id\n title\n company\n price\n year\n url\n }\n }\n```\n\nThat's it, you will get the response.\n\nhttps://i.sstatic.net/QHAu6.png\n\n========================================\n\nCode:\n```text\nPOST /graphql HTTP/1.1\nHost: local:8083\nContent-Type: application/graphql\nCache-Control: no-cache\nPostman-Token: d71a7ea9-5502-d5fe-2e36-0ae49c635a29\n\n{\n testing {\n pass(id: 1) {\n idn\n }\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Must provide query string.\"\n }\n ]\n}\n```\n\n```text\nmutation {\n update(id: 2, x1: \"zazaza\", x2: \"zazaza\", x3: \"zazaza\" ...(more more fields)...) {\n idn\n }\n}\n```\n\n```text\n{\"query\":\"mutation{update(id:1,x1:\\\"zazaz\\\",x2:\\\"zazaz\\\"......){id x1 x2}}\"}\n```\n\n```text\nContent-Type\n```\n\n```text\napplication/json\n```\n\n```text\nContent-Type\n```\n\n```text\napplication/graphql\n```\n\n```text\nhttp://localhost:8080/graphql\nMethod: POST\nContent-Type: application/graphql\nBody: \n query{\n FindAllGames{\n _id\n title\n company\n price\n year\n url\n }\n }\n```\n\n```text\nPOST\n```\n\n```text\nURL\n```\n\n```text\nContent-Type\n```\n\n```text\napplication/graphql\n```\n\n```text\napplication/json\n```\n\n```sh\nnpm install body-parser\n```\n\n```text\nconst bodyParser = require('body-parser');\n\napp.use(bodyParser.json()); // application/json\n```\n\n```text\ncontent-type\n```\n\n```text\nraw\n```\n\n```text\njson\n```\n\n```text\ngraphql\n```\n\n========================================\n\nComments:\n- \"in graphql i can send update in URL.\" <-- Do you mean `graphiql`?\n- i'm use \"postman\" to send request.\n- you need to change \"Content type\" in postman's headers to \"application/json\" and in request body use \"GraphQL\" tab with \"query\" and \"graphql variables\"\n- what is that request tester you are using?\n- Please provide some comment for your answer.\n- its not JSON. its only \"query\" : \"graphQL query string\", its not correct. We must send valid JSON but cant do this\n- where the hell does bodyParser come from, common, be thorough here, what lib?\n- @PositiveGuy, you can `npm install body-parser --save` and then `import bodyParser from 'body-parser'`;\n- you saved my day!\n- POST was what I was missing on mine. Thanks - saved the day for me too!\n- This works fine and should be the easiest!!!\n- Thanks, your menthod helped me to find a root cause of the issue: stackoverflow.com/a/73788400/3722635","metadata":{"transformedAt":"2026-08-18T18:32:36.034Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":215,"estimatedTokens":882}}166{"id":"stack-47211778","source":"stackoverflow","questionId":47211778,"title":"Cleaning Unwanted Fields From GraphQL Responses","tags":["javascript","ecmascript-6","graphql"],"text":"Title: Cleaning Unwanted Fields From GraphQL Responses\nTags: javascript, ecmascript-6, graphql\nSource: Stack Overflow\n\nQuestion:\nI have an object that my GraphQL client requests.\n\nIt's a reasonably simple object:\n\n```\ntype Element {\n content: [ElementContent]\n elementId: String\n name: String\n notes: String\n type: String\n createdAt: String\n updatedAt: String\n }\n```\n\nWith the special type `ElementContent`, which is tiny and looks like this:\n\n```\ntype ElementContent {\n content: String\n locale: String\n }\n```\n\nNow, when I query this on the clientside, both the top level object and the lower level object has additional properties (which interfere with updating the object if I attempt to clone the body exactly-as-is);\n\nNotably, GraphQL seems to supply a `__typename` property in the parent object, and in the child objects, they have typename and a `Symbol(id)` property as well.\n\nhttps://i.sstatic.net/ZFxO6.png\n\nI'd love to copy this object to state, update in state, then clone the state and ship it to my `update` mutation. However, I get roadblocked because of unknown properties that GraphQL itself supplies.\n\nI've tried doing:\n\n`delete element.__typename` to good effect, but then I also need to loop through the children (a dynamic array of objects), and likely have to remove those properties as well.\n\nI'm not sure if I'm missing something during this equation, or I should just struggle through the code and loop + delete (I received errors attempting to do a forEach loop initially). Is there a better strategy for what I'm attempting to do? Or am I on the right path and just need some good loop code to clean unwanted properties?\n\n========================================\n\nTop Answer:\nIf you want to wipe up `__typename` from GraphQL response (from the root and its children), you can use graphql-anywhere package.\n\nSomething like:\n`const wipedData = filter(inputFragment, rcvData);`\n\n- `inputFragment` is a fragment defines the fields (You can see details here)\n\n- `rcvData` is the received data from GraphQL query\n\nBy using the `filter` function, the `wipedData` includes only required fields you need to pass as mutation input.\n\n========================================\n\nCode:\n```text\ntype Element {\n content: [ElementContent]\n elementId: String\n name: String\n notes: String\n type: String\n createdAt: String\n updatedAt: String\n }\n```\n\n```text\ntype ElementContent {\n content: String\n locale: String\n }\n```\n\n```text\nElementContent\n```\n\n```text\n__typename\n```\n\n```text\nSymbol(id)\n```\n\n```text\nupdate\n```\n\n```text\ndelete element.__typename\n```\n\n```js\napollo.create({\n link: http,\n cache: new InMemoryCache({\n addTypename: false\n })\n});\n```\n\n```text\nconst cleanTypeName = new ApolloLink((operation, forward) => {\n if (operation.variables) {\n\n operation.variables = omitDeep(operation.variables,'__typename')\n }\n return forward(operation).map((data) => {\n return data;\n });\n});\n```\n\n```text\nconst cleanTypeName = new ApolloLink((operation, forward) => {\n if (operation.variables) {\n const omitTypename = (key, value) => (key === '__typename' ? undefined : value);\n operation.variables = JSON.parse(JSON.stringify(operation.variables), omitTypename);\n }\n return forward(operation).map((data) => {\n return data;\n });\n});\n```\n\n```text\nconst httpLinkWithErrorHandling = ApolloLink.from([\n cleanTypeName,\n retry,\n error,\n http,\n]);\n```\n\n```text\n__typename\n```\n\n```text\nconst wipedData = filter(inputFragment, rcvData);\n```\n\n```text\ninputFragment\n```\n\n```text\nrcvData\n```\n\n```text\nfilter\n```\n\n```text\nwipedData\n```\n\n```text\nimport { parse, stringify } from 'flatted';\n\nconst cleanTypename = new ApolloLink((operation, forward) => {\n const omitTypename = (key, value) => (key === '__typename' ? undefined : value);\n\n if ((operation.variables && !operation.getContext().hasUpload)) {\n operation.variables = parse(stringify(operation.variables), omitTypename);\n }\n\n return forward(operation);\n});\n```\n\n```text\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { createUploadLink } from 'apollo-upload-client';\nimport { ApolloClient } from 'apollo-client';\nimport { setContext } from 'apollo-link-context';\nimport { ApolloLink } from 'apollo-link';\n\nconst authLink = setContext((_, { headers }) => {\n const token = localStorage.getItem(AUTH_TOKEN);\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${ token }` : '',\n },\n };\n});\n\n\n\nconst httpLink = ApolloLink.from([\n cleanTypename,\n authLink.concat(upLoadLink),\n]);\n\nconst client = new ApolloClient({\n link: httpLink,\n cache,\n});\n\nexport default client;\n```\n\n```text\nUpdateStation({variables: { input: station }, context: {hasUpload: true }}).then()\n```\n\n```text\n__typename\n```\n\n```text\nclient.tsx\n```\n\n```text\nhasUpload\n```\n\n```text\nimport cloneDeepWith from \"lodash/cloneDeepWith\";\n\nexport const omitTypenameDeep = (\n variables: Record<string, unknown>\n): Record<string, unknown> =>\n cloneDeepWith(variables, (value) => {\n if (value && value.__typename) {\n const { __typename, ...valWithoutTypename } = value;\n return valWithoutTypename;\n }\n\n return undefined;\n });\n```\n\n```text\nconst removeTypename = new ApolloLink((operation, forward) => {\n const newOperation = operation;\n newOperation.variables = omitTypenameDeep(newOperation.variables);\n return forward(newOperation);\n});\n\n// ...\n\nconst client = new ApolloClient({\n cache: new InMemoryCache(),\n link: ApolloLink.from([removeTypename, httpLink]),\n});\n```\n\n```text\nimport {filterGraphQlFragment} from 'graphql-filter-fragment';\nimport {gql} from '@apollo/client/core';\n\nconst result = filterGraphQlFragment(\n gql`\n fragment museum on Museum {\n name\n address {\n city\n }\n }\n `,\n {\n __typename: 'Museum',\n name: 'Museum of Popular Culture',\n address: {\n __typename: 'MuseumAddress',\n street: '325 5th Ave N',\n city: 'Seattle'\n }\n }\n);\n\nexpect(result).toEqual({\n name: 'Museum of Popular Culture',\n address: {\n city: 'Seattle'\n }\n});\n```\n\n```text\nconst {\n loading,\n error,\n data,\n } = useQuery(gqlRead, {\n variables: { id },\n fetchPolicy: 'network-only',\n onCompleted: (data) => {\n const { someNestedData } = data;\n const filteredData = removeTypeNameFromGQLResult(someNestedData);\n //Do sth with filteredData\n },\n });\n \n //in helper\n export const removeTypeNameFromGQLResult = (result: Record<string, any>) => {\n return JSON.parse(\n JSON.stringify(result, (key, value) => {\n if (key === '__typename') return;\n return value;\n })\n );\n };\n```\n\n```text\nconst removeAllTypenamesNoMutate = (item) => {\n if (!item) return;\n\n const recurse = (source, obj) => {\n if (!source) return;\n\n if (Array.isArray(source)) {\n for (let i = 0; i < source.length; i++) {\n const item = source[i];\n if (item !== undefined && item !== null) {\n source[i] = recurse(item, item);\n }\n }\n return obj;\n } else if (typeof source === 'object') {\n for (const key in source) {\n if (key === '__typename') continue;\n const property = source[key];\n if (Array.isArray(property)) {\n obj[key] = recurse(property, property);\n } else if (!!property && typeof property === 'object') {\n const { __typename, ...rest } = property;\n obj[key] = recurse(rest, rest);\n } else {\n obj[key] = property;\n }\n }\n const { __typename, ...rest } = obj;\n\n return rest;\n } else {\n return obj;\n }\n };\n\n return recurse(JSON.parse(JSON.stringify(item)), {});\n};\n```\n\n```text\nconst filteredObject = Object.fromEntries(\n Object.entries(props.data).filter(([key]) => key !== \"__typename\")\n );\n```\n\n========================================\n\nComments:\n- Possible duplicate of stackoverflow.com/questions/30187860/object-deep-omit\n- \"*Notably, GraphQL seems to supply a `__typename` property in the parent object, and in the child objects, they have typename and a `Symbol(id)` property as well.*\" - no, it is not GraphQL supplying these. It's your particular client. Which one are you using?\n- Sadly, it doesn't work for me, the `__typename` is not within `operation.variables`.\n- Why do you use the incidence map `data => data`?\n- @qwerty that also works. I will update it accordingly\n- @qwerty. I reverified the function this works fine also can you please the apollo config with me\n- Sorry for confusion, I was asking why do you use the `.map` that maps `data` to itself as in `.map((data) => { return data })`- I have seen it in almost every example, but I don't understand it. It does not manipulate anything in any way.\n- The first way worked for me w/ Angular8 client. Thanks!!\n- The second way shouldn't be used. `omit-deep` inserts an empty object to fields with `undefined` value which can break requests. Having a variable with `undefined` is useful when you take many values from a form with empty values and they are not required. See the existing 2 years old PR and my working example\n- First way fails for me. If you use fragment, you get an error, cause __typename is used to match node types for fragments... Any suggestions?\n- Please try second and third ways too.that resolves your issue.\n- Unfortunately this answer is not applicable to many real-life cases. First of all, the question was about GQL *responses*, and Option 2 and 3 only modify operation variables (which are sent to the server), not responses. Only option 1 would cover both (probably), but then there's another problem: when schema is deeply nested and/or uses fragments, each option breaks cache, which relies on `__typename`. Summing up, there is no good cover-all solution here. Some options may work for your case, but if you use fragments and/or cache, most surely you just need to live with `__typename`.\n- `Cannot delete property '__typename' of #` Not working for me :(\n- Can you please the code snippet you use\n- @piotr.d Have you tried something like this, where you keep the `__typename` field but just make it non-enumerable?: `const typeName = data.__typename; delete data.__typename; if (typeName) Object.defineProperty(data, \"__typename\", {value: typeName}); // defining it this way, makes the property non-enumerable`\n- This will not work if you upload a file with some variables with __typename in one request\n- Your function `omitTypenameDeep` is not correct because it won't do a deep clone (recursively). Correction: `ts const omitTypenameDeep = ( variables: Record ): Record => cloneDeepWith(variables, (value) => { if (value?.__typename) { const { __typename, ...valWithoutTypename } = value return omitTypenameDeep(valWithoutTypename) } return undefined })`\n- Using addTypename: false can cause perfomance and duplicate items in your cache so better leave it alone. Just get the data and normalize it i believe is the best way.","metadata":{"transformedAt":"2026-08-18T18:32:36.034Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":384,"estimatedTokens":2762}}167{"id":"stack-71117269","source":"stackoverflow","questionId":71117269,"title":"Validation Error: Using global entity manager instance methods for context specific actions is disallowed","tags":["node.js","typescript","graphql","mikro-orm"],"text":"Title: Validation Error: Using global entity manager instance methods for context specific actions is disallowed\nTags: node.js, typescript, graphql, mikro-orm\nSource: Stack Overflow\n\nQuestion:\nUsing MikroORM and getting this error:\n\n```\nValidationError: Using global EntityManager instance methods for context specific actions is disallowed.\nIf you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead\n```\n\nThe code that it corresponds to is below:\n\n```\nimport { MikroORM } from \"@mikro-orm/core\";\nimport { __prod__ } from \"./constants\";\nimport { Post } from \"./entities/Post\";\nimport mikroConfig from \"./mikro-orm.config\";\n\nconst main = async () => {\n const orm = await MikroORM.init(mikroConfig);\n const post = orm.em.create(Post, {\n title: \"my first post\",\n });\n await orm.em.persistAndFlush(post);\n await orm.em.nativeInsert(Post, { title: \"my first post 2\" });\n};\n\nmain().catch((error) => {\n console.error(error);\n});\n```\n\nI am unsure where I need to use the .fork() method\n\n========================================\n\nTop Answer:\n### Don't disable validations without understanding them!\n\nI can't believe what I see in the replies here. For anybody coming here, **please don't disable the validation** (either via `MIKRO_ORM_ALLOW_GLOBAL_CONTEXT` env var or via `allowGlobalContext` configuration). Disabling the validation is fine only under very specific circumstances, mainly in unit tests.\n\n*In case you don't know me, I am the one behind MikroORM, as well as the one who added this validation - for a very good reason, so please don't just disable that, it means you have a problem to solve, not that you should add one line to your configuration to shut it up.*\n\nThis validation was added to MikroORM v5 (so not typeorm, please dont confuse those two), and it means exactly what it says - you are trying to work with the global context, while you should be working with request specific one. Consult the docs for why you need request context here: https://mikro-orm.io/docs/identity-map#why-is-request-context-needed. In general using single (global) context will result in instable API response and basically a one huge memory leak.\n\nSo now we should understand why the validation is there and why we should not disable it. Next how to get around it properly.\n\nAs others mentined (and as the validation error message mentioned too), we can create fork and use that instead:\n\n```\nconst fork = orm.em.fork();\nconst res = await fork.find(...);\n```\n\nBut that would be quite tedious, in real world apps, we usually have middlewares we can use to do this for us automatically. That is where the `RequestContext` helper comes into play. It uses the `AsyncLocalStorage` under the hood and is natively supported in the ORM.\n\nFollowing text is mostly an extraction of the MikroORM docs.\n\n### How does `RequestContext` helper work?\n\nInternally all `EntityManager` methods that work with the Identity Map (e.g. `em.find()` or `em.getReference()`) first call `em.getContext()` to access the contextual fork. This method will first check if we are running inside `RequestContext` handler and prefer the `EntityManager` fork from it.\n\n```\n// we call em.find() on the global EM instance\nconst res = await orm.em.find(Book, {});\n\n// but under the hood this resolves to\nconst res = await orm.em.getContext().find(Book, {});\n\n// which then resolves to\nconst res = await RequestContext.getEntityManager().find(Book, {});\n```\n\nThe `RequestContext.getEntityManager()` method then checks `AsyncLocalStorage` static instance we use for creating new EM forks in the `RequestContext.create()` method.\n\nThe `AsyncLocalStorage` class from Node.js core is the magician here. It allows us to track the context throughout the async calls. It allows us to decouple the `EntityManager` fork creation (usually in a middleware as shown in previous section) from its usage through the global `EntityManager` instance.\n\n### Using `RequestContext` helper via middleware\n\nIf we use dependency injection container like `inversify` or the one in `nestjs` framework, it can be hard to achieve this, because we usually want to access our repositories via DI container, but it will always provide us with the same instance, rather than new one for each request.\n\nTo solve this, we can use `RequestContext` helper, that will use `node`'s `AsyncLocalStorage` in the background to isolate the request context. MikroORM will always use request specific (forked) entity manager if available, so all we need to do is to create new request context preferably as a middleware:\n\n```\napp.use((req, res, next) => {\n RequestContext.create(orm.em, next);\n});\n```\n\nWe should register this middleware as the last one just before request handlers and before any of our custom middleware that is using the ORM. There might be issues when we register it before request processing middleware like `queryParser` or `bodyParser`, so definitely register the context after them.\n\nLater on we can then access the request scoped `EntityManager` via `RequestContext.getEntityManager()`. This method is used under the hood automatically, so we should not need it.\n\n`RequestContext.getEntityManager()` will return `undefined` if the context was not started yet.\n\n### Simple usage without the helper\n\nNow your example code from the OP is very basic, for that forking seems like the easiest thing to do, as its very bare bones, you dont have any web server there, so no middlewares:\n\n```\nconst orm = await MikroORM.init(mikroConfig);\nconst emFork = orm.em.fork(); // But we can use the `RequestContext` here too, to demonstrate how it works:\n\n```\nconst orm = await MikroORM.init(mikroConfig);\n// run things in the `RequestContext` handler\n\nawait RequestContext.createAsync(orm.em, async () => {\n // inside this handler the `orm.em` will actually use the contextual fork, created via `RequestContext.createAsync()`\n const post = orm.em.create(Post, {\n title: \"my first post\",\n });\n await orm.em.persistAndFlush(post);\n await orm.em.nativeInsert(Post, { title: \"my first post 2\" });\n});\n```\n\n### The `@UseRequestContext()` decorator\n\nThe `@UseRequestContext()` has been renamed to `@CreateRequestContext()` in v6, which also adds a new `@EnsureRequestContext()` decorator - the difference being the latter only ensures there is a non-global context, while the former always creates a new context.\n\nMiddlewares are executed only for regular HTTP request handlers, what if we need\na request scoped method outside that? One example of that is queue handlers or\nscheduled tasks (e.g. CRON jobs).\n\nWe can use the `@UseRequestContext()` decorator. It requires us to first inject the\n`MikroORM` instance to current context, it will be then used to create the context\nfor us. Under the hood, the decorator will register new request context for our\nmethod and execute it inside the context.\n\nThis decorator will wrap the underlying method in `RequestContext.createAsync()` call. Every call to such method will create new context (new `EntityManager` fork) which will be used inside.\n\n`@UseRequestContext()` should be used only on the top level methods. It should not be nested - a method decorated with it should not call another method that is also decorated with it.\n\n```\n@Injectable()\nexport class MyService {\n\n constructor(private readonly orm: MikroORM) { }\n\n @UseRequestContext()\n async doSomething() {\n // this will be executed in a separate context\n }\n\n}\n```\n\nAlternatively we can provide a callback that will return the `MikroORM` instance.\n\n```\nimport { DI } from '..';\n\nexport class MyService {\n\n @UseRequestContext(() => DI.orm)\n async doSomething() {\n // this will be executed in a separate context\n }\n\n}\n```\n\nNote that this is not a universal workaround, you should not blindly put the decorator everywhere - its actually the opposite, it should be used only for a very specific use case like CRON jobs, in other contexts where you can use middlewares this is not needed at all.\n\n========================================\n\nCode:\n```text\nValidationError: Using global EntityManager instance methods for context specific actions is disallowed.\nIf you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead\n```\n\n```text\nimport { MikroORM } from \"@mikro-orm/core\";\nimport { __prod__ } from \"./constants\";\nimport { Post } from \"./entities/Post\";\nimport mikroConfig from \"./mikro-orm.config\";\n\nconst main = async () => {\n const orm = await MikroORM.init(mikroConfig);\n const post = orm.em.create(Post, {\n title: \"my first post\",\n });\n await orm.em.persistAndFlush(post);\n await orm.em.nativeInsert(Post, { title: \"my first post 2\" });\n};\n\nmain().catch((error) => {\n console.error(error);\n});\n```\n\n```text\nconst post = orm.em.fork({}).create(Post, {\n title: \"my first post\",\n });\n```\n\n```text\nMikroORM.init\n```\n\n```text\nallowGlobalContext: true\n```\n\n```text\nem\n```\n\n```text\ncreate\n```\n\n```text\nem\n```\n\n```text\nMIKRO_ORM_ALLOW_GLOBAL_CONTEXT = true\n```\n\n```ts\nconst fork = orm.em.fork();\nconst res = await fork.find(...);\n```\n\n```ts\n// we call em.find() on the global EM instance\nconst res = await orm.em.find(Book, {});\n\n// but under the hood this resolves to\nconst res = await orm.em.getContext().find(Book, {});\n\n// which then resolves to\nconst res = await RequestContext.getEntityManager().find(Book, {});\n```\n\n```ts\napp.use((req, res, next) => {\n RequestContext.create(orm.em, next);\n});\n```\n\n```ts\nconst orm = await MikroORM.init(mikroConfig);\nconst emFork = orm.em.fork(); // <-- create the fork\nconst post = emFork.create(Post, { // <-- use the fork instead of global `orm.em`\n title: \"my first post\",\n});\nawait emFork.persistAndFlush(post); // <-- use the fork instead of global \nawait orm.em.nativeInsert(Post, { title: \"my first post 2\" }); // <-- this line could work with the global EM too, why? because `nativeInsert` is not touching the identity map = the context\n```\n\n```ts\nconst orm = await MikroORM.init(mikroConfig);\n// run things in the `RequestContext` handler\n\nawait RequestContext.createAsync(orm.em, async () => {\n // inside this handler the `orm.em` will actually use the contextual fork, created via `RequestContext.createAsync()`\n const post = orm.em.create(Post, {\n title: \"my first post\",\n });\n await orm.em.persistAndFlush(post);\n await orm.em.nativeInsert(Post, { title: \"my first post 2\" });\n});\n```\n\n```ts\n@Injectable()\nexport class MyService {\n\n constructor(private readonly orm: MikroORM) { }\n\n @UseRequestContext()\n async doSomething() {\n // this will be executed in a separate context\n }\n\n}\n```\n\n```ts\nimport { DI } from '..';\n\nexport class MyService {\n\n @UseRequestContext(() => DI.orm)\n async doSomething() {\n // this will be executed in a separate context\n }\n\n}\n```\n\n```text\nMIKRO_ORM_ALLOW_GLOBAL_CONTEXT\n```\n\n```text\nallowGlobalContext\n```\n\n```text\nRequestContext\n```\n\n```text\nAsyncLocalStorage\n```\n\n```text\nRequestContext\n```\n\n```text\nEntityManager\n```\n\n```text\nem.find()\n```\n\n```text\nem.getReference()\n```\n\n```text\nem.getContext()\n```\n\n```text\nRequestContext\n```\n\n```text\nEntityManager\n```\n\n```text\nRequestContext.getEntityManager()\n```\n\n```text\nAsyncLocalStorage\n```\n\n```text\nRequestContext.create()\n```\n\n```text\nAsyncLocalStorage\n```\n\n```text\nEntityManager\n```\n\n```text\nEntityManager\n```\n\n```text\nRequestContext\n```\n\n```text\ninversify\n```\n\n```text\nnestjs\n```\n\n```text\nRequestContext\n```\n\n```text\nnode\n```\n\n```text\nAsyncLocalStorage\n```\n\n```text\nqueryParser\n```\n\n```text\nbodyParser\n```\n\n```text\nEntityManager\n```\n\n```text\nRequestContext.getEntityManager()\n```\n\n```text\nRequestContext.getEntityManager()\n```\n\n```text\nundefined\n```\n\n```text\nRequestContext\n```\n\n```text\n@UseRequestContext()\n```\n\n```text\n@UseRequestContext()\n```\n\n```text\n@CreateRequestContext()\n```\n\n```text\n@EnsureRequestContext()\n```\n\n```text\n@UseRequestContext()\n```\n\n```text\nMikroORM\n```\n\n```text\nRequestContext.createAsync()\n```\n\n```text\nEntityManager\n```\n\n```text\n@UseRequestContext()\n```\n\n```text\nMikroORM\n```\n\n========================================\n\nComments:\n- Thanks for asking this question. I also got here by watching Ben Awad's Fullstack React GraphQL TypeScript tutorial on YouTube.\n- Please consider marking my answer as accepted one, or at least read it carefuly, because disabling the validation is simply not the right thing to do (I would say its the opposite).\n- This is wrong, dont disable validations without understanding them.\n- -1 overall it is not recommended to disable this validation. this shouldn't be the accepted answer. it's easy to have it enabled. no one should have to take this measure\n- Following the discussion from github.com/mikro-orm/mikro-orm/discussions/2531. Thank you very much for the explanation.\n- Thanks for the explanation @martin-adámek , I have a question, I have a cron job that calls a function on another service, if I use UserRequestContext decorator, does that mean I need to pass the injected orm to the function I am calling ?\n- The decorator will behave the same way as if you would have a middleware, you can use your services from the DI container as usual, and the contextual fork is used automatically. So nope, no need to pass any instance, you can work with the global ones.\n- this should be the accepted answer, very informative\n- Looks like `@UseRequestContext` has been replaced by `@CreateRequestContext`, I suppose, it's a 1:1 replacement, @martin-adámek? BTW: For me it happens, when I listen to Websockets to issue database actions. ``` import { MikroORM } from '../MikroORM'; /** @deprecated use `@CreateRequestContext()` instead, `@UseRequestContext()` will be removed in v6 */ export declare function UseRequestContext(getContext?: MikroORM | ((type?: T) => MikroORM)): MethodDecorator; ```\n- yes, its just a rename\n- updated the answer to mention this too\n- And furthermore: In a typical NestJS Service, you don't have the ORM, so `@CreateRequestContext(()=>orm)` does not work and you need something like: `await RequestContext.createAsync(this.em, async () => { ... this.em.persist(data) ... await this.em.flush() })`\n- you can inject it anywhere, including any \"typical nestjs service\". nowadays the decorator also accepts EM, not just the ORM helper object\n- Martin: What to do, if you get an event (timeout, websocket) in another service independent from the database service (e.g. in a controller), then you call the service? You should then create a context, but you don't have access to the Entity Manager, nor to the service; eventually, it's even in another module. β Is there a best practice?\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:32:36.034Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":56,"totalLines":476,"estimatedTokens":3662}}168{"id":"stack-47240085","source":"stackoverflow","questionId":47240085,"title":"Pass obtained field to another (nested) query in GraphQL","tags":["graphql"],"text":"Title: Pass obtained field to another (nested) query in GraphQL\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nImagine the following query:\n\n```\nquery {\n user {\n id\n }\n SomeOtherStuff(id: How do you pass a parameter obtained from one query to another ?\n\n========================================\n\nTop Answer:\nI agree with @DanielRearden. You should make type-resolvers so you can go infinitely deep into the graph. I made a simple server example here that shows deep relationships. Because all the noun-fields are references, it goes infinitely deep for any query.\n\nWith that server, you can run a query like this, for example:\n\n```\n{\n hero {\n name\n friends {\n name\n friends {\n name\n friends {\n name\n friends: {\n name\n }\n }\n }\n }\n }\n}\n```\n\nSo, in your example, structure it like this:\n\n```\nquery {\n user {\n id\n otherStuff {\n id\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n user {\n id\n }\n SomeOtherStuff(id: <--- I want to pass the id obtained from user) {\n id\n }\n}\n```\n\n```text\nconst userQuery = gql`query User { user { id } }`;\nconst stuffQuery = gql`query SomeOtherStuff($id: ID) { someOtherStuff(id: $id){ stuff } }`;\n\nexport default compose(\n graphql(userQuery, { name: 'userData' })\n graphql(stuffQuery, { name: 'stuffData', options: ({userData:{id}={}}) => ({variables: {id}}) }),\n)(YourComponent)\n```\n\n```text\nuser\n```\n\n```text\nSomeOtherStuff\n```\n\n```text\nQuery\n```\n\n```text\n{\n hero {\n name\n friends {\n name\n friends {\n name\n friends {\n name\n friends: {\n name\n }\n }\n }\n }\n }\n}\n```\n\n```text\nquery {\n user {\n id\n otherStuff {\n id\n }\n }\n}\n```\n\n========================================\n\nComments:\n- You haven't indicated what language and GraphQL client you are using, or whether you are working with an existing API or one that you are designing yourself. This information would be helpful in providing a more thorough answer to your question.\n- @DanielRearden I am using apollo\n- I'm learing and running into a lot of similar questions. This link proved helpful for my GraphQL query-fu: devhints.io/graphql\n- I think you should rename your question and change the query to \"nested query\", then you might get what you are actually looking for. @AdamWolski\n- Thanks for the response. It is quite not what I expected from GraphQL. I thought that the idea of combining multiple requests into one was the GraphQL main principle. It seems pretty basic scenario for me, to get some other data that depend on the user but are not nested in the user itself... Is there any way you can get the data that depends on the user and are not nested in the user type (in the same request )?\n- Short answer: no. I would venture to say being forced to deal with the situation you describe is indicative of poor API design. The point is, if there is data related to the user, it *should* be part of the User type. If the data is relating to the currently logged in user (viewer), there should probably be a context-aware viewer query that lets you access it without having to first fetch an ID for the viewer first.\n- if you use compose, will the two queries get executed within a single request-response pair ?\n- Because this answer mentions apollo, they provide 3 options for handling this scenario in this post: apollographql.com/blog/apollo-client/…\n- @AndyGarcia upvoted your comment as you provide a link of official blog talks about this topic.","metadata":{"transformedAt":"2026-08-18T18:32:36.034Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":133,"estimatedTokens":873}}169{"id":"stack-35940528","source":"stackoverflow","questionId":35940528,"title":"How to connect GraphQL and PostgreSQL","tags":["postgresql","graphql"],"text":"Title: How to connect GraphQL and PostgreSQL\nTags: postgresql, graphql\nSource: Stack Overflow\n\nQuestion:\nGraphQL has mutations, Postgres has INSERT; GraphQL has queries, Postgres has SELECT's; etc., etc.. I haven't found an example showing how you could use both in a project, for example passing all the queries from front end (React, Relay) in GraphQL, but to a actually store the data in Postgres. \n\nDoes anyone know what Facebook is using as DB and how it's connected with GraphQL? \n\nIs the only option of storing data in Postgres right now to build custom \"adapters\" that take the GraphQL query and convert it into SQL?\n\n========================================\n\nTop Answer:\nWe address this problem in Join Monster, a library we recently open-sourced to automatically translate GraphQL queries to SQL based on your schema definitions.\n\n========================================\n\nCode:\n```text\n// db.js\n// take a user object and use knex to add it to the database, then return the newly\n// created user from the db.\nconst addUser = (user) => (\n knex('users')\n .returning('id') // returns [id]\n .insert({\n username: user.username,\n password: yourPasswordHashFunction(user.password),\n created: Math.floor(Date.now() / 1000), // Unix time in seconds\n })\n .then((id) => (getUser(id[0])))\n .catch((error) => (\n console.log(error)\n ))\n);\n\n// schema.js\n// the resolve function receives the query inputs as args, then you can call\n// your addUser function using them\nconst mutationType = new GraphQLObjectType({\n name: 'Mutation',\n description: 'Functions to add things to the database.',\n fields: () => ({\n addUser: {\n type: userType,\n args: {\n username: {\n type: new GraphQLNonNull(GraphQLString),\n },\n password: {\n type: new GraphQLNonNull(GraphQLString),\n },\n },\n resolve: (_, args) => (\n addUser({\n username: args.username,\n password: args.password,\n })\n ),\n },\n }),\n});\n```\n\n```text\n/**\n * We get the node interface and field from the Relay library.\n *\n * The first method defines the way we resolve an ID to its object.\n * The second defines the way we resolve an object to its GraphQL type.\n *\n * All your types will implement this nodeInterface\n */\nconst { nodeInterface, nodeField } = nodeDefinitions(\n (globalId) => {\n const { type, id } = fromGlobalId(globalId);\n if (type === 'User') {\n return getUser(id);\n }\n return null;\n },\n (obj) => {\n if (obj instanceof User) {\n return userType;\n }\n return null;\n }\n);\n\n// a globalId is just a base64 encoding of the database id and the type\nconst userType = new GraphQLObjectType({\n name: 'User',\n description: 'A user.',\n fields: () => ({\n id: globalIdField('User'),\n username: {\n type: new GraphQLNonNull(GraphQLString),\n description: 'The username the user has selected.',\n },\n created: {\n type: GraphQLInt,\n description: 'The Unix timestamp in seconds of when the user was created.',\n },\n }),\n interfaces: [nodeInterface],\n});\n\n// The \"payload\" is the data that will be returned from the mutation\nconst userMutation = mutationWithClientMutationId({\n name: 'AddUser',\n inputFields: {\n username: {\n type: GraphQLString,\n },\n password: {\n type: new GraphQLNonNull(GraphQLString),\n },\n },\n outputFields: {\n user: {\n type: userType,\n resolve: (payload) => getUser(payload.userId),\n },\n },\n mutateAndGetPayload: ({ username, password }) =>\n addUser(\n { username, password }\n ).then((user) => ({ userId: user.id })), // passed to resolve in outputFields\n});\n\nconst mutationType = new GraphQLObjectType({\n name: 'Mutation',\n description: 'Functions to add things to the database.',\n fields: () => ({\n addUser: userMutation,\n }),\n});\n\nconst queryType = new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n user: {\n type: userType,\n args: {\n id: {\n description: 'ID number of the user.',\n type: new GraphQLNonNull(GraphQLID),\n },\n },\n resolve: (root, args) => getUser(args.id),\n },\n }),\n});\n```\n\n```text\nresolve\n```\n\n```text\nid\n```\n\n```text\nusername\n```\n\n```text\ncreated\n```\n\n```text\ngetUser\n```\n\n```text\npassword\n```\n\n```text\nuserType\n```\n\n```text\nid\n```\n\n```text\ncreated\n```\n\n```text\ngraphql-relay\n```\n\n```text\ngetUser\n```\n\n```text\nUser\n```\n\n```text\ngetUser\n```\n\n```text\nfromGlobalId\n```\n\n```text\nglobalIdField\n```\n\n```text\nmutationWithClientMutationId\n```\n\n```text\nnodeDefinitions\n```\n\n```text\ngraphql-relay\n```\n\n```text\nconst Sequelize = require('sequelize');\nconst sequelize = new Sequelize('database', 'username', 'password', {\n host: 'localhost',\n dialect: 'mysql'|'sqlite'|'postgres'|'mssql',\n\n pool: {\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000\n },\n\n // SQLite only\n storage: 'path/to/database.sqlite',\n\n // http://docs.sequelizejs.com/manual/tutorial/querying.html#operators\n operatorsAliases: false\n});\n\nconst User = sequelize.define('user', {\n username: Sequelize.STRING,\n birthday: Sequelize.DATE\n});\n\nsequelize.sync()\n .then(() => User.create({\n username: 'janedoe',\n birthday: new Date(1980, 6, 20)\n }))\n .then(jane => {\n console.log(jane.toJSON());\n });\n```\n\n========================================\n\nComments:\n- What about PostGraphQL ?\n- @Scott Looks neat\n- I wrote up this small article if you would like to have a tutorial style graphql-sequelize to through as exploration. medium.com/@leonyapkl/…\n- Wouldn't that have to be async/await for addUser function? I'm talking about non relay way which I prefer.\n- First link in the \"Relay Way\" section goes to a deprecated repo.\n- Is this also constructing tables or just querying them after you already have them - more like what PostgraphQL?\n- Just querying them after you already have them. The difference is that you still write your own API layer, rather than having the API automatically generated.\n- Where's GraphQL part in this answer?\n- This have nothing to do with the question, it's just bringing confusion...\n- Please add further details to expand on your answer, such as working code or documentation citations.\n- @Irere Em12 I assume you're referring to the server-side code. Can you add that detail, and maybe a link to official documentation for an example ORM?\n- You can find the documentation for Typeorm Docs and for sequelize Docs also if you need resources on how to set it up i have github repo here Typeorm + Graphql","metadata":{"transformedAt":"2026-08-18T18:32:36.034Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":279,"estimatedTokens":1638}}170{"id":"stack-33088119","source":"stackoverflow","questionId":33088119,"title":"When should I use a Relay GraphQL connection and when a plain list?","tags":["graphql","relayjs"],"text":"Title: When should I use a Relay GraphQL connection and when a plain list?\nTags: graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nIn Relay GraphQL, connections and lists are both array-like, but they have different features. When should I use each?\n\n========================================\n\nCode:\n```text\nRANGE_ADD\n```\n\n```text\nRANGE_DELETE\n```\n\n```text\nNODE_DELETE\n```\n\n```text\nfirst\n```\n\n```text\nlast\n```\n\n```text\nedges\n```\n\n```text\nfirst\n```\n\n========================================\n\nComments:\n- Is connection-related functionality in Relay on the client side entirely declarative? I'm seeing that by using connections you gain \"fine-grained mutation support\" in the client. Are there any imperative APIs that use this functionality? I'm not seeing anyβjust want to confirm I'm not missing anything.\n- Also, why do lists provide no support for pagination? I mean, you could build your own pagination using a list-type field, right?\n- @dimadima You can absolutely support pagination with lists. At graph.cool we support both a relay compatible and a simple graphql endpoint using lists for your data model. list queries support pagination through a skip and take mechanism. For example {allUsers(skip: 20, take: 10)} would return the third page. The issue with this approach that relay addresses is that if data is added between the page requests the pages will be shifted and you risk missing a node or returning duplicates. This is why the cursor is required.\n- Where can I see an example of defining and storing edge specific data?","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":45,"estimatedTokens":385}}171{"id":"stack-50021669","source":"stackoverflow","questionId":50021669,"title":"Why am I getting a \"Cannot return null for non-nullable field\" error when doing a mutation?","tags":["javascript","node.js","express","graphql","apollo-server"],"text":"Title: Why am I getting a \"Cannot return null for non-nullable field\" error when doing a mutation?\nTags: javascript, node.js, express, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm trying my hand at (Apollo) GraphQL on the server side and have been having a probably silly issue. I'm trying to sign up a user, but keep getting the error shown in the linked image below. What is the problem? Ignore the very simple auth flow, as I'm just testing out the GraphQl \n\nhttps://i.sstatic.net/l9gUD.png\n\nHere are the relevant code snippets:\n\n**Schema**\n\n```\nexport default `\n\ntype User {\n id: ID!\n name: String!\n email: String!\n}\n\ntype Query {\n allUsers: [User]\n currentUser: User\n}\n\ntype Mutation {\n createAccount(name: String!, email: String!, password: String!): User\n loginUser(email: String!, password: String!): User\n updatePassword(email: String!, password: String!, newPassword: String!): User\n deleteAccount(email: String!, password: String!): User\n}\n\n`\n```\n\n**Resolvers**\n\n```\ncreateAccount: async (\n parent,\n { name, email, password },\n { User },\n info\n) => {\n try {\n // Check for invalid (undefined) credentials\n if (!name || !email || !password) {\n return 'Please provide valid credentials';\n }\n\n // Check if there is a user with the same email\n const foundUser = await User.findOne({ email });\n\n if (foundUser) {\n return 'Email is already in use';\n }\n\n // If no user with email create a new user\n const hashedPassword = await bcrypt.hash(password, 10);\n await User.insert({ name, email, password: hashedPassword });\n\n const savedUser = await User.findOne({ email });\n\n return savedUser;\n } catch (error) {\n return error.message;\n }\n},\n```\n\n========================================\n\nCode:\n```text\nexport default `\n\ntype User {\n id: ID!\n name: String!\n email: String!\n}\n\ntype Query {\n allUsers: [User]\n currentUser: User\n}\n\ntype Mutation {\n createAccount(name: String!, email: String!, password: String!): User\n loginUser(email: String!, password: String!): User\n updatePassword(email: String!, password: String!, newPassword: String!): User\n deleteAccount(email: String!, password: String!): User\n}\n\n`\n```\n\n```text\ncreateAccount: async (\n parent,\n { name, email, password },\n { User },\n info\n) => {\n try {\n // Check for invalid (undefined) credentials\n if (!name || !email || !password) {\n return 'Please provide valid credentials';\n }\n\n // Check if there is a user with the same email\n const foundUser = await User.findOne({ email });\n\n if (foundUser) {\n return 'Email is already in use';\n }\n\n // If no user with email create a new user\n const hashedPassword = await bcrypt.hash(password, 10);\n await User.insert({ name, email, password: hashedPassword });\n\n const savedUser = await User.findOne({ email });\n\n return savedUser;\n } catch (error) {\n return error.message;\n }\n},\n```\n\n```text\n// Check if there is a user with the same email\nconst foundUser = await User.findOne({ email })\n\nif (foundUser) throw new Error('Email is already in use')\n\n// If no user with email create a new user\nconst hashedPassword = await bcrypt.hash(password, 10);\nawait User.insert({ name, email, password: hashedPassword });\n\nconst savedUser = await User.findOne({ email });\n\nreturn savedUser;\n```\n\n```text\n{\n \"data\": {\n \"createAccount\": null\n },\n \"errors\": [\n {\n \"message\": \"Email is already in use\",\n \"locations\": [\n {\n \"line\": 4,\n \"column\": 3\n }\n ],\n \"path\": [\n \"createAccount\"\n ]\n }\n ]\n}\n```\n\n```text\nUser\n```\n\n```text\ncreateAccount\n```\n\n```text\nUser\n```\n\n```text\nnull\n```\n\n```text\nUser!\n```\n\n```text\nnull\n```\n\n```text\nUser\n```\n\n```text\nname\n```\n\n```text\nemail\n```\n\n```text\nUser\n```\n\n```text\nerrors\n```\n\n```text\nformatError\n```\n\n```text\nformatResponse\n```\n\n```text\ncode\n```\n\n========================================\n\nComments:\n- I got this error on an codegen'ed Amplify mutation with a hardcoded response maxDepth. I worked around it by creating a custom mutation with a subset of a response only fetching the exact fields I needed for the query.\n- HI DANIEL ARE YOU SAYING HW SHOULD NOT RETURN a string?I'm facing the same problem\n- my cents, in my case I forgot to use return statement on the DataSource API callback. this post helped to give a look into that area of cause! Thanks.\n- @Jatinder, you just saved a life with that mention of return statement. It's been 30mins of head scratching. I had this `resolve: (source, args, { pgApi }) => {pgApi.userInfo(source.userId)}` instead of `resolve: (source, args, { pgApi }) => pgApi.userInfo(source.userId)`","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":232,"estimatedTokens":1156}}172{"id":"stack-48003767","source":"stackoverflow","questionId":48003767,"title":"The difference between Mutation and Query","tags":["graphql"],"text":"Title: The difference between Mutation and Query\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI'm reading GraphQL Docs about `Query` and `Mutation`. However, there is a lack of real examples which shows the difference and most importantly β when is it appropriate to use them.\n\nMany thanks for the explanations.\n\n========================================\n\nTop Answer:\nIn simple words the query is SELECT statement and mutation is INSERT Operation.\n\nQuery in graphql is used to fetch data while mutation is used for INSERT/UPDATE/DELETE operation.\n\n========================================\n\nCode:\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nQuery\n```\n\n```text\nSELECT\n```\n\n```text\nMutation\n```\n\n```text\nINSERT\n```\n\n```text\nUPDATE\n```\n\n```text\nDELETE\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n========================================\n\nComments:\n- At this point, do i have to commit transactions manually everytime or GraphQL handles it automatically?\n- under which category does the \"login\" operation fall?\n- it depends on you where you want to put. but in my case i always put login in Query. because it does not update anything. please checkout here for more info. and sorry for late reply didn't got notification.\n- It is a really really superficial answer. Here on SO, we all should **downvote** answers like this (sorry, author). If you want to post an answer - post something **thoroughly investigated**, like the accepted answer\n- actually, this answer is just a comment or a small amendment for the accepted one\n- @maxkoryukov Yes this is short answer but if you see the accepted answer is one year later than this. this was the first answer for the question.\n- It is a really really superficial answer. Here on SO, we all should **downvote** answers like this (sorry, author). If you want to post an answer - post something **thoroughly investigated**, like the accepted answer\n- actually, this answer is just a comment or a small amendment for the accepted one\n- It is a really really superficial answer. Here on SO, we all should **downvote** answers like this (sorry, author). If you want to post an answer - post something **thoroughly investigated**, like the accepted answer\n- actually, this answer is just a comment or a small amendment for the accepted one","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":72,"estimatedTokens":571}}173{"id":"stack-40792344","source":"stackoverflow","questionId":40792344,"title":"Does apollo-client work on node.js?","tags":["javascript","node.js","graphql","apollostack"],"text":"Title: Does apollo-client work on node.js?\nTags: javascript, node.js, graphql, apollostack\nSource: Stack Overflow\n\nQuestion:\nI need a graphql client lib **to run on node.js** for some testing and some data mashup - not in a production capacity. I'm using apollo everywhere else (`react-apollo`, apollo's `graphql-server-express`). My needs are pretty simple.\n\nIs `apollo-client` a viable choice? I can find no examples or docs on using it on node - if you're aware of any, please .\n\nOr maybe I should/can use the reference graphql client on node?\n\n========================================\n\nTop Answer:\nNewer Apollo version provide a simpler approach to perform this, as described in Apollo docs, check the section \"Standalone\". Basically one can simply use `ApolloLink` in order to perform a query or mutation.\n\nBelow is copy of the example code from the docs as of writing this, with `node-fetch` usage as config to `createHttpLink`. Check the docs for more details on how to use these tools.\n\n```\nimport { execute, makePromise } from 'apollo-link';\nimport { createHttpLink } from 'apollo-link-http';\nimport gql from 'graphql-tag';\nimport fetch from 'node-fetch';\n\nconst uri = 'http://localhost:4000/graphql';\nconst link = createHttpLink({ uri, fetch });\n\nconst operation = {\n query: gql`query { hello }`,\n variables: {} //optional\n operationName: {} //optional\n context: {} //optional\n extensions: {} //optional\n};\n\n// execute returns an Observable so it can be subscribed to\nexecute(link, operation).subscribe({\n next: data => console.log(`received data: ${JSON.stringify(data, null, 2)}`),\n error: error => console.log(`received error ${error}`),\n complete: () => console.log(`complete`),\n})\n\n// For single execution operations, a Promise can be used\nmakePromise(execute(link, operation))\n .then(data => console.log(`received data ${JSON.stringify(data, null, 2)}`))\n .catch(error => console.log(`received error ${error}`))\n```\n\n========================================\n\nCode:\n```text\nreact-apollo\n```\n\n```text\ngraphql-server-express\n```\n\n```text\napollo-client\n```\n\n```js\nimport { ApolloClient, gql, HttpLink, InMemoryCache } from \"@apollo/client\";\n\nimport { InsertJob } from \"./graphql-types\";\nimport fetch from \"cross-fetch\";\n\nconst client = new ApolloClient({\n link: new HttpLink({ uri: process.env.PRODUCTION_GRAPHQL_URL, fetch }),\n cache: new InMemoryCache(),\n});\n\n\nclient.mutate<InsertJob.AddCompany, InsertJob.Variables>({\n mutation: gql`mutation insertJob($companyName: String!) {\n addCompany(input: { displayName: $companyName } ) {\n id\n }\n }`,\n variables: {\n companyName: \"aaa\"\n }\n})\n .then(result => console.log(result));\n```\n\n```text\n1. run npm install\n2. start server with \"node server.js\"\n3. hit \"http://localhost:8080/graphiql\" for graphiql client\n```\n\n```text\nvar graphql = require ('graphql').graphql \nvar express = require('express') \nvar graphQLHTTP = require('express-graphql') \n\nvar Schema = require('./schema') \n\n// This is just an internal test\nvar query = 'query{starwar{name, gender,gender}}' \ngraphql(Schema, query).then( function(result) { \n console.log(JSON.stringify(result,null,\" \"));\n});\n\nvar app = express() \n .use('/', graphQLHTTP({ schema: Schema, pretty: true, graphiql: true }))\n .listen(8080, function (err) {\n console.log('GraphQL Server is now running on localhost:8080');\n });\n```\n\n```text\n//schema.js\nvar graphql = require ('graphql'); \nvar http = require('http');\n\nvar StarWar = [ \n { \n \"name\": \"default\",\n \"gender\": \"default\",\n \"mass\": \"default\"\n }\n];\n\nvar TodoType = new graphql.GraphQLObjectType({ \n name: 'starwar',\n fields: function () {\n return {\n name: {\n type: graphql.GraphQLString\n },\n gender: {\n type: graphql.GraphQLString\n },\n mass: {\n type: graphql.GraphQLString\n }\n }\n }\n});\n\n\n\nvar QueryType = new graphql.GraphQLObjectType({ \n name: 'Query',\n fields: function () {\n return {\n starwar: {\n type: new graphql.GraphQLList(TodoType),\n resolve: function () {\n return new Promise(function (resolve, reject) {\n var request = http.get({\n hostname: 'swapi.co',\n path: '/api/people/1/',\n method: 'GET'\n }, function(res){\n res.setEncoding('utf8');\n res.on('data', function(response){\n StarWar = [JSON.parse(response)];\n resolve(StarWar)\n\n console.log('On response success:' , StarWar);\n });\n });\n\n request.on('error', function(response){\n console.log('On error' , response.message);\n });\n\n request.end(); \n });\n }\n }\n }\n }\n});\n\nmodule.exports = new graphql.GraphQLSchema({ \n query: QueryType\n});\n```\n\n```text\ngraphql\n```\n\n```js\nrequire('dotenv').config();\nconst gql = require('graphql-tag');\nconst ApolloClient = require('apollo-boost').ApolloClient;\nconst fetch = require('cross-fetch/polyfill').fetch;\nconst createHttpLink = require('apollo-link-http').createHttpLink;\nconst InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;\nconst client = new ApolloClient({\n link: createHttpLink({\n uri: process.env.API,\n fetch: fetch\n }),\n cache: new InMemoryCache()\n});\n\nclient.mutate({\n mutation: gql`\n mutation popJob {\n popJob {\n id\n type\n param\n status\n progress\n creation_date\n expiration_date\n }\n }\n `,\n}).then(job => {\n console.log(job);\n})\n```\n\n```text\nimport ApolloClient from \"apollo-client\";\nimport { ApolloLink } from 'apollo-link'\nimport { HttpLink } from 'apollo-link-http'\nimport { onError } from 'apollo-link-error'\nimport fetch from 'node-fetch'\nimport { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'\nimport introspectionQueryResultData from '../../fragmentTypes.json';\nimport { AppConfig } from 'app-config';\n\n\nconst config: AppConfig = require('../../../appConfig.js');\n\nexport class GraphQLQueryClient {\n protected apolloClient: any;\n\n constructor(headers: { [name: string]: string }) {\n const api: any = {\n spaceId: config.app.spaceId,\n environmentId: config.app.environmentId,\n uri: config.app.uri,\n cdnApiPreviewToken: config.cdnApiPreviewToken,\n };\n // console.log(JSON.stringify(api));\n const ACCESS_TOKEN = api.cdnApiPreviewToken;\n const uri = api.uri;\n\n console.log(`Apollo client setup to query uri: ${uri}`);\n\n const fragmentMatcher = new IntrospectionFragmentMatcher({\n introspectionQueryResultData\n });\n\n this.apolloClient = new ApolloClient({\n link: ApolloLink.from([\n onError(({ graphQLErrors, networkError }:any) => {\n if (graphQLErrors) {\n graphQLErrors.map((el:any) =>\n console.warn(\n el.message || el\n )\n )\n graphQLErrors.map(({ message, locations, path }:any) =>\n console.warn(\n `[GraphQL error - Env ${api.environmentId}]: Message: ${message}, Location: ${JSON.stringify(locations)}, Path: ${path}`\n )\n )\n }\n if (networkError) console.log(`[Network error]: ${networkError}`)\n }),\n new HttpLink({\n uri,\n credentials: 'same-origin',\n headers: {\n Authorization: `Bearer ${ACCESS_TOKEN}`\n },\n fetch\n })\n ]),\n cache: new InMemoryCache({ fragmentMatcher }),\n // fetchPolicy as network-only avoids using the cache.\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'network-only',\n errorPolicy: 'ignore',\n },\n query: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all',\n },\n }\n });\n }\n}\n```\n\n```text\nlet response = await this.apolloClient.query({ query: gql`${query}` });\n```\n\n```js\nimport { execute, makePromise } from 'apollo-link';\nimport { createHttpLink } from 'apollo-link-http';\nimport gql from 'graphql-tag';\nimport fetch from 'node-fetch';\n\nconst uri = 'http://localhost:4000/graphql';\nconst link = createHttpLink({ uri, fetch });\n\nconst operation = {\n query: gql`query { hello }`,\n variables: {} //optional\n operationName: {} //optional\n context: {} //optional\n extensions: {} //optional\n};\n\n// execute returns an Observable so it can be subscribed to\nexecute(link, operation).subscribe({\n next: data => console.log(`received data: ${JSON.stringify(data, null, 2)}`),\n error: error => console.log(`received error ${error}`),\n complete: () => console.log(`complete`),\n})\n\n// For single execution operations, a Promise can be used\nmakePromise(execute(link, operation))\n .then(data => console.log(`received data ${JSON.stringify(data, null, 2)}`))\n .catch(error => console.log(`received error ${error}`))\n```\n\n```text\nApolloLink\n```\n\n```text\nnode-fetch\n```\n\n```text\ncreateHttpLink\n```\n\n```text\nimport { request, gql } from 'graphql-request'\n \n const query = gql`\n {\n Movie(title: \"Inception\") {\n releaseDate\n actors {\n name\n }\n }\n }\n`\n \nrequest('https://api.graph.cool/simple/v1/movies', query).then((data) => console.log(data))\n```\n\n========================================\n\nComments:\n- The client is designed to run in the browser. With graphql-tools, and graphql-server-express (previous apollo server) you can do almost anything.\n- So, what if I want the server make graphql queries to some other server? Then, I need a graphql client library running on the server, yes?\n- This was 8 months ago... if you had any insights since could you please ?\n- @YakirNa See answer below\n- Apollo Client should work just fine on Node. Check my answer\n- Thanks for the help. If you don't want a global polyfill you can inject fetch into ApolloClient instead: `import fetch from 'cross-fetch'; const client = new ApolloClient({ fetch, uri: ...`\n- do Apollo caching works without their React render props / hooks?\n- What tool did you use to generate types for the `InsertJob` method?\n- @George graphql-code-generator.com\n- I like this lightweight `apollo-link` solution much better. I had issues with node-fetch with Typescript, see #513, so I'm using cross-fetch instead.\n- It doesn't seem to support subsctiptions though.","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":376,"estimatedTokens":2727}}174{"id":"stack-33399901","source":"stackoverflow","questionId":33399901,"title":"In Relay, what role do the node interface and the global ID spec play?","tags":["reactjs","graphql","relayjs","graphql-js"],"text":"Title: In Relay, what role do the node interface and the global ID spec play?\nTags: reactjs, graphql, relayjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI started out with the `relay-starter-kit` and also worked my way through the Relay and GraphQL documentation. But there are quite a few areas that are unexplained and mysterious.\n\nSeriously I read a lot of documentations everywhere about all these things but couldn't find any satisfying explanations for the following questions:\n\nWhat is this for? I put logging but it never even gets called at all:\n\n```\nvar {nodeInterface, nodeField} = nodeDefinitions(\n (globalId) => {\n var {type, id} = fromGlobalId(globalId);\n if (type === 'User') {\n return getUser(id);\n } else if (type === 'Widget') {\n return getWidget(id);\n } else {\n return null;\n }\n },\n (obj) => {\n if (obj instanceof User) {\n return userType;\n } else if (obj instanceof Widget) {\n return widgetType;\n } else {\n return null;\n }\n }\n);\n```\n\nAnd what is the actual effect of this:\n\n```\ninterfaces: [nodeInterface],\n```\n\nMaybe related to that, what does the `node` field here do:\n\n```\nvar queryType = new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n // Add your own root fields here\n viewer: {\n type: userType,\n resolve: () => getViewer(),\n },\n }),\n});\n```\n\nAnd what is the magic around the `id` field? What is `globalIdField` for?\n\nI have an `id` in my database and thought I could use it in my GraphQL objects:\n\nInstead of:\n\n```\nid: globalIdField('User'),\n```\n\nI want to use my database id:\n\n```\nid: {\n type: GraphQLID,\n description: 'The identifier'\n},\n```\n\nBut if I do that I get an error in the browser saying `RelayQueryWriter: Could not find a type name for record '1'`.\n\nI can get rid of that error by adding `__typename` to my component containers Relay Query but that seems all wrong.\n\nIt would be great if you could give some deeper insides and a better explanation here and enhance the official documentation.\n\nThank you\n\n========================================\n\nCode:\n```js\nvar {nodeInterface, nodeField} = nodeDefinitions(\n (globalId) => {\n var {type, id} = fromGlobalId(globalId);\n if (type === 'User') {\n return getUser(id);\n } else if (type === 'Widget') {\n return getWidget(id);\n } else {\n return null;\n }\n },\n (obj) => {\n if (obj instanceof User) {\n return userType;\n } else if (obj instanceof Widget) {\n return widgetType;\n } else {\n return null;\n }\n }\n);\n```\n\n```js\ninterfaces: [nodeInterface],\n```\n\n```js\nvar queryType = new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n // Add your own root fields here\n viewer: {\n type: userType,\n resolve: () => getViewer(),\n },\n }),\n});\n```\n\n```js\nid: globalIdField('User'),\n```\n\n```js\nid: {\n type: GraphQLID,\n description: 'The identifier'\n},\n```\n\n```text\nrelay-starter-kit\n```\n\n```text\nnode\n```\n\n```text\nid\n```\n\n```text\nglobalIdField\n```\n\n```text\nid\n```\n\n```text\nRelayQueryWriter: Could not find a type name for record '1'\n```\n\n```text\n__typename\n```\n\n```js\nquery {\n viewer {\n stories(first: 10) {\n edges {\n node {\n id,\n comments(first: 10) @include(if: $showComments) { \n author, \n commentText \n }\n text,\n }\n }\n }\n }\n}\n```\n\n```text\nquery {\n node(id: \"ABC123\") { \n fragment on Story { comments(first: 10) { author, commentText } }\n }\n node(id: \"DEF456\") { \n fragment on Story { comments(first: 10) { author, commentText } }\n }\n node(id: \"GHI789\") { \n fragment on Story { comments(first: 10) { author, commentText } }\n }\n ...\n}\n```\n\n```text\nNode\n```\n\n```text\nthis.props.relay.forceFetch()\n```\n\n```text\nnode\n```\n\n```text\n$showComments\n```\n\n```text\nfalse\n```\n\n```text\nid\n```\n\n```text\ntext\n```\n\n```text\n$showComments\n```\n\n```text\ntrue\n```\n\n```text\nnode\n```\n\n```text\nglobalIdField\n```\n\n```text\nnodeDefinitions\n```\n\n```text\nnodeInterface\n```\n\n========================================\n\nComments:\n- Hopefully this will make its way into the tutorial soon. I was also confused by this for quite a while until I finally worked through everything and put the pieces together.\n- Maybe add a bit more to this answer regarding `fromGlobalId` and `toGlobalId`? and how they facilitate refetching of any object type? Reading github.com/graphql/graphql-relay-js/blob/master/src/node/… and other files in that repo helped me a lot, but distilling that stuff into words would have saved me lots of time.\n- For a concise (you can skip to the end for the summary) & code-illustrated explanation of what the mysterious nodeInterface, nodeField, globalFieldId are, perhaps medium.com/p/relay-graphql-de-mystifying-node-id-38757121b9c\n- @steveluscher But this will cause to refetch `stories` data again. What if I just want the `comments`? I couldn't find any real world example with `nodeDefinitions`. Or I am missing something?\n- @user6227254 You'll only fetch the first 10 comments of each story. The remaining fields of the story aren't fetched since they are not included in the node query.\n- This sentence \"Relay will refetch only the data it needs using the node root field.\" explained everything to me. Thanks a lot!\n- Updated the URL for you, cglacet. Itβs the serverβs responsibility.","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":264,"estimatedTokens":1326}}175{"id":"stack-52769993","source":"stackoverflow","questionId":52769993,"title":"How to correctly declare a GraphQL query without parameters.","tags":["visual-studio-code","graphql","lint"],"text":"Title: How to correctly declare a GraphQL query without parameters.\nTags: visual-studio-code, graphql, lint\nSource: Stack Overflow\n\nQuestion:\nI'm using vs code + graphql-cli for validating & linting the schema. In the following declaration (in the graphql schema file):\n\n```\ntype Query {\n users(): Int\n}\n```\n\nThe `users` declaration above is marked as en error, but it doesn't make any problem (or warning) by the server - it's only vs code and `graphql lint` reporting it as an error:\n\n```\n2:9 Syntax Error: Expected Name, found ) undefined\n```\n\nIf I add a parameter to the query, eg:\n\n```\ntype Query {\n users(n: Int): Int\n}\n```\n\nthen there is no problem reported by vs code or graphql-cli.\nHow can I properly declare a graphql query without parameters.\n\n========================================\n\nCode:\n```text\ntype Query {\n users(): Int\n}\n```\n\n```text\n2:9 Syntax Error: Expected Name, found ) undefined\n```\n\n```text\ntype Query {\n users(n: Int): Int\n}\n```\n\n```text\nusers\n```\n\n```text\ngraphql lint\n```\n\n```text\ntype Query {\n users: Int\n}\n```\n\n```text\nquery UsersQuery {\n users {\n name\n posts (onlyNew: true) {\n title\n }\n }\n}\n```\n\n========================================\n\nComments:\n- There's a GraphQL bug that makes it fail to parse `users()` as a valid query, even though the `n` parameter is optional. You're forced to write `users` if all parameters are missing.\n- What about a query with one optional parameter? How should that be defined so that both `users(n: 100)` and `users()` are valid?\n- Arguments are nullable by default. The latter will never be valid because it's invalid syntax. If you don't pass in any arguments, you need to omit the parentheses.","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":80,"estimatedTokens":421}}176{"id":"stack-37981269","source":"stackoverflow","questionId":37981269,"title":"How to search string values in GraphQL","tags":["graphql"],"text":"Title: How to search string values in GraphQL\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nHow do you query using GraphQL in a manor similar to SQL's `like` operator?\n\nExample: What users have a first name starting with `jason`?\n\n`select * from users where first_name like \"jason%\"`\n\n========================================\n\nTop Answer:\nNot sure if this is relevant to you because you want it to start with \"jason\" (ie would return \"jason bourne\" but not \"bourne jason\") but I recently came across a way to query GraphQL in a \"%Like%\" manner. For your use case it would look something like this:\n\n```\nexport const allUsersQuery = `\n query allUsers($UserName: String!){\n allUsers(\n filter: {first_name_contains: $UserName}\n ) {\n id\n first_name\n ...INSERT_OTHER_FIELDS_HERE...\n }\n }\n`;\n```\n\nFWIW: I did this using a GraphCool BAAS. I don't think you were using GraphCool because GraphCool doesn't allow \"_\" in variable names.\n\nHope this helps someone down the line :)\n\n========================================\n\nCode:\n```text\nlike\n```\n\n```text\njason\n```\n\n```text\nselect * from users where first_name like \"jason%\"\n```\n\n```text\ntype Query {\n users(firstName: String!): [User]\n}\n\ntype User {\n firstName: String\n lastName: String\n}\n```\n\n```text\n{\n Query: {\n users(root, args){\n return sql.raw('SELECT * FROM `users` WHERE `firstName` LIKE ?', args.firstName);\n }\n }\n}\n```\n\n```text\n{\n users(firstName: 'jason%'){\n firstName\n lastName\n }\n}\n```\n\n```text\nlike\n```\n\n```text\nusers\n```\n\n```text\nexport const allUsersQuery = `\n query allUsers($UserName: String!){\n allUsers(\n filter: {first_name_contains: $UserName}\n ) {\n id\n first_name\n ...INSERT_OTHER_FIELDS_HERE...\n }\n }\n`;\n```\n\n========================================\n\nComments:\n- the Q in graphql is misleading, is not a query language, is more like a structure language\n- Note that `users(firstName: String): [User]` with no exclamation mark after `String` can be used to make `firstName` optional. Then you can program your server so that `users` returns all users while `users(firstName: \"Max\")` returns only users whose first name is `Max`.","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":106,"estimatedTokens":537}}177{"id":"stack-63681650","source":"stackoverflow","questionId":63681650,"title":"What is the difference between useQuery and useLazyQuery in Apollo graphQL?","tags":["reactjs","graphql","apollo"],"text":"Title: What is the difference between useQuery and useLazyQuery in Apollo graphQL?\nTags: reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI was going through the documentation of Apollo React hooks.\n\nAnd saw there are two queries hooks to use for which is `useQuery` and `useLazyQuery`\n\nI was reading this page.\nhttps://www.apollographql.com/docs/react/api/react/hooks/\n\nCan someone explain me what is the difference between them and in which case it should be used.\n\n========================================\n\nTop Answer:\nSuppose you have a component where you call useQuery, then as soon as the component mounts, useQuery runs and the data is fetched from the server.\nBut if you use useLazyQuery in that component instead of useQuery, query doesn't run and data isn't fetched when component mounts. Instead you can run the query based on your requirement, say after clicking a button. Example:\n\n```\nimport React, { useState } from 'react';\nimport { useLazyQuery } from '@apollo/client';\n\nfunction DelayedQuery() {\n const [dog, setDog] = useState(null);\n const [getDog, { loading, data }] = useLazyQuery(GET_DOG_PHOTO);\n\n if (loading) return Loading ...\n\n;\n\n if (data && data.dog) {\n setDog(data.dog);\n }\n\n return (\n \n {dog && }\n getDog({ variables: { breed: 'bulldog' } })}>\n Click me!\n \n \n );\n}\n```\n\nHere, as soon as you click the button, then only the query runs and data is fetched and the image is displayed. But if you had used useQuery instead, before clicking the button (i.e when the component mounts), the data would have been fetched and the image would have been displayed\n\n========================================\n\nCode:\n```text\nuseQuery\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nuseQuery\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nuseQuery\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nuseQuery\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nimport React, { useState } from 'react';\nimport { useLazyQuery } from '@apollo/client';\n\nfunction DelayedQuery() {\n const [dog, setDog] = useState(null);\n const [getDog, { loading, data }] = useLazyQuery(GET_DOG_PHOTO);\n\n if (loading) return <p>Loading ...</p>;\n\n if (data && data.dog) {\n setDog(data.dog);\n }\n\n return (\n <div>\n {dog && <img src={dog.displayImage} />}\n <button onClick={() => getDog({ variables: { breed: 'bulldog' } })}>\n Click me!\n </button>\n </div>\n );\n}\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nrefetch\n```\n\n```text\nuseQuery\n```\n\n========================================\n\nComments:\n- I was using \"useLazyQuery\" and I was sending variables from a state with the request and every time I change the state of the inputs the request executed every time the component mount, although I was using it onClick event.\n- @Sharif there should be a bug on how you use it (e.g inadvertantly execute the query function) or otherwise you may report issue github.com/apollographql/apollo-client/issues since this is not the case based on their documentation\n- you can create a new question and provide here so I can take a look? a minimal reproducible environment like codesandbox is deeply appreciated also.\n- Yap, I was about 3 hours trying to figure out why my query is always fetching from API even with `cache-first` rule. I didn't see anything in the docs talking about it","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":128,"estimatedTokens":816}}178{"id":"stack-53984094","source":"stackoverflow","questionId":53984094,"title":"Notable differences between buildSchema and GraphQLSchema?","tags":["graphql","graphql-js"],"text":"Title: Notable differences between buildSchema and GraphQLSchema?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nAre there any notable differences between the two? Im interested in anything from runtime and startup performance to features and workflow differences. Documentation does a poor job on explaining the difference and when I should use one over the other.\n\n### Example in both versions:\n\n### buildSchema\n\n```\nconst { graphql, buildSchema } = require('graphql');\n\nconst schema = buildSchema(`\n type Query {\n hello: String\n }\n`);\n\nconst root = { hello: () => 'Hello world!' };\n\ngraphql(schema, '{ hello }', root).then((response) => {\n console.log(response);\n});\n```\n\n### GraphQLSchema\n\n```\nconst { graphql, GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql');\n\nconst schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n hello: {\n type: GraphQLString,\n resolve: () => 'Hello world!'\n }\n })\n })\n});\n\ngraphql(schema, '{ hello }').then((response) => {\n console.log(response);\n});\n```\n\n========================================\n\nCode:\n```js\nconst { graphql, buildSchema } = require('graphql');\n\nconst schema = buildSchema(`\n type Query {\n hello: String\n }\n`);\n\nconst root = { hello: () => 'Hello world!' };\n\ngraphql(schema, '{ hello }', root).then((response) => {\n console.log(response);\n});\n```\n\n```js\nconst { graphql, GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql');\n\nconst schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n hello: {\n type: GraphQLString,\n resolve: () => 'Hello world!'\n }\n })\n })\n});\n\ngraphql(schema, '{ hello }').then((response) => {\n console.log(response);\n});\n```\n\n```text\nconst schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n hello: {\n type: GraphQLString,\n }\n })\n })\n});\n\nconst root = { hello: () => 'Hello world!' };\n\ngraphql(schema, '{ hello }', root).then((response) => {\n console.log(response);\n});\n```\n\n```text\nconst typeDefs = `\n type Query {\n hello: String\n }\n`\n\nconst resolvers = {\n Query: {\n hello: () => 'Hello!',\n },\n}\n\nconst schema = makeExecutableSchema({ typeDefs, resolvers })\n```\n\n```text\nconst resolvers = {\n Query: {\n animals: () => getAnimalsFromDB(),\n }\n Animal: {\n __resolveType: (obj) => obj.constructor.name\n },\n Cat: {\n owner: (cat) => getOwnerFromDB(cat.ownerId),\n }\n}\n```\n\n```text\nbuildSchema\n```\n\n```text\nGraphQLSchema\n```\n\n```text\nbuildSchema\n```\n\n```text\nbuildSchema\n```\n\n```text\nbuildSchema\n```\n\n```text\nresolveType\n```\n\n```text\nisTypeOf\n```\n\n```text\nUnions\n```\n\n```text\nInterfaces\n```\n\n```text\nbuildSchema\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nbuildSchema\n```\n\n```text\nroot\n```\n\n```text\nresolve\n```\n\n```text\nhello\n```\n\n```text\nhello\n```\n\n```text\nhello\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nSubscription\n```\n\n```text\nbuildSchema\n```\n\n```text\nbuildSchema\n```\n\n```text\ngraphql-tools\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\napollo-server\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nresolvers\n```\n\n```text\nbuildSchema\n```\n\n```text\nresolveType\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nGraphQLSchema\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nbuildSchema\n```\n\n```text\nbuildSchema\n```\n\n========================================\n\nComments:\n- I'm doing totally fine with vanilla buildSchema and JS TBH. Adding the overhead of frameworks or libs really doesn't do a thing for me. I have no need for resolvers for individual fields honestly","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":41,"totalLines":285,"estimatedTokens":915}}179{"id":"stack-42021113","source":"stackoverflow","questionId":42021113,"title":"How to use curl to access the github graphql API","tags":["curl","github","graphql"],"text":"Title: How to use curl to access the github graphql API\nTags: curl, github, graphql\nSource: Stack Overflow\n\nQuestion:\nAfter referring this guide I needed to access the github `graphql` by using `curl` for a testing purpose. I tried this simple command\n\n```\ncurl -i -H \"Authorization: bearer myGithubAccessToken\" -X POST -d '{\"query\": \"query {repository(owner: \"wso2\", name: \"product-is\") {description}}\"}' https://api.github.com/graphql\n```\n\nbut it gives me\n\nproblems parsing JSON\n\nwhat I am doing wrong. I spent nearly 2 hours trying to figure it and tried different examples but none of them worked. Can you please be kind enough help me resolve this\n\n========================================\n\nTop Answer:\nIf you want your queries to stay nice and multiline, you may do like this:\n\n```\nscript='query {\n repositoryOwner(login:\\\"danbst\\\") {\n repositories(first: 100) {\n edges {\n node {\n nameWithOwner\n pullRequests(last: 100, states: OPEN) {\n edges {\n node {\n title\n url\n author {\n login\n }\n labels(first: 20) {\n edges {\n node {\n name\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}'\nscript=\"$(echo $script)\" # the query should be a one-liner, without newlines\n\ncurl -i -H 'Content-Type: application/json' \\\n -H \"Authorization: bearer .........\" \\\n -X POST -d \"{ \\\"query\\\": \\\"$script\\\"}\" https://api.github.com/graphql\n```\n\n========================================\n\nCode:\n```bash\ncurl -i -H \"Authorization: bearer myGithubAccessToken\" -X POST -d '{\"query\": \"query {repository(owner: \"wso2\", name: \"product-is\") {description}}\"}' https://api.github.com/graphql\n```\n\n```text\ngraphql\n```\n\n```text\ncurl\n```\n\n```text\n$ curl -i -H 'Content-Type: application/json' -H \"Authorization: bearer myGithubAccessToken\" -X POST -d '{\"query\": \"query {repository(owner: \\\"wso2\\\", name: \\\"product-is\\\") {description}}\"}' https://api.github.com/graphql\n```\n\n```sh\nscript='query {\n repositoryOwner(login:\\\"danbst\\\") {\n repositories(first: 100) {\n edges {\n node {\n nameWithOwner\n pullRequests(last: 100, states: OPEN) {\n edges {\n node {\n title\n url\n author {\n login\n }\n labels(first: 20) {\n edges {\n node {\n name\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}'\nscript=\"$(echo $script)\" # the query should be a one-liner, without newlines\n\ncurl -i -H 'Content-Type: application/json' \\\n -H \"Authorization: bearer .........\" \\\n -X POST -d \"{ \\\"query\\\": \\\"$script\\\"}\" https://api.github.com/graphql\n```\n\n```text\nβ― ./ghgql.sh examplequery.gql\n\n {\"data\":{\"user\":{\"repositories\":{\"nodes\":[{\"name\":\"firstrepo\",\"languages\":{\"nodes\":[]}},{\"name\":\"secondrepo\",\"languages\":{\"nodes\":[{\"name\":\"Shell\"},{\"name\":\"Vim script\"}]}},{\"name\":\"thirdrepo\",\"languages\":{\"nodes\":[{\"name\":\"TeX\"}]}}]}}}}\n\nβ― ./ghgql.sh examplequery.gql \\\n | jq -c '.data.user.repositories.nodes | to_entries | .[]' \\\n | grep 'TeX' \\\n | jq -r '.value.name'\n\n thirdrepo\n```\n\n```bash\n#!/usr/bin/env bash\n\nif [ ! -f $1 ] || [ $# -ne 1 ]\nthen\n echo Queries the github graphql API\n echo \"Usage:\"\n echo\n echo \"$0 somefile.gql\"\nfi\n\n# read the gql query from the file named in the argument\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nTOKEN=$(cat $DIR/token)\nQUERY=$(jq -n \\\n --arg q \"$(cat $1 | tr -d '\\n')\" \\\n '{ query: $q }')\n\n# do the query\ncurl -s -X POST \\\n -H \"Content-Type: application/json\" \\\n -H \"Authorization: bearer $TOKEN\" \\\n --data \"$QUERY\" \\\n https://api.github.com/graphql\n```\n\n```text\n{\n user(login: \"MatrixManAtYrService\") {\n repositories(first: 3) {\n nodes {\n name\n languages(first: 3) {\n nodes {\n name\n }\n }\n }\n }\n }\n}\n```\n\n```text\nexamplequery.gql\n```\n\n```text\n$ curl \\\n --request POST \\\n --header 'Content-Type: application/json' \\\n --data '{\"query\": \"query { fish(key:\\\"838\\\") { name } }\"}' \\\n http://localhost:4001\n\n{\"data\":{\"fish\":{\"name\":\"plecy\"}}}\n```\n\n========================================\n\nComments:\n- I came to this answer trying to access my own Django/Graphene based API; for that, I needed an extra `-H 'Content-Type: application/json'`\n- Why one needs `script=\"$(echo $script)\"`?\n- @dkrikun To remove newlines. As of time of writing newlines were not allowed in request body. `sed` solution would work here as well\n- it looks like newlines are now allowed, I've got them in my JSON (similar to the structure the explorer uses) and as long as the quotes are escaped, it works perfectly\n- I updated the solution to avoid escaping quotes, by using sed to do it.\n- Or you could just use `curl -H \"Authorization: token YOUR_GITHUB_TOKEN\" -X POST https://api.github.com/graphql --data @gql.json` with a file named `gql.json` having your object, where you can easily make changes with your favorite code editor with json formatter, etc.\n- `script=\"$(echo $script)\"` is unnecessarily obscure, and shellcheck and friends will complain about the bare `$script` without double quotes around it. I use `script=$(echo \"$script\" | tr -d '\\n')`, which is clear about what it does.\n- I change bearer to my GitHub user name and place a PAT from GitHub in a file named token in the working directory, but still get `{ \"message\": \"This endpoint requires you to be authenticated.\", \"documentation_url\": \"https://docs.github.com/graphql/guides/forming-calls-with-g‌​raphql#authenticatin‌​g-with-graphql\" }` Am I not understanding the way token is intended to be passed?\n- @robartsd the word `bearer` is not the name of a GitHub user. So you should keep it at `bearer`. I think it indicates a GitHub personal access token is comming. A working syntax could be: `-H \"Authorization: bearer somegithubpersonalaccesstoken\" `.\n- THANK YOU! underrated answer imo. This is so much easier to focus on the graphql query itself without messing up with the json formatting\n- is AFR API standard? the ones I've seen that worked all define a named query, then pass variables, and then call the query. eq query MyQuery {},\"variables\":null,\"operationName\":\"MyQuery\"","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":199,"estimatedTokens":1571}}180{"id":"stack-59891325","source":"stackoverflow","questionId":59891325,"title":"Apollo Client Cache vs. Redux","tags":["reactjs","redux","graphql","apollo-client","react-context"],"text":"Title: Apollo Client Cache vs. Redux\nTags: reactjs, redux, graphql, apollo-client, react-context\nSource: Stack Overflow\n\nQuestion:\nI'm trying to migrate from **Redux Store** to use **Apollo Client Cache** that comes with Apollo Graphql Client. \n\nOne of the key features that sets Apollo Client apart from other data management solutions is its **normalized cache**. Just by setting up Apollo Client, you get an intelligent cache out of the box with no additional configuration required. \n\nWith Redux we have to write actions, types and dispatch actions based on the response received from the side-effect and set the data in the store using reducers, which is done by Apollo Client automatically.\n\n**Questions**:\n\n1) What are the advantages of moving from Redux to Apollo Client Cache?\n\n2) Is there anything that I should be worrying about before migrating to Apollo Client Cache?\n\n========================================\n\nTop Answer:\nI think you made a good point here: \"With Redux we have to write actions, types and dispatch actions based on the response received from the side-effect and set the data in the store using reducers, which is done by Apollo Client automatically.\"\n\nFor side effects, Redux is imperative, and Apollo is declarative. Declarative code is usually shorter, since you're delegating logic to the library/framework.\n\nDaniel Rearden made a good point that comparing Redux and the Apollo client cache is like apples and oranges. The apples and oranges here are the different **types of state**, specifically *remote* and *local* state. Unfortunately, Redux encourages us to treat all state the same.\n\nI would leverage Apollo cache for state that needs to be retrieved, updated, and mutated on the server. I would reach for lighter tools like React's Context API for preventing prop drilling, global app state, and hooks for business logic (e.g. useReducer/useState).\n\nThe tricky part is when remote state and local/global app state mix. So I would be careful to define patterns around how they interact\n\n========================================\n\nCode:\n```text\nredux\n```\n\n```text\napollo-client\n```\n\n```text\nredux\n```\n\n```text\nredux\n```\n\n```text\nredux\n```\n\n```text\nredux\n```\n\n```text\napollo-client\n```\n\n```text\nuseReducer\n```\n\n```text\n@client\n```\n\n```text\napollo-client\n```\n\n```text\nredux\n```\n\n========================================\n\nComments:\n- you can use both in the same time, just move [incrementally] all data fetching/updating into apollo, move global app state management later/when ready\n- NOT ONLY GRAPHQL backend - apollo client can use REST API, apollo server can do this, too\n- @xadm you got me wrong, I didn't say apollo client \"CAN'T\", if the backend uses REST apis, then in front end in order to use the apollo client we would have to write local resolvers which would be an overhead. In my opinion using redux in such scenarios would be more suitable.\n- my comment was an addition ... **you can go with apollo even if you can't quickly adapt/wrap REST api, it can be one of [many] migration steps** ... not my downvote\n- Thanks for thr insights. Very helpful\n- The link you shared is from an article written in 2016. Just because it's old, doesn't mean it's not relevant advice. However, we've learned a lot about state management in the past 4 years. Specifically, the dangers of using one tool for every job. Redux was never designed to handle remote/async state. For side effects such as data fetching or web socket events, I think Apollo can help a lot with its cache.\n- Check out ngxs.io for the successor to ngrx\n- Thanks for your good article. I got inspired a lot from this article regarding global state management in react. One thing I am a bit curious is at the last paragraph, you noted that `apollo-client` cannot replace `redux`. I thought we can migrate from redux based app to apollo-client based... so I am not sure about your opinion.\n- \"redux allows you to create a predictable state container that changes in response to the actions you define\" Actually, Apollo's state container also changes automatically when mutations are made. Just my 2 cents.\n- Apparently, apollo client is able to replace redux. Tools like react-query is also able to replace redux. But remember, apollo and react-query also come with server state management out of the box. redux is just a client side state management solution.\n- I disagree in general. Too many devs use redux for server-side state. For those, the comparison is apples to apples.","metadata":{"transformedAt":"2026-08-18T18:32:36.035Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":91,"estimatedTokens":1121}}181{"id":"stack-65517979","source":"stackoverflow","questionId":65517979,"title":"expressGraphQL is not a function","tags":["javascript","graphql","graphql-js","nodemon","macos-big-sur"],"text":"Title: expressGraphQL is not a function\nTags: javascript, graphql, graphql-js, nodemon, macos-big-sur\nSource: Stack Overflow\n\nQuestion:\nI am learning GraphQL for my project using this tutorial:\nhttps://www.youtube.com/watch?v=ZQL7tL2S0oQ&ab_channel=WebDevSimplified\n\nand I get the error:\n\n```\nTypeError: expressGraphQL is not a function\nat Object.\n```\n\nI have already tried:\n\n- this solution: graphqlHTTP is not a function - the program crashes all the same with {} parentheses and without them\n\n- adding a semicolon after various lines\n\nThe code for now looks like this:\n\n```\nconst express = require ('express')\nconst { expressGraphQL } = require('express-graphql')\nconst app = express();\n\napp.use('/graphql', expressGraphQL({\n graphiql: true,\n})\n)\napp.listen(5000., () => console.log('Server Running'))\n```\n\nIf I comment out this section:\n\n```\napp.use('/graphql', expressGraphQL({\ngraphiql: true,\n})\n)\n```\n\nthe code works perfectly fine both with {} parentheses and without them.\n\n========================================\n\nTop Answer:\nUse following as a solution.\n\n```\nconst express = require('express');\nconst expressGraphQL = require('express-graphql').graphqlHTTP;\n\nconst app = express();\n\napp.use('/graphql', expressGraphQL({\n graphiql:true\n}));\n\napp.listen(4000, () => {\n console.log('Listning');\n})\n```\n\n========================================\n\nCode:\n```text\nTypeError: expressGraphQL is not a function\nat Object.<anonymous>\n```\n\n```text\nconst express = require ('express')\nconst { expressGraphQL } = require('express-graphql')\nconst app = express();\n\napp.use('/graphql', expressGraphQL({\n graphiql: true,\n})\n)\napp.listen(5000., () => console.log('Server Running'))\n```\n\n```text\napp.use('/graphql', expressGraphQL({\ngraphiql: true,\n})\n)\n```\n\n```text\nconst { graphqlHTTP } = require('express-graphql');\n```\n\n```text\nconst expressGraphQL = require('express-graphql').graphqlHTTP\n```\n\n```text\nconst { graphqlHTTP } = require('express-graphql');\n```\n\n```text\nconst graphqlHTTP = require('express-graphql').graphqlHTTP;\n```\n\n```text\nenter code here\n```\n\n```text\nconst express = require('express');\nconst expressGraphQL = require('express-graphql').graphqlHTTP;\n\n\nconst app = express();\n\napp.use('/graphql', expressGraphQL({\n graphiql:true\n}));\n\napp.listen(4000, () => {\n console.log('Listning');\n})\n```\n\n```text\nconst { graphqlHTTP } = require(\"express-graphql\");\n\napp.use(\"/graphql\", graphqlHTTP({ graphiql: true }));\n```\n\n========================================\n\nComments:\n- I think this question is so popular because this tutorial gives incorrect instructions\n- and +1 also coming from this tutorial (:\n- I am also coming from the same tutorial. I opened a PR on the author's github repo fixing the issue.\n- github.com/ankitamasand/gql-server/pull/3\n- best answer! Also, you can use it as a reference expressGraphQL using `const { graphqlHTTP: expressGraphQL } = require('express-graphql');`\n- Can anyone explain why this destructuring is needed? I worked with graph before and you didnt have to call .graphqlHTTP. I worked the same way this persons tutorial is stating so I am just curious what changed in the last year or so and why this is now needed?","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":144,"estimatedTokens":793}}182{"id":"stack-41944291","source":"stackoverflow","questionId":41944291,"title":"Apollo client is giving me an error of 'store already contains an id' - what does that mean?","tags":["graphql","react-apollo","apollo-client"],"text":"Title: Apollo client is giving me an error of 'store already contains an id' - what does that mean?\nTags: graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nIn a react native project I am creating an object and then redirecting the screen to the newly created object's details page and I'm getting this error:\n\nPossible Unhandled Promise Rejection (id: 0):\nNetwork error: Store error: the application attempted to write an object with no provided id but the store already contains an id of XYZ for this object.\n\nLooking in the database I see that the item is properly created in the previous step. Navigating to the same screen and item through a list (not after a create and redirect) seems to work fine. Do I have to wait or somehow set some sort of timing for the apollo store to stay correct?\n\nI'm using the standard apollo client @graphql binding/wrapping\n\ngql:\n\n```\nquery getEvent($eventId: ID!) {\n Event(id:$eventId) {\n id\n headline\n photo\n location\n startTime\n creator {\n username\n photo\n }\n }\n }\n`;\n```\n\nAnd here's a code snippet\n\n```\n@graphql(getEventGql,{\n options: ({route}) => {\n console.log('route params', route.params);\n return {\n variables: {\n eventId: route.params.eventId,\n }\n }\n },\n})\n\n@connect((state) => ({ user: state.user }))\nexport default class EventDetailScreen extends Component {\n...\n```\n\n========================================\n\nCode:\n```text\nquery getEvent($eventId: ID!) {\n Event(id:$eventId) {\n id\n headline\n photo\n location\n startTime\n creator {\n username\n photo\n }\n }\n }\n`;\n```\n\n```text\n@graphql(getEventGql,{\n options: ({route}) => {\n console.log('route params', route.params);\n return {\n variables: {\n eventId: route.params.eventId,\n }\n }\n },\n})\n\n@connect((state) => ({ user: state.user }))\nexport default class EventDetailScreen extends Component {\n...\n```\n\n```text\nquery getEvent($eventId: ID!) {\n Event(id:$eventId) {\n id\n headline\n photo\n location\n startTime\n creator {\n id\n username\n photo\n }\n }\n }\n```\n\n```text\nid\n```\n\n```text\ncreator\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- Had this error where there was no need for an id in a nested property but needed the id at the root level, so this answer was helpful. I would appreciate an explanation of why though.\n- @ABCD.ca I am not 100% sure, but it seems that some result caching is going on, so you have to provide the unique identifier for apollo client to retrieve it. Makes some sense, but I have not had this issue prior to the release of 1.0.0, so I have temporarily reverted to 0.10.1\n- Also be careful include `__typename` or avoid it if you're testing with MockProvider. But in some cases you have to include `__typename` allowing it in the MockProvider","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":124,"estimatedTokens":714}}183{"id":"stack-47283891","source":"stackoverflow","questionId":47283891,"title":"GraphQL - fetch a field conditionally","tags":["graphql"],"text":"Title: GraphQL - fetch a field conditionally\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nImagine that I have a following query (I am using Apollo):\n\n```\nconst userQuery = gql`\n query {\n user {\n id\n name\n }\n }\n `;\n```\n\nI want to fetch `name` field only if some condition is met (let's say variable `shouldFetchName` is `true`). How should I approach this and what is the best practice?\n\n========================================\n\nCode:\n```text\nconst userQuery = gql`\n query {\n user {\n id\n name\n }\n }\n `;\n```\n\n```text\nname\n```\n\n```text\nshouldFetchName\n```\n\n```text\ntrue\n```\n\n```text\nname @include(if: $shouldFetchName)\n```\n\n========================================\n\nComments:\n- This a partial solution, with \"include\", the database still makes the calculations to return \"name\", but the \"include\" just filters the response to the client. So this will not result in a faster query. Do you know a better solution ?\n- If the `@include` directive evaluates to false then the `name` resolver will not be called. What your database does is entirely up to you: Apollo Server doesn't know or care about that part. If you want to dynamically build SQL queries from your GraphQL queries, you may like github.com/join-monster/join-monster.","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":55,"estimatedTokens":315}}184{"id":"stack-46163036","source":"stackoverflow","questionId":46163036,"title":"What is AST in graphql?","tags":["graphql","abstract-syntax-tree","graphql-js"],"text":"Title: What is AST in graphql?\nTags: graphql, abstract-syntax-tree, graphql-js\nSource: Stack Overflow\n\nQuestion:\nWhat is AST in graphql ? I am using graphql-js. How does it help with anything?\n\nNothing in any documentation seems to explain what AST is\n\n========================================\n\nComments:\n- AST stands for Abstract Syntax Tree in web technologies not only in graphql. You can read it up here: en.wikipedia.org/wiki/Abstract_syntax_tree\n- Actually not only in web technologies, AST is a broader term in computer science.\n- AST = abstract syntax tree","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":15,"estimatedTokens":141}}185{"id":"stack-50462944","source":"stackoverflow","questionId":50462944,"title":"Is it possible to query the same field multiple times with graphql","tags":["graphql"],"text":"Title: Is it possible to query the same field multiple times with graphql\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nWhat I want to do is to query for a particular field multiple times with different arguments. Is that possible in GraphQL? \n\nSomething like this:\n\n```\nquery {\n myItem(size: 100, type: 2) {\n id,\n name\n }\n myItem(size: 150, type: 2) {\n id,\n name\n }\n myItem(size: 10, type: 1) {\n id,\n name\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n myItem(size: 100, type: 2) {\n id,\n name\n }\n myItem(size: 150, type: 2) {\n id,\n name\n }\n myItem(size: 10, type: 1) {\n id,\n name\n }\n}\n```\n\n```text\nquery {\n item1: myItem(size: 100, type: 2) {\n id,\n name\n }\n item2: myItem(size: 150, type: 2) {\n id,\n name\n }\n item3: myItem(size: 10, type: 1) {\n id,\n name\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":62,"estimatedTokens":220}}186{"id":"stack-44711161","source":"stackoverflow","questionId":44711161,"title":"What is the difference between OData, JsonAPI, GraphQL?","tags":["odata","graphql","json-api"],"text":"Title: What is the difference between OData, JsonAPI, GraphQL?\nTags: odata, graphql, json-api\nSource: Stack Overflow\n\nQuestion:\nI have used OData in my career quite a bit and now few of my colleagues from different teams recommended we move to JsonAPI and GraphQL as its not tied to Microsoft. I don't have much experience in both these query languages. As far as i know OData is a standard used by Salesforce, IBM, Microsoft and it is very mature. Why should one switch to JsonAPI and/or GraphQL? Is there a real benefit? Is JsonAPI and GraphQL new standard? Changing public api implementations based on popularity seems useless especially when there is no big benefit. \n\nCan someone please enlighten me?\n\n========================================\n\nCode:\n```text\nlink\n```\n\n========================================\n\nComments:\n- GraphQL is not a replacement for REST but an alternative when versioning may be an issue\n- They all seem to suffer NIH syndrome. Like MS is evil etc.","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":21,"estimatedTokens":244}}187{"id":"stack-39471075","source":"stackoverflow","questionId":39471075,"title":"When to use GraphQLID instead of GraphQLInt?","tags":["graphql","graphql-js"],"text":"Title: When to use GraphQLID instead of GraphQLInt?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nIt is not clear when to use `GraphQLID` instead of `GraphQLInt`.\n\nConsider the following schema:\n\n```\ntype User {\n id: Int!\n firstName: String!\n lastName: String!\n}\n\ntype Query {\n user (id: ID!): User\n}\n```\n\nIn case of `Query.user`, it seem to make no difference whether to use `GraphQLID` or `GraphQLInt`.\n\nIn case of `User.id`, using `GraphQLID` will cast the input to string. Using `GraphQLInt` will ensure that the input is an integer.\n\nThis makes the query and type system inconsistent.\n\nThe graphql-js spec simply says:\n\n A `GraphQLScalarType` that represents an ID.\n\nIs this an implementation detail (e.g. should GraphQL client cast `GraphQLID` to an integer when it can), or is it expected that `ID` is always a string in graphql?\n\n========================================\n\nCode:\n```text\ntype User {\n id: Int!\n firstName: String!\n lastName: String!\n}\n\ntype Query {\n user (id: ID!): User\n}\n```\n\n```text\nGraphQLID\n```\n\n```text\nGraphQLInt\n```\n\n```text\nQuery.user\n```\n\n```text\nGraphQLID\n```\n\n```text\nGraphQLInt\n```\n\n```text\nUser.id\n```\n\n```text\nGraphQLID\n```\n\n```text\nGraphQLInt\n```\n\n```text\nGraphQLScalarType\n```\n\n```text\nGraphQLID\n```\n\n```text\nID\n```\n\n```text\nString\n```\n\n```text\nString\n```\n\n```text\nString\n```\n\n```text\n\"4\"\n```\n\n```text\n4\n```\n\n```text\n4.0\n```\n\n```text\nbase64\n```\n\n```text\ngraphql-relay-js\n```\n\n```text\ntoGlobalId\n```\n\n```text\nfromGlobalId\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":131,"estimatedTokens":371}}188{"id":"stack-46562561","source":"stackoverflow","questionId":46562561,"title":"Apollo/GraphQL field type for object with dynamic keys","tags":["graphql","apollo","apollo-server"],"text":"Title: Apollo/GraphQL field type for object with dynamic keys\nTags: graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nLet's say my graphql server wants to fetch the following data as JSON where `person3` and `person5` are some id's:\n\n```\n\"persons\": {\n \"person3\": {\n \"id\": \"person3\",\n \"name\": \"Mike\"\n },\n \"person5\": {\n \"id\": \"person5\",\n \"name\": \"Lisa\"\n }\n}\n```\n\n**Question**: How to create the schema type definition with apollo?\n\nThe keys `person3` and `person5` here are dynamically generated depending on my query (i.e. the `area` used in the query). So at another time I might get `person1`, `person2`, `person3` returned.\nAs you see `persons` is not an Iterable, so the following won't work as a graphql type definition I did with apollo:\n\n```\ntype Person {\n id: String\n name: String\n}\ntype Query {\n persons(area: String): [Person]\n}\n```\n\nThe keys in the `persons` object may always be different.\n\nOne solution of course would be to transform the incoming JSON data to use an array for `persons`, but is there no way to work with the data as such?\n\n========================================\n\nTop Answer:\nYou can write your own `GraphQLScalarType` and precisely describe your object and your dynamic keys, what you allow and what you do not allow or transform.\n\nSee https://graphql.org/graphql-js/type/#graphqlscalartype\n\nYou can have a look at taion/graphql-type-json where he creates a Scalar that allows and transforms any kind of content:\n\nhttps://github.com/taion/graphql-type-json/blob/master/src/index.js\n\n========================================\n\nCode:\n```text\n\"persons\": {\n \"person3\": {\n \"id\": \"person3\",\n \"name\": \"Mike\"\n },\n \"person5\": {\n \"id\": \"person5\",\n \"name\": \"Lisa\"\n }\n}\n```\n\n```text\ntype Person {\n id: String\n name: String\n}\ntype Query {\n persons(area: String): [Person]\n}\n```\n\n```text\nperson3\n```\n\n```text\nperson5\n```\n\n```text\nperson3\n```\n\n```text\nperson5\n```\n\n```text\narea\n```\n\n```text\nperson1\n```\n\n```text\nperson2\n```\n\n```text\nperson3\n```\n\n```text\npersons\n```\n\n```text\npersons\n```\n\n```text\npersons\n```\n\n```text\ntype Query {\n persons(area: String): JSON\n}\n```\n\n```text\nGraphQLScalarType\n```\n\n```text\nquery lookupPersons {\n persons {\n personKeys\n person3: personValue(key: \"person3\") {\n id\n name\n }\n }\n}\n```\n\n```text\n{\n data: {\n persons: {\n personKeys: [\"person1\", \"person2\", \"person3\"]\n person3: {\n id: \"person3\"\n name: \"Mike\"\n }\n }\n }\n}\n```\n\n```text\ntype Person {\n id: String\n name: String\n}\n\ntype PersonsResult {\n personKeys: [String]\n personValue(key: String): Person\n}\n\ntype Query {\n persons(area: String): PersonsResult\n}\n```\n\n```text\npersonKeys\n```\n\n========================================\n\nComments:\n- Can you clarify what you mean by `b` and `g` being `dynamically generated depending on my query`? Does the presence of one or the other depend on the fields present in the request?\n- @DanielRearden So `b` and `g` are id's. Perhaps I should make that clearer in the question. The query will contain options to only get a subset of people, so for one query the response will contain people with id's `a`, `b`, `c` and for another query for example `b` and `g` as in the question.\n- @DanielRearden I now changed `b` to `person3` and `g` to `person 5` and added some text and a variable to make it clearer. The query will contain options to only get a subset of people as now outlined in the text.\n- github.com/graphql/graphql-spec/issues/101\n- Thanks for your comments! I transform the incoming data from the server. FYI: The reason for objects with ids was faster retrieval on client side because it's just a lookup of an id to access a particular person.\n- My situation is returning validation errors via a Rails / GraphQL API. I don't know in advance what keys will have errors, hence I'm using a custom JSON scalar.\n- Actually I changed my approach to use nested arrays which allowed me to consistently return the fields with errors.\n- What does the server-side GraphQL schema look like for this? It's a bit unclear to me. (you only show the query's client-provided shape, and the server's response)","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":187,"estimatedTokens":1033}}189{"id":"stack-64105940","source":"stackoverflow","questionId":64105940,"title":"GraphQLError: Query root type must be provided","tags":["postgresql","graphql","nestjs","typeorm"],"text":"Title: GraphQLError: Query root type must be provided\nTags: postgresql, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS, TypeORM and GraphQL for my backend API. I'm getting the following error:\n\n```\nGraphQLError [Object]: Query root type must be provided.\n at SchemaValidationContext.reportError (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:88:19)\n at validateRootTypes (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:107:13)\n at validateSchema (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:52:3)\n at graphqlImpl (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:79:62)\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:28:59\n at new Promise ()\n at Object.graphql (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:26:10)\n at GraphQLSchemaFactory. (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:49:52)\n at Generator.next ()\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/tslib/tslib.js:114:75\n```\n\nThis is what my file structure and code looks like:\nhttps://i.sstatic.net/fpUEL.png\n\nCan someone please help me. My repo: https://github.com/wise-introvert/nestjs-graphql-api.git\n\n========================================\n\nTop Answer:\nAlso ensure the Resolver is added in the module providers\n\n```\n@Module({\n imports: [\n GraphQLModule.forRoot({\n installSubscriptionHandlers: true,\n autoSchemaFile: true,\n }),\n ],\n controllers: [],\n providers: [FooResolver], //< This\n})\nexport class FooModule {}\n```\n\n========================================\n\nCode:\n```text\nGraphQLError [Object]: Query root type must be provided.\n at SchemaValidationContext.reportError (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:88:19)\n at validateRootTypes (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:107:13)\n at validateSchema (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:52:3)\n at graphqlImpl (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:79:62)\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:28:59\n at new Promise (<anonymous>)\n at Object.graphql (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:26:10)\n at GraphQLSchemaFactory.<anonymous> (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:49:52)\n at Generator.next (<anonymous>)\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/tslib/tslib.js:114:75\n```\n\n```js\n@Resolver()\nexport class FooResolver {\n\n @Query(() => String)\n sayHello(): string {\n return 'Hello World!';\n }\n}\n```\n\n```text\n@Query()\n```\n\n```js\n@Module({\n imports: [\n GraphQLModule.forRoot({\n installSubscriptionHandlers: true,\n autoSchemaFile: true,\n }),\n ],\n controllers: [],\n providers: [FooResolver], //< This\n})\nexport class FooModule {}\n```\n\n```js\n// Correct\nimport { Resolver, Query } from '@nestjs/graphql';\n\n// Incorrect in NestJS\nimport { Resolver, Query } from 'type-graphql';\n```\n\n```text\n@Module({ providers: [NftsResolver, NftsService] })\nexport class NftsModule {}\n```\n\n```text\nnfts.module.ts\n```\n\n```text\napp.module.ts\n```\n\n```js\n@Module({\n imports: [\n GraphQLModule.forRoot<ApolloDriverConfig>({\n driver: ApolloDriver,\n typePaths: ['./**/*.graphql'],\n definitions: {\n path: join(process.cwd(), 'src/graphql.ts'),\n outputAs: 'class',\n },\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n```\n\n```text\ntypePaths\n```\n\n```text\ndefinitions\n```\n\n```text\n*.graphql\n```\n\n========================================\n\nComments:\n- I've added a dummy function under `@Query` decorator in my resolver but it's still throwing the same error.\n- Thanks! This was the issue for me. The accepted answer did not solve the bug for me.\n- What was missing for me was `autoSchemaFile: true` in the options object.","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":147,"estimatedTokens":1136}}190{"id":"stack-48940240","source":"stackoverflow","questionId":48940240,"title":"Using GraphQL Fragment on multiple types","tags":["graphql","apollo"],"text":"Title: Using GraphQL Fragment on multiple types\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nIf I have a set of field that is common to multiple types in my GraphQL schema, is there a way to do something like this?\n\n```\ntype Address {\n line1: String\n city: String\n state: String \n zip: String\n}\n\nfragment NameAndAddress on Person, Business {\n name: String\n address: Address\n}\n\ntype Business {\n ...NameAndAddress\n hours: String\n}\n\ntype Customer {\n ...NameAndAddress\n customerSince: Date\n}\n```\n\n========================================\n\nTop Answer:\nFragments are only used on the client-side when making requests -- they can't be used inside your schema. GraphQL does not support type inheritance or any other mechanism that would reduce the redundancy of having to write out the same fields for different types.\n\nIf you're using `apollo-server`, the type definitions that make up your schema are just a string, so you can implement the functionality you're looking for through template literals:\n\n```\nconst nameAndAddress = `\n name: String\n address: Address\n`\n\nconst typeDefs = `\n type Business {\n ${nameAndAddress}\n hours: String\n }\n\n type Customer {\n ${nameAndAddress}\n customerSince: Date\n }\n`\n```\n\nAlternatively, there are libraries out there, like graphql-s2s, that allow you to use type inheritance.\n\n========================================\n\nCode:\n```text\ntype Address {\n line1: String\n city: String\n state: String \n zip: String\n}\n\nfragment NameAndAddress on Person, Business {\n name: String\n address: Address\n}\n\ntype Business {\n ...NameAndAddress\n hours: String\n}\n\ntype Customer {\n ...NameAndAddress\n customerSince: Date\n}\n```\n\n```text\ninterface NameAndAddress {\n name: String\n address: Address\n}\n\n\ntype Address {\n line1: String\n city: String\n state: String \n zip: String\n}\n\ntype Business implements NameAndAddress {\n # by design you have to write those properties again\n name: String\n address: Address\n\n hours: String\n}\n\ntype Customer implements NameAndAddress {\n name: String\n address: Address\n\n customerSince: Date\n}\n```\n\n```text\n# define a fragment on the interface\nfragment NameAndAddress on NameAndAddress {\n name: String\n address: Address\n}\n\n# you can then get the fields as follow\nquery {\n business {\n ...NameAndAddress\n }\n\n customer {\n ...NameAndAddress\n }\n}\n```\n\n```text\nconst nameAndAddress = `\n name: String\n address: Address\n`\n\nconst typeDefs = `\n type Business {\n ${nameAndAddress}\n hours: String\n }\n\n type Customer {\n ${nameAndAddress}\n customerSince: Date\n }\n`\n```\n\n```text\napollo-server\n```\n\n========================================\n\nComments:\n- I find it strange that this isn't supported in GraphQL. It's the case that a type and its corresponding input have a lot of shared fields. Using string interpolation means I can't use just plain `.graphql` files. It also means another language can't use that same `.graphql` file. Seems like this should really be supported in GraphQL.\n- It is pretty strange there is no type inheritance.\n- Is there an update on this ?\n- Just as shocked as everyone else here. This should be a thing.\n- Interfaces can only be used in schemas not when making requests.\n- Yes, but you can then add a fragment on the interface\n- If the server does not provide a common interface type, is there nothing the client can do? Even if the fields are the same.\n- The purpose of defining an interface on the server side is to ensure compatibility and consistency of properties, even if the fields the same name. Sharing the same fragment among different types would break this safety. *I did not try*, but perhaps you can make use of an union type ? something like this: ``` interface A { id: ID! name: String! } interface B { id: ID! surname: String! } union AorB = A | B fragment CommonId on AorB { ...on A { id } ...on B { id } } ``` otherwise try using a client side schema transformer (but ugly)","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":169,"estimatedTokens":980}}191{"id":"stack-55259856","source":"stackoverflow","questionId":55259856,"title":"How to remove the `__typename` field from the graphql response which fails the mutations","tags":["node.js","graphql","apollo","apollo-client","express-graphql"],"text":"Title: How to remove the `__typename` field from the graphql response which fails the mutations\nTags: node.js, graphql, apollo, apollo-client, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI tried changing the addTypeName: false in the Apollo client in GraphQL\n\n```\napollo.create({\n link: httpLinkWithErrorHandling,\n cache: new InMemoryCache({ addTypename: false }),\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all'\n }\n }\n```\n\nBut it works and it throws the following messages in the console\n\n```\nfragmentMatcher.js:26 You're using fragments in your queries, but either don't have the addTypename:true option set in Apollo Client, or you are trying to write a fragment to the store without the __typename.Please turn on the addTypename option and include __typename when writing fragments so that Apollo Clientcan accurately match fragments.\n```\n\n,\n\n```\nCould not find __typename on Fragment PopulatedOutageType\n```\n\nand\n\n```\nfragmentMatcher.js:28 DEPRECATION WARNING: using fragments without __typename is unsupported behavior and will be removed in future versions of Apollo client. You should fix this and set addTypename to true now.\n```\n\neven if i change false to true `new InMemoryCache({ addTypename: true }),` the mutations start failing because of the unwanted typename in the mutation \n\nis there any way to resolve this issue\n\n========================================\n\nTop Answer:\nA clean solution with the latest Apollo Client consists of using an appropriate `Link` within the apollo client.\n\nHere is an example\n\n```\nimport { removeTypenameFromVariables } from '@apollo/client/link/remove-typename';\n\nconst removeTypenameLink = removeTypenameFromVariables();\n\nimport { from } from '@apollo/client';\n\nconst link = from([removeTypenameLink, httpLink]);\n\nconst client = new ApolloClient({\n link,\n // ... other options\n});\n```\n\nA full detail from Apollo docs can be found here\n\n========================================\n\nCode:\n```text\napollo.create({\n link: httpLinkWithErrorHandling,\n cache: new InMemoryCache({ addTypename: false }),\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all'\n }\n }\n```\n\n```text\nfragmentMatcher.js:26 You're using fragments in your queries, but either don't have the addTypename:true option set in Apollo Client, or you are trying to write a fragment to the store without the __typename.Please turn on the addTypename option and include __typename when writing fragments so that Apollo Clientcan accurately match fragments.\n```\n\n```text\nCould not find __typename on Fragment PopulatedOutageType\n```\n\n```text\nfragmentMatcher.js:28 DEPRECATION WARNING: using fragments without __typename is unsupported behavior and will be removed in future versions of Apollo client. You should fix this and set addTypename to true now.\n```\n\n```text\nnew InMemoryCache({ addTypename: true }),\n```\n\n```text\nimport { removeTypenameFromVariables } from '@apollo/client/link/remove-typename';\n\nconst removeTypenameLink = removeTypenameFromVariables();\n\nimport { from } from '@apollo/client';\n\nconst link = from([removeTypenameLink, httpLink]);\n\nconst client = new ApolloClient({\n link,\n // ... other options\n});\n```\n\n```text\nLink\n```\n\n========================================\n\nComments:\n- Asked and answered here: Apollo boost - __typename in query prevent new mutation. If you're using a query results as initial state, you'll need to transform it first to strip out the `__typename` fields (and any other fields that may not be valid input fields).\n- Probably worth noting that this will likely break caching unless you make adjustments. github.com/apollographql/apollo-client/issues/2881\n- This question was more generalized but got more attention and has a more reviewed answer. stackoverflow.com/questions/47211778/…\n- This works only for variables. The question was about graphql responses, where your approach won't work!","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":122,"estimatedTokens":986}}192{"id":"stack-39551325","source":"stackoverflow","questionId":39551325,"title":"Github graphQL OrderBy","tags":["github","graphql","github-graphql"],"text":"Title: Github graphQL OrderBy\nTags: github, graphql, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQL query.\nI cannot understand why it is not working.\n\n```\n{\n repositoryOwner(login: \"Naramsim\") {\n login\n repositories(first: 3, isFork: true, orderBy: {field: CREATED_AT}) {\n edges {\n node {\n description\n }\n }\n }\n }\n}\n```\n\nLink\n\n========================================\n\nCode:\n```graphql\n{\n repositoryOwner(login: \"Naramsim\") {\n login\n repositories(first: 3, isFork: true, orderBy: {field: CREATED_AT}) {\n edges {\n node {\n description\n }\n }\n }\n }\n}\n```\n\n```text\nArgument 'orderBy' on Field 'repositories' has an invalid value.\nExpected type 'RepositoryOrder'.\n```\n\n```graphql\n{\n repositoryOwner(login: \"Naramsim\") {\n login\n repositories(first: 3, isFork: true, orderBy: {field: CREATED_AT, direction: ASC}) {\n edges {\n node {\n description\n }\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- can I get all repositories without pagination?\n- @DaviWesley I think that's best asked in a separate question, if it hasn't been asked already (which it probably has)\n- Hi Alex, What about if I want to change the created_at field with dropdown? Like name etc. I need something dynamically.\n- @UfukUYSAL this is bit of work. You start with dynamic react graph and then move on to the gui with react. As your comment is one year old, maybe you did that?\n- In the ordering, you use `CREATED_AT` with `_`. There is also `CREATEDAT` without hiven. What is the diff?\n- Can you point us to the docs where you got the snippet \"Argument...\" from? I found repo object info, but without `orderby`.","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":72,"estimatedTokens":426}}193{"id":"stack-59555497","source":"stackoverflow","questionId":59555497,"title":"Validation error of type SubSelectionRequired: Sub selection required for type null of field","tags":["graphql","graphql-java"],"text":"Title: Validation error of type SubSelectionRequired: Sub selection required for type null of field\nTags: graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI am working on a graphql issue where I am getting following error for the request\n\n```\n{\n customer(id: \"5ed6092b-6924-4d31-92d0-b77d4d777b47\") {\n id\n firstName\n lastName\n carsInterested\n }\n}\n\n \"message\": \"Validation error of type SubSelectionRequired: Sub selection required for type null of field carsInterested @ 'customer/carsInterested'\",\n```\n\nBelow is my schema\n\n```\ntype Customer {\n id: ID!\n firstName: String!\n lastName: String!\n # list of cars that the customer is interested in\n carsInterested: [Car!]\n\n}\n\ntype Query {\n # return 'Customer'\n customer(id: ID!): Customer\n}\n```\n\nI do have a CustomerResolver with function carsInterested in it.It looks as follows\n\n```\n@Component\npublic class CustomerResolver implements GraphQLResolver {\n\n private final CarRepository carRepo;\n\n public CustomerResolver(CarRepository carRepo) {this.carRepo = carRepo;}\n\n public List carsInterested(Customer customer) {\n return carRepo.getCarsInterested(customer.getId());\n }\n}\n```\n\nWhen I query for customer without 'carsInterested', it works properly. Any idea why I am getting this error?\n\nThanks\n\n========================================\n\nTop Answer:\nIf you are using codegen, you may need to regenerate the code for the GraphQL types as the frontend could be out of sync.\n\n========================================\n\nCode:\n```text\n{\n customer(id: \"5ed6092b-6924-4d31-92d0-b77d4d777b47\") {\n id\n firstName\n lastName\n carsInterested\n }\n}\n\n \"message\": \"Validation error of type SubSelectionRequired: Sub selection required for type null of field carsInterested @ 'customer/carsInterested'\",\n```\n\n```text\ntype Customer {\n id: ID!\n firstName: String!\n lastName: String!\n # list of cars that the customer is interested in\n carsInterested: [Car!]\n\n}\n\ntype Query {\n # return 'Customer'\n customer(id: ID!): Customer\n}\n```\n\n```text\n@Component\npublic class CustomerResolver implements GraphQLResolver<Customer> {\n\n private final CarRepository carRepo;\n\n public CustomerResolver(CarRepository carRepo) {this.carRepo = carRepo;}\n\n public List<Car> carsInterested(Customer customer) {\n return carRepo.getCarsInterested(customer.getId());\n }\n}\n```\n\n```text\n{\n customer(id: \"5ed6092b-6924-4d31-92d0-b77d4d777b47\") {\n id\n firstName\n lastName\n carsInterested {\n # one or more Car fields here\n }\n }\n}\n```\n\n```text\ncarsInterested\n```\n\n```text\nCars\n```\n\n```text\nCar\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":133,"estimatedTokens":641}}194{"id":"stack-48004805","source":"stackoverflow","questionId":48004805,"title":"How to get requested fields inside GraphQL resolver?","tags":["graphql","graphql-js"],"text":"Title: How to get requested fields inside GraphQL resolver?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am using `graphql-tools`. After receiving a GraphQL query, I execute a search using ElasticSearch and return the data.\n\nHowever, usually the requested query includes only a few of the possible fields, not all. I want to pass only the requested fields to ElasticSearch. \nFirst, I need to get the requested fields.\n\nI can already get the whole query as a string. For example, in the resolver,\n\n```\nconst resolvers = {\n Query: {\n async user(p, args, context) {\n //can print query as following\n console.log(context.query) \n }\n .....\n }\n}\n```\n\nIt prints as\n\n```\nquery User { user(id:\"111\") { id name address } }\n```\n\nIs there any way to get the requested fields in a format like\n\n```\n{ id:\"\", name:\"\", address:\"\" }\n```\n\n========================================\n\nTop Answer:\nThere is an `info` object passed as the 4th argument in the resolver. This argument contains the information you're looking for.\n\nIt can be helpful to use a library as `graphql-fields` to help you parse the graphql query data:\n\n```\nconst graphqlFields = require('graphql-fields');\n\nconst resolvers = {\n Query: {\n async user(_, args, context, info) {\n const topLevelFields = graphqlFields(info);\n console.log(Object.keys(topLevelFields)); // ['id', 'name', 'address']\n },\n};\n```\n\n========================================\n\nCode:\n```text\nconst resolvers = {\n Query: {\n async user(p, args, context) {\n //can print query as following\n console.log(context.query) \n }\n .....\n }\n}\n```\n\n```text\nquery User { user(id:\"111\") { id name address } }\n```\n\n```text\n{ id:\"\", name:\"\", address:\"\" }\n```\n\n```text\ngraphql-tools\n```\n\n```text\n// See below about resolver functions.\ntype GraphQLFieldResolveFn = (\n source?: any,\n args?: {[argName: string]: any},\n context?: any,\n info?: GraphQLResolveInfo\n) => any\n\ntype GraphQLResolveInfo = {\n fieldName: string,\n fieldNodes: Array<Field>,\n returnType: GraphQLOutputType,\n parentType: GraphQLCompositeType,\n schema: GraphQLSchema,\n fragments: { [fragmentName: string]: FragmentDefinition },\n rootValue: any,\n operation: OperationDefinition,\n variableValues: { [variableName: string]: any },\n}\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nfieldNodes\n```\n\n```text\nselectionSet\n```\n\n```text\nselections\n```\n\n```text\nconst graphqlFields = require('graphql-fields');\n\nconst resolvers = {\n Query: {\n async user(_, args, context, info) {\n const topLevelFields = graphqlFields(info);\n console.log(Object.keys(topLevelFields)); // ['id', 'name', 'address']\n },\n};\n```\n\n```text\ninfo\n```\n\n```text\ngraphql-fields\n```\n\n```text\npublic List<User> getUsers(final UsersFilter filter, DataFetchingEnvironment env) {\n\n DataFetchingFieldSelectionSet selectionSet = env.getSelectionSet();\n selectionSet.getFields(); // <---List of selected fields\n selectionSet.getArguments(); // <--- Similarly but MAP\n ...\n\n }\n```\n\n```text\ngraphql-java\n```\n\n```text\nmyGetUsersResolverMethod(... DataFetchingEnvironment env)\n```\n\n```text\nDataFetchingEnvironment\n```\n\n```text\nDataFetchingEnvironment\n```\n\n```text\ngraph\n```\n\n```text\nquery operationName($var: String!) {\n queryName(arg1: $var) {\n a\n b {\n c\n }\n }\n }\n```\n\n```js\n// my resolver\n{\n Query: {\n queryName: async (_, args, __, info) => {\n\n const topLevelFields = info.fieldNodes.reduce((all, currentNode) => {\n all.push(\n ...currentNode.selectionSet.selections.map(\n selection => {\n // or if selection.selectionSet is present, we can recursively get it's name.value, ('c' in this example)\n return selection.name.value;\n }\n )\n );\n return all;\n }, []);\n\n console.log(topLevelFields); // ['a','b']\n }\n }\n}\n```\n\n```text\nimport { lookahead } from 'graphql-lookahead'\n\nexport const resolvers = {\n Query: {\n async user(_parent, _args, _context, info) {\n const requestedFields = []\n lookahead({ info, next: ({ field }) => requestedFields.push(field) })\n\n console.log(requestedFields)\n // => ['id', 'name', 'address']\n\n // or the object format from your question:\n const requestFieldObject = {}\n lookahead({ info, next: ({ field }) => (requestFieldObject[field] = '') })\n\n console.log(requestedFields)\n // => {Β id: '', name: '', address: '' }\n }\n // ...\n }\n}\n```\n\n```text\ninfo\n```\n\n```text\nselectionSet\n```\n\n```text\ninfo.fieldNodes\n```\n\n========================================\n\nComments:\n- This is a essentially a duplicate of How to get the fields requested in a query from resolver\n- I did not see such argument . I am using \"graphql-tools\".\n- I could see my query from info.fieldNodes[0].selectionSet.selections[0].loc.source.bod‌​y\n- I am thinking put `graphqlFields` method to a graphql middleware can reduce the duplicated code.\n- Note that the author of graphql-fields recommends using `graphql-parse-resolve-info` going forward.","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":250,"estimatedTokens":1268}}195{"id":"stack-40697597","source":"stackoverflow","questionId":40697597,"title":"GraphQL mutation that accepts an array of dynamic size and common scalar types in one request","tags":["javascript","graphql","apollostack"],"text":"Title: GraphQL mutation that accepts an array of dynamic size and common scalar types in one request\nTags: javascript, graphql, apollostack\nSource: Stack Overflow\n\nQuestion:\nI need to be able to create a user and add it's favourite movies (An array of objects with a reference to the Movies collection and his personal rating for each movie) in a single request.\n\nSomething that could look like this (pseudocode)\n\n```\nvar exSchema = `\n type Mutation {\n addUser(\n name: String!\n favMovies: [{ movie: String! #ref to movies coll\n personal_rating: Int! # this is different for every movie\n }]\n ) : User\n }\n...\n`\n```\n\nWhat is the graphql way of doing this in a single request? I know I can achieve the result with multiple mutations/requests but I would like to do it in a single one.\n\n========================================\n\nTop Answer:\nI came up with this simple solution - NO JSON used. Only one input is used. Hope it will help someone else.\n\nI had to add to this type:\n\n```\ntype Option {\n id: ID!\n status: String!\n products: [Product!]!\n}\n```\n\nWe can add to mutation type and add input as follows:\n\n```\ntype Mutation {\n createOption(data: [createProductInput!]!): Option!\n // other mutation definitions\n}\n\ninput createProductInput {\n id: ID!\n name: String!\n price: Float!\n producer: ID!\n status: String\n}\n```\n\nThen following resolver could be used:\n\n```\nconst resolvers = {\n Mutation: {\n createOption(parent, args, ctx, info) {\n\n const status = args.data[0].status;\n\n // Below code removes 'status' from all array items not to pollute DB.\n // if you query for 'status' after adding option 'null' will be shown. \n // But 'status': null should not be added to DB. See result of log below.\n args.data.forEach((item) => {\n delete item.status\n });\n\n console.log('args.data - ', args.data);\n\n const option = {\n id: uuidv4(),\n status: status, // or if using babel status,\n products: args.data\n }\n\n options.push(option)\n\n return option\n },\n // other mutation resolvers\n }\n```\n\nNow you can use this to add an option (STATUS is taken from first item in the array - it is nullable):\n\n```\nmutation{\n createOption(data:\n [{\n id: \"prodB\",\n name: \"componentB\",\n price: 20,\n producer: \"e4\",\n status: \"CANCELLED\"\n },\n {\n id: \"prodD\",\n name: \"componentD\",\n price: 15,\n producer: \"e5\"\n }\n ]\n ) {\n id\n status\n products{\n name\n price\n }\n }\n}\n```\n\nProduces:\n\n```\n{\n \"data\": {\n \"createOption\": {\n \"id\": \"d12ef60f-21a8-41f3-825d-5762630acdb4\",\n \"status\": \"CANCELLED\",\n \"products\": [\n {\n \"name\": \"componentB\",\n \"price\": 20,\n },\n {\n \"name\": \"componentD\",\n \"price\": 15,\n }\n ]\n }\n }\n}\n```\n\nNo need to say that to get above result you need to add:\n\n```\ntype Query {\n products(query: String): [Product!]!\n // others\n}\n\ntype Product {\n id: ID!\n name: String!\n price: Float!\n producer: Company!\n status: String\n}\n```\n\nI know it is not the best way, but I did not find a way of doing it in documentation.\n\n========================================\n\nCode:\n```text\nvar exSchema = `\n type Mutation {\n addUser(\n name: String!\n favMovies: [{ movie: String! #ref to movies coll\n personal_rating: Int! # this is different for every movie\n }]\n ) : User\n }\n...\n`\n```\n\n```text\nvar MovieSchema = `\n type Movie {\n name: String\n }\n input MovieInput {\n name: String\n }\n mutation {\n addMovies(movies: [MovieInput]): [Movie]\n }\n`\n```\n\n```text\nmutation {\n addMovies(movies: [{name: 'name1'}, {name: 'name2'}]) {\n name\n }\n}\n```\n\n```js\nconst id = 5;\nconst title = 'Title test';\n\nlet formattedAttachments = '';\nattachments.map(attachment => {\n formattedAttachments += `{ id: ${attachment.id}, short_id: \"${attachment.shortid}\" }`; \n // { id: 1, short_id: \"abcxyz\" }{ id: 2, short_id: \"bcdqrs\" }\n});\n\n// Query\nconst query = `\n mutation {\n addChallengeReply(\n challengeId: ${id}, \n title: \"${title}\", \n attachments: [${formattedAttachments}]\n ) {\n id\n title\n description\n }\n }\n`;\n```\n\n```text\ntype Option {\n id: ID!\n status: String!\n products: [Product!]!\n}\n```\n\n```text\ntype Mutation {\n createOption(data: [createProductInput!]!): Option!\n // other mutation definitions\n}\n\ninput createProductInput {\n id: ID!\n name: String!\n price: Float!\n producer: ID!\n status: String\n}\n```\n\n```text\nconst resolvers = {\n Mutation: {\n createOption(parent, args, ctx, info) {\n\n const status = args.data[0].status;\n\n // Below code removes 'status' from all array items not to pollute DB.\n // if you query for 'status' after adding option 'null' will be shown. \n // But 'status': null should not be added to DB. See result of log below.\n args.data.forEach((item) => {\n delete item.status\n });\n\n console.log('args.data - ', args.data);\n\n const option = {\n id: uuidv4(),\n status: status, // or if using babel status,\n products: args.data\n }\n\n options.push(option)\n\n return option\n },\n // other mutation resolvers\n }\n```\n\n```text\nmutation{\n createOption(data:\n [{\n id: \"prodB\",\n name: \"componentB\",\n price: 20,\n producer: \"e4\",\n status: \"CANCELLED\"\n },\n {\n id: \"prodD\",\n name: \"componentD\",\n price: 15,\n producer: \"e5\"\n }\n ]\n ) {\n id\n status\n products{\n name\n price\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"createOption\": {\n \"id\": \"d12ef60f-21a8-41f3-825d-5762630acdb4\",\n \"status\": \"CANCELLED\",\n \"products\": [\n {\n \"name\": \"componentB\",\n \"price\": 20,\n },\n {\n \"name\": \"componentD\",\n \"price\": 15,\n }\n ]\n }\n }\n}\n```\n\n```text\ntype Query {\n products(query: String): [Product!]!\n // others\n}\n\ntype Product {\n id: ID!\n name: String!\n price: Float!\n producer: Company!\n status: String\n}\n```\n\n```text\nconst user = {\n name:\"Rohit\", \n age:27, \n marks: [10,15], \n subjects:[\n {name:\"maths\"},\n {name:\"science\"}\n ]\n};\n\nconst query = `mutation {\n createUser(user:${user}) {\n name\n }\n}`\n```\n\n```text\n\"mutation {\n createUser(user:[object Object]) {\n name\n }\n}\"\n```\n\n```text\n\"mutation {\n createUser(user:{\n name: \"Rohit\" ,\n age: 27 ,\n marks: [10 ,15 ] ,\n subjects: [\n {name: \"maths\" } ,\n {name: \"science\" } \n ] \n }) {\n name\n }\n}\"\n```\n\n```text\nconst user = {\n name:\"Rohit\", \n age:27, \n marks: [10,15], \n subjects:[\n {name:\"maths\"},\n {name:\"science\"}\n ]\n};\n\nconst query = gqlast`mutation {\n createUser(user:${user}) {\n name\n }\n}`\n```\n\n```text\n\"mutation {\n createUser(user:{\n name: \"Rohit\" ,\n age: 27 ,\n marks: [10 ,15 ] ,\n subjects: [\n {name: \"maths\" } ,\n {name: \"science\" } \n ] \n }) {\n name\n }\n}\"\n```\n\n```text\nquery\n```\n\n```text\nfunction createProject() {\n for (let i = 0; i < state.arrOfItems.length; i++) {\n const { mutate: addImplementation } = useMutation(\n post_dataToServer,\n () => ({\n variables: {\n implementation_type_id: state.arrOfItems[i],\n sow_id: state.newSowId,\n },\n })\n );\n\n addImplementation();\n }\n}\n```\n\n```text\n<div v-for=\"(card, id) in state.arrOfItems\">\n <ChildComponent\n :id=\"id\"\n :card=\"card\"\n />\n</div>\n```\n\n```text\nconst { mutate: addImplementation } = useMutation(\n post_dataToServer,\n () => ({\n variables: {\n implementation_id: props.arrOfItems,\n id: props.id,\n },\n })\n );\n```\n\n========================================\n\nComments:\n- Define an input type on your schema that has your `name` and `favMovies`. Have `addUser()` take an instance of that type as its argument. AFAIK, list fields are valid for input types.\n- Yep, I have to give that a try, I was looking for a better example though\n- In Javascript you can convert a json array to meet this schema like so: `favMovies: ${JSON.stringify(moviesArray).replace(/\"([^(\")\"]+)\":/g,\"$1:\"‌​)}`\n- @Gazta I have the same problem, have you find a way to pass the JSON array as a string? How did you escape it?\n- @EdmondTamas added the solution\n- JSON.stringify also parses the key though: addMovies(movies: [{ \"name\": \"name1\" }] -- which throws an error\n- this would be so cool but as I change `movies: String` to `movies: [MovieInput]` graphql throws *Error: Expected Input type.* Of course before this I have declared the `Type MovieInput`\n- @octohedron Thank you so much! I've been trying to figure this out.\n- @EdmondTamas note that `MovieInput` is not a type, but rather an `input`; So like shown in the answer, got to have two definitions, one for the `type` and another for the `input` - and the names must be different from each other as well, since two definitions with the same name are not allowed.","metadata":{"transformedAt":"2026-08-18T18:32:36.036Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":474,"estimatedTokens":2293}}196{"id":"stack-58475780","source":"stackoverflow","questionId":58475780,"title":"React Apollo Error: Invariant Violation: Could not find \"client\" in the context or passed in as an option","tags":["reactjs","graphql","apollo","next.js"],"text":"Title: React Apollo Error: Invariant Violation: Could not find \"client\" in the context or passed in as an option\nTags: reactjs, graphql, apollo, next.js\nSource: Stack Overflow\n\nQuestion:\nI'm building a project using React, Apollo and Next.js. I'm trying to update react-apollo to 3.1.3 and I'm now getting the following error when viewing the site.\n\n Invariant Violation: Could not find \"client\" in the context or passed in as an option. Wrap the root component in an , or pass an ApolloClient instance in via options.\n\nIf I downgrade the react-apollo package to 2.5.8 it works without issue so I'm thinking something has changed between 2.5 and 3.x but can't find anything in the react-apollo or next-with-apollo documentation to indicate what that might be. Any assistance would be greatly appreciated.\n\nwithData.js\n\n```\nimport withApollo from 'next-with-apollo';\nimport ApolloClient from 'apollo-boost';\nimport { endpoint } from '../config';\n\nfunction createClient({ headers }) {\n return new ApolloClient({\n uri: endpoint,\n request: operation => {\n operation.setContext({\n fetchOptions: {\n credentials: 'include'\n },\n headers\n });\n },\n // local data\n clientState: {\n resolvers: {\n Mutation: {}\n },\n defaults: {}\n }\n });\n}\n\nexport default withApollo(createClient);\n```\n\n_app.js\n\n```\nimport App from 'next/app';\nimport { ApolloProvider } from 'react-apollo';\nimport Page from '../components/Page';\nimport { Overlay } from '../components/styles/Overlay';\nimport withData from '../lib/withData';\n\nclass MyApp extends App {\n static async getInitialProps({ Component, ctx }) {\n let pageProps = {};\n if (Component.getInitialProps) {\n pageProps = await Component.getInitialProps(ctx);\n }\n\n // this exposes the query to the user\n pageProps.query = ctx.query;\n return { pageProps };\n }\n\n render() {\n const { Component, apollo, pageProps } = this.props;\n\n return (\n \n \n \n \n \n \n );\n }\n}\n\nexport default withData(MyApp);\n```\n\n========================================\n\nTop Answer:\nI've had a mixture of solutions, i think it does boil down to how you initially go about setting up all the related packages.\n\n\"Some packages don't work well with others when it comes to connecting the client to Reacts `Context.Provider`\"\n\nI've had two go two fixes that seem to work well (With new projects and updating old):\n\n1: Uninstall `@apollo/react-hooks`\n\nThen:\n\n```\nimport { ApolloProvider } from \"@apollo/client\";\n```\n\ninstead of:\n\n```\nimport { ApolloProvider } from \"react-apollo\";\n```\n\n(This allowed me to keep the \"@apollo/react-hooks\" package without conflicts)\n\n3: Double-check that the server that is serving `HttpLink` client `URI` is up and running for the client to connect (This give a different error then the one were talking about but is still good to know in this situation)\n\n**Conclusion:** It can be a slight bit of trial and error, but try to use the matching/pairing packages\n\n========================================\n\nCode:\n```text\nimport withApollo from 'next-with-apollo';\nimport ApolloClient from 'apollo-boost';\nimport { endpoint } from '../config';\n\nfunction createClient({ headers }) {\n return new ApolloClient({\n uri: endpoint,\n request: operation => {\n operation.setContext({\n fetchOptions: {\n credentials: 'include'\n },\n headers\n });\n },\n // local data\n clientState: {\n resolvers: {\n Mutation: {}\n },\n defaults: {}\n }\n });\n}\n\nexport default withApollo(createClient);\n```\n\n```text\nimport App from 'next/app';\nimport { ApolloProvider } from 'react-apollo';\nimport Page from '../components/Page';\nimport { Overlay } from '../components/styles/Overlay';\nimport withData from '../lib/withData';\n\nclass MyApp extends App {\n static async getInitialProps({ Component, ctx }) {\n let pageProps = {};\n if (Component.getInitialProps) {\n pageProps = await Component.getInitialProps(ctx);\n }\n\n // this exposes the query to the user\n pageProps.query = ctx.query;\n return { pageProps };\n }\n\n render() {\n const { Component, apollo, pageProps } = this.props;\n\n return (\n <ApolloProvider client={apollo}>\n <Overlay id=\"page-overlay\" />\n <Page>\n <Component {...pageProps} />\n </Page>\n </ApolloProvider>\n );\n }\n}\n\nexport default withData(MyApp);\n```\n\n```text\nreact-apollo@3.0.1\n```\n\n```text\n@apollo/react-hooks@3.0.0\n```\n\n```text\n@apollo/react-hooks\n```\n\n```text\nreact-apollo\n```\n\n```text\npackage.json\n```\n\n```text\n@apollo/client\n```\n\n```text\napollo-link\n```\n\n```text\nimport { ApolloProvider } from \"@apollo/client\";\n```\n\n```text\nimport { ApolloProvider } from \"react-apollo\";\n```\n\n```text\nContext.Provider\n```\n\n```text\n@apollo/react-hooks\n```\n\n```text\nHttpLink\n```\n\n```text\nURI\n```\n\n```text\nimport gql from 'graphql-tag';\nimport {graphql} from '@apollo/react-hoc';\nimport { ApolloClient, InMemoryCache } from '@apollo/client';\nimport { ApolloProvider } from '@apollo/react-hooks';\n```\n\n```text\n\"resolutions\": {\n \"@apollo/react-common\": \"3.1.3\",\n \"@apollo/react-hooks\": \"3.1.3\",\n },\n```\n\n========================================\n\nComments:\n- Then there's also `react-apollo-hooks` vs `@apollo/react-hooks` β you want the latter, watch out!\n- Similar case for me- I had been importing ApolloProvider from react-apollo but importing useQuery from @apollo/react-hooks. Importing ApolloProvider from @apollo/react-hooks fixed the issue for me.\n- @DannyRosenblatt that was the case for me as well, I think most of the tutorials online the approach of importing the ApolloProvider from 'react-apollo' instead of @apollo/react-hooks.\n- The documentation for apollo v2 is terrible - if you wanna use react components, instead of hooks, you'll need to manually install @apollo/react-components and import everything from there instead. It doesn't say that anywhere, had to figure it out hard way.\n- You found what to be the solution?\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":252,"estimatedTokens":1589}}197{"id":"stack-68437734","source":"stackoverflow","questionId":68437734,"title":"Jest has detected the following 1 open handle potentially keeping Jest from exiting: TCPSERVERWRAP","tags":["typescript","jestjs","graphql","nestjs","supertest"],"text":"Title: Jest has detected the following 1 open handle potentially keeping Jest from exiting: TCPSERVERWRAP\nTags: typescript, jestjs, graphql, nestjs, supertest\nSource: Stack Overflow\n\nQuestion:\nI am doing a basic end to end testing here, for the moment it's failing, but first I can't get rid of the open handle.\n\n```\nRan all test suites.\n\nJest has detected the following 1 open handle potentially keeping Jest from exiting:\n\n β TCPSERVERWRAP\n\n 40 | }\n 41 | return request(app.getHttpServer())\n > 42 | .post('/graphql')\n | ^\n 43 | .send(mutation)\n 44 | .expect(HttpStatus.OK)\n 45 | .expect((response) => {\n\n at Test.Object..Test.serverAddress (../node_modules/supertest/lib/test.js:61:33)\n at new Test (../node_modules/supertest/lib/test.js:38:12)\n at Object.obj. [as post] (../node_modules/supertest/index.js:27:14)\n at Object. (app.e2e-spec.ts:42:8)\n```\n\n```\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { HttpStatus, INestApplication } from \"@nestjs/common\";\nimport * as request from 'supertest'\nimport { AppModule } from '../src/app.module'\n\ndescribe('AppController (e2e)', () => {\n let app: INestApplication\n\n beforeEach(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile()\n\n app = moduleFixture.createNestApplication()\n await app.init()\n })\n\n afterAll(async () => {\n await app.close()\n })\n\n it('/ (GET)', () => {\n return request(app.getHttpServer())\n .get('/')\n .expect(HttpStatus.OK)\n .expect('Hello World!')\n })\n\n it('mutation', async () => {\n const mutation = {\n query: `mutation Create($title: String!) {\n create(title: $title) {\n id,\n title\n }\n }`,\n variables: {\n title: 'Mon programme',\n },\n }\n return request(app.getHttpServer())\n .post('/graphql')\n .send(mutation)\n .expect(HttpStatus.OK)\n .expect( (response) => {\n expect(response.body).toBe({\n id: expect.any(String),\n title: 'Mon programme',\n })\n })\n })\n})\n```\n\nAny idea what's blocking the test runner ?\n\nNote that, as I am using NestJs, I shouldn't need to use the `.end(done)` method at the end of the test.\n\nPS: apparently I have to much code on this question and I need to add some more details, but have no clue what I can say more.\n\n========================================\n\nTop Answer:\nThis is the problem right here\n\n```\nit('/ (GET)', () => {\n return request(app.getHttpServer())\n ^^^^^^^^^^^^^^^^^^^^^\n .get('/')\n .expect(HttpStatus.OK)\n .expect('Hello World!')\n })\n```\n\nThe server isn't being closed and remains open after the test. You need to create a variable to reference the instance and close it after each test.\nI just spent a couple of hours trying to figure this out. And hope this helps anyone experiencing similar issues.\n\nHere is an example of your code with my idea for a fix:\n\n```\ndescribe('AppController (e2e)', () => {\n let app: INestApplication\n let server: SERVER_TYPE\n\n beforeEach(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile()\n\n app = moduleFixture.createNestApplication()\n await app.init()\n // Reference the server instance\n server = app.getHttpServer()\n })\n\n afterEach(async () => {\n await app.close()\n // Close the server instance after each test\n server.close()\n })\n\n it('/ (GET)', async () => {\n // Make the request on the server instance\n return await request(server)\n .get('/')\n .expect(HttpStatus.OK)\n .expect('Hello World!')\n })\n```\n\nAlso, I noticed you're using `beforeEach` and `afterAll`. You're creating a new app each time for each test so I think that could also cause some issues for the HTTP server. I'm not certain on that though.\n\n```\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { HttpStatus, INestApplication } from \"@nestjs/common\";\nimport * as request from 'supertest'\nimport { AppModule } from '../src/app.module'\n\nbeforeEach(() => {\n ...\n})\n\nafterEach(() => {\n ...\n})\n\ndescribe('tests', () => {\n ...\n})\n```\n\nBut, that's just my preference, up to you. :)\n\nUPDATE: Meant to use `beforeEach` not `beforeAll` because we need to close the server before EACH test, not a global setup and teardown.\n\nUPDATE 2: Using async/await otherwise, it will always pass because request is asynchronous and doesn't complete unless you wait for it to finish.\n\n========================================\n\nCode:\n```text\nRan all test suites.\n\nJest has detected the following 1 open handle potentially keeping Jest from exiting:\n\n β TCPSERVERWRAP\n\n 40 | }\n 41 | return request(app.getHttpServer())\n > 42 | .post('/graphql')\n | ^\n 43 | .send(mutation)\n 44 | .expect(HttpStatus.OK)\n 45 | .expect((response) => {\n\n at Test.Object.<anonymous>.Test.serverAddress (../node_modules/supertest/lib/test.js:61:33)\n at new Test (../node_modules/supertest/lib/test.js:38:12)\n at Object.obj.<computed> [as post] (../node_modules/supertest/index.js:27:14)\n at Object.<anonymous> (app.e2e-spec.ts:42:8)\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { HttpStatus, INestApplication } from \"@nestjs/common\";\nimport * as request from 'supertest'\nimport { AppModule } from '../src/app.module'\n\ndescribe('AppController (e2e)', () => {\n let app: INestApplication\n\n beforeEach(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile()\n\n app = moduleFixture.createNestApplication()\n await app.init()\n })\n\n afterAll(async () => {\n await app.close()\n })\n\n it('/ (GET)', () => {\n return request(app.getHttpServer())\n .get('/')\n .expect(HttpStatus.OK)\n .expect('Hello World!')\n })\n\n it('mutation', async () => {\n const mutation = {\n query: `mutation Create($title: String!) {\n create(title: $title) {\n id,\n title\n }\n }`,\n variables: {\n title: 'Mon programme',\n },\n }\n return request(app.getHttpServer())\n .post('/graphql')\n .send(mutation)\n .expect(HttpStatus.OK)\n .expect( (response) => {\n expect(response.body).toBe({\n id: expect.any(String),\n title: 'Mon programme',\n })\n })\n })\n})\n```\n\n```text\n.end(done)\n```\n\n```text\njest --config ./test/jest-e2e.json --forceExit\n```\n\n```text\nbeforeEach\n```\n\n```text\nafterAll\n```\n\n```text\nrequest\n```\n\n```text\nbeforeEach\n```\n\n```text\nbeforeAll\n```\n\n```text\ntest('mutation', async (done) => {\n const mutation = {\n query: `mutation Create($title: String!) {\n create(title: $title) {\n id,\n title\n }\n }`,\n variables: {\n title: 'Mon programme',\n },\n }\n const response = request(app.getHttpServer())\n .post('/graphql')\n .send(mutation)\n expect(response).to.be(HttpStatus.Ok)\n done()\n })\n```\n\n```text\nit\n```\n\n```text\ntest\n```\n\n```text\ndone\n```\n\n```js\nit('the description', (done) => {\n request(app)\n .get('/some-path')\n .end(done);\n });\n```\n\n```js\nit('/ (GET)', () => {\n return request(app.getHttpServer())\n ^^^^^^^^^^^^^^^^^^^^^\n .get('/')\n .expect(HttpStatus.OK)\n .expect('Hello World!')\n })\n```\n\n```js\ndescribe('AppController (e2e)', () => {\n let app: INestApplication\n let server: SERVER_TYPE\n\n beforeEach(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [AppModule],\n }).compile()\n\n app = moduleFixture.createNestApplication()\n await app.init()\n // Reference the server instance\n server = app.getHttpServer()\n })\n\n afterEach(async () => {\n await app.close()\n // Close the server instance after each test\n server.close()\n })\n\n it('/ (GET)', async () => {\n // Make the request on the server instance\n return await request(server)\n .get('/')\n .expect(HttpStatus.OK)\n .expect('Hello World!')\n })\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing'\nimport { HttpStatus, INestApplication } from \"@nestjs/common\";\nimport * as request from 'supertest'\nimport { AppModule } from '../src/app.module'\n\nbeforeEach(() => {\n ...\n})\n\nafterEach(() => {\n ...\n})\n\ndescribe('tests', () => {\n ...\n})\n```\n\n```text\nbeforeEach\n```\n\n```text\nafterAll\n```\n\n```text\nbeforeEach\n```\n\n```text\nbeforeAll\n```\n\n```text\nafterEach\n```\n\n```text\nafterEach(async () => {\n```\n\n```text\nawait userService.logout();\n```\n\n```text\n});\n```\n\n```text\npackage.json\n```\n\n```text\nscripts\n```\n\n```text\ntest:e2e\n```\n\n```text\n--detectOpenHandles\n```\n\n```text\n\"test:e2e\": \"jest --config ./test/jest-e2e.json --forceExit\"\n```\n\n```text\n--no-cache --watchAll\n```\n\n```text\n\"test\": \"jest --watchAll --no-cache --detectOpenHandles\"\n```\n\n```text\n\"test:e2e\": \"jest --config ./test/jest-e2e.json --no-cache --detectOpenHandles\",\n```\n\n```text\nafterAll(async () => {\n await server.close();\n await pool.end();\n});\n```\n\n```text\nprocess.exit()\n```\n\n========================================\n\nComments:\n- Thank for the answer. But unfortunately it has no effect.\n- @AMehmeto hm, strange, are you running multiple tests in parallel or just one file?\n- Just one file only.\n- @AMehmeto my second guess is that something is happening within your app that keeps it from exiting. Have you read through this thread, expecially the linked comment?\n- thank you so much I have spent hours trying to mock the setInterval() function causing problems but it didn't work. This is an easy, simple fix.\n- I had --forceExit and --detectOpenHandles in my script after removed --detectOpenHandles it solved \"test:e2e\": \"jest --config ./test/jest-e2e.json --forceExit\"\n- adding `--no-cache --watchAll` fixed for me, as answered by tonskton. my script: `jest --config ./test/jest-e2e.json --detectOpenHandles --watchAll --no-cache`\n- i don't think you need `--detectOpenHandles` in your script since that's more for debugging. I guess if you want to always have that output, then sure, but it's not necessary to get jest to exit.\n- `--watchAll` fixes the issue for me too but then requires interaction. This isn't great in a CI/CD build though.\n- No joy here. So far only the `--forceExit` options works for me.\n- it and test are the same\n- Actually there are two approaches mixed here, either use async or the done callback. You will notice using both isn't possible in Typescript, where it refuses to run this code.\n- As itβs currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- I don't know why, but this is the only thing that worked for me, `--no-cache --watchAll` did the trick. `--watchAll` is not optional which makes no sense to me, however I'm happy it works, I am using mongoose and mongodb-memory-server\n- but it seems like not the best option due to: \"The cache should only be disabled if you are experiencing caching related problems. On average, disabling the cache makes Jest at least two times slower.\" from official docs","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":468,"estimatedTokens":2763}}198{"id":"stack-56319137","source":"stackoverflow","questionId":56319137,"title":"Why does a GraphQL query return null?","tags":["graphql","graphql-js","apollo-server"],"text":"Title: Why does a GraphQL query return null?\nTags: graphql, graphql-js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI have an `graphql`/`apollo-server`/`graphql-yoga` endpoint. This endpoint exposes data returned from a database (or a REST endpoint or some other service).\n\nI know my data source is returning the correct data -- if I log the result of the call to the data source inside my resolver, I can see the data being returned. However, my GraphQL field(s) always resolve to null.\n\nIf I make the field non-null, I see the following error inside the `errors` array in the response:\n\n Cannot return null for non-nullable field\n\nWhy is GraphQL not returning the data?\n\n========================================\n\nTop Answer:\nI had the same issue on Nest.js.\n\nIf you like to solve the issue. You can add {nullable: true} option to your @Query decorator.\n\nHere's an example.\n\n```\n@Resolver(of => Team)\nexport class TeamResolver {\n constructor(\n private readonly teamService: TeamService,\n private readonly memberService: MemberService,\n ) {}\n\n @Query(returns => Team, { name: 'team', nullable: true })\n @UseGuards(GqlAuthGuard)\n async get(@Args('id') id: string) {\n return this.teamService.findOne(id);\n }\n}\n```\n\nThen, you can return null object for query.\n\nhttps://i.sstatic.net/zDdrN.png\n\n========================================\n\nCode:\n```text\ngraphql\n```\n\n```text\napollo-server\n```\n\n```text\ngraphql-yoga\n```\n\n```text\nerrors\n```\n\n```text\ntype Query {\n post(id: ID): Post\n posts: [Post]\n}\n\ntype Post {\n id: ID\n title: String\n body: String\n}\n```\n\n```text\nquery {\n post {\n id\n title\n body\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"post\" {\n \"id\": null,\n \"title\": \"My First Post\",\n \"body\": null,\n }\n }\n}\n```\n\n```text\nfunction post (root, args) {\n // axios\n return axios.get(`http://SOME_URL/posts/${args.id}`)\n .then(res => res.data);\n\n // fetch\n return fetch(`http://SOME_URL/posts/${args.id}`)\n .then(res => res.json());\n\n // request-promise-native\n return request({\n uri: `http://SOME_URL/posts/${args.id}`,\n json: true\n });\n}\n```\n\n```text\n{\n \"status\": 200,\n \"result\": {\n \"id\": 1,\n \"title\": \"My First Post\",\n \"body\": \"Hello world!\"\n },\n}\n```\n\n```text\nfunction post (root, args) {\n // axios\n return axios.get(`http://SOME_URL/posts/${args.id}`)\n .then(res => res.data.result);\n\n // fetch\n return fetch(`http://SOME_URL/posts/${args.id}`)\n .then(res => res.json())\n .then(data => data.result);\n\n // request-promise-native\n return request({\n uri: `http://SOME_URL/posts/${args.id}`,\n json: true\n })\n .then(res => res.result);\n}\n```\n\n```text\nfunction post(root, args, context) {\n return context.Post.find({ where: { id: args.id } })\n}\n```\n\n```text\nfunction post(root, args, context) {\n return context.Post.find({ where: { id: args.id } })\n .then(posts => posts[0])\n}\n```\n\n```text\nfunction post(root, args, context) {\n return context.Post.findOne({ where: { id: args.id } })\n}\n```\n\n```text\nfunction posts (root, args) {\n return fetch('http://SOME_URL/posts')\n .then(res => res.json())\n}\n```\n\n```text\n{\n \"count\": 10,\n \"next\": \"http://SOME_URL/posts/?page=2\",\n \"previous\": null,\n \"results\": [\n {\n \"id\": 1,\n \"title\": \"My First Post\",\n \"body\" \"Hello World!\"\n },\n ...\n ]\n}\n```\n\n```text\nfunction posts (root, args) {\n return fetch('http://SOME_URL/posts')\n .then(res => res.json())\n .then(data => data.results)\n}\n```\n\n```text\nfunction post(root, args) {\n return getPost(args.id)\n}\n```\n\n```text\nfunction post(root, args) {\n getPost(args.id)\n}\n```\n\n```text\nfunction post(root, args) {\n return getPost(args.id)\n .then(post => {\n console.log(post)\n })\n}\n```\n\n```text\nfunction post(root, args) {\n return getPost(args.id)\n .then(post => {\n console.log(post)\n return post // <----\n })\n}\n```\n\n```text\nfunction post(root, args) {\n return getFoo()\n .then(foo => {\n // Do something with foo\n return getBar() // return next Promise in the chain\n })\n .then(bar => {\n // Do something with bar\n return getPost(args.id) // return next Promise in the chain\n })\n```\n\n```text\nfunction post(root, args) {\n return Post.findOne({ where: { id: args.id } }, function (err, post) {\n return post\n })\n```\n\n```text\nfunction post(root, args) {\n return new Promise((resolve, reject) => {\n Post.findOne({ where: { id: args.id } }, function (err, post) {\n if (err) {\n reject(err)\n } else {\n resolve(post)\n }\n })\n })\n```\n\n```text\ndata\n```\n\n```text\npost\n```\n\n```text\n{ title: 'My First Post', bod: 'Hello World!' }\n```\n\n```text\nPost\n```\n\n```text\npost\n```\n\n```text\ntitle\n```\n\n```text\ntitle\n```\n\n```text\npost\n```\n\n```text\nid\n```\n\n```text\npost\n```\n\n```text\nid\n```\n\n```text\nbody\n```\n\n```text\nbod\n```\n\n```text\nbody\n```\n\n```text\nbod\n```\n\n```text\nbody\n```\n\n```text\n(parent) => parent.bod\n```\n\n```text\npost\n```\n\n```text\nPost\n```\n\n```text\npost\n```\n\n```text\npost\n```\n\n```text\nPost\n```\n\n```text\nid\n```\n\n```text\ntitle\n```\n\n```text\nbody\n```\n\n```text\nid\n```\n\n```text\ntitle\n```\n\n```text\nbody\n```\n\n```text\nResult\n```\n\n```text\nrows\n```\n\n```text\nfields\n```\n\n```text\nrowCount\n```\n\n```text\ncommand\n```\n\n```text\nPost\n```\n\n```text\nsequelize\n```\n\n```text\nfindAll\n```\n\n```text\nmongoose\n```\n\n```text\ntypeorm\n```\n\n```text\nfind\n```\n\n```text\nWHERE\n```\n\n```text\npost\n```\n\n```text\nfindOne\n```\n\n```text\nINSERT\n```\n\n```text\nUPDATE\n```\n\n```text\nsequelize\n```\n\n```text\nupsert\n```\n\n```text\nreturning\n```\n\n```text\nmongoose\n```\n\n```text\nfindOneAndUpdate\n```\n\n```text\nvalue\n```\n\n```text\nposts\n```\n\n```text\nList\n```\n\n```text\nPost\n```\n\n```text\n{ id: 1, title: 'Hello!' }\n```\n\n```text\nList\n```\n\n```text\nerrors\n```\n\n```text\ngetPost\n```\n\n```text\npost\n```\n\n```text\ngetPosts\n```\n\n```text\nreturn\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n```text\ngetPost\n```\n\n```text\nUnhandledPromiseRejectionWarning\n```\n\n```text\nreturn\n```\n\n```text\ngetPost\n```\n\n```text\nthen\n```\n\n```text\nArray.map\n```\n\n```text\nthen\n```\n\n```text\nthen\n```\n\n```text\nthen\n```\n\n```text\nthen\n```\n\n```text\nundefined\n```\n\n```text\nthen\n```\n\n```text\ngetFoo\n```\n\n```text\ngetBar\n```\n\n```text\ngetPost\n```\n\n```text\nmongoose\n```\n\n```text\nfindOne\n```\n\n```text\nPost.findOne\n```\n\n```text\npost\n```\n\n```text\nmongoose\n```\n\n```js\n@Resolver(of => Team)\nexport class TeamResolver {\n constructor(\n private readonly teamService: TeamService,\n private readonly memberService: MemberService,\n ) {}\n\n @Query(returns => Team, { name: 'team', nullable: true })\n @UseGuards(GqlAuthGuard)\n async get(@Args('id') id: string) {\n return this.teamService.findOne(id);\n }\n}\n```\n\n```js\nintercept(\n context: ExecutionContext,\n next: CallHandler,\n ): Observable<Response<T>> {\n if (context['contextType'] === 'graphql') return next.handle();\n\n return next\n .handle()\n .pipe(map(data => {\n return {\n data: isObject(data) ? this.transformResponse(data) : data\n };\n }));\n }\n```\n\n```js\n// This will return values, as you expect.\n\nconst typeDefs = require('./schema');\nconst resolvers = require('./resolver');\n\nconst server = new ApolloServer({typeDefs,resolvers});\n```\n\n```js\n// This will return null, since ApolloServer constructor is not using correct properties.\n\nconst withDifferentVarNameSchema = require('./schema');\nconst withDifferentVarNameResolver= require('./resolver');\n\nconst server = new ApolloServer({withDifferentVarNameSchema,withDifferentVarNameResolver});\n```\n\n```text\napollo-server-express\n```\n\n```text\ntype TypeName {\n id: ID!\n ...\n _version: Int!\n _deleted: Boolean\n _lastChangedAt: AWSTimestamp!\n createdAt: AWSDateTime!\n updatedAt: AWSDateTime!\n }\n```\n\n```text\n_lastChangedAt\n```\n\n```text\nAWSTimestamp\n```\n\n```text\nremove the null-check (!) from the field\n```\n\n```text\namplify.push\n```\n\n========================================\n\nComments:\n- Note: This question is meant to serve as a reference question and a potential dupe target for similar questions. This is why the question is broad and omits any specific code or schema details. See this meta post for additional details.\n- I think you should change title as this is still not easy findable by \"Cannot return null for non-nullable field\" or even \"[graphql] Cannot return null for non-nullable field\" .... \"Cannot return null for non-nullable field - why it returns null?\" ?\n- Wow... ya, graphql solves a problem if you're facebook, for the rest of us, we have to read responses like this to understand the most basic concepts of it. Maybe at the end of the day the problem is increased complexity with unclear added value. e.g. graphql\n- I posted this answer here because a question on this URL(stackoverflow.com/questions/58140891/…) is marked as duplication of this question.\n- I was using Nest JS and forgot to register the module π€¦\n- GraphQl will only accept `typeDefs` and `resolvers` as key names, so `withDifferentVarNameSchema` and `withDifferentVarNameResolver` won't work\n- @darKnight I was trying to saying the same as your comment. I think you missed the text for respective code example, note as well, Attached the same text to code example now\n- Or, just use Typescript.","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":115,"totalLines":683,"estimatedTokens":2285}}199{"id":"stack-49897319","source":"stackoverflow","questionId":49897319,"title":"graphql, union scalar type?","tags":["graphql","graphql-js"],"text":"Title: graphql, union scalar type?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nThe `payload` field can be `Int` or `String` scalar type.\nwhen I write it like union type:\n\n```\nconst schema = `\n input QuickReply {\n content_type: String\n title: String\n payload: Int | String\n image_url: String\n }\n`\n```\n\nI got an error:\n\n```\nGraphQLError: Syntax Error GraphQL request (45:18) Expected Name, found |\n\n 44: title: String\n 45: payload: Int | String\n ^\n 46: image_url: String\n```\n\nIt seems `GraphQL` does not support the union scalar type.\n\nSo, how can I solve this situation?\n\n========================================\n\nCode:\n```js\nconst schema = `\n input QuickReply {\n content_type: String\n title: String\n payload: Int | String\n image_url: String\n }\n`\n```\n\n```sh\nGraphQLError: Syntax Error GraphQL request (45:18) Expected Name, found |\n\n 44: title: String\n 45: payload: Int | String\n ^\n 46: image_url: String\n```\n\n```text\npayload\n```\n\n```text\nInt\n```\n\n```text\nString\n```\n\n```text\nGraphQL\n```\n\n```text\nconst MAX_INT = 2147483647\nconst MIN_INT = -2147483648\nconst coerceIntString = (value) => {\n if (Array.isArray(value)) {\n throw new TypeError(`IntString cannot represent an array value: [${String(value)}]`)\n }\n if (Number.isInteger(value)) {\n if (value < MIN_INT || value > MAX_INT) {\n throw new TypeError(`Value is integer but outside of valid range for 32-bit signed integer: ${String(value)}`)\n }\n return value\n }\n return String(value)\n}\nconst IntString = new GraphQLScalarType({\n name: 'IntString',\n serialize: coerceIntString,\n parseValue: coerceIntString,\n parseLiteral(ast) {\n if (ast.kind === Kind.INT) {\n return coerceIntString(parseInt(ast.value, 10))\n }\n if (ast.kind === Kind.STRING) {\n return ast.value\n }\n return undefined\n }\n})\n```\n\n```text\ntype Post {\n content: String | Int\n}\n```\n\n```text\ntype PostString {\n content: String\n}\n\ntype PostInt {\n content: Int\n}\n\nunion Post = PostString | PostInt\n```\n\n========================================\n\nComments:\n- Super interesting answer!!! I couldn't find such a relevant example anywhere else....\n- That sounds like a good solution for mixing multiple scalars. In my case there is a response of a task, and it may be either scalar (Int, String) or object type. I could use scalar JSON instead of object types, but JSON does not validate internal fields and can't guarantee they are in the response, and not an option. So I ran into the same issue, but it seems that this solution won't work for something like: `union = String | Int | MyTypeOne | MyTypeTwo ... MyTypeTen`. Any suggestions?\n- @Mihail Instead of using a JSON scalar, you could still create a custom scalar with validation specific to your use case baked in. Outside of that, if you're using this for an output type, you can use a union for the parent type as described above.\n- This union solution doesn't actually work exactly. If you try it you'll find the following error: `Fields \"content\" conflict because they return conflicting types \"String\" and \"Boolean\". Use different aliases on the fields to fetch both if this was intention` It turns out the \"content\" field name has to be different for each, which is pretty ugly, but the only way to make this work.","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":129,"estimatedTokens":828}}200{"id":"stack-54983080","source":"stackoverflow","questionId":54983080,"title":"Return file from GraphQL resolve","tags":["node.js","file","express","download","graphql"],"text":"Title: Return file from GraphQL resolve\nTags: node.js, file, express, download, graphql\nSource: Stack Overflow\n\nQuestion:\nI am currently working on an application with the current tech stack:\n\nBackend:\n\nMongoose\n\nExpress\n\nApollo\n\nGraphQL\n\nFrontend:\n\nVuejs\n\nApollo\n\nGraphQL\n\nI have succeeded in uploading files to the server using GraphQL, what I am stuck with is how to implement the 'download' feature. With a normal RESTApi endpoint I can use res.download(filePath) and it works. How do I do this with GraphQL since I don't want to use REST.\n\nOr is there any other standard to go by in this scenario?\n\nThanks!\n\n========================================\n\nTop Answer:\n### It's better to send a hashed & temporary link to download it\n\n- Save the file and hash the name on your static server (to limit access to other users)\n\n- The file should be temporary and should expire in a short time\n\n- Send the link of the file in response to API\n\n========================================\n\nComments:\n- Is that better architecture design? Giving the user the file url and letting them download it directly is what I'm currently doing, but there's no check there whether the user has permission to that file. I want to add permissions, and gql seems like a promising way to do that.\n- So what you mean to say is, that everytime a user requests a file, the server saves it locally and hashes it while generating a temporary link the user can then use to download it if need be. This link survives for, lets say, a few hours and many users can download it if they have access to it, and after it expires, a new one is generated whenever a new user requests for it again?\n- can you give code example for how to save file, hash it in the server and make a temporary link out of it ?","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":48,"estimatedTokens":442}}201{"id":"stack-50809147","source":"stackoverflow","questionId":50809147,"title":"How do I specify a graphql type that takes multiple types?","tags":["graphql","graphql-js"],"text":"Title: How do I specify a graphql type that takes multiple types?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI want to create a graphql type that can return either an `Array of Integers` or `String`.\n\nI've already tried using union in the form\n`union CustomVal = [Int] | String`, but this returns an error.\n\nThe schema declaration is:\n\n```\nunion CustomValues = [Int] | String\n\ntype Data {\n name: String\n slug: String\n selected: Boolean\n values: CustomValues\n}\n```\n\nThe error is:\n\n```\nnode_modules/graphql/error/syntaxError.js:24\nreturn new _GraphQLError.GraphQLError('Syntax Error: ' + description, undefined, source, [position]);\nSyntax Error: Expected Name, found [\nGraphQL request (81:23)\n80: \n81: union CustomValues = [Int] | String\n```\n\nIs this possible to do in graphql? If not, can you please suggest an alternative to do this.\n\nI ask this as the union documentation says that `Note that members of a union type need to be concrete object types; you can't create a union type out of interfaces or other unions.`\n\nAny solutions would be highly helpful.\n\n========================================\n\nTop Answer:\nAs per Graphql specification,\n\nThe member types of a Union type must all be Object base types.\nScalar, Interface and Union types must not be member types of a Union.\n\nThen instead of \"**union**\", you can use custom scalar to solve this use-case. Since any scalar type is valid JSON, hence we can use a custom JSON scalar here.\n\nYou can use this package graphql-type-json for custom scalar json type.\n\n```\nscalar JSON\n\ntype Data {\n name: String\n slug: String\n selected: Boolean\n values: JSON\n}\n```\n\nIn this way, you can associate any scalar values (*i.e. Int, Float, String etc..*) or its array associations (*i.e. [Int], [String], etc..*) with member \"***Data.values***\" without violating the specifications.\n\n========================================\n\nCode:\n```text\nunion CustomValues = [Int] | String\n\ntype Data {\n name: String\n slug: String\n selected: Boolean\n values: CustomValues\n}\n```\n\n```text\nnode_modules/graphql/error/syntaxError.js:24\nreturn new _GraphQLError.GraphQLError('Syntax Error: ' + description, undefined, source, [position]);\nSyntax Error: Expected Name, found [\nGraphQL request (81:23)\n80: \n81: union CustomValues = [Int] | String\n```\n\n```text\nArray of Integers\n```\n\n```text\nString\n```\n\n```text\nunion CustomVal = [Int] | String\n```\n\n```text\nNote that members of a union type need to be concrete object types; you can't create a union type out of interfaces or other unions.\n```\n\n```text\nunion IntOrString = IntBox | StringBox\n\ntype IntBox {\n value: Int\n}\n\ntype StringBox {\n value: String\n}\n```\n\n```text\nscalar JSON\n\ntype Data {\n name: String\n slug: String\n selected: Boolean\n values: JSON\n}\n```\n\n========================================\n\nComments:\n- Can you try removing `[]` from `[Int]`?\n- Still throws an error, and I want the type to either take an `Array of Integers` or a `String`, and isn't array type declared in graphql using `[]`? The error is `Union type CustomValues can only include Object types, it cannot include Int. Union type CustomValues can only include Object types, it cannot include String.`\n- You need to use `[]` if you want a list (array), but if you want to return different types on different inputs then you'll have to define how to do that in your resolver function.\n- Did you find an answer? I am currently having a similar issue when I want to create a Union type that accepts an object and an array of this object, and I get an error that it is not possible to use array in a Union type..","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":134,"estimatedTokens":899}}202{"id":"stack-40923977","source":"stackoverflow","questionId":40923977,"title":"What are some GraphQL schema naming best practices?","tags":["graphql","schema","idioms"],"text":"Title: What are some GraphQL schema naming best practices?\nTags: graphql, schema, idioms\nSource: Stack Overflow\n\nQuestion:\nI'm beginning development on a nontrivial application for which we're considering GraphQL. When working on the initial draft of our schema, I've become a bit paralyzed trying to establish naming conventions that will scale as the product matures. I would really appreciate some insight from anyone who has had to grow a schema and run into, or successfully avoided dead ends or inconsistencies:\n\nIs it generally useful/idiomatic to keep the name \"Interface\" in the name of an interface? For example, would `Profile` or `ProfileInterface` be preferable in a large app?\n\n```\ninterface ProfileInterface {\n # fields here...\n}\n\ntype UserProfile implements ProfileInterface {\n # implemented fields here...\n}\n```\n\nIs it common to specify single-enum values as \"constants\"?\n\n```\nenum GeoJSONFeatureTypeConstant {\n feature\n}\n\ninterface GeoJSONFeatureInterface {\n id: ID\n type: GeoJSONFeatureTypeConstant!\n geometry: GeoJSONGeometryInterface!\n properties: GeoJSONProperties\n}\n```\n\nIs it best practice to declare all-or-nothing `object`s as `scalar` or `type`, and where is the line drawn between the two? Imagine a `Point` type that is would typically be represented as an array `[x,y]`; which would be more idiomadic?\n\n```\nscalar Point\n\ntype Point {\n x: Float\n y: Float\n}\n```\n\n- Any other best-practices specifically related to naming conventions or type declarations in GraphQL that would be difficult to know without experience.\n\nThanks in advance!\n\nThis question hasn't gained the momentum I would have liked, so I'm going to start posting useful snippets as I find them, which may evolve into an answer of sorts.\n\n Naming input types with Input on the end is a useful convention,\n because you will often want both an input type and an output type that\n are slightly different for a single conceptual object.\n\nhttp://graphql.org/graphql-js/mutations-and-input-types/\n\n========================================\n\nTop Answer:\nI found this graphql API design tutorial from Shopify some time ago. I think there is no explicit chapter but best practice w.r.t. naming convention spread across the tutorial.\n\n========================================\n\nCode:\n```text\ninterface ProfileInterface {\n # fields here...\n}\n\ntype UserProfile implements ProfileInterface {\n # implemented fields here...\n}\n```\n\n```text\nenum GeoJSONFeatureTypeConstant {\n feature\n}\n\ninterface GeoJSONFeatureInterface {\n id: ID\n type: GeoJSONFeatureTypeConstant!\n geometry: GeoJSONGeometryInterface!\n properties: GeoJSONProperties\n}\n```\n\n```text\nscalar Point\n\ntype Point {\n x: Float\n y: Float\n}\n```\n\n```text\nProfile\n```\n\n```text\nProfileInterface\n```\n\n```text\nobject\n```\n\n```text\nscalar\n```\n\n```text\ntype\n```\n\n```text\nPoint\n```\n\n```text\n[x,y]\n```\n\n========================================\n\nComments:\n- Enums: should have their type name in PascalCase, and their value names in ALL_CAPS, since they are similar to constants. source: apollographql.com/docs/guides/schema-design.html\n- These are great, and your link is perfect. Thanks.\n- As per the Graphql Specification, it is ok to use `_` in names but in all the examples `camelCase` is used. Does it mean that there is no fixed rule for naming conventions?\n- @yogesh_desai GraphQL has no *enforced* naming rulesβonly recommendations based on conventions from other languages like JavaScript.","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":132,"estimatedTokens":857}}203{"id":"stack-44982279","source":"stackoverflow","questionId":44982279,"title":"GraphQL large integer error: Int cannot represent non 32-bit signed integer value","tags":["javascript","mongodb","mongoose","graphql"],"text":"Title: GraphQL large integer error: Int cannot represent non 32-bit signed integer value\nTags: javascript, mongodb, mongoose, graphql\nSource: Stack Overflow\n\nQuestion:\nIΒ΄m trying to store a UNIX timestamp in `MongoDB` using `GraphQL`, but it seens that GraphQL has a limit to handle integers. See the mutation below:\n\n```\nconst addUser = {\n type: UserType,\n description: 'Add an user',\n args: {\n data: {\n name: 'data',\n type: new GraphQLNonNull(CompanyInputType)\n }\n },\n resolve(root, params) {\n\n params.data.creationTimestamp = Date.now();\n\n const model = new UserModel(params.data);\n const saved = model.save();\n\n if (!saved)\n throw new Error('Error adding user');\n\n return saved;\n }\n}\n```\n\nResult:\n\n```\n\"errors\": [\n {\n \"message\": \"Int cannot represent non 32-bit signed integer value: 1499484833027\",\n \"locations\": [\n {\n \"line\": 14,\n \"column\": 5\n }\n ],\n \"path\": [\n \"addUser\",\n \"creationTimestamp\"\n ]\n }\n```\n\nIΒ΄m currently using `GraphQLInteger` for this field on type definition:\n\n```\ncreationTimestamp: { \n type: GraphQLInt\n}\n```\n\nHow can I solve that situation if there is no larger `GraphQLInt` available in `GraphQL` ?\n\n========================================\n\nTop Answer:\n**β οΈNot recommended due to potential loss of precision...**\n\n... but if you want a quick fix (maybe you don't have the time to implement a custom scalar), you can use the `Float` type instead of `Int`.\n\n========================================\n\nCode:\n```text\nconst addUser = {\n type: UserType,\n description: 'Add an user',\n args: {\n data: {\n name: 'data',\n type: new GraphQLNonNull(CompanyInputType)\n }\n },\n resolve(root, params) {\n\n params.data.creationTimestamp = Date.now();\n\n const model = new UserModel(params.data);\n const saved = model.save();\n\n if (!saved)\n throw new Error('Error adding user');\n\n return saved;\n }\n}\n```\n\n```text\n\"errors\": [\n {\n \"message\": \"Int cannot represent non 32-bit signed integer value: 1499484833027\",\n \"locations\": [\n {\n \"line\": 14,\n \"column\": 5\n }\n ],\n \"path\": [\n \"addUser\",\n \"creationTimestamp\"\n ]\n }\n```\n\n```text\ncreationTimestamp: { \n type: GraphQLInt\n}\n```\n\n```text\nMongoDB\n```\n\n```text\nGraphQL\n```\n\n```text\nGraphQLInteger\n```\n\n```text\nGraphQLInt\n```\n\n```text\nGraphQL\n```\n\n```text\nFloat\n```\n\n```text\nInt\n```\n\n```text\nFloat\n```\n\n```text\nInt\n```\n\n```text\nInt\n```\n\n```text\nFloat\n```\n\n========================================\n\nComments:\n- Thanks for the links. Could we get an explanation? :D\n- @reergymerej what is still unclear from the answer?\n- I think what @reergymerej meant is a TLDR for why GraphQL doesn't support integers larger than 32 bits.\n- github.com/graphql/graphql-js/issues/292#issuecomment-186702‌​763\n- Hey, I downvoted your comment because it's not very helpful and you're even \"Not recommending\" it, yourself. Float and Int the same bit-size.\n- I mean I know but when I came to this error I didn't had the time at all to refactorise all my schema like mentioned in the valid answer :/ this error is kind of unexpected since simple timestamp doesn't fit in (and please try it by your own because this 'trick' works I found it in this issue). So yes maybe it's not the best answer but it could definitively help someone which faced the same problem so there is no reason to downvote it.\n- This says not recommended, but does not provide a reason why you wouldn't want to do this.\n- @Gakio Because it's better to use the right type for what you need. If you don't need to use some floats there is no point.\n- The real issue is that a signed 32 bit integer can exactly represent any integer up to about 2 x 10^9. A 32 bit float can exactly represent any integer up to about 1.5 x 10^7 but can **approximately** represent numbers up to about 3 x 10^38: a hugely wider range but at the cost of precision. Sometimes loss of precision is fine and other times it very isn't.","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":175,"estimatedTokens":999}}204{"id":"stack-58002078","source":"stackoverflow","questionId":58002078,"title":"Is there anyway to do nested Pick<> types in Typescript","tags":["typescript","graphql"],"text":"Title: Is there anyway to do nested Pick<> types in Typescript\nTags: typescript, graphql\nSource: Stack Overflow\n\nQuestion:\nSo I am trying to get safety on my client side GraphQL queries (so if there is a better approach to this let me know). \n\nBut what I have been doing is defining my query like this. \n\n```\nexport const tenantManagePageQuery = async (tenantId: string) =>\n graphQLClient.request(\n /* GraphQL */ `\n query tenants($tenantId: String!) {\n tenants(tenantIds: [$tenantId]) {\n id\n description\n name\n approvedUsers {\n id\n alias\n }\n pendingUsers {\n id\n alias\n }\n }\n }\n `,\n { tenantId },\n );\n```\n\nin order to define the `TenantManagePageQueryTenant` type I do something like this \n\n```\ninterface TenantManagePageQueryTenant\n extends Pick {}\n```\n\nWhere the base Tenant model is my GQL model type. \n\nIs there anyway to do this kind of Pick statement but to also pick the nested properties. \n\nsomething like \n\n```\ninterface TenantManagePageQueryTenant\n extends Pick {}\n```\n\n========================================\n\nTop Answer:\nThe code posted by @Avius is on the right track, but the interface extending the intersection type generates an error. I believe you'd need to use type:\n\n```\ntype TenantManagePageQueryTenant = Pick\n & { approvedUsers: Pick[] }\n{ }\n\ninterface Tenant {\n id:string;\n description:string;\n name:string;\n}\n\ninterface ApprovedUser {\n id:string;\n alias:string;\n}\n\nlet tenant:TenantManagePageQueryTenant = {\n id: \"123\",\n description: \"456\",\n name: \"789\",\n approvedUsers: [{\n id: \"aaa\",\n alias: \"bbb\" // To see the desired type warning, try removing 'alias' \n }]\n}\n```\n\nPlayground Link\n\n========================================\n\nCode:\n```text\nexport const tenantManagePageQuery = async (tenantId: string) =>\n graphQLClient.request<{\n tenants: TenantManagePageQueryTenant[];\n }>(\n /* GraphQL */ `\n query tenants($tenantId: String!) {\n tenants(tenantIds: [$tenantId]) {\n id\n description\n name\n approvedUsers {\n id\n alias\n }\n pendingUsers {\n id\n alias\n }\n }\n }\n `,\n { tenantId },\n );\n```\n\n```text\ninterface TenantManagePageQueryTenant\n extends Pick<Tenant, 'id' | 'description' | 'name'> {}\n```\n\n```text\ninterface TenantManagePageQueryTenant\n extends Pick<Tenant, 'id' | 'description' | 'name' | Pick<approvedUser| 'id' | 'alias'> {}\n```\n\n```text\nTenantManagePageQueryTenant\n```\n\n```text\n// Existing type\ntype Tenant = {\n id:string;\n description:string;\n name:string;\n approvedUsers: Array<{\n id:string;\n alias:string;\n }>\n}\n\n// Pick it apart\ntype TenantManagePageQueryTenant = \n Pick<Tenant, 'id' | 'description' | 'name'> & {\n approvedUsers: Array<Pick<Tenant['approvedUsers'][0], 'id' | 'alias'>>\n }\n```\n\n```text\ntype TenantSubset = Pick<Tenant, 'id' | 'description' | 'name'>\ntype ApprovedUserSubset = Pick<Tenant['approvedUsers'][number], 'id' | 'alias'>\n\ntype TenantManagePageQueryTenant = TenantSubset & { approvedUsers: Array<ApprovedUserSubset> }\n```\n\n```text\ntype TenantManagePageQueryTenant = { \n id: Tenant['id'],\n description: Tenant['description'],\n name: Tenant['name'],\n approvedUsers: Array<{\n id: Tenant['approvedUsers'][number]['id'],\n alias: Tenant['approvedUsers'][number]['alias'],\n }> \n}\n```\n\n```text\ninterface TenantManagePageQueryTenant extends\n Pick<Tenant, 'id' | 'description' | 'name'>\n & { approvedUsers: Pick<ApprovedUser | 'id' | 'alias'>[] }\n{}\n```\n\n```text\n{\n id: \"123\",\n description: \"456\",\n name: \"789\",\n approvedUsers: [{\n id: \"aaa\",\n alias: \"bbb\"\n }]\n}\n```\n\n```text\n// missing alias in approvedUsers[0]\n\n{\n id: \"123\",\n description: \"456\",\n name: \"789\",\n approvedUsers: [{\n id: \"aaa\"\n }]\n}\n```\n\n```text\n// unknown field extra in approvedUsers[0]\n{\n id: \"123\",\n description: \"456\",\n name: \"789\",\n approvedUsers: [{\n id: \"aaa\",\n alias: \"bbb\",\n extra: 345678\n }]\n}\n```\n\n```text\napprovedUsers\n```\n\n```text\nTenantManagePageQueryTenant\n```\n\n```text\ntype TenantManagePageQueryTenant = Pick<Tenant, 'id' | 'description' | 'name'>\n & { approvedUsers: Pick<ApprovedUser, 'id' | 'alias'>[] }\n{ }\n\ninterface Tenant {\n id:string;\n description:string;\n name:string;\n}\n\ninterface ApprovedUser {\n id:string;\n alias:string;\n}\n\nlet tenant:TenantManagePageQueryTenant = {\n id: \"123\",\n description: \"456\",\n name: \"789\",\n approvedUsers: [{\n id: \"aaa\",\n alias: \"bbb\" // To see the desired type warning, try removing 'alias' \n }]\n}\n```\n\n```text\ninterface Tenant {\n id: string\n description: string\n name: string\n approvedUsers: User[]\n pendingUsers: User[]\n createdBy: string // only data source\n}\n\ninterface User {\n id: string\n alias: string\n name: string // only data source\n}\n```\n\n```text\ntype TenantManagePageQueryTenant = Pick<Tenant, 'id' | 'description' | 'name'>\n```\n\n```text\ntype UserQuery = Pick<User, 'id' | 'alias'>\n\ninterface {\n approvedUsers: UserQuery[]\n pendingUsers: UserQuery[]\n}\n```\n\n```text\ntype PickAndAssignType<S, P extends keyof S, T> = {\n [property in P]: T\n}\n```\n\n```text\ntype TenantManagePageQueryTenant = Pick<Tenant, 'id' | 'description' | 'name'> &\n PickAndAssignType <Tenant, 'approvedUsers' , UserQuery[]> &\n PickAndAssignType <Tenant, 'pendingUsers', UserQuery[]>\n```\n\n```text\ntype TenantManagePageQueryTenant = Pick<Tenant, 'id' | 'description' | 'name'> &\n PickAndAssignType <Tenant, 'approvedUsers' | 'pendingUsers', UserQuery[]>\n```\n\n```text\nTenantManagePageQueryTenant\n```\n\n```text\nUserQuery[]\n```\n\n```text\nS\n```\n\n```text\nP\n```\n\n```text\nS\n```\n\n```text\nT\n```\n\n```text\nPick\n```\n\n```text\nTenantManagePageQueryTenant\n```\n\n```text\napprovedUsers\n```\n\n```text\npendingUsers\n```\n\n```text\nP extends keyof S\n```\n\n```text\nPickAndAssignType\n```\n\n```text\npendingUsers\n```\n\n```text\nTenant\n```\n\n```text\nwaitingUser\n```\n\n```text\nTenantManagePageQueryTenant\n```\n\n========================================\n\nComments:\n- What's the use case? You want a type union of all possible keys (even if nested under another key?)\n- I want to Pick a field of the root type, but ensure that the keys in that field are all valid keys of some other type\n- This is exactly what I wanted Thanks alot\n- I generally like typescript but it's looking at types like these when I feel that I should look into other languages, cause surely stuff like this cannot be the norm?\n- @IvanP I think the \"norm\" depends on your codebase. I would say *most* of the projects I work keep the types more simple than this. I've also worked on types that are more complex, especially for libraries. Take a look at the type definitions of some popular libraries like React, it gets hairy. At the end of the day, only you (and your team) can decide if the complexity provides value. I would also say the above could be cleaned up, extract out an ApprovedUser type, etc but the question was aimed at nested picks\n- this is super messy and will be unusable for some data types\n- @ICW The question asks for a nested pick - while the answer may not be the \"cleanest\", TypeScript doesn't lend to anything better in its current form. As mentioned in the comment above, it could be cleaned up by abstracting types, and its probably not something I would use in my own projects but it answers the question.\n- @ICW I've added two alternatives, thoughts?\n- This is great but the downside of this is it doesn't fully tie the `approvedUsers` field in the new `TenantManagePageQueryTenant` type to the field of the same name in the original `Tenant` type. So the name of the field `approvedUsers` can change (to something like `approvedUserList`), and it does not require the name to change in the `TenantManagePageQueryTenant` type. @LuCio 's solution addresses this but is also more verbose.","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":370,"estimatedTokens":1984}}205{"id":"stack-61892306","source":"stackoverflow","questionId":61892306,"title":"Is there any way to upload files via postman into a GraphQL API?","tags":["file","graphql","upload","postman"],"text":"Title: Is there any way to upload files via postman into a GraphQL API?\nTags: file, graphql, upload, postman\nSource: Stack Overflow\n\nQuestion:\nCurrently I'm using Altair to upload files (in my case it's just for images) to my GraphQL API. However, all my other routes are stored in postman and it'd be nice if I could use just one application - Postman - for everything.\n\nIn Altair I can simply select an image and store that as a variable that I put as the value for my GraphQL Upload field. \n\nDoes anyone know if Postman supports that (or a similiar) feature?\n\nThank you!\n\n========================================\n\nTop Answer:\nAnswer from @Brad Larson is correct. But contains a typo:\n\nYou should have `{\"0\":[\"variables.file\"]}` instead of `\"[variables.file]\"`\n\n(Sorry I don't have enough reputation to comment)\n\n========================================\n\nCode:\n```text\n{\"query\":\"mutation updateAvatar($avatar:Upload!) {\\n updateAvatar(avatar: $avatar)\\n}\"}\n```\n\n```text\n{\"0\": [\"variables.avatar\"]}\n```\n\n```text\n{\"0\":[\"variables.file\"]}\n```\n\n```text\n\"[variables.file]\"\n```\n\n```text\ncurl --location --request POST '<REDACTED>/graphql' \\\n--header 'Authorization: Bearer <REDACTED>' \\\n--form '0=@\"/home/user/Downloads/Five.pdf\"' \\\n--form 'map=\"{\\\"0\\\": [\\\"variables.data.attachments\\\"]}\"' \\\n--form 'operations=\"{\n \\\"query\\\": \\\"mutation AddPOAttachments($data: AddProductAttachmentsInput!) { add_product_attachments(data: $data) { attachments { id url purpose file_info { name type size_in_bytes} __typename } __typename }}\\\",\n \\\"variables\\\":\n {\n \\\"data\\\":\n {\n \\\"sku\\\": \\\"123456sku\\\",\n \\\"attachments\\\": null,\n \\\"purpose\\\": \\\"Test\\\"\n }\n }\n}\"'\n```\n\n```text\ngraphene-file-upload==1.2.2\n```\n\n```text\ncurl\n```\n\n```text\nscalar Upload\n\ntype Mutation {\nuploadFloorMap(floorMapImage: Upload!) : String\n}\n```\n\n```text\n<dependency>\n <groupId>com.graphql-java-kickstart</groupId>\n <artifactId>graphql-java-servlet</artifactId>\n <version>14.0.0</version>\n </dependency>\n <!-- https://mvnrepository.com/artifact/com.graphql-java/graphql-java-extended-scalars -->\n <dependency>\n <groupId>com.graphql-java</groupId>\n <artifactId>graphql-java-extended-scalars</artifactId>\n </dependency>\n```\n\n```text\nimport graphql.kickstart.servlet.apollo.ApolloScalars;\nimport graphql.schema.GraphQLScalarType;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration\npublic class GraphQLConfiguration {\n\n@Bean\npublic GraphQLScalarType uploadScalarDefine() {\nreturn ApolloScalars.Upload;\n }\n}\n```\n\n```text\nAltair\n```\n\n========================================\n\nComments:\n- Perfect, that works! I was wondering where you could get the 'select file prompt', but i eventually found it. It's kind of hidden as you need to hover over the key field to change it from 'Text' to 'File'. Thank you!\n- operations is not being detected by graphql for me. I get the error ``` Bad POST multipart request: no part named \"graphql\" or \"query\" ```\n- I get this error \"KeyError at / graphql / 'variables' \" Can you tell me why? prnt.sc/yu73z9 - error\n- In my case `{\"0\": [\"varilables.avatar\"]}` is only populating `variables.avatar` with the value `\"0\"` (and not with the file we used as its content). Do you have suggestions?\n- `varilables` seems like a typo\n- I have tried the solution provided here but I got the error `POST body missing, invalid Content-Type, or JSON object has no keys.` any idea on this?\n- this worked for me with graphql-spring-boot\n- @EmadBaqeri I had the same problem and this worked for me stackoverflow.com/a/69607115/4984903.\n- For graphene and django users: you would find the upload contents of the mutation in `info.context.FILES`\n- How would you do to add others variables? E.g. filename, prefix, etc.\n- This gives me the issue \"message\": \"The variables are expected to mutable at this point.\" for hotchocolate, it can be fixed if you add on \"variables\" behind the mutation. Refer to Javi answer below if anybody meets with the same issue.\n- Could you please the content of the query as well please? In my case `profile_picture` is not populating the query variables and `query` is not being passed to graphene/django. I have to use `operations` as in the other answer (but `map` is not populating the query variables either).\n- btw, same thing works if you use Phoenix + Absinthe (Elixir)\n- What is the *query* data that you put as the value? The screenshot doesn't make it clear how the file input (variable) is defined in the query string. Thanks.\n- This answer is useless if you are not showing the content of `query`\n- The correct answer gave me the error: \"message\": \"The variables are expected to mutable at this point.\" for hotchocolate. Using this answer it solves the problem.","metadata":{"transformedAt":"2026-08-18T18:32:36.037Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":128,"estimatedTokens":1213}}206{"id":"stack-55201963","source":"stackoverflow","questionId":55201963,"title":"GraphQL mutation: Invariant Violation: Must contain a query definition","tags":["reactjs","graphql","apollo-client"],"text":"Title: GraphQL mutation: Invariant Violation: Must contain a query definition\nTags: reactjs, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am trying to make a **`mutation`** call to my graphQL server from a react application. The react code looks like the following:\n\n```\nclient.query({\n query: gql`\n mutation{\n addTeam(input:{name:\"Somename\", label:\"somelabel\"})\n {error, status}\n }`\n }).then((resp: any) => {\n console.log(\"Success\", resp);\n }).catch(err => {\n throw err;\n })\n```\n\nAnd I am getting the following error:\n\nhttps://i.sstatic.net/S4705.png\n\nBut if I change the same request, from `mutation` to `query`, and make the necessary changes in my node-graphQL-server to handle it as `query` instead of `mutation` the same code works.\n\n### Apollo-Client `Mutation` docs says\n\nIn GraphQL, mutations are identical to queries in syntax, the only difference being that you use the keyword `mutation` instead of `query`...\n\nOh and BTW, the same `mutation` query WORKS in **`Playground`**.\nPlease help guys, my work is kinda stopped coz of this issue.\n\nThanks!\n\n========================================\n\nTop Answer:\nThere is currently a GitHub issue that speaks of this error: https://github.com/apollographql/apollo-client/issues/1539\n\n========================================\n\nCode:\n```text\nclient.query({\n query: gql`\n mutation{\n addTeam(input:{name:\"Somename\", label:\"somelabel\"})\n {error, status}\n }`\n }).then((resp: any) => {\n console.log(\"Success\", resp);\n }).catch(err => {\n throw err;\n })\n```\n\n```text\nmutation\n```\n\n```text\nmutation\n```\n\n```text\nquery\n```\n\n```text\nquery\n```\n\n```text\nmutation\n```\n\n```text\nMutation\n```\n\n```text\nmutation\n```\n\n```text\nquery\n```\n\n```text\nmutation\n```\n\n```text\nPlayground\n```\n\n```text\nclient.mutate({\n mutation: gql`\n mutation {\n addTeam(input:{name:\"Somename\", label:\"somelabel\"}) {\n error\n status\n }\n }`,\n})\n```\n\n```text\nmutate\n```\n\n```text\nquery\n```\n\n```text\nmutate\n```\n\n```text\nrefetchQueries\n```\n\n```text\nconst query1 = gql`\n query GetPost {\n id\n title\n }\n`\nconst result = await apolloClient.query(query: query1)\n```\n\n========================================\n\nComments:\n- Thank you so much, I didn't realize that I was user \"client.query\" for mutation. +1\n- Jeez! \"client.mutate\"... who knew?\n- This answer solved my problem, but can this be done with a single `gql` string as opposed to the `mutation` object (where `mutation` is used twice)? I'm using the `@rest` call from the Apollo Client docs. They use a `gql` query string, followed by a `client.query({ query })` api call. Curious if that's possible with the same inputs that you used here.\n- your doc link no longer works, could you update it please?","metadata":{"transformedAt":"2026-08-18T18:32:36.038Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":143,"estimatedTokens":684}}207{"id":"stack-49047259","source":"stackoverflow","questionId":49047259,"title":"How to parse GraphQL request string into an object","tags":["javascript","node.js","graphql","apollo-server"],"text":"Title: How to parse GraphQL request string into an object\nTags: javascript, node.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am running Apollo lambda server for GraphQL. I want to intercept the GraphQL query/mutation from the POST request body and parse it so I can find out which query/mutation the request is asking for. The environment is Node.js.\n\nThe request isn't JSON, it's GraphQL query language. I've looked around to try and find a way to parse this into an object that I can navigate but I'm drawing a blank.\n\nThe Apollo server must be parsing it somehow to direct the request. Does anyone know a library that will do this or pointers on how I can parse the request? Examples of request bodies and what I want to retrieve below.\n\n```\n{\"query\":\"{\\n qQueryEndpoint {\\n id\\n }\\n}\",\"variables\":null,\"operationName\":null}\n```\n\nI would like to identify that this is a query and that `qQueryEndpoint` is being asked for.\n\n```\n{\"query\":\"mutation {\\\\n saveSomething {\\\\n id\\\\n }\\\\n}\",\"variables\":null}\n```\n\nI would like to identify that this is a mutation and the `saveSomething` mutation is being used.\n\nMy first idea for this is to strip out the line breaks and try and use regular expressions to parse the request but it feels like a very brittle solution.\n\n========================================\n\nTop Answer:\n`graphql-tag` is built upon the core `graphql` library (and thus installs it along) - if you just want to get the type of operation and the name of it you can do so, by using `graphql` directly and analyze the full AST of the parsed GraphQL operation:\n\n```\nconst { parse } = require('graphql');\n\nconst query = `\n{\n qQueryEndpoint {\n id\n }\n} \n`;\n\nconst mutation = `\nmutation {\n saveSomething {\n id\n }\n}\n`;\nconst firstOperationDefinition = (ast) => ast.definitions[0];\nconst firstFieldValueNameFromOperation = (operationDefinition) => operationDefinition.selectionSet.selections[0].name.value;\n\nconst parsedQuery = parse(query);\nconst parsedMutation = parse(mutation);\n\nconsole.log('operation', firstOperationDefinition(parsedQuery).operation);\nconsole.log('firstFieldName', firstFieldValueNameFromOperation(firstOperationDefinition(parsedQuery)));\n\nconsole.log('operation', firstOperationDefinition(parsedMutation).operation);\nconsole.log('firstFieldName', firstFieldValueNameFromOperation(firstOperationDefinition(parsedMutation)));\n```\n\nThat way you do not need to depend on `graphql-tag` and you can use, the *real* GraphQL AST (and thus easily adapt to further requirements) - because `graphql-tag` does not provide the full AST.\n\nSee the AST for the query in AST Explorer.\n\n========================================\n\nCode:\n```text\n{\"query\":\"{\\n qQueryEndpoint {\\n id\\n }\\n}\",\"variables\":null,\"operationName\":null}\n```\n\n```text\n{\"query\":\"mutation {\\\\n saveSomething {\\\\n id\\\\n }\\\\n}\",\"variables\":null}\n```\n\n```text\nqQueryEndpoint\n```\n\n```text\nsaveSomething\n```\n\n```text\nconst gql = require('graphql-tag');\n\nconst query = `\n {\n qQueryEndpoint {\n id\n }\n }\n`;\n\nconst obj = gql`\n ${query}\n`;\n\nconsole.log('operation', obj.definitions[0].operation);\nconsole.log('name', obj.definitions[0].selectionSet.selections[0].name.value);\n```\n\n```text\noperation query\nname qQueryEndpoint\n```\n\n```text\noperation mutation\nname saveSomething\n```\n\n```js\nconst { parse } = require('graphql');\n\nconst query = `\n{\n qQueryEndpoint {\n id\n }\n} \n`;\n\nconst mutation = `\nmutation {\n saveSomething {\n id\n }\n}\n`;\nconst firstOperationDefinition = (ast) => ast.definitions[0];\nconst firstFieldValueNameFromOperation = (operationDefinition) => operationDefinition.selectionSet.selections[0].name.value;\n\nconst parsedQuery = parse(query);\nconst parsedMutation = parse(mutation);\n\nconsole.log('operation', firstOperationDefinition(parsedQuery).operation);\nconsole.log('firstFieldName', firstFieldValueNameFromOperation(firstOperationDefinition(parsedQuery)));\n\nconsole.log('operation', firstOperationDefinition(parsedMutation).operation);\nconsole.log('firstFieldName', firstFieldValueNameFromOperation(firstOperationDefinition(parsedMutation)));\n```\n\n```text\ngraphql-tag\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql-tag\n```\n\n```text\ngraphql-tag\n```\n\n```js\nconst { parse, visit } = require('graphql');\n\nconst query = `\n {\n books {\n ...rest of the query\n }\n }\n`\n\nconst ast = parse(query);\n\nconst newAst = visit(ast, {\n enter(node, key, parent, path, ancestors) {\n // do some work\n },\n leave(node, key, parent, path, ancestors) {\n // do some more work\n }\n});\n```\n\n```text\ngraphql-js\n```\n\n```text\nconst gql = require('graphql-tag');\n\nconst query = `\n {\n qQueryEndpoint {\n id\n }\n }\n`;\n\nconst obj = gql`\n ${query}\n`;\n\nconsole.log('operation', obj.definitions[0].operation);\nconsole.log('operationName', obj.definitions[0].name.value);\n```\n\n```text\ngraphql-tag\n```\n\n========================================\n\nComments:\n- Possible duplicate of What is JavaScript AST, how to play with it?\n- My question was wrong. The request is GraphQL query language, not AST. I have edited. Thank you for your input!\n- npmjs.com/package/graphql-parser ?\n- @GabrielBleu from what I understand of the docs, that package generates queries from objects not object from queries.\n- It parses the query string and returns an object, but npmjs.com/package/graphql-tag seems way more popular.\n- @GabrielBleu From the docs of that package: 'That's where this package comes in - it lets you write your queries with ES2015 template literals and compile them into an AST with the gql tag.' I can't find which functionality gets me an object, am I missing something?\n- I was thinking something like : `const query = gql`${body.query}``\n- @GabrielBleu ahhhh ok, I'll go give it a spin locally and report back!\n- Do we have someting similar for golang ?","metadata":{"transformedAt":"2026-08-18T18:32:36.038Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":226,"estimatedTokens":1452}}208{"id":"stack-45227332","source":"stackoverflow","questionId":45227332,"title":"Is it possible to implement multiple interfaces in GraphQL?","tags":["graphql"],"text":"Title: Is it possible to implement multiple interfaces in GraphQL?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nIs it possible to specify a type that implements multiple interfaces within a GraphQL schema? If so, how would this be accomplished?\n\n========================================\n\nTop Answer:\nIt seems comma separating the interfaces doesn't work anymore. I had to use \"&\" instead to make it work (Apollo), see this answer https://stackoverflow.com/a/49521662/1959584\n\n```\ntype Something implements First & Second\n```\n\n========================================\n\nCode:\n```text\nconst { ApolloServer, gql } = require(\"apollo-server\");\n\nconst typeDefs = gql`\n type Query {\n someAnimal: Animal!\n someBird: Bird!\n }\n\n interface Bird {\n wingspan: Int!\n }\n\n interface Animal {\n speed: Int!\n }\n\n type Swallow implements Animal & Bird {\n wingspan: Int!\n speed: Int!\n }\n`;\n\nconst resolvers = {\n Query: {\n someAnimal: (root, args, context) => {\n return { wingspan: 7, speed: 24 };\n },\n someBird: (root, args, context) => {\n return { wingspan: 6, speed: 25 };\n }\n },\n Bird: {\n __resolveType: () => \"Swallow\"\n },\n Animal: {\n __resolveType: () => \"Swallow\"\n }\n};\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers\n});\n\nserver.listen().then(({ url }) => {\n console.log(`π Server ready at ${url}`);\n});\n```\n\n```text\nsomething\n```\n\n```text\n&\n```\n\n```text\ntype Something implements First & Second\n```\n\n```text\ninterface NamedEntity {\n name: String\n}\n\ninterface ValuedEntity {\n value: Int\n}\n\ntype Person implements NamedEntity {\n name: String\n age: Int\n}\n\ntype Business implements NamedEntity & ValuedEntity {\n name: String\n value: Int\n employeeCount: Int\n}\n```\n\n========================================\n\nComments:\n- Per the latest version of the spec (graphql.github.io/graphql-spec/draft/#sec-Interfaces): \"Types may also implement multiple interfaces. For example, `Business` implements both the `NamedEntity` and `ValuedEntity` interfaces in the example [below].\" `type Business implements NamedEntity & ValuedEntity {`\n- Per the latest version of the spec (graphql.github.io/graphql-spec/draft/#sec-Interfaces): \"Types may also implement multiple interfaces. For example, `Business` implements both the `NamedEntity` and `ValuedEntity` interfaces in the example [below].\" `type Business implements NamedEntity & ValuedEntity {`\n- Per the latest version of the spec (graphql.github.io/graphql-spec/draft/#sec-Interfaces): \"Types may also implement multiple interfaces. For example, `Business` implements both the `NamedEntity` and `ValuedEntity` interfaces in the example [below].\" `type Business implements NamedEntity & ValuedEntity {`","metadata":{"transformedAt":"2026-08-18T18:32:36.038Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":108,"estimatedTokens":677}}209{"id":"stack-47874344","source":"stackoverflow","questionId":47874344,"title":"Should I handle a GraphQL ID as a string on the client?","tags":["mysql","sequelize.js","graphql","apollo"],"text":"Title: Should I handle a GraphQL ID as a string on the client?\nTags: mysql, sequelize.js, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI am building an application using:\n\n- MySQL as the backend database\n\n- Apollo GraphQL server as a query layer for that database\n\n- Sequelize as the ORM layer between GraphQL and MySQL\n\nAs I am building out my GraphQL schema I'm using the GraphQL ID data type to uniquely identify records. Here's an example schema and its MySQL resolver/connector\n\n**Graphql Type:**\n\n```\ntype Person {\n id: ID!\n firstName: String\n middleName: String\n lastName: String\n createdAt: String\n updatedAt: String\n}\n```\n\n**Sequelize connector**\n\n```\nexport const Person = sequelize.define('person', {\n firstName: { type: Sequelize.STRING },\n middleName: { type: Sequelize.STRING },\n lastName: { type: Sequelize.STRING },\n});\n```\n\n**GraphQL resolver:**\n\n```\nQuery: {\n person(_, args) {\n return Person.findById(args.id);\n}\n```\n\nSo that all works. Here's my question. GraphQL seems to treat the `ID` type as a string. While the ID value gets stored in the MySQL database as an `INT` by Sequelize. I can use GraphQL to query the MySQL db with either a string or a integer that matches the ID value in the database. However, GraphQL will always return the ID value as a string.\n\nHow should I be handling this value in the client? Should I always convert it to an integer as soon as I get it from GraphQL? Should I modify my sequelize code to store the ID value as a string? Is there a correct way to proceed when using GraphQL IDs like this?\n\n========================================\n\nCode:\n```text\ntype Person {\n id: ID!\n firstName: String\n middleName: String\n lastName: String\n createdAt: String\n updatedAt: String\n}\n```\n\n```text\nexport const Person = sequelize.define('person', {\n firstName: { type: Sequelize.STRING },\n middleName: { type: Sequelize.STRING },\n lastName: { type: Sequelize.STRING },\n});\n```\n\n```text\nQuery: {\n person(_, args) {\n return Person.findById(args.id);\n}\n```\n\n```text\nID\n```\n\n```text\nINT\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n========================================\n\nComments:\n- This is an excellent explanation of the various considerations around this issue. Thanks. GraphQL offers such an open ended approach to data structures that it can be difficult to figure out the **right** way.\n- Can I just use Int instead of ID type for mysql primary columns? React apollo already allows a custom function 'dataObjectId' to set an object ID. Setting ID scalar type for primary keys doesn't seem to have any benefits.\n- What does it mean by `...it is not intended to be humanβreadable` ? Anything is readable as long as the length overexceeds the boundary.\n- human-readable text refers to natural language text that can easily be read and understood by a human familiar with the language used for the text. As opposed to machine-readable text, that can be easily processed by a computer. For example, using latin letters for a string is better human-readable than using ASCII codes, which is more machine-readable.\n- I'd say use ID datatype only if it's a string. Although GraphQL docs says it's agnostic to datatype it clearly prefers strings. Agnostic would be not touching the datatype.\n- If the `ID` really just resolves to a `int` or `string` why do we even need it in the spec? Just use `int` or `string`. I don't understand why we need this abstract `ID` thing that can be either one.","metadata":{"transformedAt":"2026-08-18T18:32:36.038Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":117,"estimatedTokens":872}}210{"id":"stack-48558681","source":"stackoverflow","questionId":48558681,"title":"Add custom header to apollo client polling request","tags":["javascript","graphql","apollo","apollo-client","graphql-js"],"text":"Title: Add custom header to apollo client polling request\nTags: javascript, graphql, apollo, apollo-client, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am using the `apollo-client` library to query data from my `Graphql` server. Some of the queries are sent to the server every 5 seconds through apollo polling ability.\n\nIs there a generic way to add a custom header to all requests that are sent by my polling client?\n\n========================================\n\nTop Answer:\nTal Z's answer is very good. However, I thought I'd just paste how to implement the two methods he's listed for those using Angular.\n\n**Adding the header for each individual apollo call**\n\n```\nimport { Component, OnInit } from '@angular/core';\nimport { LocalStorageService } from 'angular-2-local-storage';\nimport { Apollo } from 'apollo-angular';\nimport gql from 'graphql-tag';\nimport { Pineapples, Pineapple } from './models/pineapples';\n\nexport class AppComponent {\n\n constructor(private apollo: Apollo,\n private localStorageService: LocalStorageService) {\n }\n\n callGraphQLQuery() {\n\n const token = this.localStorageService.get('loginToken');\n this.apollo\n .watchQuery({\n\n query: gql`\n {\n pineapples{\n id\n name\n }\n }\n `, \n context: {\n headers: new HttpHeaders().set(\"Authorization\", \"Bearer \" + token),\n }\n })\n .valueChanges.subscribe(result => {\n // handle results here\n });\n\n }\n\n}\n```\n\n**Adding the header in the middleware**\n\n```\nconst uri = 'https://localhost:5001/graphql'; \n\nexport function createApollo(httpLink: HttpLink, localStorage: LocalStorageService) {\n\n const http = httpLink.create({ uri });\n\n const authLink = new ApolloLink((operation, forward) => {\n // Get the authentication token from local storage if it exists\n const token = localStorage.get('loginToken');\n\n // Use the setContext method to set the HTTP headers.\n operation.setContext({\n headers: {\n 'Authorization': token ? `Bearer ${token}` : ''\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n });\n\n return {\n link: authLink.concat(http),\n cache: new InMemoryCache()\n };\n}\n\n@NgModule({\n exports: [ApolloModule, HttpLinkModule],\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink, LocalStorageService],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\n========================================\n\nCode:\n```text\napollo-client\n```\n\n```text\nGraphql\n```\n\n```text\nconst someQuery = graphql(gql`query { ... }`, {\n options: { \n context: { \n headers: { \n \"x-custom-header\": \"pancakes\" // this header will reach the server\n } \n },\n // ... other options \n }\n})\n```\n\n```text\n{\n options: { \n context: { \n canHazPancakes: true //this will not reach the server\n }\n }\n }\n```\n\n```text\nimport {setContext} from 'apollo-link-context'\n\n//... \n\nconst pancakesLink = setContext((operation, previousContext) => { \n const { headers, canHazPancakes } = previousContext\n if (!canHazPancakes) { \n return previousContext\n }\n\n return {\n ...previousContext,\n headers: { \n ...headers,\n \"x-with-pancakes\": \"yes\" //your custom header\n }\n }\n})\n```\n\n```text\nconst client = new ApolloClient({\n // ...\n link: ApolloLink.from([\n pancakesLink,\n <yourHttpLink>\n ])\n})\n```\n\n```text\noptions\n```\n\n```text\ncontext\n```\n\n```text\ncontext\n```\n\n```text\ncontext\n```\n\n```text\nheaders\n```\n\n```text\ncontext\n```\n\n```text\nheaders\n```\n\n```text\napollo-link-context\n```\n\n```text\nimport { Component, OnInit } from '@angular/core';\nimport { LocalStorageService } from 'angular-2-local-storage';\nimport { Apollo } from 'apollo-angular';\nimport gql from 'graphql-tag';\nimport { Pineapples, Pineapple } from './models/pineapples';\n\nexport class AppComponent {\n\n constructor(private apollo: Apollo,\n private localStorageService: LocalStorageService) {\n }\n\n callGraphQLQuery() {\n\n const token = this.localStorageService.get('loginToken');\n this.apollo\n .watchQuery<Pineapples>({\n\n query: gql`\n {\n pineapples{\n id\n name\n }\n }\n `, \n context: {\n headers: new HttpHeaders().set(\"Authorization\", \"Bearer \" + token),\n }\n })\n .valueChanges.subscribe(result => {\n // handle results here\n });\n\n\n }\n\n}\n```\n\n```text\nconst uri = 'https://localhost:5001/graphql'; \n\nexport function createApollo(httpLink: HttpLink, localStorage: LocalStorageService) {\n\n const http = httpLink.create({ uri });\n\n const authLink = new ApolloLink((operation, forward) => {\n // Get the authentication token from local storage if it exists\n const token = localStorage.get('loginToken');\n\n // Use the setContext method to set the HTTP headers.\n operation.setContext({\n headers: {\n 'Authorization': token ? `Bearer ${token}` : ''\n }\n });\n\n // Call the next link in the middleware chain.\n return forward(operation);\n });\n\n return {\n link: authLink.concat(http),\n cache: new InMemoryCache()\n };\n}\n\n@NgModule({\n exports: [ApolloModule, HttpLinkModule],\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink, LocalStorageService],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\n```js\nexport async function getServerSideProps(context) {\n const cookies = context.req.headers.cookie;\n const token = getCookie(\"tokenId\", cookies);\n\n const { data } = await client2.query({\n query: gql`\n query {\n me {\n firstName\n sureName\n }\n }\n `,\n context: {\n headers: {\n authorization: token,\n },\n },\n });\n\n \n return {\n props: {\n dataFromServer: data,\n },\n };\n}\n```\n\n========================================\n\nComments:\n- I deleted my answer so that others see this as unanswered.\n- Ok, but how to setContext if the app has been initialized already and ApolloClient has already been created?\n- This is my question as well. The middleware doesn't seem capable of dynamic headers... hopefully I'm wrong? Also how would I go about implementing this within a component?\n- Can you please provide documentation link for the Quick and Easy Solution? I can't get it to work.\n- Hi, Just to note on the quick and easy solution - I didnt need the options property - just the context and below worked for me\n- why set cookie in localstorage?","metadata":{"transformedAt":"2026-08-18T18:32:36.038Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":317,"estimatedTokens":1587}}211{"id":"stack-40484900","source":"stackoverflow","questionId":40484900,"title":"How do I handle deletes in react-apollo","tags":["javascript","graphql","apollo-server","react-apollo"],"text":"Title: How do I handle deletes in react-apollo\nTags: javascript, graphql, apollo-server, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have a mutation like\n\n```\nmutation deleteRecord($id: ID) {\n deleteRecord(id: $id) {\n id\n }\n}\n```\n\nand in another location I have a list of elements.\n\nIs there something better I could return from the server, and how should I update the list?\n\nMore generally, what is best practice for handling deletes in apollo/graphql?\n\n========================================\n\nTop Answer:\nHere is a similar solution that works without underscore.js. It is tested with `react-apollo` in version 2.1.1. and creates a component for a delete-button:\n\n```\nimport React from \"react\";\nimport { Mutation } from \"react-apollo\";\n\nconst GET_TODOS = gql`\n{\n allTodos {\n id\n name\n }\n}\n`;\n\nconst DELETE_TODO = gql`\n mutation deleteTodo(\n $id: ID!\n ) {\n deleteTodo(\n id: $id\n ) {\n id\n }\n }\n`;\n\nconst DeleteTodo = ({id}) => {\n return (\n {\n const { allTodos } = cache.readQuery({ query: GET_TODOS });\n cache.writeQuery({\n query: GET_TODOS,\n data: { allTodos: allTodos.filter(e => e.id !== id)}\n });\n }}\n >\n {(deleteTodo, { data }) => (\n {\n deleteTodo({\n variables: {\n id\n }\n });\n }}\n >Delete \n )}\n \n );\n};\n\nexport default DeleteTodo;\n```\n\n========================================\n\nCode:\n```text\nmutation deleteRecord($id: ID) {\n deleteRecord(id: $id) {\n id\n }\n}\n```\n\n```text\nimport { graphql, compose } from 'react-apollo';\nimport gql from 'graphql-tag';\nimport update from 'react-addons-update';\nimport _ from 'underscore';\n\n\nconst SceneCollectionsQuery = gql `\nquery SceneCollections {\n myScenes: selectedScenes (excludeOwner: false, first: 24) {\n edges {\n node {\n ...SceneCollectionScene\n }\n }\n }\n}`;\n\n\nconst DeleteSceneMutation = gql `\nmutation DeleteScene($sceneId: String!) {\n deleteScene(sceneId: $sceneId) {\n ok\n scene {\n id\n active\n }\n }\n}`;\n\nconst SceneModifierWithStateAndData = compose(\n ...,\n graphql(DeleteSceneMutation, {\n props: ({ mutate }) => ({\n deleteScene: (sceneId) => mutate({\n variables: { sceneId },\n updateQueries: {\n SceneCollections: (prev, { mutationResult }) => {\n const myScenesList = prev.myScenes.edges.map((item) => item.node);\n const deleteIndex = _.findIndex(myScenesList, (item) => item.id === sceneId);\n if (deleteIndex < 0) {\n return prev;\n }\n return update(prev, {\n myScenes: {\n edges: {\n $splice: [[deleteIndex, 1]]\n }\n }\n });\n }\n }\n })\n })\n })\n)(SceneModifierWithState);\n```\n\n```text\nint\n```\n\n```text\nupdateQueries\n```\n\n```text\nimport React from \"react\";\nimport { Mutation } from \"react-apollo\";\n\nconst GET_TODOS = gql`\n{\n allTodos {\n id\n name\n }\n}\n`;\n\nconst DELETE_TODO = gql`\n mutation deleteTodo(\n $id: ID!\n ) {\n deleteTodo(\n id: $id\n ) {\n id\n }\n }\n`;\n\nconst DeleteTodo = ({id}) => {\n return (\n <Mutation\n mutation={DELETE_TODO}\n update={(cache, { data: { deleteTodo } }) => {\n const { allTodos } = cache.readQuery({ query: GET_TODOS });\n cache.writeQuery({\n query: GET_TODOS,\n data: { allTodos: allTodos.filter(e => e.id !== id)}\n });\n }}\n >\n {(deleteTodo, { data }) => (\n <button\n onClick={e => {\n deleteTodo({\n variables: {\n id\n }\n });\n }}\n >Delete</button> \n )}\n </Mutation>\n );\n};\n\nexport default DeleteTodo;\n```\n\n```text\nreact-apollo\n```\n\n```text\nconst MY_QUERY = gql``;\n\n// it's local 'cleaner' - relatively easy to maintain as you can require proper cleaner updates during code review when query will change\nexport function removeUserFromMyQuery(apolloClient, userId) {\n // clean here\n}\n```\n\n```text\nfunction handleUserDeleted(userId, client) {\n removeUserFromMyQuery(userId, client)\n removeUserFromSearchQuery(userId, client)\n removeIdFrom20MoreQueries(userId, client)\n}\n```\n\n```text\nuser\n```\n\n```text\n1\n```\n\n```text\napolloClient.removeItem({__typeName: \"User\", id: \"1\"})\n```\n\n```text\nnull\n```\n\n```text\n[User]\n```\n\n```text\nconst [deleteExpressHelp] = useDeleteExpressHelpMutation({\n update: (cache, {data}) => {\n cache.evict({\n id: cache.identify({\n __typename: 'express_help',\n id: data?.delete_express_help_by_pk?.id,\n }),\n });\n },\n});\n```\n\n========================================\n\nComments:\n- Note to self: This page may be useful dev.apollodata.com/react/cache-updates.html#updateQueries\n- TLDR: Basically, you don't. Instead, you loose your hair, curse the Apollo team in a loop, and go through a huge list of compromising half-working workarounds provided by users like you on their Github page. github.com/apollographql/apollo-client/issues/621\n- I can almost guarantee that someday there will be a way to invalidate the deleted item such that Apollo automatically refetches any queries containing it, because the current ways of doing this are very far from perfect.\n- Could you give an example of using `updateQueries` to remove records: specifically where they are in more than 1 place in the tree.\n- Do you have to remove it from all locations?\n- Have you worked it out @derekdreery? I haven't figure it out how to use `updateQueries` to remove the items\n- No I'm still wondering about it. I might raise it as an issue on the lib.\n- We use to have an alternate mutation result interface that is optimized for stuff like this, but it wasn't ideal. Please file an issue and we can talk about it more!\n- If you open the issue, put the link here please! Nevermind, I found the issue already :)\n- Hi @vwrobel thanks for the answer. I'm interested in removing any remenant of this record in the cache (I use `${type}:${id}` for my cache key). Would this do that as well?\n- Hi @derekdreery. When I use `updateQuery`, only the specified code is applied to previous query results. In the code I've posted, the only change I get is that my deleted item is removed from list SceneCollections.myScenes. Besides, if I have an other query to get `user { id, sceneCounter }`, I would have to update the sceneCounter manually from updateQueries: even if my DeleteSceneMutation returns an updated `user { id, sceneCounter }`, the other query results are not updated when I use updateQueries. Not sure it answers your question, my apollo knowledge is rather limited...\n- No worries - my knowledge is limited too!!\n- This is awesome, thanks. What happens when the named queries were called with `id`s? Can Apollo figure out which set of data to modify in `updateQueries`? i.e. What if you had multiple results from `SceneCollections(id: \"xyz\")` in the store already?\n- This is exactly my issue, I have many queries/lists in the cache that use the same value. And I really don't want to keep track of all of them.\n- I like this approach\n- Docs also say you should call cache.gc() after.","metadata":{"transformedAt":"2026-08-18T18:32:36.038Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":283,"estimatedTokens":1767}}212{"id":"stack-62290875","source":"stackoverflow","questionId":62290875,"title":"How to load a .graphql file using `apollo-server`?","tags":["node.js","graphql","apollo","apollo-server"],"text":"Title: How to load a .graphql file using `apollo-server`?\nTags: node.js, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am currently loading the GraphQL schema using a separate `.graphql` file, but it is encapsulated within strings:\n\n`schema.graphql`\n\n```\nconst schema = `\n type CourseType {\n _id: String!\n name: String!\n }\n\n type Query {\n courseType(_id: String): CourseType\n courseTypes: [CourseType]!\n }\n`\n\nmodule.exports = schema\n```\n\nThen using it for the `apollo-server`:\n\n`index.js`\n\n```\nconst { ApolloServer, makeExecutableSchema } = require('apollo-server')\nconst typeDefs = require('./schema.graphql')\n\nconst resolvers = { ... }\n\nconst schema = makeExecutableSchema({\n typeDefs: typeDefs,\n resolvers\n})\n\nconst server = new ApolloServer({\n schema: schema\n})\n\nserver.listen().then(({ url }) => {\n console.log(`Server ready at ${url}.`)\n})\n```\n\nIs there any way to simply load a .graphql that looks as such?\n`schema.graphql`\n\n```\ntype CourseType {\n _id: String!\n name: String!\n}\n\ntype Query {\n courseType(_id: String): CourseType\n courseTypes: [CourseType]!\n}\n```\n\nThen it would be parsed in the `index.js`? I noticed that `graphql-yoga` supports this, but was wondering if `apollo-server` does. I cannot find it anywhere in the docs. I can't get `fs.readFile` to work either.\n\n========================================\n\nTop Answer:\nBack in the day I wrote a teeny-tiny `.graphql` loader myself. It is very small, very simple, and the only thing you have to do is import it before you try to import any `.graphql` files. I have used it ever since even though I am sure that there are some 3rd party loaders available. Here's the code:\n\n```\n// graphql-loader.js\n\nconst oldJSHook = require.extensions[\".js\"];\n\nconst loader = (module, filename) => {\n const oldJSCompile = module._compile;\n module._compile = function (code, file) {\n code = `module.exports = \\`\\r${code}\\`;`;\n module._compile = oldJSCompile;\n module._compile(code, file);\n };\n oldJSHook(module, filename);\n};\n\nrequire.extensions[\".graphql\"] = loader;\nrequire.extensions[\".gql\"] = loader;\n```\n\nAnd then in your app:\n\n```\n// index.js\n\nimport \"./graphql-loader\"; // (or require(\"./graphql-loader\") if you prefer)\n```\n\nThat's it, you can then `import typeDefs from \"./type-defs.graphql\"` wherever you want.\n\nThe loader works by wrapping the text in your `.graphql` file inside a template string and compiling it as a simple JS module:\n\n```\nmodule.exports = ` ...your gql schema... `;\n```\n\n========================================\n\nCode:\n```text\nconst schema = `\n type CourseType {\n _id: String!\n name: String!\n }\n\n type Query {\n courseType(_id: String): CourseType\n courseTypes: [CourseType]!\n }\n`\n\nmodule.exports = schema\n```\n\n```js\nconst { ApolloServer, makeExecutableSchema } = require('apollo-server')\nconst typeDefs = require('./schema.graphql')\n\nconst resolvers = { ... }\n\nconst schema = makeExecutableSchema({\n typeDefs: typeDefs,\n resolvers\n})\n\nconst server = new ApolloServer({\n schema: schema\n})\n\nserver.listen().then(({ url }) => {\n console.log(`Server ready at ${url}.`)\n})\n```\n\n```text\ntype CourseType {\n _id: String!\n name: String!\n}\n\ntype Query {\n courseType(_id: String): CourseType\n courseTypes: [CourseType]!\n}\n```\n\n```text\n.graphql\n```\n\n```text\nschema.graphql\n```\n\n```text\napollo-server\n```\n\n```text\nindex.js\n```\n\n```text\nschema.graphql\n```\n\n```text\nindex.js\n```\n\n```text\ngraphql-yoga\n```\n\n```text\napollo-server\n```\n\n```text\nfs.readFile\n```\n\n```text\nconst { readFileSync } = require('fs')\n\n// we must convert the file Buffer to a UTF-8 string\nconst typeDefs = readFileSync(require.resolve('./type-defs.graphql')).toString('utf-8')\n```\n\n```text\nconst { loadDocuments } = require('@graphql-tools/load');\nconst { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader');\n\n// this can also be a glob pattern to match multiple files!\nconst typeDefs = await loadDocuments('./type-defs.graphql', { \n file, \n loaders: [\n new GraphQLFileLoader()\n ]\n})\n```\n\n```text\nimport typeDefs from './type-defs.graphql'\n```\n\n```text\n.graphql\n```\n\n```text\ngraphql-tools\n```\n\n```js\nconst fs = require('fs')\nconst mongoUtil = require('./mongoUtil')\nconst { ApolloServer, makeExecutableSchema } = require('apollo-server')\n\nfunction readContent (file, callback) {\n fs.readFile(file, 'utf8', (err, content) => {\n if (err) return callback(err)\n callback(null, content)\n })\n}\n\nmongoUtil.connectToServer((error) => {\n if (error) {\n console.error('Error connecting to MongoDB.', error.stack)\n process.exit(1)\n }\n\n console.log('Connected to database.')\n\n const Query = require('./resolvers/Query')\n\n const resolvers = {\n Query\n }\n\n readContent('./schema.graphql', (error, content) => {\n if (error) throw error\n\n const schema = makeExecutableSchema({\n typeDefs: content,\n resolvers\n })\n\n const server = new ApolloServer({\n schema: schema\n })\n\n server.listen().then(({ url }) => {\n console.log(`Server ready at ${url}.`)\n })\n })\n})\n```\n\n```text\ntype CourseType {\n _id: String!\n name: String!\n}\n\ntype Query {\n courseType(_id: String): CourseType\n courseTypes: [CourseType]!\n}\n```\n\n```text\nfs\n```\n\n```text\nindex.js\n```\n\n```text\nschema.graphql\n```\n\n```text\n// graphql-loader.js\n\nconst oldJSHook = require.extensions[\".js\"];\n\nconst loader = (module, filename) => {\n const oldJSCompile = module._compile;\n module._compile = function (code, file) {\n code = `module.exports = \\`\\r${code}\\`;`;\n module._compile = oldJSCompile;\n module._compile(code, file);\n };\n oldJSHook(module, filename);\n};\n\nrequire.extensions[\".graphql\"] = loader;\nrequire.extensions[\".gql\"] = loader;\n```\n\n```text\n// index.js\n\nimport \"./graphql-loader\"; // (or require(\"./graphql-loader\") if you prefer)\n```\n\n```text\nmodule.exports = ` ...your gql schema... `;\n```\n\n```text\n.graphql\n```\n\n```text\n.graphql\n```\n\n```text\nimport typeDefs from \"./type-defs.graphql\"\n```\n\n```text\n.graphql\n```\n\n```text\nconst { gql } = require('apollo-server');\nconst fs = require('fs');\nconst path = require('path');\n\n//function that imports .graphql files\nconst importGraphQL = (file) =>{\n return fs.readFileSync(path.join(__dirname, file),\"utf-8\");\n}\n\nconst gqlWrapper = (...files)=>{\n return gql`${files}`;\n}\n\n\nconst enums = importGraphQL('./enums.graphql');\nconst schema = importGraphQL('./schema.graphql');\n\nmodule.exports = gqlWrapper(enums,schema);\n```\n\n```js\nimport { readFileSync } from \"fs\";\nconst requireGQL = (file) =>\n gql`${readFileSync(require.resolve(file)).toString(\"utf-8\")}`;\n```\n\n```js\nconst client = new ApolloClient({ uri: 'https://myendpoint.com/graphql' });\nconst { data } = await client.query({ query: requireGQL(\"./myquery.gql\") });\n```\n\n```text\n// ...other imports\n\nimport { readFileSync } from 'fs';\n\n\n// Note: this uses a path relative to the project's\n\n// root directory, which is the current working directory\n\n// if the server is executed using `npm run`.\n\nconst typeDefs = readFileSync('./schema.graphql', { encoding: 'utf-8' });\n\n\nconst server = new ApolloServer<MyContext>({\n\n typeDefs,\n\n resolvers,\n\n});\n\n\n// ... start our server\n```\n\n```text\nreadFileSync\n```\n\n========================================\n\nComments:\n- github.com/apollographql/graphql-tag#importing-graphql-files\n- This is amazing! No way there's an equivalent `GraphQLFileLoader` method from `apollo-server`?\n- Maybe in a future version.\n- It should be noted that `readFileSync` only returns a string if you specify an encoding, eg: `const typeDefs = readFileSync('./schema.graphql', 'utf-8')`. If you do not include an encoding, it returns as a Buffer which ApolloServer's constructor does not understand.\n- thank you for noting about `'utf-8'` in `readFileSync`, I would have missed that\n- @DanielRearden I am getting this error when loading a subgraph schema in a federated graph `ts Unknown directive \"@key\". Cannot extend type \"Membership\" because it is not defined. Unknown directive \"@key\". Unknown directive \"@external\". Unknown type \"Query\".`\n- @Hazem Alabiad I used the 1st option from this answer and wrapped it within `gql` for the federated subgraph. `const typeDefs = gql(readFileSync(require.resolve('./schema.graphql')).toStri‌​ng('utf-8'));`\n- @DanielRearden where is the file variable coming from in the 2nd example ie in the graphql-tools example\n- @DanielRearden did you get this working with Apollo Server-I tried the graphql-tools method with Apollo server, but getting this error: \" Unable to find any GraphQL type definitions for the following pointers\" - wondering if you need to do anything extra to get it working with Apollo Server","metadata":{"transformedAt":"2026-08-18T18:32:36.038Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":414,"estimatedTokens":2157}}213{"id":"stack-51805890","source":"stackoverflow","questionId":51805890,"title":"How to do a simple join in GraphQL?","tags":["javascript","database","graphql"],"text":"Title: How to do a simple join in GraphQL?\nTags: javascript, database, graphql\nSource: Stack Overflow\n\nQuestion:\nI am very new in GraphQL and trying to do a simple join query. My sample tables look like below:\n\n```\n{\n phones: [\n {\n id: 1,\n brand: 'b1',\n model: 'Galaxy S9 Plus',\n price: 1000,\n },\n {\n id: 2,\n brand: 'b2',\n model: 'OnePlus 6',\n price: 900,\n },\n ],\n brands: [\n {\n id: 'b1',\n name: 'Samsung'\n },\n {\n id: 'b2',\n name: 'OnePlus'\n }\n ]\n}\n```\n\nI would like to have a query to return a *phone* object with its brand name in it instead of the brand code.\n\nE.g. If queried for the phone with `id = 2`, it should return:\n\n```\n{id: 2, brand: 'OnePlus', model: 'OnePlus 6', price: 900}\n```\n\n========================================\n\nTop Answer:\n### TL;DR\n\nYes, GraphQL does support a sort of pseudo-join. You can see the books and authors example below running in my demo project.\n\n### Example\n\nConsider a simple database design for storing info about books:\n\n```\ncreate table Book ( id string, name string, pageCount string, authorId string ); \ncreate table Author ( id string, firstName string, lastName string );\n```\n\nBecause we know that Author can write many Books that database model puts them in separate tables. Here is the GraphQL schema:\n\n```\ntype Query {\n bookById(id: ID): Book\n}\n\ntype Book {\n id: ID\n title: String\n pageCount: Int\n author: Author\n}\n\ntype Author {\n id: ID\n firstName: String\n lastName: String\n}\n```\n\nNotice there is no `authorId` on the `Book` type but a type `Author`. The database `authorId` column on the book table is not exposed to the outside world. It is an internal detail.\n\nWe can pull back a book and it's author using this GraphQL query:\n\n```\n{\n bookById(id:\"book-1\"){\n id\n title\n pageCount\n author {\n firstName\n lastName\n }\n }\n}\n```\n\nHere is a screenshot of it in action using my demo project:\n\nhttps://i.sstatic.net/XcVGK.png\n\nThe result nests the Author details:\n\n```\n{\n \"data\": {\n \"book1\": {\n \"id\": \"book-1\",\n \"title\": \"Harry Potter and the Philosopher's Stone\",\n \"pageCount\": 223,\n \"author\": {\n \"firstName\": \"Joanne\",\n \"lastName\": \"Rowling\"\n }\n }\n }\n}\n```\n\nThe single GQL query resulted in two separate fetch-by-id calls into the database. When a single logical query turns into multiple physical queries we can quickly run into the infamous `N+1` problem.\n\n### The `N+1` Problem\n\nIn our case above a book can only have one author. If we only query one book by ID we only get a \"read amplification\" against our database of 2x. Imaging if you can query books with a title that starts with a prefix:\n\n```\ntype Query {\n booksByTitleStartsWith(titlePrefix: String): [Book]\n}\n```\n\nThen we call it asking it to fetch the books with a title starting with \"Harry\":\n\n```\n{\n booksByTitleStartsWith(titlePrefix:\"Harry\"){\n id\n title\n pageCount\n author {\n firstName\n lastName\n }\n }\n}\n```\n\nIn this GQL query we will fetch the books by a database query of `title like 'Harry%'` to get many books including the `authorId` of each book. It will then make an individual fetch by `ID` for every author of every book. This is a total of `N+1` queries where the `1` query pulls back `N` records and we then make `N` separate fetches to build up the full picture.\n\nThe easy fix for that example is to not expose a field `author` on `Book` and force the person using your API to fetch all the authors in a separate query `authorsByIds` so we give them two queries:\n\n```\ntype Query {\n booksByTitleStartsWith(titlePrefix: String): [Book] /* The key thing to note about that last example is that there is no way in that model to walk from one entity type to another. If the person using your API wants to deep load the books and their authors at they need send two queries in the same post to the server:\n\n```\nquery {\n booksByIDs(authorIds: [\"book-1\",\"book-2\",\"book-3\"]) {\n id\n title\n }\n authorsByIds(authorIds: [\"author-1\",\"author-2\",\"author-3\"]) {\n id\n firstName\n lastName\n }\n}\n```\n\nHere the person writing the query (perhaps using JavaScript in a web browser) sends a single GraphQL post to the server asking for all the book data and all the author data by the IDs returned to them when they had previously searched using `booksByTitleStartsWith`. The server can now make two efficient database calls.\n\nThis approach shows that there is \"no magic bullet\" for how to map the \"logical model\" to the \"physical model\" when it comes to performance. This is known as the Objectβrelational impedance mismatch problem. More on that below.\n\n### Is Fetch-By-ID So Bad?\n\nNote that the default behaviour of GraphQL is still very helpful. You can map GraphQL onto anything. You can map it onto internal REST APIs. You can map some types into a relational database and other types into a NoSQL database. These can be in the same schema and the same GraphQL end-point. There is no reason why you cannot have `Author` stored in Postgres and `Book` stored in MongoDB. This is because GraphQL doesn't by default \"join in the datastore\" it will fetch each type independently and build the response in memory to send back to the client.\n\nThese days there are some stunningly fast (yet expensive) cloud-native NoSQL engines that can do a ton of fetches by IDs with sub-millisecond response times (e.g. CosmosDB, Bigtable, DynamoDB). Even if you use a budget database like postgres it ***might*** be the case that you can use a model that only joins to a small dataset that works well. Yet you must test performance with realist traffic volumes querying a full sized data set. Then **maybe** won't have a performance problem and benefit from all the advantages of GraphQL.\n\n### What About ORM?\n\nThere is a project called Join Monster which does look at your database schema, looks at the runtime GraphQL query, and tries to generate efficient database joins on-the-fly. That is a form of Object Relational Mapping which sometimes gets a lot of \"Orm Hate\". This is mainly due to Objectβrelational impedance mismatch problem.\n\nIn my experience, any ORM works if you write the database model to exactly support your object API. In my experience, any ORM tends to fail when you have an existing database model that you try to map with an ORM framework.\n\nIMHO, when the data model is written and optimised without thinking about ORM, then avoid using ORM, else you risk getting \"Orm Hate\".\n\n### What Is Practical?\n\nCarefully performance test using realist data whenever any GraphQL fields return an array. If you hit an `N+1` problem when doing pseudo-joins in GraphQL write custom code to map specific \"field fetches\" onto hand-written database queries.\n\nEven when you can put in hand written queries you may hit scenarios where those joins don't run fast enough. In which case consider the CQRS pattern and denormalise some of the data model to allow for fast lookups.\n\n### Update: GraphQL Java \"Look-Ahead\"\n\nIn our case we use graphql-java and use pure configuration files to map DataFetchers to database queries. There is a some generic logic that looks at the graph query being run and calls parameterized sql queries that are in a custom configuration file. We saw this article Building efficient data fetchers by looking ahead which explains that you can inspect at runtime the what the person who wrote the query selected to be returned. We can use that to \"look-ahead\" at what other entities we would be asked to fetch to satisfy the entire query. At which point we can join the data in the database and pull it all back efficiently in the a single database call. The graphql-java engine will still make `N` in-memory fetches to our code. The `N` requests to get the author of each book are satisfied by simply lookups in a hashmap that we loaded out of the single database call that joined the author table to the books table returning `N` complete rows efficiently.\n\nOur approach might sound a little like ORM yet we did not make any attempt to make it intelligent. The developer creating the API via our custom configuration files has to decide which graphql selection paths, under which graphql queries, will be mapped onto specific database queries. Our generic logic just \"looks-ahead\" at what the runtime graphql query actually selects in total to understand all the database columns that it needs to load out of each row returned by the SQL. It then deduplicates by id into a hashmap.\n\nOur approach can only handle parent-child-grandchild style trees of data. Yet this is a very common use case for us. The developer making the API still needs to keep a careful eye on performance. They need to adapt both the API and the custom mapping files to avoid poor performance.\n\n========================================\n\nCode:\n```text\n{\n phones: [\n {\n id: 1,\n brand: 'b1',\n model: 'Galaxy S9 Plus',\n price: 1000,\n },\n {\n id: 2,\n brand: 'b2',\n model: 'OnePlus 6',\n price: 900,\n },\n ],\n brands: [\n {\n id: 'b1',\n name: 'Samsung'\n },\n {\n id: 'b2',\n name: 'OnePlus'\n }\n ]\n}\n```\n\n```text\n{id: 2, brand: 'OnePlus', model: 'OnePlus 6', price: 900}\n```\n\n```text\nid = 2\n```\n\n```text\nquery myComponentQuery {\n phone {\n id\n brand\n model\n price\n }\n}\n```\n\n```text\nPhone: {\n id(root, args, context) {\n pg.query('Select * from Phones where name = ?', ['blah']).then(d => {/*doStuff*/})\n //OR\n fetch(context.upstream_url + '/thing/' + args.id).then(d => {/*doStuff*/})\n\n return {/*the result of either of those calls here*/}\n },\n price(root, args, context) {\n return 9001\n },\n},\n```\n\n```sql\ncreate table Book ( id string, name string, pageCount string, authorId string ); \ncreate table Author ( id string, firstName string, lastName string );\n```\n\n```text\ntype Query {\n bookById(id: ID): Book\n}\n\ntype Book {\n id: ID\n title: String\n pageCount: Int\n author: Author\n}\n\ntype Author {\n id: ID\n firstName: String\n lastName: String\n}\n```\n\n```text\n{\n bookById(id:\"book-1\"){\n id\n title\n pageCount\n author {\n firstName\n lastName\n }\n }\n}\n```\n\n```json\n{\n \"data\": {\n \"book1\": {\n \"id\": \"book-1\",\n \"title\": \"Harry Potter and the Philosopher's Stone\",\n \"pageCount\": 223,\n \"author\": {\n \"firstName\": \"Joanne\",\n \"lastName\": \"Rowling\"\n }\n }\n }\n}\n```\n\n```text\ntype Query {\n booksByTitleStartsWith(titlePrefix: String): [Book]\n}\n```\n\n```text\n{\n booksByTitleStartsWith(titlePrefix:\"Harry\"){\n id\n title\n pageCount\n author {\n firstName\n lastName\n }\n }\n}\n```\n\n```text\ntype Query {\n booksByTitleStartsWith(titlePrefix: String): [Book] /* <- single database call */\n authorsByIds(authorIds: [ID]) [Author] /* <- single database call */\n booksByIds(bookIds: [ID]) [Book] /* <- single database call */\n}\n\ntype Book {\n id: ID\n title: String\n pageCount: Int\n}\n\ntype Author {\n id: ID\n firstName: String\n lastName: String\n}\n```\n\n```text\nquery {\n booksByIDs(authorIds: [\"book-1\",\"book-2\",\"book-3\"]) {\n id\n title\n }\n authorsByIds(authorIds: [\"author-1\",\"author-2\",\"author-3\"]) {\n id\n firstName\n lastName\n }\n}\n```\n\n```text\nauthorId\n```\n\n```text\nBook\n```\n\n```text\nAuthor\n```\n\n```text\nauthorId\n```\n\n```text\nN+1\n```\n\n```text\nN+1\n```\n\n```text\ntitle like 'Harry%'\n```\n\n```text\nauthorId\n```\n\n```text\nID\n```\n\n```text\nN+1\n```\n\n```text\n1\n```\n\n```text\nN\n```\n\n```text\nN\n```\n\n```text\nauthor\n```\n\n```text\nBook\n```\n\n```text\nauthorsByIds\n```\n\n```text\nbooksByTitleStartsWith\n```\n\n```text\nAuthor\n```\n\n```text\nBook\n```\n\n```text\nN+1\n```\n\n```text\nN\n```\n\n```text\nN\n```\n\n```text\nN\n```\n\n========================================\n\nComments:\n- Are you able to provide an example in resolver for brand ? That seems to be what the question is trying to get at.\n- Thank you for your post. I am discovering GraphQL. So sorry if my question is bad but the problem is not resolved. Can you give the code for query booksByAuthor(authorId: ID) [Book]?\n- the code depend on which graphql implementation you use. we use graphql-java.com. we have mapped it to our database with SQL statemens like `select {gql_selected} from books where authorId=@id` and we get back a list if hashmaps like `{βtitleβ=βMony Dickβ, βauthorIdβ=99,βpageCountβ=321}`. there is no magic here just a basic query for a list of books. this is the point that there is no joining in that example.\n- @Laurent i have expanded upon the example to be more specific that the api that you are asking about requires the client to make multiple queries explaining why that approach is efficient.","metadata":{"transformedAt":"2026-08-18T18:32:36.038Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":476,"estimatedTokens":3119}}214{"id":"stack-65861041","source":"stackoverflow","questionId":65861041,"title":"How to filter list objects by field value in GraphQL?","tags":["graphql"],"text":"Title: How to filter list objects by field value in GraphQL?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nSay I have the following json data:\n\n```\n\"data\": {\n \"continents\": [\n {\n \"code\": \"AF\",\n \"name\": \"Africa\",\n },\n {\n \"code\": \"EU\",\n \"name\": \"Europe\"\n },\n // ...\n ]\n}\n```\n\nWhat would be the correct GraphQL query to fetch a list item with: `code : \"AF\"`? In other words, how to produce the following result:\n\n```\n\"data\": {\n \"code\": \"AF\",\n \"name\": \"Africa\"\n}\n```\n\nSo far, I have:\n\n```\nquery {\n continents {\n code\n name\n }\n}\n```\n\nbut that simply returns the full array.\n\nI've been running my examples on: https://lucasconstantino.github.io/graphiql-online/\n\n========================================\n\nTop Answer:\nAs it turns out, there is no built-in `filter` function defined on lists/arrays! *GraphQL (query language) is basically about selecting **fields** on **objects*** [Schemas and Types | GraphQL].\n\nOne only needs to look at the GraphQL schema in question:\n\n```\ntype Query {\n continents(filter: ContinentFilterInput): [Continent!]!\n // ...\n}\ntype Continent {\n code: ID!\n name: String!\n countries: [Country!]!\n}\ninput ContinentFilterInput {\n code: StringQueryOperatorInput\n}\ninput StringQueryOperatorInput {\n eq: String\n ne: String\n in: [String]\n nin: [String]\n regex: String\n glob: String\n}\n// ...\n```\n\nWe see that query `continents` has a parameter `filter` of input type `ContinentFilterInput`. That's enough information for us to start building our filter query:\n\n```\nquery {\n continents(filter: ...) {\n code\n name\n }\n}\n```\n\nUpon inspecting `ContinentFilterInput`, we observe that it has a single field `code` of input type `StringQueryOperatorInput`:\n\n```\nquery {\n continents(filter: { code: ...}) {\n code\n name\n }\n}\n```\n\nFinally, we find a field `eq` inside input type `StringQueryOperatorInput` which is a scalar type (`String`) and we are done:\n\n```\nquery {\n continents(filter: { code: { eq: \"AF\" } }) {\n code\n name\n }\n}\n```\n\n========================================\n\nCode:\n```json\n\"data\": {\n \"continents\": [\n {\n \"code\": \"AF\",\n \"name\": \"Africa\",\n },\n {\n \"code\": \"EU\",\n \"name\": \"Europe\"\n },\n // ...\n ]\n}\n```\n\n```json\n\"data\": {\n \"code\": \"AF\",\n \"name\": \"Africa\"\n}\n```\n\n```text\nquery {\n continents {\n code\n name\n }\n}\n```\n\n```text\ncode : \"AF\"\n```\n\n```text\nquery {\n continents(filter: {code: {eq: \"AF\"}}) {\n name\n }\n}\n```\n\n```text\ntype Query {\n continents(filter: ContinentFilterInput): [Continent!]!\n // ...\n}\ntype Continent {\n code: ID!\n name: String!\n countries: [Country!]!\n}\ninput ContinentFilterInput {\n code: StringQueryOperatorInput\n}\ninput StringQueryOperatorInput {\n eq: String\n ne: String\n in: [String]\n nin: [String]\n regex: String\n glob: String\n}\n// ...\n```\n\n```text\nquery {\n continents(filter: ...) {\n code\n name\n }\n}\n```\n\n```text\nquery {\n continents(filter: { code: ...}) {\n code\n name\n }\n}\n```\n\n```text\nquery {\n continents(filter: { code: { eq: \"AF\" } }) {\n code\n name\n }\n}\n```\n\n```text\nfilter\n```\n\n```text\ncontinents\n```\n\n```text\nfilter\n```\n\n```text\nContinentFilterInput\n```\n\n```text\nContinentFilterInput\n```\n\n```text\ncode\n```\n\n```text\nStringQueryOperatorInput\n```\n\n```text\neq\n```\n\n```text\nStringQueryOperatorInput\n```\n\n```text\nString\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":248,"estimatedTokens":827}}215{"id":"stack-44120314","source":"stackoverflow","questionId":44120314,"title":"Result of a delete mutation?","tags":["graphql","graphql-ruby"],"text":"Title: Result of a delete mutation?\nTags: graphql, graphql-ruby\nSource: Stack Overflow\n\nQuestion:\nWhat should be the result of a delete mutation in Graphql? I'm using the graphql-ruby gem. Here's an example of my mutation, but I'm just not sure what I should be returning as the response.\n\n```\nMutations::Brands::Delete = GraphQL::Relay::Mutation.define do\n name \"DeleteBrand\"\n description \"Delete a brand\"\n\n input_field :id, types.ID\n\n # return_field ??\n\n resolve ->(object, inputs, ctx) {\n brand = Brand.find(inputs[:id])\n brand.destroy\n }\nend\n```\n\n========================================\n\nTop Answer:\nI don't think a clear de facto standard exists as of July, 2017, and I see a lot of differences between implementations (GitHub, Yelp, GraphCool, Shopify).\n\nHowever, if you look at some of recent GraphQL APIs to come out, there seems to be a common trend. Largely, the input type and response type are specific to the mutation. So for instance, for an `updateBrand` mutation you might expect an `UpdateBrandInput`, and return an `UpdateBrandPayload` response. Notice, the input is not `BrandInput`, and responding with `Brand`. Nor would you respond with a scalar boolean (eg. `true` if successful) or the `id` of the deleted entity (in the case of a delete mutation). Per this convention, you could have a `createBrand` mutation, with a `CreateBrandInput` and a `CreateBrandPayload` response. \n\nBy creating mutation specific `input` and `payload` types, you have a lot of flexibility in the fields you expect and respond with. Per deletion, you might have a `DeleteBrandPayload` response that not only includes shallow (eg. only scalar) fields of the brand, but also other related data (eg. `clientMutationId`), etc..\n\nTo be honest, I think the GraphQL spec gives just enough rope to hang yourself with, so it's smart to look at how some of the big guys are rolling this out.\n\n========================================\n\nCode:\n```text\nMutations::Brands::Delete = GraphQL::Relay::Mutation.define do\n name \"DeleteBrand\"\n description \"Delete a brand\"\n\n input_field :id, types.ID\n\n # return_field ??\n\n resolve ->(object, inputs, ctx) {\n brand = Brand.find(inputs[:id])\n brand.destroy\n }\nend\n```\n\n```text\nDestroy = GraphQL::Relay::Mutation.define do\nname 'DestroyComment'\ndescription 'Delete a comment and return post and deleted comment ID'\n\n# Define input parameters\ninput_field :id, !types.ID\n\n# Define return parameters\nreturn_field :deletedId, !types.ID\nreturn_field :article, ArticleType\nreturn_field :errors, types.String\n\nresolve ->(_obj, inputs, ctx) {\n comment = Comment.find_by_id(inputs[:id])\n return { errors: 'Comment not found' } if comment.nil?\n\n article = comment.article\n comment.destroy\n\n { article: article.reload, deletedId: inputs[:id] }\n}\n```\n\n```text\nupdateBrand\n```\n\n```text\nUpdateBrandInput\n```\n\n```text\nUpdateBrandPayload\n```\n\n```text\nBrandInput\n```\n\n```text\nBrand\n```\n\n```text\ntrue\n```\n\n```text\nid\n```\n\n```text\ncreateBrand\n```\n\n```text\nCreateBrandInput\n```\n\n```text\nCreateBrandPayload\n```\n\n```text\ninput\n```\n\n```text\npayload\n```\n\n```text\nDeleteBrandPayload\n```\n\n```text\nclientMutationId\n```\n\n========================================\n\nComments:\n- I think best practice is to return exactly what you deleted so that graphql knows what needs to go away.\n- Would this not result in a memory bloat ? @eshaiju\n- Funny thing: I was looking for exactly this answer (thank you, it was very useful), and as it happens, the mutations I'm working on are named \"createBrand\", \"updateBrand\" and \"deleteBrand\" :D\n- Would have been interesting to have the link of some examples of the \"big guys\" code you're talking about, they've dozens of repositories\n- You can try the GraphQL API from Github here docs.github.com/en/graphql/overview/explorer (you have to sign in), they use this naming: `DeleteBrandInput`, `DeleteBrandPayload`.","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":141,"estimatedTokens":965}}216{"id":"stack-53507972","source":"stackoverflow","questionId":53507972,"title":"What is the purpose of template literals (backticks) following a function in ES6?","tags":["javascript","ecmascript-6","graphql","styled-components","template-literals"],"text":"Title: What is the purpose of template literals (backticks) following a function in ES6?\nTags: javascript, ecmascript-6, graphql, styled-components, template-literals\nSource: Stack Overflow\n\nQuestion:\nIn GraphQL you can write something like this to define a query:\n\n```\nconst USER_QUERY = gql`\n {\n user(id: 2) {\n name\n }\n }\n`\n```\n\nIn styled components you can define a styled component like this:\n\n```\nconst Button = styled.button`\n background-color: papayawhip;\n`\n```\n\nWhat is this syntax? I know with template literals you can sub in variables with this syntax: `${foo}` but I have never seen this used. Any guidance would be appreciated.\n\n========================================\n\nTop Answer:\nTemplate literals have an additional feature called tagged templates. That's what the prefix before the opening backtick is. The prefix is actually the name of a function - the function is passed the constant parts of the template strings and the interpolated values (stuff in the `${}` sections) and can process the resulting string into whatever it wants (although generally another string, doesn't have to be).\n\nSee this page on MDN for more details on how tagged templates work.\n\n========================================\n\nCode:\n```text\nconst USER_QUERY = gql`\n {\n user(id: 2) {\n name\n }\n }\n`\n```\n\n```text\nconst Button = styled.button`\n background-color: papayawhip;\n`\n```\n\n```text\n${foo}\n```\n\n```js\nfunction upperV(strings, ...vars) {\n /* make vars uppercase */\n console.log(\"vars: \", vars) // an array of the passed in variables\n console.log(\"strings:\", strings) // the string parts\n\n // put them together\n return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);\n}\n\nlet adverb = \"boldly\"\nlet output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;\nconsole.log(output)\n```\n\n```text\n${}\n```\n\n```text\n${}\n```\n\n========================================\n\nComments:\n- Where is this example coming from?\n- these are examples of how queries and styled components can be instantiated via those libraries, to exemplify the question on this syntax\n- Tagged template literals?\n- Backticks calling a function || What is the usage of the backtick symbol (`) in JavaScript? (which mentions tagged template literal, but not in the first answer)\n- \"the function is passed the constant parts of the template strings\" - what does this mean?\n- It's the parts of the template string that aren't in the `${}` blocks. Read the page I linked to, it has all the details.","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":89,"estimatedTokens":633}}217{"id":"stack-45382069","source":"stackoverflow","questionId":45382069,"title":"Search for code in GitHub using GraphQL (v4 API)","tags":["github","graphql","github-api"],"text":"Title: Search for code in GitHub using GraphQL (v4 API)\nTags: github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nI am using the GitHub's GraphQL API to search for files/code containing a particular word. A simple (contrived) example of a search which in this case is to find the term \"beef\" in files located in \"recipes\" (the repo) for \"someuser\" (the owner for the repo) is shown below:\n\n```\n{\n search(query: \"beef repo:someuser/recipes\", type: REPOSITORY, first: 10) {\n repositoryCount\n edges {\n node {\n ... on Repository {\n name\n }\n }\n }\n }\n}\n```\n\nI tried this in GitHub's GraphQL Explorer (https://developer.github.com/v4/explorer/) and receive zero results from the search which is incorrect as I can confirm that the word (\"beef\" in the example above) is in the files in the repo:\n\n```\n{\n \"data\": {\n \"search\": {\n \"repositoryCount\": 0,\n \"edges\": []\n }\n }\n}\n```\n\nWhen I try this using GitHub's REST API (v3) via curl, I definitely get results:\n\n```\ncurl --header 'Accept: application/vnd.github.v3.raw' https://api.github.com/search/code?q=beef+repo:someuser/recipes\n```\n\n... So I know that the query (REST v3 API) is valid, and my understanding is that the query string in the GraphQL (v4) API is identical to that for the REST (v3) API.\n\nMy questions are:\n\n- Am I incorrectly using the GitHub GraphQL (v4) API or am I specifying the query string improperly, or am I trying to use functionality that is not yet supported?\n\n- Is there an example of how to do this that someone can provide (or link to) that illustrates how to search code for specific words?\n\n========================================\n\nTop Answer:\nYou can add qualifiers, if you want to search \"beef\" just in names than change the query like \n\nsearch(query: \"beef in:name\", type: REPOSITORY, first: 10) {\n\nfor further detail you can look at https://help.github.com/en/articles/searching-for-repositories#search-based-on-the-contents-of-a-repository\n\n========================================\n\nCode:\n```text\n{\n search(query: \"beef repo:someuser/recipes\", type: REPOSITORY, first: 10) {\n repositoryCount\n edges {\n node {\n ... on Repository {\n name\n }\n }\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"search\": {\n \"repositoryCount\": 0,\n \"edges\": []\n }\n }\n}\n```\n\n```text\ncurl --header 'Accept: application/vnd.github.v3.raw' https://api.github.com/search/code?q=beef+repo:someuser/recipes\n```\n\n```text\nType: CODE\n```\n\n```text\ntype: REPOSITORY\n```\n\n```text\nsearch(query: \"beef\", type: REPOSITORY, first: 10) {\n```\n\n========================================\n\nComments:\n- If it's this difficult I'm not betting on GraphQL becoming a standard any time soon!\n- two years later and `type: CODE` is still not supported, we still need to use the v3 API for this..\n- Make that three years later\n- We are at 4 years now :)\n- 5 Years! :)))))\n- see also the supported values for search type\n- Update: 6 years!!\n- 7 years later :))))))\n- 8 years later :O","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":115,"estimatedTokens":742}}218{"id":"stack-50063202","source":"stackoverflow","questionId":50063202,"title":"What is the difference between GraphQL and SPARQL?","tags":["graphql","sparql","rdf","semantic-web","ontology"],"text":"Title: What is the difference between GraphQL and SPARQL?\nTags: graphql, sparql, rdf, semantic-web, ontology\nSource: Stack Overflow\n\nQuestion:\nI'm doing a lot of research right now on Semantic Web and complex data models that represent relationships between individuals and organizations.\nI knew a little semantic ontologies although I never understood what it was used if not make graphs.\n\nI saw on university wiki that the language to question an ontology is the SPARQL (tell me if I'm wrong).\n\nBut recently I saw a company that had created a semantic ontology put it in the form of GraphQL that I did not know (https://diffuseur.datatourisme.gouv.fr/graphql/voyager/).\n\nIt seems to me that semantic ontologies are made to better find information, for example to make a chatbot (it's what I want to do), but here they transformed a semantic ontology into an API, is it right? To make a GraphQL, should I build first a semantic ontology?\n\nCould you explain to me a little the difference between all this, honestly it's a little vague for me.\n\n========================================\n\nTop Answer:\n**GraphQL** and **SPARQL** are different languages for different purposes. SPARQL is a language to work with **Triple stores**, graph datasets, and RDF nodes. GraphQL is a API language, preferably for working with **JSON** structures. As for your specific case, I would recommend to clarify your goal on using AI in your application. If you require to apply a graph dataset in your application, perform more advance knowledge discovery like reasoning on dataset, then you may need a Semantic Web approach to apply SPARQL on top of your dataset. As you can see in the picture below, Semantic Web presents different layers to perform knowledge discovery, perform reasoning, by ontology design and RDF-izing datasets.\n\nhttps://i.sstatic.net/p09Pa.png\n\nsee here to read more.\nIf your AI application does not have such requirements and you can accomplish your data analysis using a JSON-based database, GraphQL is probably a good choice to create your API, as it is widely used by different Web and Mobile applications these days. In particular, it is used to your data through different platforms and microservices. See here for more information.\n\nhttps://i.sstatic.net/RZdch.png\n\n========================================\n\nCode:\n```text\n:rcs\n```\n\n========================================\n\nComments:\n- BTW, the link is not working now. Do you know actual link?\n- Hi,you can try : framagit.org/datatourisme/ontology/tree/master\n- Hello, thank you for your anwser. So, should i better use sparql or graphql to build my AI ? Why did this compagny did an ontology then a graphql ? Did they used ontology to build the logic of the data model then a graphql to query it faster ? thank you\n- Thank you, For a chatbot, which one of this tech would you use ?\n- In the first picture, why does RDF sit above XML? Does this indicate that RDF requires XML in some way and cannot be used without it?\n- @ErwanPesle I use both technology in different projects. I mostly use Semantic Web for doing research deeply. For example, when I want to answer sophisticated queries over a graph database. On the other side, I use graphql in a company to build a API on top of relational database, instead of using REST API.\n- @jaco0646 XML is primarily a serialization format, while RDF is primarily a data model. In other words, we represent data in XML format, while RDF is a more higher level and a general aspect of data structure (e.g., each object can be defined as SUBJECT, OBJECT, and PREDICATE). So RDF triples can be represented by different formats like turtle, XML , .... Hope I could explain it well! read here cambridgesemantics.com/blog/semantic-university/learn-rdf/…\n- So in the picture, XML is only an example? It could say \"Syntax: JSON-LD\" and have the same meaning?\n- @jaco0646 Yes, could be. The picture was taken from the first SW architecture. Time to time, more data representations were added to the architecture.\n- Thank you for your impressive anwser Stanislav, My goal is to help citizens to act and participate to the daily life of their city, that's why i thought about build an ontology to desribe the ecosystem of the city (individuals - organizations), and for the IHM, to build a chatbot, an AI. Would you have any advices ?\n- @ErwanPesle, unfortunately, I'm not familiar with the subject... I hope, the T. Gruber's interview would be helpful.\n- Please update link to hypergraphql.org. Stackoverflow doesnβt allow edit less than 6 characters for me.","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":50,"estimatedTokens":1140}}219{"id":"stack-49618392","source":"stackoverflow","questionId":49618392,"title":"When to use watchQuery or query in Apollo-Angular?","tags":["angular","graphql","apollo","apollo-client"],"text":"Title: When to use watchQuery or query in Apollo-Angular?\nTags: angular, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am using a watchQuery or query in Apollo-Angular (graphql)\n\nHow is the logic and difference of the watchQuery and query\n\n========================================\n\nCode:\n```text\nquery\n```\n\n```text\nwatchQuery\n```\n\n========================================\n\nComments:\n- What is the difference between `watchQuery` and subscriptions?\n- @PaulRazvanBerg good question since this is causing a lot of confusion. `watchQuery` will continue to emit results, as long as this data changes in Apollo's cache memory store. Subscriptions will emit results based on changes/events from the server side.\n- Broken link now","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":26,"estimatedTokens":186}}220{"id":"stack-44137710","source":"stackoverflow","questionId":44137710,"title":"GitHub GraphQL equivalent of the contents API","tags":["github","github-api","graphql"],"text":"Title: GitHub GraphQL equivalent of the contents API\nTags: github, github-api, graphql\nSource: Stack Overflow\n\nQuestion:\nDoes GitHub's GraphQL API have an equivalent to the contents API?\n\nI can't seem to come up with a query that accepts repo owner, repo name and file path and returns the contents of the file. I'm guessing it has something to do with the tree object?\n\nhttps://developer.github.com/early-access/graphql/explorer/\n\n========================================\n\nCode:\n```text\nquery {\n repository(name: \"repoName\", owner: \"repoOwner\") {\n object(expression: \"branch:path/to/file\") {\n ... on Blob {\n text\n }\n }\n }\n}\n```\n\n```text\nexpression\n```\n\n```text\nobject\n```\n\n```text\nrev-parse\n```\n\n========================================\n\nComments:\n- what about binary content with base64 encoded? we have that in v3, but couldn't find a way in v4.\n- what's the \"...\" supposed to be?\n- @SW_user2953243 GraphQL syntax, do not replace the dots\n- @SW_user2953243 You are querying for a `GitObject`, which could be a `Blob` (file), but could also be a `Commit`, `Tag` or `Tree`. The `... on Blob` is an inline fragment, that allows you to conditionally query for the `text` field if the returned `GitObject` is a `Blob`.\n- @SamTolmay I tried same with Tag GitObject but getting empty response. Have any ideas? For invalid tags getting null object. For valid tags only empty json object. { repository(owner: \"gradle\", name: \"gradle\") { url object(expression: \"v5.3.0\") { ... on Tag { oid id } } } }\n- Does not work when the object is a submodule: it returns `object: null`.","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":47,"estimatedTokens":399}}221{"id":"stack-38021899","source":"stackoverflow","questionId":38021899,"title":"What does the \"operation name\" reference?","tags":["graphql"],"text":"Title: What does the \"operation name\" reference?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI'm learning about GraphQL and I'm very interested in the `operation name` the part of the query that comes after the `query` or `mutation` (depending on the root query type). I found a couple of code examples using the operation name, and I'm confused as to where they come from? There seems to be no references in the code about them, and they seem completely arbitrary.\n\n```\nquery Welcome {\n echo (email: \"hi@example.com\")\n}\n```\n\nand\n\n```\nquery HeroNameQuery {\n hero {\n name\n }\n}\n```\n\nI don't understand why a given schema can't just contain the queries and types that (eg. `user`, `article`, `order`, etc.), and I don't understand the namespacing system and the operation name provides any sort of advantage.\n\nhttps://github.com/mugli/learning-graphql/blame/master/7.%20Deep%20Dive%20into%20GraphQL%20Type%20System.md#L436\n\nhttp://graphql.org/docs/queries/\n\n========================================\n\nTop Answer:\nThe Query/Mutation name is optional. You can use it on the backend for stored queries if your backend supports it. However, it is generally used for logging. You can use a unique name for each query/mutation. Then, when you are having problems, you can grep through your logs for the query name to see what was happening with that specific query.\n\n========================================\n\nCode:\n```text\nquery Welcome {\n echo (email: \"hi@example.com\")\n}\n```\n\n```text\nquery HeroNameQuery {\n hero {\n name\n }\n}\n```\n\n```text\noperation name\n```\n\n```text\nquery\n```\n\n```text\nmutation\n```\n\n```text\nuser\n```\n\n```text\narticle\n```\n\n```text\norder\n```\n\n```text\n// GraphQL Query\n\nquery Welcome ($data: String!) {\n echo (email: $data) {\n name\n }\n}\n\n// GraphQL Variables\n\n{\n \"data\": \"hi@example.com\"\n}\n```\n\n========================================\n\nComments:\n- I'm pretty sure the name can be omitted (I think `query` too) if you're only sending one. I believe the names are basically used for stored queries. You could put those on the server and execute them by name rather than sending the whole query...I believe that's the idea, but I'm a GQL noob too.\n- very explicit text - graphql.org/learn/queries/#operation-name\n- I read that in the docs too (graphql.org/learn/queries/#operation-name). The confusing part is, the client side optionally sets the query operation name to whatever they want, so i can't see how that's useful for debugging via server side logs!\n- @spinkus yes, the operation name doesn't necessarily convey meaning if the client has merely generated it. But it could still be useful for inspecting logs in case you have access to the client and can find out which query they sent.","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":98,"estimatedTokens":679}}222{"id":"stack-49087643","source":"stackoverflow","questionId":49087643,"title":"GraphQL Java client library","tags":["java","client","graphql"],"text":"Title: GraphQL Java client library\nTags: java, client, graphql\nSource: Stack Overflow\n\nQuestion:\nI am looking for a java *client* library for GraphQL. \nThis is to use for server-to-server communication, both in java.\nNo android, not javascript... just java.\nApollo is the nearest answer, and it seems like it is for Android only, not for plain-java applications.\nLots of examples about build server in java, nothing about client.\nAny idea?\nThanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":12,"estimatedTokens":112}}223{"id":"stack-49317582","source":"stackoverflow","questionId":49317582,"title":"How to chain two GraphQL queries in sequence using Apollo Client","tags":["graphql","apollo","react-apollo","apollo-client","graphcool"],"text":"Title: How to chain two GraphQL queries in sequence using Apollo Client\nTags: graphql, apollo, react-apollo, apollo-client, graphcool\nSource: Stack Overflow\n\nQuestion:\nI am using Apollo Client for the frontend and Graphcool for the backend. There are two queries `firstQuery` and `secondQuery` that I want them to be called in sequence when the page opens. Here is the sample code (the definition of TestPage component is not listed here):\n\n```\nexport default compose(\n graphql(firstQuery, {\n name: 'firstQuery'\n }),\n graphql(secondQuery, { \n name: 'secondQuery' ,\n options: (ownProps) => ({\n variables: {\n var1: *getValueFromFirstQuery*\n }\n })\n })\n)(withRouter(TestPage))\n```\n\nI need to get `var1` in `secondQuery` from the result of `firstQuery`. How can I do that with Apollo Client and compose? Or is there any other way to do it? Thanks in advance.\n\n========================================\n\nTop Answer:\nFor anyone using react apollo hooks the same approach works.\n\nYou can use two `useQuery` hooks and pass in the result of the first query into the `skip` `option` of the second, \n\nexample code:\n\n```\nconst AlertToolbar = ({ alertUid }: AlertToolbarProps) => {\n const authenticationToken = useSelectAuthenticationToken()\n\n const { data: data1 } = useQuery(query, {\n skip: !authenticationToken,\n variables: {\n alertUid,\n },\n context: makeContext(authenticationToken),\n })\n\n const { data: data2, error: error2 } = useQuery(query2, {\n skip:\n !authenticationToken ||\n !data1 ||\n !data1.alertOverview ||\n !data1.alertOverview.deviceId,\n variables: {\n deviceId:\n data1 && data1.alertOverview ? data1.alertOverview.deviceId : null,\n },\n context: makeContext(authenticationToken),\n })\n\n if (error2 || !data2 || !data2.deviceById || !data2.deviceById.id) {\n return null\n }\n const { deviceById: device } = data2\n return (\n \n ...\n // do some stuff here with data12\n```\n\n========================================\n\nCode:\n```text\nexport default compose(\n graphql(firstQuery, {\n name: 'firstQuery'\n }),\n graphql(secondQuery, { \n name: 'secondQuery' ,\n options: (ownProps) => ({\n variables: {\n var1: *getValueFromFirstQuery*\n }\n })\n })\n)(withRouter(TestPage))\n```\n\n```text\nfirstQuery\n```\n\n```text\nsecondQuery\n```\n\n```text\nvar1\n```\n\n```text\nsecondQuery\n```\n\n```text\nfirstQuery\n```\n\n```text\nexport default compose(\n graphql(firstQuery, {\n name: 'firstQuery'\n }),\n graphql(secondQuery, { \n name: 'secondQuery',\n skip: ({ firstQuery }) => !firstQuery.data,\n options: ({firstQuery}) => ({\n variables: {\n var1: firstQuery.data.someQuery.someValue\n }\n })\n })\n)(withRouter(TestPage))\n```\n\n```text\n<Query query={firstQuery}>\n {({ data: { someQuery: { someValue } = {} } = {} }) => (\n <Query\n query={secondQuery}\n variables={{var1: someValue}}\n skip={someValue === undefined}\n >\n {({ data: secondQueryData }) => (\n // your component here\n )}\n</Query>\n```\n\n```text\nconst { data: { someQuery: { someValue } = {} } = {} } = useQuery(firstQuery)\nconst variables = { var1: someValue }\nconst skip = someValue === undefined\nconst { data: secondQueryData } = useQuery(secondQuery, { variables, skip })\n```\n\n```text\nconst [doA] = useMutation(MUTATION_A)\nconst [doB] = useMutation(MUTATION_B)\n\n// elsewhere\nconst { data: { someValue } } = await doA()\nconst { data: { someResult } } = await doB({ variables: { someValue } })\n```\n\n```text\nfirstQuery\n```\n\n```text\nskip\n```\n\n```text\nQuery\n```\n\n```text\nskip\n```\n\n```text\nnull\n```\n\n```text\nskip\n```\n\n```text\nuseQuery\n```\n\n```js\nconst AlertToolbar = ({ alertUid }: AlertToolbarProps) => {\n const authenticationToken = useSelectAuthenticationToken()\n\n const { data: data1 } = useQuery<DataResponse>(query, {\n skip: !authenticationToken,\n variables: {\n alertUid,\n },\n context: makeContext(authenticationToken),\n })\n\n const { data: data2, error: error2 } = useQuery<DataResponse2>(query2, {\n skip:\n !authenticationToken ||\n !data1 ||\n !data1.alertOverview ||\n !data1.alertOverview.deviceId,\n variables: {\n deviceId:\n data1 && data1.alertOverview ? data1.alertOverview.deviceId : null,\n },\n context: makeContext(authenticationToken),\n })\n\n if (error2 || !data2 || !data2.deviceById || !data2.deviceById.id) {\n return null\n }\n const { deviceById: device } = data2\n return (\n <Toolbar>\n ...\n // do some stuff here with data12\n```\n\n```text\nuseQuery\n```\n\n```text\nskip\n```\n\n```text\noption\n```\n\n========================================\n\nComments:\n- Work like a charm! Thanks Daniel. It's strange that I didn't find the documentation on this anywhere.\n- I can't believe this is working. Couldn't find this anywhere else\n- Thank you @Damian, your post helped me to understand this feature. In my opinion this approach works only for the 2-3 sequenced queues etc., otherwise, the `skip` arguments list will be too long, just like in the answer\n- This works. Regarding the chain of `||`, you can actually optimize them away with the `?.` optional chaining operator! e.g. `data1?.alertOverview?.deviceId`","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":237,"estimatedTokens":1295}}224{"id":"stack-59162265","source":"stackoverflow","questionId":59162265,"title":"Why are GraphQL queries POST requests even when we are trying to fetch data and not update/submit new data?","tags":["graphql","postman"],"text":"Title: Why are GraphQL queries POST requests even when we are trying to fetch data and not update/submit new data?\nTags: graphql, postman\nSource: Stack Overflow\n\nQuestion:\nI am using Postman to fetch data from my server and when I use a REST call it is a GET request but when I use a GraphQL API call, it needs to be a POST request. Why is it so?\n\n========================================\n\nCode:\n```text\napplication/json\n```\n\n========================================\n\nComments:\n- You can also use GET requests like `http://myapi/graphql?query={me{name}}` (Source: graphql.org/learn/serving-over-http/#get-request) I think this depends on your API configuration.","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":18,"estimatedTokens":169}}225{"id":"stack-57527710","source":"stackoverflow","questionId":57527710,"title":"How to fix \"Initializer provides no value for this binding element and the binding element has no default value\" in TypeScript?","tags":["javascript","node.js","typescript","graphql"],"text":"Title: How to fix \"Initializer provides no value for this binding element and the binding element has no default value\" in TypeScript?\nTags: javascript, node.js, typescript, graphql\nSource: Stack Overflow\n\nQuestion:\nI am migrating an Apollo GraphQL API project written in JavaScript to TypeScript. And I am getting an error at finding a user code block, saying that:\n\n`var idArg: any Initializer provides no value for this binding element and the binding element has no default value.ts(2525)`\n\n```\nasync findOne({ id: idArg } = {}) {\n // Red line here ^^^^^\n const user = await this.knex('users')\n .where('id', idArg)\n .first();\n\n if (!user) return;\n return user;\n }\n```\n\nCurrently I added `any` to it without really knowing the actual solution, and the warning is gone:\n\n```\nasync findOne({ id: idArg }: any = {}) {\n const user = await this.knex('users')\n .where('id', idArg)\n .first();\n\n if (!user) return;\n return user;\n }\n```\n\nHowever I'd still like to know the actual solution. Should I add a `number` type instead of `any`? But when I do that, the error is:\n\n`Type '{}' is not assignable to type 'number'.ts(2322)`.\n\n========================================\n\nCode:\n```ts\nasync findOne({ id: idArg } = {}) {\n // Red line here ^^^^^\n const user = await this.knex('users')\n .where('id', idArg)\n .first();\n\n if (!user) return;\n return user;\n }\n```\n\n```ts\nasync findOne({ id: idArg }: any = {}) {\n const user = await this.knex('users')\n .where('id', idArg)\n .first();\n\n if (!user) return;\n return user;\n }\n```\n\n```text\nvar idArg: any Initializer provides no value for this binding element and the binding element has no default value.ts(2525)\n```\n\n```text\nany\n```\n\n```text\nnumber\n```\n\n```text\nany\n```\n\n```text\nType '{}' is not assignable to type 'number'.ts(2322)\n```\n\n```text\n// The compiler checks the object { id: '1' } and it knows it has an id property\nvar { id } = { id: '1' }\n\n/* The compiler is confused. It check the object {} and it knows it doesn't have \na property id1, so it is telling you it doesn't know where to get the value \nfor id1\n*/\nvar { id1 } = {}\n\n/* In this case the compiler knows the object doesn't have the property id2 but\nsince you provided a default value it uses it 'default value'.\n */\nvar { id2 = 'default value' } = {}\n\n/* In your case there are a couple of solutions: */\n\n// 1) Provide the value in the initializer\nfunction findOne({ id: idArg } = { id: 'value here' }) {\n console.log(id)\n}\nfindOne()\n\n// 2) Provide a default value\nfunction findOne1({ id: idArg = 'value here 1' } = {}) {}\n\n// 3) Provide initializer and type definition\nfunction findOne2({ id: idArg}: { id?: number } = {}) {}\n\n// 3) Do not provide initializer\nfunction findOne3({ id: idArg}: { id: number }) {}\n```\n\n========================================\n\nComments:\n- I have a tiny issue, if I fix this issue with default value `const { rToken = undefined, theData = undefined } = { ...data };` tslint would complain for `no-unnecessary-initializer`.\n- Variables without a value are `undefined`, so `rToken = undefined` is unnecessary.\n- I already know that but I don't know why TSC throws errors without it.","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":123,"estimatedTokens":791}}226{"id":"stack-48116781","source":"stackoverflow","questionId":48116781,"title":"GitHub API v4: How can I traverse with pagination? (GraphQL)","tags":["rest","github","graphql","github-api","github-graphql"],"text":"Title: GitHub API v4: How can I traverse with pagination? (GraphQL)\nTags: rest, github, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm using Github API v4 to run search query.\n\nFrom the API documentation I can understand that the following query gives me pageInfo but I don't know how to use it to traverse.\n\n```\nquery {\n search(first: 100, type:USER, query:\"location:usa repos:>0 language:java\") {\n pageInfo {\n startCursor\n hasNextPage\n endCursor\n }\n userCount\n nodes {\n ... on User {\n bio\n company\n email\n id\n isBountyHunter\n isCampusExpert\n isDeveloperProgramMember\n isEmployee\n isHireable\n isSiteAdmin\n isViewer\n location\n login\n name\n url\n websiteUrl\n }\n }\n }\n}\n```\n\nAnd response is:\n\n```\n{\n \"data\": {\n \"search\": {\n \"pageInfo\": {\n \"startCursor\": \"Y3Vyc29yOjE=\",\n \"hasNextPage\": true,\n \"endCursor\": \"Y3Vyc29yOjEwMA==\"\n },\n ...\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n search(first: 100, type:USER, query:\"location:usa repos:>0 language:java\") {\n pageInfo {\n startCursor\n hasNextPage\n endCursor\n }\n userCount\n nodes {\n ... on User {\n bio\n company\n email\n id\n isBountyHunter\n isCampusExpert\n isDeveloperProgramMember\n isEmployee\n isHireable\n isSiteAdmin\n isViewer\n location\n login\n name\n url\n websiteUrl\n }\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"search\": {\n \"pageInfo\": {\n \"startCursor\": \"Y3Vyc29yOjE=\",\n \"hasNextPage\": true,\n \"endCursor\": \"Y3Vyc29yOjEwMA==\"\n },\n ...\n}\n```\n\n```text\nquery {\n search(first: 100, after:\"Y3Vyc29yOjEwMA==\", type:USER, query:\"location:usa repos:>0 language:java\") {\n pageInfo {\n startCursor\n hasNextPage\n endCursor\n }\n userCount\n nodes {\n ... on User {\n bio\n company\n email\n id\n isBountyHunter\n isCampusExpert\n isDeveloperProgramMember\n isEmployee\n isHireable\n isSiteAdmin\n isViewer\n location\n login\n name\n url\n websiteUrl\n }\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":138,"estimatedTokens":554}}227{"id":"stack-35036221","source":"stackoverflow","questionId":35036221,"title":"Support of aggregate function in GraphQL","tags":["graphql"],"text":"Title: Support of aggregate function in GraphQL\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI'm am very interested by GraphQL for an analytic solution (think of an webapp displaying graphs). But I cannot find any examples of GraphQL using aggregate function. This is a main aspect of most of the queries done by my frontend.\n\nFor my solution, we have 3 typical backend calls.\n\n- Search\n\n- Aggregate\n\n- Time Series\n\nLet say we have this type specified in GraphQL\n\n```\ntype Person {\n name: String\n age: Int\n create_time: Date\n}\n```\n\n- Search\n\nThis seems to be well handled by GraphQL. No question here.\n\nex. Search age of Person named Bob\n{\n Person(name: \"Bob\") {\n age\n }\n}\n\n- Aggregate\n\nThis is the typical case where I want to display the info in a Pie Chart. So let say I want to count the number of person by age.\n\nHere would be the PostgreSQL query:\n\n```\nSELECT age, count(*) from Ticket group by age;\n```\n\nWhat would be the equivalent in GraphQL?\n\nTime Series\nThis is the typical case where I want to display the info in a BarChart with the X axis as time.\n\nex. Let say I want to count the number of created user per hour.\n\nHere would be the PostgreSQL query:\n\n```\nSELECT date_trunc('hour', create_time) as create_time_bin, count(*) from Person group by create_time_bin order by create_time_bin ASC;\n```\n\nWhat would be the GraphQL equivalent query?\n\n========================================\n\nTop Answer:\n@Damien, those problems are not GraphQL's problems. \n\nWhenever you want do something in GraphQL you must define a **Type of return data**, **Spec of function you implement**, and sometimes a **Type of input data** to feed into your function. Finally you write code to do the job.\n\nIn fact, it looks like you (re)write your code in GraphQL language.\n\nTake the example where you want to display the info in a Pie Chart:\n\n```\nSELECT age, count(*) from Ticket group by age;\n```\n\nDefine your return data here is a list of age and count:\n\n```\ntype TickGroupByAge {\n age: Int\n count: Int\n }\n```\n\nDefine your function or Query in GraphQL language:\n\n```\ngetTicketGroupByAge : [TickGroupByAge]`\n```\n\nFinally write a function to implement above query:\n\n```\nasync function(){\n const res = await client.query(\"SELECT age, count(*) from Ticket group by age\");\n return res.rows;\n}\n```\n\n@Ryan I totally agree with you that GraphQL forces you to write a lot of type definitions to resolve a simple task. For that reason, I ended up building my own NextQL - GraphQL-liked engine which is similar to GraphQL but simpler.\n\nMy project supports complex nested type definitions, which free you from define a lot of useless ones.\n\n========================================\n\nCode:\n```text\ntype Person {\n name: String\n age: Int\n create_time: Date\n}\n```\n\n```text\nSELECT age, count(*) from Ticket group by age;\n```\n\n```text\nSELECT date_trunc('hour', create_time) as create_time_bin, count(*) from Person group by create_time_bin order by create_time_bin ASC;\n```\n\n```text\nSELECT age, count(*) from Ticket group by age;\n```\n\n```text\ntype TickGroupByAge {\n age: Int\n count: Int\n }\n```\n\n```text\ngetTicketGroupByAge : [TickGroupByAge]`\n```\n\n```text\nasync function(){\n const res = await client.query(\"SELECT age, count(*) from Ticket group by age\");\n return res.rows;\n}\n```\n\n```text\nload json from \"http://url/person\" as l return l.age, count(1)\n```\n\n```text\nload json from \"http://url/person\" as l return barchart(toint(l.age)) as age_distribution\n```\n\n========================================\n\nComments:\n- Not to mention, how do you do range comparisons for scalars, like SELECT * WHERE timestamp > β¦ AND timestamp < β¦? Or sorting of results by a scalar? I donβt see any of these in the spec. What am I missing?\n- You add parameters to your fields that allow for that type of filtering.\n- I think I get what you are saying, but I get how the implementation of this would look like.\n- @Damien, every GraphQL query is responded to by a resolve() function. The query parameters you give to the query are the arguments to this function. The resolve() function then goes away and does anything you want, say retrieve the results of a SQL query from elsewhere, then you can aggregate that data as you like, and finally return the outcome of all that as your response to the GraphQL query. Point being: You're supposed to do the aggregation as if resolve() was just another JS function returning numbers. But the querying client doesn't need to know or care.\n- As a nitpicky aside, I don't see the sense in shortening 'Ticket' to 'Tick' in the suggest type 'TickGroupByAge'. It hurts the readability, and characters are cheap.\n- What way does Ticket group by age match the GraphQL funciton getTicketGroupByAge?","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":162,"estimatedTokens":1177}}228{"id":"stack-51522902","source":"stackoverflow","questionId":51522902,"title":"Apollo Query with Variable","tags":["graphql","apollo","react-apollo"],"text":"Title: Apollo Query with Variable\nTags: graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nJust a basic apollo query request\n\n```\nthis.client.query({\n query: gql`\n {\n User(okta: $okta){\n id\n }\n }`\n}).then(result => {\n this.setState({userid: result.data.User});\n console.log(this.state.userid.id)\n}).catch(error => {\n this.setState({error: Error});\n});\n```\n\nThe question is, how/where to set the $okta variable.\n\nDidn't find a solution on Stackoverflow or Google - would be great if someone could help me:)\n\n========================================\n\nCode:\n```text\nthis.client.query({\n query: gql`\n {\n User(okta: $okta){\n id\n }\n }`\n}).then(result => {\n this.setState({userid: result.data.User});\n console.log(this.state.userid.id)\n}).catch(error => {\n this.setState({error: <Alert color=\"danger\">Error</Alert>});\n});\n```\n\n```text\nconst query = gql`\n query User($okta: String) {\n User(okta: $okta){\n id\n }\n }\n`;\n\nclient.query({\n query: query,\n variables: {\n okta: 'some string'\n }\n})\n```\n\n========================================\n\nComments:\n- NP, my pleasure!\n- But it should be noted that this generic functionality is only to be found under the React section of the docs, which is pretty ridiculous.\n- s in the example query definition string needs to be capitalized\n- Note that `client.query` is async, and should be awaited...","metadata":{"transformedAt":"2026-08-18T18:32:36.039Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":70,"estimatedTokens":347}}229{"id":"stack-58904403","source":"stackoverflow","questionId":58904403,"title":"Unable to find any GraphQL type definitions for the following pointers: src/**/*.graphql","tags":["typescript","graphql","code-generation","graphql-codegen"],"text":"Title: Unable to find any GraphQL type definitions for the following pointers: src/**/*.graphql\nTags: typescript, graphql, code-generation, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nI am using the `@graphql-codegen/cli` tool to generate typescript types out of my graphql server.\nHere is my `codegen.yml` content:\n\n```\noverwrite: true\nschema: \"http://localhost:3001/graphql\"\ndocuments: \"src/**/*.graphql\"\ngenerates:\n src/generated/graphql.tsx:\n plugins:\n - \"typescript\"\n - \"typescript-operations\"\n - \"typescript-react-apollo\"\n ./graphql.schema.json:\n plugins:\n - \"introspection\"\n```\n\nHere is the `package.json` script I use to generate my types (`yarn schema`):\n\n```\n\"schema\": \"graphql-codegen --config codegen.yml\"\n```\n\nAll these have been automatically generated by executing the cli wizard `yarn codegen init`.\n\nBut when I run `yarn schema`, these are the errors I get:\n\nhttps://i.sstatic.net/5RvHt.png\n\n(server is positively running at `http://localhost:3001/graphql` and exposes the graph schema.\n\nThanks for your help and suggestion\n\nHere is the .graphql file hosted in my server (http://localhost:3001/graphql\n\n```\n# -----------------------------------------------\n# !!! THIS FILE WAS GENERATED BY TYPE-GRAPHQL !!!\n# !!! DO NOT MODIFY THIS FILE BY YOURSELF !!!\n# -----------------------------------------------\n\n\"\"\"Date custom scalar type\"\"\"\nscalar Date\n\ntype Mutation {\n create_user(user: UserInput!): User!\n create_pofficer(pofficer: POfficerCreateInput!): POfficer!\n create_incident(incident: TIncidentInput!): TIncident!\n add_incident_type(incident_type: TIncidentTypeInput!): TIncidentType!\n}\n\ntype POfficer {\n _id: ID!\n userid: ID!\n user: User!\n}\n\ninput POfficerCreateInput {\n name: String!\n surname: String!\n phone: String!\n}\n\ntype Query {\n users: [User!]!\n pofficers: [POfficer!]!\n incidents: [TIncident!]!\n incident_types: [TIncidentType!]!\n}\n\ntype TIncident {\n _id: ID!\n createdAt: Date!\n incidenttype_id: ID!\n pofficer_id: ID!\n toffender_id: ID\n toffender_phone: String!\n carnumber: String!\n incident_status: String!\n pofficer: POfficer!\n toffender: User!\n incident_type: TIncidentType!\n}\n\ninput TIncidentInput {\n incidenttype_id: ID!\n pofficer_id: ID!\n toffender_phone: String!\n carnumber: String!\n}\n\ntype TIncidentType {\n _id: ID!\n name: String!\n description: String\n}\n\ninput TIncidentTypeInput {\n name: String!\n description: String\n}\n\ntype User {\n _id: ID!\n name: String!\n surname: String!\n email: String\n phone: String!\n}\n\ninput UserInput {\n name: String!\n surname: String!\n email: String!\n phone: String!\n}\n```\n\n========================================\n\nTop Answer:\nIn my case I refactored all my queries into a single file in a new folder: `lib/queries.tsx`.\n\nWhat I needed to do then is add that filepath to `codegen.yml`:\n\n```\ndocuments:\n - \"./lib/queries.tsx\"\n```\n\n========================================\n\nCode:\n```text\noverwrite: true\nschema: \"http://localhost:3001/graphql\"\ndocuments: \"src/**/*.graphql\"\ngenerates:\n src/generated/graphql.tsx:\n plugins:\n - \"typescript\"\n - \"typescript-operations\"\n - \"typescript-react-apollo\"\n ./graphql.schema.json:\n plugins:\n - \"introspection\"\n```\n\n```text\n\"schema\": \"graphql-codegen --config codegen.yml\"\n```\n\n```text\n# -----------------------------------------------\n# !!! THIS FILE WAS GENERATED BY TYPE-GRAPHQL !!!\n# !!! DO NOT MODIFY THIS FILE BY YOURSELF !!!\n# -----------------------------------------------\n\n\"\"\"Date custom scalar type\"\"\"\nscalar Date\n\ntype Mutation {\n create_user(user: UserInput!): User!\n create_pofficer(pofficer: POfficerCreateInput!): POfficer!\n create_incident(incident: TIncidentInput!): TIncident!\n add_incident_type(incident_type: TIncidentTypeInput!): TIncidentType!\n}\n\ntype POfficer {\n _id: ID!\n userid: ID!\n user: User!\n}\n\ninput POfficerCreateInput {\n name: String!\n surname: String!\n phone: String!\n}\n\ntype Query {\n users: [User!]!\n pofficers: [POfficer!]!\n incidents: [TIncident!]!\n incident_types: [TIncidentType!]!\n}\n\ntype TIncident {\n _id: ID!\n createdAt: Date!\n incidenttype_id: ID!\n pofficer_id: ID!\n toffender_id: ID\n toffender_phone: String!\n carnumber: String!\n incident_status: String!\n pofficer: POfficer!\n toffender: User!\n incident_type: TIncidentType!\n}\n\ninput TIncidentInput {\n incidenttype_id: ID!\n pofficer_id: ID!\n toffender_phone: String!\n carnumber: String!\n}\n\ntype TIncidentType {\n _id: ID!\n name: String!\n description: String\n}\n\ninput TIncidentTypeInput {\n name: String!\n description: String\n}\n\ntype User {\n _id: ID!\n name: String!\n surname: String!\n email: String\n phone: String!\n}\n\ninput UserInput {\n name: String!\n surname: String!\n email: String!\n phone: String!\n}\n```\n\n```text\n@graphql-codegen/cli\n```\n\n```text\ncodegen.yml\n```\n\n```text\npackage.json\n```\n\n```text\nyarn schema\n```\n\n```text\nyarn codegen init\n```\n\n```text\nyarn schema\n```\n\n```text\nhttp://localhost:3001/graphql\n```\n\n```text\nquery GetUsers {\n user {\n _id\n __typename\n name\n surname\n email\n phone\n }\n}\n```\n\n```text\nget-users.query.graphql\n```\n\n```text\nsrc\n```\n\n```text\n.graphql\n```\n\n```text\nsrc\n```\n\n```text\n.graphql\n```\n\n```text\ndocuments:\n - \"./lib/queries.tsx\"\n```\n\n```text\nlib/queries.tsx\n```\n\n```text\ncodegen.yml\n```\n\n```text\ndocuments: \"src/**/*.graphql\"\n```\n\n```text\n/home/my project folder with spaces/node_modules/*\n```\n\n```text\ndocuments\n```\n\n```text\ngraphql-code\n```\n\n```text\nsrc/**/*.graphql\n```\n\n```text\nsrc\n```\n\n```text\ncreate-next-app\n```\n\n```text\nsrc\n```\n\n```text\n.graphql\n```\n\n```text\n.graphql\n```\n\n```text\nconst config: CodegenConfig = {\n schema: 'http://localhost:4000/graphql',\n\n documents: ['./src/graphql/queries.gql', './src/graphql/mutations.gql'],\n\n generates: {\n './src/graphql/generated/': {\n preset: 'client',\n },\n```\n\n========================================\n\nComments:\n- Did you create any `.graphql` files with a query or a mutation? Could you post them here?\n- @Felipe I have edited my question and I have added the `.graphql` file hosted and exposed by my server at `http://localhost:3001/graphql`\n- Thanks @Felipe. I have marked your suggestion as the solution to my issue\n- Why do I have to manually create these queries and mutations? Could the generator not automatically pick them up for me?\n- Yes, these are the queries and mutations that you are going to execute on your server. The definitions for the available queries and mutations provided by your server are automatically generated by the codegen.\n- @Felipe can you explain that further? Why do the queries nee to be declared in a dedicated file? The generator could not create the queries by using the introspection feature?\n- @Stefan 1) They don't have to be in a dedicated file. They can all be in one file. 2) Introspection just sucks as right now because of TS limits. See type-graphql for example. 3) Generating types from schema is much cleaner then the other way around, less error prone, less work overall. I tried literally all TS frameworks for graphql and this method is my all time favourite.\n- @MikeS. Link to new question?","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":378,"estimatedTokens":1763}}230{"id":"stack-62384215","source":"stackoverflow","questionId":62384215,"title":"More ways to construct a GraphQL query string in Python","tags":["python","graphql","graphene-python"],"text":"Title: More ways to construct a GraphQL query string in Python\nTags: python, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI'm trying to do this (see title), but it's a bit complicated since the string I'm trying to build has to have the following properties:\n\n- mulitiline\n\n- contains curly braces\n\n- I want to inject variables into it\n\nUsing a normal `''''''` multiline string makes injecting variables difficult. Using multiple f-strings makes injecting variables easy, but every curly brace, of which there are a lot, has to be doubled. And an `f` has to be prepended to each line. On the other hand, if I try using `format`, it also gets confused by all the curly braces.\n\nAre there even more ways that I haven't considered yet? Which?\n\n========================================\n\nTop Answer:\nyou can use the following package graphql-query\n\nFor example, for the query\n\n```\n{\n leftComparison: hero(episode: EMPIRE) {\n ...comparisonFields\n }\n rightComparison: hero(episode: JEDI) {\n ...comparisonFields\n }\n}\n\nfragment comparisonFields on Character {\n name\n appearsIn\n friends {\n name\n }\n}\n```\n\nwe have the following code\n\n```\nfrom graphql_query import Argument, Operation, Query, Fragment, Field\n\ncomparisonFields = Fragment(\n name=\"comparisonFields\",\n type=\"Character\",\n fields=[\"name\", \"appearsIn\", Field(name=\"friends\", fields=[\"name\"])]\n)\n\nleftComparison = Query(\n name=\"hero\",\n alias=\"leftComparison\",\n arguments=[Argument(name=\"episode\", value=\"EMPIRE\")],\n fields=[comparisonFields]\n)\n\nrightComparison = Query(\n name=\"hero\",\n alias=\"rightComparison\",\n arguments=[Argument(name=\"episode\", value=\"JEDI\")],\n fields=[comparisonFields]\n)\n\noperation = Operation(\n type=\"query\",\n queries=[leftComparison, rightComparison],\n fragments=[comparisonFields]\n)\nprint(operation.render())\n# query {\n# leftComparison: hero(\n# episode: EMPIRE\n# ) {\n# ...comparisonFields\n# }\n#\n# rightComparison: hero(\n# episode: JEDI\n# ) {\n# ...comparisonFields\n# }\n# }\n#\n# fragment comparisonFields on Character {\n# name\n# appearsIn\n# friends {\n# name\n# }\n# }\n```\n\n========================================\n\nCode:\n```text\n''''''\n```\n\n```text\nf\n```\n\n```text\nformat\n```\n\n```text\nquery = \"\"\"\n mutation ($input:[ContactInput!]!) {\n AddContacts(contacts: $input) {\n user_id\n }\n }\n\"\"\"\nvariables = {'input': my_arrofcontacts}\nr = requests.post(url, json={'query': query , 'variables': variables})\n```\n\n```text\nContactInput\n```\n\n```text\nquery variables\n```\n\n```graphql\n{\n leftComparison: hero(episode: EMPIRE) {\n ...comparisonFields\n }\n rightComparison: hero(episode: JEDI) {\n ...comparisonFields\n }\n}\n\nfragment comparisonFields on Character {\n name\n appearsIn\n friends {\n name\n }\n}\n```\n\n```py\nfrom graphql_query import Argument, Operation, Query, Fragment, Field\n\ncomparisonFields = Fragment(\n name=\"comparisonFields\",\n type=\"Character\",\n fields=[\"name\", \"appearsIn\", Field(name=\"friends\", fields=[\"name\"])]\n)\n\nleftComparison = Query(\n name=\"hero\",\n alias=\"leftComparison\",\n arguments=[Argument(name=\"episode\", value=\"EMPIRE\")],\n fields=[comparisonFields]\n)\n\nrightComparison = Query(\n name=\"hero\",\n alias=\"rightComparison\",\n arguments=[Argument(name=\"episode\", value=\"JEDI\")],\n fields=[comparisonFields]\n)\n\noperation = Operation(\n type=\"query\",\n queries=[leftComparison, rightComparison],\n fragments=[comparisonFields]\n)\nprint(operation.render())\n# query {\n# leftComparison: hero(\n# episode: EMPIRE\n# ) {\n# ...comparisonFields\n# }\n#\n# rightComparison: hero(\n# episode: JEDI\n# ) {\n# ...comparisonFields\n# }\n# }\n#\n# fragment comparisonFields on Character {\n# name\n# appearsIn\n# friends {\n# name\n# }\n# }\n```\n\n```py\n\"\"\"\n{\n 'ultimate': 'The %(foo)s is %(bar)s'\n}\n\"\"\" % {'foo':'answer', 'bar':42}\n```\n\n========================================\n\nComments:\n- Maybe template strings, or a full blown template library? Or write yourself a library to construct your graphql in a functional way, and hide the details.\n- I only found this lib pypi.org/project/gql-query-builder\n- 30 upvotes and closed as opinion-based. Stackoverflow has become so irrelevant :D\n- How can syntax highlighting be applied to this multiline string?\n- It does not work In my case, (**python 3.8**). This link is the solution by @chris-lindseth. With string format like as, Just use multiline string (\"\"\") with **f** prefix and for variable use '{*variable*}'. for brace ('*{*', '*}*') use double for that like as ('*{{*', '*}}*')\n- It would be extremely helpful for less experienced programmers to provide a working example of the best practices mentioned in your 'answer' instead of just sharing a single link (which not necessarily people will understand), and saying what NOT to do, and what to learn.\n- @lowercase00 Not working with python ... you have a working example in accepted answer ... this answer extends this, explains general graphql rules, why question (requirements), in general, is misleading ... passing variables is not 'best practice', it's a basic graphql knowledge ... look for more tutorials if still not understood or ask own, specific problem question, not about 'best practice' as asking for PERSONAL OPINIONS are off-topic on SO\n- Full documentation can be found at this link denisart.github.io/graphql-query\n- Please mention your affiliation with the project.\n- I think the OP mentioned that","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":224,"estimatedTokens":1345}}231{"id":"stack-51999721","source":"stackoverflow","questionId":51999721,"title":"AWS GraphQL: Variable 'input' has coerced Null value for NonNull type 'Input!'","tags":["reactjs","graphql","aws-appsync","aws-amplify"],"text":"Title: AWS GraphQL: Variable 'input' has coerced Null value for NonNull type 'Input!'\nTags: reactjs, graphql, aws-appsync, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI'm using ReactJS and `aws-amplify` to execute graphql operations.\n\n**CODE:**\n\n```\nimport {\n API,\n graphqlOperation\n} from 'aws-amplify';\n\nimport { UpdateInput } from './mutations.js';\n\n// Call mutation\nconst input = { /* some values */ };\nAPI.graphql(graphqlOperation(UpdateInput, input)).then(...);\n```\n\nGraphQL mutation definition:\n\n```\nexport const UpdateInput = `mutation UpdateInput($input: Input!) {\n updateInput(input: $input) {\n id, \n name\n } \n}`\n```\n\nGraphQL Schema:\n\n```\ninput Input {\n id: ID!\n name: String\n}\n\ntype Mutation {\n updateInput(input: Input!): String\n}\n```\n\nHowever, I get an error:\n\n [Log] Variable 'input' has coerced Null value for NonNull type\n 'Input!'\n\nUsing AWS console my mutation works and `input` is NonNull (using a debugger)\n\nAny ideas what's causing the error?\n\n========================================\n\nCode:\n```text\nimport {\n API,\n graphqlOperation\n} from 'aws-amplify';\n\nimport { UpdateInput } from './mutations.js';\n\n// Call mutation\nconst input = { /* some values */ };\nAPI.graphql(graphqlOperation(UpdateInput, input)).then(...);\n```\n\n```text\nexport const UpdateInput = `mutation UpdateInput($input: Input!) {\n updateInput(input: $input) {\n id, \n name\n } \n}`\n```\n\n```text\ninput Input {\n id: ID!\n name: String\n}\n\ntype Mutation {\n updateInput(input: Input!): String\n}\n```\n\n```text\naws-amplify\n```\n\n```text\ninput\n```\n\n```text\nupdateInput(input: Input!): String\n // ^^^^^ input key\n```\n\n```text\nconst variables = {\n input: someData, // key is \"input\" based on the mutation above\n};\n\nAPI.graphql(graphqlOperation(UpdateInput, variables)).then(...);\n```\n\n```text\ninput\n```\n\n```text\nupdateInput\n```\n\n========================================\n\nComments:\n- Thanks! This solution helped me figure out that I don't pass 'input' to a query, and instead I just pass 'id'.","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":124,"estimatedTokens":501}}232{"id":"stack-49990427","source":"stackoverflow","questionId":49990427,"title":"GraphQL : the object name is defined in resolvers, but not in schema","tags":["graphql","apollo"],"text":"Title: GraphQL : the object name is defined in resolvers, but not in schema\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI want to define a mutation using graphql.\n\nMy mutation is getting an object as argument. So I defined the new Object in the schema and in the resolver using GraphQLObjectType. \n\nHowever I m getting this error : \n\n Error: Agreement.name defined in resolvers, but not in schema\n\nAny idea ?\n\nHere is my Schema definition\n\n```\nconst typeDefs = `\n\n type Agreement {\n id: Int\n }\n\n type Mutation {\n agreementsPost(agreement: Agreement) : String\n }\n`;\n```\n\nAnd Here is my resolver : \n\n```\nconst appResolvers = {\n\n Agreement: new GraphQLObjectType({\n name: 'Agreement',\n fields: {\n id: { type: GraphQLInt },\n }\n }),\nMutation: {\n\n agreementsPost(root, args) {\n return axios.post(\"....\").then(res => res.data);\n },\n }\n```\n\n========================================\n\nTop Answer:\nExtra data (Related to the error - not to the Q code).\n\n### hello-world\n\n We define our resolvers in a **map**, where the map's\n keys **correspond** to our schema's types.\n https://www.apollographql.com/docs/tutorial/resolvers/\n\nThe most basic **\"hello world\"** example of this **\"wrong map\" error**.\n\nI was wrong on **purpose** (under resolver definitions - use `hello2` instead of `hello`).\n\ngraphql-yoga server example:\n\n```\n/*index.js*/\nconst { GraphQLServer } = require('graphql-yoga')\n\nconst typeDefs = `\n type Query {\n hello(name: String): String!\n }\n`\n\nconst resolvers = {\n Query: {\n hello2: (_, { name }) => `Hello ${name || 'World'}`,\n },\n}\n\nconst server = new GraphQLServer({ typeDefs, resolvers })\nserver.start(() => console.log('Server is running on localhost:4000'))\n```\n\n**Throw error:**\n\n [Error: Query.hello2 defined in resolvers, but not in schema]\n\nChange the **resolver** to `hello` (match to `hello` schema type) to fix this error:\n\nhttps://i.sstatic.net/EtX8x.png\n\n**Related:** \n\n- **schema docs:** https://graphql.org/learn/schema/\n\n- **Great tuturial:** https://www.apollographql.com/docs/tutorial/introduction/\n\n========================================\n\nCode:\n```text\nconst typeDefs = `\n\n type Agreement {\n id: Int\n }\n\n type Mutation {\n agreementsPost(agreement: Agreement) : String\n }\n`;\n```\n\n```text\nconst appResolvers = {\n\n Agreement: new GraphQLObjectType({\n name: 'Agreement',\n fields: {\n id: { type: GraphQLInt },\n }\n }),\nMutation: {\n\n agreementsPost(root, args) {\n return axios.post(\"....\").then(res => res.data);\n },\n }\n```\n\n```text\ntype Mutation {\n agreementsPost(agreement: Agreement): String\n}\n\ninput Agreement {\n id: Int\n}\n```\n\n```text\ntype Mutation {\n agreementsPost(agreement: AgreementInput): String\n}\n\ntype Agreement {\n id: Int\n}\n\ninput AgreementInput {\n id: Int\n}\n```\n\n```text\nconst resolvers = {\n Foo: {\n someFooProperty: (foo, args, context, info) => {}\n },\n Bar: {\n someBarProperty: (bar, args, context, info) => {}\n someOtherBarProperty: (bar, args, context, info) => {}\n },\n Query: {\n someQuery: (root, args, context, info) => {}\n },\n Mutation: {\n someMutation: (root, args, context, info) => {}\n },\n}\n```\n\n```text\ninput\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\ntype\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nAgreement\n```\n\n```text\nInput\n```\n\n```text\nAgreementInput\n```\n\n```text\nAgreement\n```\n\n```text\nAgreementInput\n```\n\n```text\ngraphql\n```\n\n```text\nGraphQLSchema\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nFoo\n```\n\n```text\nBar\n```\n\n```text\nresolvers\n```\n\n```text\nresolvers\n```\n\n```text\nresolve\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nname\n```\n\n```text\nfields\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\n// GraphQL: Schema\nconst SERVER = new ApolloServer({\n typeDefs: typeDefs,\n resolvers: resolvers,\n introspection: true,\n uploads: false,\n playground: {\n endpoint: `http://localhost:3000/graphql`,\n settings: {\n 'editor.theme': 'light'\n }\n }\n});\n```\n\n```text\nuploads: false\n```\n\n```text\nUploads\n```\n\n```text\n/*index.js*/\nconst { GraphQLServer } = require('graphql-yoga')\n\nconst typeDefs = `\n type Query {\n hello(name: String): String!\n }\n`\n\nconst resolvers = {\n Query: {\n hello2: (_, { name }) => `Hello ${name || 'World'}`,\n },\n}\n\nconst server = new GraphQLServer({ typeDefs, resolvers })\nserver.start(() => console.log('Server is running on localhost:4000'))\n```\n\n```text\nhello2\n```\n\n```text\nhello\n```\n\n```text\nhello\n```\n\n```text\nhello\n```\n\n========================================\n\nComments:\n- Excellent! it works, thank you so much for your perfect response","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":323,"estimatedTokens":1146}}233{"id":"stack-46280014","source":"stackoverflow","questionId":46280014,"title":"Is GraphQL an ORM?","tags":["orm","graphql"],"text":"Title: Is GraphQL an ORM?\nTags: orm, graphql\nSource: Stack Overflow\n\nQuestion:\nIs GraphQL an ORM? It seems like it is. At the end of the day it needs to query the database for information. You need to give it a schema (just like an ORM). From my understanding, on the front end you pass it the specifics that you want and GraphQL on the back end will give you *just* the info you requested.\n\nThe only difference I see from traditional ORMs, such as Sequelize or ActiveRecord, is that GraphQL will give you only what you want, making it very attractive and flexible. I suspect though that whatever's going on under the hood may leave you with some inefficient queries (common to ORMs). So is GraphQL simply an ORM that gives you 100% flexibility in what you ask for and receive?\n\n========================================\n\nTop Answer:\nNo it's not. With only GraphQL, we can't access the database easily, because the language needed to send query isn't mapped by an ORM.\n\nORM makes it easy to access a database, which is in a sense is more like creating a virtual database which our programming language can easily access. Then GraphQL send its query into that virtual database.\n\n========================================\n\nComments:\n- ORM's can work without a DataBase. ORM's query the objects in memory. \"Understanding the concept of a DB\" doesn't describe an ORM. ORMs also gets data from a datasource which could be static, a file etc. ;)\n- Fair enough, but the question referred to databases.\n- To understand if something is an ORM is to understand that it works with objects. Object Mapping is not synonymous with a Database. The flow is: Retrieve data from source (DB, File, API...), populate objects, collect subset from objects based on Graph Query by iterating through objects, return result. The question is \"Is GraphQL is an ORM\" and the answer is \"Yes\". An ORM is not a DB query tool. It can merely populate objects ALSO from a DB.","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":22,"estimatedTokens":485}}234{"id":"stack-59729656","source":"stackoverflow","questionId":59729656,"title":"HTTP status code handling in GraphQL APIs","tags":["graphql","http-status-codes"],"text":"Title: HTTP status code handling in GraphQL APIs\nTags: graphql, http-status-codes\nSource: Stack Overflow\n\nQuestion:\nA lot of resources say, that GraphQL should always respond with a 200 status code, even when an error occurred:\n\n- https://www.graph.cool/docs/faq/api-eep0ugh1wa/#how-does-error-handling-work-with-graphcool\n\n- https://github.com/rmosolgo/graphql-ruby/issues/1130#issuecomment-347373937\n\n- https://blog.hasura.io/handling-graphql-hasura-errors-with-react/\n\nBecause GraphQL can return multiple responses in one response, this makes sense. When a user requests two resources in one request, and only has access to the first resource, you can send back the first resource and return a `forbidden` error for the second resource.\n\nHowever, this is just something I figured out along the way reading docs of multiple GraphQL libraries and blog posts. **I didn't find anything about HTTP status codes in the offical specs, here https://spec.graphql.org/ or here https://graphql.org/**\n\n### So I still have a few questions left:\n\n- Is it ok to return a HTTP 500 status code if I have an unexpected server error?\n\n- Is it ok to return a HTTP 401 status code, if credentials are wrong?\n\n- Should I include the *potential* HTTP status code inside the `errors` key of the GraphQL response like this\n\n```\n{\n \"errors\" => [{\n \"message\" => \"Graphql::Forbidden\",\n \"locations\" => [],\n \"extensions\" => {\n \"error_class\" => \"Graphql::Forbidden\", \"status\" => 403\n }\n }]\n}\n```\n\n- Should I match common errors like a wrong field name to the HTTP status code `400 Bad Request`?\n\n```\n{\n \"errors\" => [{\n \"message\" => \"Field 'foobar' doesn't exist on type 'UserConnection'\",\n \"locations\" => [{\n \"line\" => 1,\n \"column\" => 11\n }],\n \"path\" => [\"query\", \"users\", \"foobar\"],\n \"extensions\" => {\n \"status\" => 400, \"code\" => \"undefinedField\", \"typeName\" => \"UserConnection\", \"fieldName\" => \"foobar\"\n }\n }]\n}\n```\n\nI'd be great if you could your experiences / resources / best practises when handling HTTP status codes in GraphQL.\n\n========================================\n\nCode:\n```text\n{\n \"errors\" => [{\n \"message\" => \"Graphql::Forbidden\",\n \"locations\" => [],\n \"extensions\" => {\n \"error_class\" => \"Graphql::Forbidden\", \"status\" => 403\n }\n }]\n}\n```\n\n```text\n{\n \"errors\" => [{\n \"message\" => \"Field 'foobar' doesn't exist on type 'UserConnection'\",\n \"locations\" => [{\n \"line\" => 1,\n \"column\" => 11\n }],\n \"path\" => [\"query\", \"users\", \"foobar\"],\n \"extensions\" => {\n \"status\" => 400, \"code\" => \"undefinedField\", \"typeName\" => \"UserConnection\", \"fieldName\" => \"foobar\"\n }\n }]\n}\n```\n\n```text\nforbidden\n```\n\n```text\nerrors\n```\n\n```text\n400 Bad Request\n```\n\n```text\ntype Mutation {\n login(username: String!, password: String!): LoginPayload!\n}\n\ntype LoginPayload {\n user: User\n error: Error\n}\n```\n\n```text\ntype Mutation {\n login(username: String!, password: String!): LoginPayload!\n}\n\nunion LoginPayload = User | InvalidCredentialsError | ExceededLoginAttemptsError\n```\n\n```text\nGENERIC_SERVER\n```\n\n```text\nINVALID_INPUT\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- Thanks for the detailed explanation! I think I'm gonna cut the line between the controller and GraphQL: Authentication happens BEFORE any GraphQL relevant code is execute, so I serve the appropriate HTTP Status Codes like `401 unauthorized`. Everything later gets a 200 response, except for severe server errors `500`. Let's see if this pays of\n- FYI: Apparently there is now an HTTP-transport specific proposal for how to handle status codes (among other things): github.com/graphql/graphql-over-http This is not yet officially part of the spec, but there seems to be movement.\n- \"This is the current thinking\". Three years have passed. What is the sentiment about this topic in the GraphQL community, today?","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":137,"estimatedTokens":959}}235{"id":"stack-53863934","source":"stackoverflow","questionId":53863934,"title":"Is graphql schema circular reference an anti-pattern?","tags":["graphql","apollo"],"text":"Title: Is graphql schema circular reference an anti-pattern?\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\ngraphql schema like this:\n\n```\ntype User {\n id: ID!\n location: Location\n}\n\ntype Location {\n id: ID!\n user: User\n}\n```\n\nNow, the client sends a `graphql` query. Theoretically, the `User` and `Location` can circular reference each other infinitely.\n\nI think it's an anti-pattern. For my known, there is no middleware or way to limit the nesting depth of query both in `graphql` and `apollo` community.\n\nThis infinite nesting depth query will cost a lot of resources for my system, like bandwidth, hardware, performance. Not only server-side, but also client-side.\n\nSo, if graphql schema allow circular reference, there should be some middlewares or ways to limit the nesting depth of query. Or, add some constraints for the query.\n\nMaybe do not allow circular reference is a better idea?\n\nI prefer to sending another query and doing multiple operations in one query. It's much more simple.\n\n**Update**\n\nI found this library: https://github.com/slicknode/graphql-query-complexity. If graphql doesn't limit circular reference. This library can protect your application against resource exhaustion and DoS attacks.\n\n========================================\n\nTop Answer:\n**TLDR;** Circular references are an anti-pattern for non-rate-limited GraphQL APIs. APIs with rate limiting can safely use them.\n\n**Long Answer:** Yes, true circular references are an anti-pattern on smaller/simpler APIs ... but when you get to the point of rate-limiting your API you can use that limiting to \"kill two birds with one stone\".\n\nA perfect example of this was given in one of the other answers: Github's GraphQL API let's you request a repository, with its owner, with their repositories, with their owners ... infinitely ... or so you might think from the schema.\n\nIf you look at the API though (https://developer.github.com/v4/object/user/) you'll see their structure isn't directly circular: there are types in-between. For instance, `User` doesn't reference `Repository`, it references `RepositoryConnection`. Now, `RepositoryConnection` *does* have a `RepositoryEdge`, which *does* have a `nodes` property of type `[Repository]` ... \n\n... but when you look at the *implementation* of the API: https://developer.github.com/v4/guides/resource-limitations/ you'll see that the resolvers behind the types are rate-limited (ie. no more than X nodes per query). This guards both against consumers who request too much (breadth-based issues) *and* consumers who request infinitely (depth-based issues).\n\nWhenever a user requests a resource on GitHub it can allow circular references because it puts the burden on not letting them be circular onto the consumer. If the consumer fails, the query fails because of the rate-limiting.\n\nThis lets responsible users ask for the user, of the repository, owned by the same user ... if they really need that ... as long as they don't keep asking for the repositories owned by the owner of that repository, owned by ...\n\nThus, GraphQL APIs have two options:\n\n- avoid circular references (I think this is the default \"best practice\")\n\n- allow circular references, but limit the total nodes that can be queried per call, so that **infinite** circles aren't possible\n\nIf you don't want to rate-limit, GraphQL's approach of using different types can still give you a clue to a solution.\n\nLet's say you have users and repositories: you need two types for both, a User and UserLink (or UserEdge, UserConnection, UserSummary ... take your pick), and a Repository and RepositoryLink.\n\nWhenever someone requests a user via a root query, you return the User type. But that User type would *not* have:\n\n```\nrepositories: [Repository]\n```\n\nit would have:\n\n```\nrepositories: [RepositoryLink]\n```\n\n`RepositoryLink` would have the same \"flat\" fields as Repository has, but none of its potentically circular object fields. Instead of `owner: User`, it would have `owner: ID`.\n\n========================================\n\nCode:\n```js\ntype User {\n id: ID!\n location: Location\n}\n\ntype Location {\n id: ID!\n user: User\n}\n```\n\n```text\ngraphql\n```\n\n```text\nUser\n```\n\n```text\nLocation\n```\n\n```text\ngraphql\n```\n\n```text\napollo\n```\n\n```text\ntype Query {\n user(id: ID): User\n location(id: ID): Location\n}\n\ntype User {\n id: ID!\n location: Location\n}\n\ntype Location {\n id: ID!\n user: User\n}\n```\n\n```text\n{\n # query 1\n user(id: ID) {\n id\n location {\n id\n }\n }\n\n # query 2\n location(id: ID) {\n id\n user {\n id\n }\n }\n}\n```\n\n```text\nuser\n```\n\n```text\nuser\n```\n\n```text\nLocation\n```\n\n```text\nlocation\n```\n\n```text\nuser\n```\n\n```text\ndataloader\n```\n\n```text\ndataloader\n```\n\n```text\nrepositories\n```\n\n```text\nrepositories: [Repository]\n```\n\n```text\nrepositories: [RepositoryLink]\n```\n\n```text\nUser\n```\n\n```text\nRepository\n```\n\n```text\nRepositoryConnection\n```\n\n```text\nRepositoryConnection\n```\n\n```text\nRepositoryEdge\n```\n\n```text\nnodes\n```\n\n```text\n[Repository]\n```\n\n```text\nRepositoryLink\n```\n\n```text\nowner: User\n```\n\n```text\nowner: ID\n```\n\n========================================\n\nComments:\n- `dataloader` is for `N+1` query issue. I think it's another question. Personally, I don't like circular reference.\n- As far as the node ecosystem, there's `graphql-depth-limit` :) It provides a validation rule you can drop right in your schema that prevents fetching past a specified query depth\n- Client-side caching of graphql objects is inherently difficult for everything beyond the root element of a query regardless of circular references.","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":234,"estimatedTokens":1396}}236{"id":"stack-51840201","source":"stackoverflow","questionId":51840201,"title":"Apollo: You are calling concat on a terminating link, which will have no effect","tags":["graphql","apollo"],"text":"Title: Apollo: You are calling concat on a terminating link, which will have no effect\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI am working in Apollo, GraphQL and Nuxtjs project, when setting up Apollo configuration I got this Warning:\n\n```\nlink.js:38 Error: You are calling concat on a terminating link, which will have no effect\nat new LinkError (linkUtils.js:41)\nat concat (link.js:38)\nat ApolloLink.webpackJsonp../node_modules/apollo-link/lib/link.js.ApolloLink.concat (link.js:65)\nat link.js:13\nat Array.reduce ()\nat from (link.js:13)\nat createApolloClient (index.js:58)\nat webpackJsonp../.nuxt/apollo-module.js.__webpack_exports__.a (apollo-module.js:66)\nat _callee2$ (index.js:140)\nat tryCatch (runtime.js:62)\n```\n\nHere is my code:\n\n```\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { createHttpLink } from 'apollo-link-http';\nimport { ApolloLink } from 'apollo-link';\n\nexport default ({ store, env }) => {\n const httpLink = new createHttpLink({ uri: env.GRAPH_BASE_URL });\n\n // middleware\n const middlewareLink = new ApolloLink((operation, forward) => {\n const token = store.getters['user/GET_TOKEN'];\n\n if (token) {\n operation.setContext({\n headers: { authorization: `Bearer ${token}` }\n });\n }\n\n return forward(operation);\n });\n\n const link = middlewareLink.concat(httpLink);\n\n return {\n link,\n cache: new InMemoryCache()\n }\n};\n```\n\nI Searched on Google for any similar issue, I found this one https://github.com/Akryum/vue-cli-plugin-apollo/issues/47\nbut it did not help me.\nI tried to change:\n\n```\nconst link = middlewareLink.concat(httpLink);\n```\n\nto: \n\n```\nconst link = Apollo.from([middlewareLink, httpLink]);\n```\n\nbut it still gives me the same warning,\nany help please\n\n========================================\n\nTop Answer:\nIn my case, i solved the issue, changing the order in array, example: \n\nBefore:\n\n```\nconst links = [...middlewares, localLink, authLink, httpLink, errorLink]\n```\n\nAfter:\n\n```\nconst links = [...middlewares, localLink, authLink, errorLink, httpLink]\n```\n\n========================================\n\nCode:\n```text\nlink.js:38 Error: You are calling concat on a terminating link, which will have no effect\nat new LinkError (linkUtils.js:41)\nat concat (link.js:38)\nat ApolloLink.webpackJsonp../node_modules/apollo-link/lib/link.js.ApolloLink.concat (link.js:65)\nat link.js:13\nat Array.reduce (<anonymous>)\nat from (link.js:13)\nat createApolloClient (index.js:58)\nat webpackJsonp../.nuxt/apollo-module.js.__webpack_exports__.a (apollo-module.js:66)\nat _callee2$ (index.js:140)\nat tryCatch (runtime.js:62)\n```\n\n```js\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { createHttpLink } from 'apollo-link-http';\nimport { ApolloLink } from 'apollo-link';\n\nexport default ({ store, env }) => {\n const httpLink = new createHttpLink({ uri: env.GRAPH_BASE_URL });\n\n // middleware\n const middlewareLink = new ApolloLink((operation, forward) => {\n const token = store.getters['user/GET_TOKEN'];\n\n if (token) {\n operation.setContext({\n headers: { authorization: `Bearer ${token}` }\n });\n }\n\n return forward(operation);\n });\n\n const link = middlewareLink.concat(httpLink);\n\n return {\n link,\n cache: new InMemoryCache()\n }\n};\n```\n\n```text\nconst link = middlewareLink.concat(httpLink);\n```\n\n```text\nconst link = Apollo.from([middlewareLink, httpLink]);\n```\n\n```text\n...\nconst param = {\n link: ApolloLink.from([\n onError(...) =>...,\n authLink...,\n new HttpLink({\n uri: '/graphql',\n credentials: 'same-origin'\n })\n ]),\n cache: ...,\n connectToDevTools: ...\n}\n\nnew ApolloClient(param);\n```\n\n```text\nHttp Link\n```\n\n```text\napollo-client\n```\n\n```text\napollo-cache-inmemory\n```\n\n```text\napollo-link\n```\n\n```text\napollo-link-http\n```\n\n```text\napollo-link-context\n```\n\n```text\napollo-link-error\n```\n\n```text\nreturn {\n link,\n cache: new InMemoryCache()\n defaultHttpLink: false, // this should do the trick\n}\n```\n\n```text\nconst links = [...middlewares, localLink, authLink, httpLink, errorLink]\n```\n\n```text\nconst links = [...middlewares, localLink, authLink, errorLink, httpLink]\n```\n\n```js\nconst links = [errorLink, retryLink, uploadLink];\n```\n\n```js\nimport { createHttpLink, split } from '@apollo/client';\n\nconst finalLink = split(operation => operation.getContext().version === 1, httpLink, httpLink2);\n\nreturn new Map()\n .set('MUTATION_QUEUE', mutationQueueLink)\n .set('RETRY', retryLink)\n .set('AUTH', authLink)\n .set('GQL_CACHE', gqlCacheLink)\n .set('ERROR', errorLink)\n .set('HTTP', finalLink);\n```\n\n```text\nsplit\n```\n\n========================================\n\nComments:\n- take a look apollographql.com/docs/link/composition.html#additive and github.com/mrdulin/react-apollo-graphql/blob/master/client/s‌​rc/…\n- still facing this issue.\n- were you able to fix it? I'm still having the same issue\n- for me this order worked: ApolloLink.from([errorLink, middlewareLink, httpLink]);\n- Thanks, I solved the same way!, but I forget to put the answer, thank you for posting that.\n- What about the WebSocketLink? If you would want to have both http:// and ws:// links, which one would go last? Both http and ws are terminating links. Can't figure this one out.\n- Hi @aurinxki did you figure this out?\n- @phainix, I ended up replacing the httpLink with the wsLink. I found that both were terminating links in the documentation(apollographql.com/docs/react/api/link/apollo-l‌​ink-ws, apollographql.com/docs/react/api/link/apollo-link-http). When initializing the client, first had to chain errorlink and uploadLink errorLink.concat(uploadLink) into a const. Then link: from([ chainedLink, wsLink ]),\n- Thanks @aurinxki, I used the apollo-client split, and it worked quite well. It splits into ws or http based on the type, the split is then used as the last link, you can check it out here (apollographql.com/docs/react/data/subscriptions/…)\n- This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":239,"estimatedTokens":1557}}237{"id":"stack-45756493","source":"stackoverflow","questionId":45756493,"title":"Special characters in GraphQL schema","tags":["graphql","graphql-js"],"text":"Title: Special characters in GraphQL schema\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nIs there any way of enabling special characters in GraphQL schema (e.g., `/`, `:`, `@` in the field names)? \n\nAnd if there isn't (which I suspect is the case) do you have an idea what would be relatively easiest way to modify the node.js code (https://github.com/graphql/graphql-js) to achieve such functionality?\n\n========================================\n\nCode:\n```text\n/\n```\n\n```text\n:\n```\n\n```text\n@\n```\n\n========================================\n\nComments:\n- For those that down voted this without bothering to be helpful and educate, I hope you feel proud of yourself as you got to feel superior by showing that you know why this is not a good idea without even explaining why.\n- Thanks, @otissv. Yes - bad, bad stackoverflow-ers! ;)\n- @otissv Downvoting doesn't mean that at all, it can mean a variety of things, like poor research or unclear question. Their isn't enough downvoting on this site.\n- @MartinDawson Given the variety reasons for downvoting, downvoting without explation is pointless and unhelpful. A simple comment as \"downvoted - unclear question\" is far more constructive. Else it only indcates that something is wrong. And to downvote this question would mean you know the answer. A simple \"research graphql spec\" comment would point in the right direction. Maybe if there where more downvoting with explations you wouldn't feel there isn't enough downvoting on this site.\n- I see, thanks for your response! I'll surely need to reconsider my goals, but my basic intention is to support some form of namespace mechanism (loosely around the lines of medium.com/@oleg.ilyenko/…) and offer the possibility of generating responses containing special keys such us \"dc:title\" or \"@id\", potentially useful when applying GraphQL to linked data.\n- To namespace something like `authors/create` you would need to write your own parser. Not worth it and it won't be compatible with the rest of graphql. The way I do it is, prefix methods with the type name using camelcase, e.g `authorsCreate`. `@` sign is a special character and so is `:`. `/` is not allowed in the current spec so is a good candidate. But you could use `_` to separate which won't break current parsers\n- @szymon if this answers your question, please mark as answered.","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":34,"estimatedTokens":592}}238{"id":"stack-55269777","source":"stackoverflow","questionId":55269777,"title":"NestJS Get current user in GraphQL resolver authenticated with JWT","tags":["node.js","jwt","graphql","nestjs"],"text":"Title: NestJS Get current user in GraphQL resolver authenticated with JWT\nTags: node.js, jwt, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am currently implementing JWT authentication with Passport.js into a NestJS application. \n\nIn some of my GraphQL resolvers I need to access the currently authenticated user. I know that passport will attach the authenticated user to the request object (at least I hope that this is correct), but I do not know how to access the request object inside a resolver. \n\nI followed the issue https://github.com/nestjs/nest/issues/1326 and the mentioned link https://github.com/ForetagInc/fullstack-boilerplate/tree/master/apps/api/src/app/auth inside the issue. I saw some code that uses `@Res() res: Request` as a method parameter in the GraphQL resolver methods, but I always get `undefined` for `res`. \n\nThese are the current implementations I have:\n\n**GQLAuth**\n\n```\nimport { Injectable, ExecutionContext } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';\nimport { AuthenticationError } from 'apollo-server-core';\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n canActivate(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const { req } = ctx.getContext();\n console.log(req);\n\n return super.canActivate(new ExecutionContextHost([req]));\n }\n\n handleRequest(err: any, user: any) {\n if (err || !user) {\n throw err || new AuthenticationError('GqlAuthGuard');\n }\n return user;\n }\n}\n```\n\n**Resolver that needs to access the current user**\n\n```\nimport { UseGuards, Req } from '@nestjs/common';\nimport { Resolver, Query, Args, Mutation, Context } from '@nestjs/graphql';\nimport { Request } from 'express';\n\nimport { UserService } from './user.service';\nimport { User } from './models/user.entity';\nimport { GqlAuthGuard } from '../auth/guards/gql-auth.guard';\n\n@Resolver(of => User)\nexport class UserResolver {\n constructor(private userService: UserService) {}\n\n @Query(returns => User)\n @UseGuards(GqlAuthGuard)\n whoami(@Req() req: Request) {\n console.log(req);\n return this.userService.findByUsername('aw');\n }\n}\n```\n\n**JWT Strategy**\n\n```\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { JwtPayload } from './interfaces/jwt-payload.interface';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authService: AuthService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.SECRET,\n });\n }\n\n async validate(payload: JwtPayload) {\n const user = await this.authService.validateUser(payload);\n if (!user) {\n throw new UnauthorizedException();\n }\n return user;\n }\n}\n```\n\nAuthorization and creating JWT tokens works fine. GraphQL guard also works fine for methods that do not need to access the user. But for methods that need access to the currently authenticated user, I see no way of getting it. \n\nIs there a way to accomplish something like this ?\n\n========================================\n\nTop Answer:\nIn order to use an AuthGuard with GraphQL, extend the built-in AuthGuard class and override the `getRequest()` method.\nCreate a file called `gql.guard.ts` (Naming your wish)\n\n```\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req;\n }\n}\n```\n\nTo get the current authenticated user in your graphql resolver, you can define a `@CurrentUser()` decorator (create a file called `user.decorator.graphql.ts`)\n\n```\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\nexport const CurrentUser = createParamDecorator(\n (data: unknown, context: ExecutionContext) => {\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req.user;\n },\n);\n```\n\nTo use above decorator in your resolver, be sure to include it as a parameter of your query or mutation\n\n```\n@Query(returns => User)\n@UseGuards(GqlAuthGuard)\nwhoAmI(@CurrentUser() user: User) {\n return this.usersService.findById(user.id);\n}\n```\n\nRead More : https://docs.nestjs.com/security/authentication#graphql\n\n========================================\n\nCode:\n```text\nimport { Injectable, ExecutionContext } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';\nimport { AuthenticationError } from 'apollo-server-core';\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n canActivate(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const { req } = ctx.getContext();\n console.log(req);\n\n return super.canActivate(new ExecutionContextHost([req]));\n }\n\n handleRequest(err: any, user: any) {\n if (err || !user) {\n throw err || new AuthenticationError('GqlAuthGuard');\n }\n return user;\n }\n}\n```\n\n```text\nimport { UseGuards, Req } from '@nestjs/common';\nimport { Resolver, Query, Args, Mutation, Context } from '@nestjs/graphql';\nimport { Request } from 'express';\n\nimport { UserService } from './user.service';\nimport { User } from './models/user.entity';\nimport { GqlAuthGuard } from '../auth/guards/gql-auth.guard';\n\n@Resolver(of => User)\nexport class UserResolver {\n constructor(private userService: UserService) {}\n\n @Query(returns => User)\n @UseGuards(GqlAuthGuard)\n whoami(@Req() req: Request) {\n console.log(req);\n return this.userService.findByUsername('aw');\n }\n}\n```\n\n```text\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { AuthService } from './auth.service';\nimport { JwtPayload } from './interfaces/jwt-payload.interface';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authService: AuthService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.SECRET,\n });\n }\n\n async validate(payload: JwtPayload) {\n const user = await this.authService.validateUser(payload);\n if (!user) {\n throw new UnauthorizedException();\n }\n return user;\n }\n}\n```\n\n```text\n@Res() res: Request\n```\n\n```text\nundefined\n```\n\n```text\nres\n```\n\n```text\n// user.decorator.ts\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n (data, req) => req.user,\n);\n```\n\n```text\nimport { User as CurrentUser } from './user.decorator';\n\n @Query(returns => User)\n @UseGuards(GqlAuthGuard)\n whoami(@CurrentUser() user: User) {\n console.log(user);\n return this.userService.findByUsername(user.username);\n }\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\n\nexport const GetUser = createParamDecorator((data, context: ExecutionContext) => {\n const ctx = GqlExecutionContext.create(context).getContext();\nreturn ctx.user\n});\n```\n\n```text\nget-user.decorator.ts\n```\n\n```text\n// get-user.decorator.ts\n\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nimport { User } from '../../user/entity/user.entity';\n\nexport const GetAuthenticatedUser = createParamDecorator((data, ctx: ExecutionContext): User => {\n const req = ctx.switchToHttp().getRequest();\n return req.user;\n});\n```\n\n```text\n// auth.controller.ts\n\nimport { GetAuthenticatedUser } from './decarator/get-user.decorator';\n\n...\n\n@Controller('api/v1/auth')\nexport class AuthController {\n constructor(private authService: AuthService) {\n //\n }\n\n ...\n\n /**\n * Get the currently authenticated user.\n *\n * @param user\n */\n @Post('/user')\n @UseGuards(AuthGuard())\n async getAuthenticatedUser(@GetAuthenticatedUser() user: User) {\n console.log('user', user);\n }\n```\n\n```text\n// console.log output:\n\nuser User {\n id: 1,\n email: 'email@test.com',\n ...\n}\n```\n\n```text\nauth.controller\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\nexport const CurrentUser = createParamDecorator(\n (data, context: ExecutionContext) => {\n const ctx = GqlExecutionContext.create(context).getContext();\n return ctx.req.user;\n },\n);\n```\n\n```text\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req;\n }\n}\n```\n\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\nexport const CurrentUser = createParamDecorator(\n (data: unknown, context: ExecutionContext) => {\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req.user;\n },\n);\n```\n\n```text\n@Query(returns => User)\n@UseGuards(GqlAuthGuard)\nwhoAmI(@CurrentUser() user: User) {\n return this.usersService.findById(user.id);\n}\n```\n\n```text\ngetRequest()\n```\n\n```text\ngql.guard.ts\n```\n\n```text\n@CurrentUser()\n```\n\n```text\nuser.decorator.graphql.ts\n```\n\n```text\nexport const CurrentUser = createParamDecorator(\n (data, context: ExecutionContextHost) => {\n return GqlExecutionContext.create(context).getContext().req.user;\n },\n);\n```\n\n========================================\n\nComments:\n- Instead of implement your own `canActivate` method in your `GqlAuthGuard` you should create a `getRequest` method and return `GqlExecutionContext.create(context).getContext().req;`. This is a better approach in my opinion.\n- Would you a link to your GitHub repo? I'm new to Nest.js, I'm also using GraphQL and I'm stuck with the authentication implementation. Thanks!\n- This really needs to be part of the framework and in the default docs, something like this missing makes me think if people are actually using it, lol\n- Thank you! Also, as this is a working answer you should accept it even if it's your own. Thanks again, I searched for a solution for at least an hour before finding this and it worked perfectly.\n- In v7 of Nest createParamDecorator has change. Retrieving the user is done through the GraphQL context. See here: docs.nestjs.com/graphql/other-features#custom-decorators\n- Note that this will only work for REST services. When using GraphQL you will need to make use of the context associated with GraphQL `GqlExecutionContext.create(context).getContext()` and not `ctx.switchToHttp().getRequest()`\n- This worked for me on August, 2022","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":393,"estimatedTokens":2742}}239{"id":"stack-56964838","source":"stackoverflow","questionId":56964838,"title":"Trying call useQuery in function with react-apollo-hooks","tags":["javascript","reactjs","graphql","react-hooks","react-apollo"],"text":"Title: Trying call useQuery in function with react-apollo-hooks\nTags: javascript, reactjs, graphql, react-hooks, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI want to call useQuery whenever I need it,\n\nbut useQuery can not inside the function.\n\nMy trying code is:\n\n```\nexport const TestComponent = () => {\n...\n const { data, loading, error } = useQuery(gql(GET_USER_LIST), {\n variables: {\n data: {\n page: changePage,\n pageSize: 10,\n },\n },\n })\n ...\n ...\n const onSaveInformation = async () => {\n try {\n await updateInformation({...})\n // I want to call useQuery once again.\n } catch (e) {\n return e\n }\n}\n...\n```\n\nHow do I call useQuery multiple times?\n\nCan I call it whenever I want?\n\nI have looked for several sites, but I could not find a solutions.\n\n========================================\n\nTop Answer:\nFrom apollo docs\n\nWhen React mounts and renders a component that calls the useQuery hook, Apollo Client automatically executes the specified query. But what if you want to execute a query in response to a different event, such as a user clicking a button?\n\nThe useLazyQuery hook is perfect for executing queries in response to\nevents other than component rendering\n\nI suggest useLazyQuery. In simple terms, useQuery will run when your component get's rendered, you can use `skip` option to skip the initial run. And there are some ways to refetch/fetch more data whenever you want. Or you can stick with `useLazyQuery`\n\nE.g If you want to fetch data when only user clicks on a button or scrolls to the bottom, then you can use `useLazyQuery` hook.\n\n========================================\n\nCode:\n```text\nexport const TestComponent = () => {\n...\n const { data, loading, error } = useQuery(gql(GET_USER_LIST), {\n variables: {\n data: {\n page: changePage,\n pageSize: 10,\n },\n },\n })\n ...\n ...\n const onSaveInformation = async () => {\n try {\n await updateInformation({...})\n // I want to call useQuery once again.\n } catch (e) {\n return e\n }\n}\n...\n```\n\n```js\nconst GET_USER_LIST = gql`\n query GetUserList {\n users {\n id\n name\n }\n }\n`;\n\nconst UPDATE_USER = gql`\n mutation UpdateUser($id: ID!, $name: String!) {\n updateUser(id: $id, update: { name: $name }) {\n success\n user {\n id\n name\n }\n }\n }\n`;\n\nconst UserListComponen = (props) => {\n const { data, loading, error } = useQuery(GET_USER_LIST);\n const [updateUser] = useMutation(UPDATE_USER);\n\n const onSaveInformation = (id, name) => updateUser({ variables: { id, name });\n\n return (\n // ... use data.users and onSaveInformation in your JSX\n );\n}\n```\n\n```text\nuseQuery\n```\n\n```text\nreact-apollo\n```\n\n```text\nupdateInformation\n```\n\n```text\n__typename\n```\n\n```text\nid\n```\n\n```text\nskip\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nconst { loading, client, fetchMore } = useQuery(GET_USER_LIST);\nconst submit = async () => {\n // Perform save operation\n\n const userResp = await fetchMore({\n variables: {\n // Pass any args here\n },\n updateQuery(){\n\n }\n });\n console.log(userResp.data)\n };\n```\n\n```text\nconst [getUser, { loading, client, data }] = useLazyQuery(GET_USER_LIST);\nconst submit = async () => {\n const userResp = await getUser({\n variables: {\n // Pass your args here\n },\n updateQuery() {},\n });\n console.log({ userResp }); // undefined\n };\n```\n\n```text\nconst { loading, data, refetch } = useQuery(Query_Data)\n```\n\n```text\nrefetch()\n```\n\n```js\n// Create query\nconst query = `\n query GetUserList ($data: UserDataType){\n getUserList(data: $data){\n uid,\n first_name\n }\n }\n`;\n\n\n// Component\nexport const TestComponent (props) {\n\n const onSaveInformation = async () => {\n \n // I want to call useQuery once again. \n const getUsers = await fetchUserList();\n }\n \n\n // This is the reusable fetch function.\n const fetchUserList = async () => {\n\n // Update the URL to your Graphql Endpoint.\n return await fetch('http://localhost:8080/api/graphql?', {\n \n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n body: JSON.stringify({\n query,\n variables: { \n data: {\n page: changePage,\n pageSize: 10,\n },\n },\n })\n }).then(\n response => { return response.json(); } \n ).catch(\n error => console.log(error) // Handle the error response object\n );\n }\n\n return (\n <h1>Test Component</h1>\n );\n \n}\n```\n\n```js\nconst { refetch } = useQuery(GET_USER_LIST, {\n variables: {\n data: {\n page: changePage,\n pageSize: 10,\n },\n },\n }\n);\n\n\nconst onSaveInformation = async () => {\n try {\n await updateInformation({...});\n const res = await refetch({ variables: { ... }});\n console.log(res);\n } catch (e) {\n return e;\n }\n}\n```\n\n========================================\n\nComments:\n- In case somebody still didnt get a full picture, here is quite nice example. ultimatecourses.com/blog/…\n- Thank you for the description. I just do not get how this function could be rendered. The only way that a functional components being rendered are via its own state or props. But when I do console.log(props) it is empty but in the return it still re-render when the loading is false\n- This answer should have been the accepted answer according to the title of the post. Let me upvote it.\n- not true that it (useQuery) can't be stopped ....there is a 'skip' option\n- refetch() is not refresh or reload , refetch when parameter are same with before call load from cash not from server","metadata":{"transformedAt":"2026-08-18T18:32:36.040Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":273,"estimatedTokens":1455}}240{"id":"stack-44534644","source":"stackoverflow","questionId":44534644,"title":"How to flat query result?","tags":["graphql"],"text":"Title: How to flat query result?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nWith a sample make it easy understand, with https://developer.github.com/v4/explorer/ \n\nquery the viewer info:\n\n```\nquery {\n viewer {\n followers {\n totalCount\n }\n following {\n totalCount\n }\n }\n}\n```\n\nthe result is:\n\n```\n{\n \"data\": {\n \"viewer\": {\n \"followers\": {\n \"totalCount\": 131\n },\n \"following\": {\n \"totalCount\": 28\n }\n }\n }\n}\n```\n\nwhat I want is:\n\n```\n{\n \"data\": {\n \"viewer\": {\n \"followersCount\" 131,\n \"followingCount\": 28\n }\n }\n}\n```\n\nso does GraphQL support this ? and how to do it?\n\n========================================\n\nCode:\n```text\nquery {\n viewer {\n followers {\n totalCount\n }\n following {\n totalCount\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"viewer\": {\n \"followers\": {\n \"totalCount\": 131\n },\n \"following\": {\n \"totalCount\": 28\n }\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"viewer\": {\n \"followersCount\" 131,\n \"followingCount\": 28\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.041Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":95,"estimatedTokens":252}}241{"id":"stack-37635328","source":"stackoverflow","questionId":37635328,"title":"What is the meaning of viewer field in GraphQL?","tags":["graphql","relayjs"],"text":"Title: What is the meaning of viewer field in GraphQL?\nTags: graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nWhat is the purpose of root query field `viewer` in GraphQL?\n\nBased on this article, `viewer` could be used to accept a token parameter so we can see who is currently logged in.\n\nHow should I implement it?\n\n========================================\n\nTop Answer:\nThe idea behind the `viewer` field (design pattern) was to group the top-level query fields that are only relevant to the currently logged in user. For example:\n\n```\n# EXAMPLE 1\n\nquer {\n viewer {\n stories { ... } # the list of published stores as well as drafts (current user)\n }\n\n stories { ... } # the list of published stories (all users)\n}\n```\n\nThis currently logged user data was either merged into `viewer` field itself or nested under it:\n\n```\n# EXAMPLE 2\n\nquery {\n viewer {\n id\n email\n displayName\n stories { ... }\n }\n}\n\n# EXAMPLE 3\n\nquery {\n viewer {\n me { id email displayName }\n stories { ... }\n }\n}\n```\n\nAll three examples above can be simplified by removing the `viewer` field altogether and still have the exact same functionality (recommended):\n\n```\nquery {\n # The currently logged in user or NULL if not logged in\n me {\n id\n email\n displayName\n }\n\n # Published stories only (all users)\n stories {\n ...\n }\n\n # Published stories as well as drafts (the current user)\n stories(drafts: true) {\n ...\n }\n}\n```\n\nYou can find the complete example in GraphQL API and Relay Starter Kit which can be used either as a reference project or a seed/template for new developments. See `api/graphql.ts`.\n\n========================================\n\nCode:\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\nviewer: {\n type: GraphQLUser,\n resolve: () => getViewer(),\n},\n```\n\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\nuser\n```\n\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\nLoginMutation\n```\n\n```text\nauthToken\n```\n\n```text\nviewer\n```\n\n```text\nauthToken\n```\n\n```graphql\n# EXAMPLE 1\n\nquer {\n viewer {\n stories { ... } # the list of published stores as well as drafts (current user)\n }\n\n stories { ... } # the list of published stories (all users)\n}\n```\n\n```graphql\n# EXAMPLE 2\n\nquery {\n viewer {\n id\n email\n displayName\n stories { ... }\n }\n}\n\n# EXAMPLE 3\n\nquery {\n viewer {\n me { id email displayName }\n stories { ... }\n }\n}\n```\n\n```graphql\nquery {\n # The currently logged in user or NULL if not logged in\n me {\n id\n email\n displayName\n }\n\n # Published stories only (all users)\n stories {\n ...\n }\n\n # Published stories as well as drafts (the current user)\n stories(drafts: true) {\n ...\n }\n}\n```\n\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\napi/graphql.ts\n```\n\n========================================\n\nComments:\n- there is no need for viewer pattern anymore in Relay Modern\n- It's strange that I can't find any concrete example (with SQL or Mongo), just a lot of abstraction on this topic. Hope there is a real example, just want to see the implementation.\n- I don't recommend Viewer pattern anymore, it was a Relay Classic thing, you should use a me: UserType field instead check Relay Workshop for a better example github.com/sibelius/relay-workshop/blob/master/packages/serv‌​er/…\n- You can't name it whatever you want if you want to use the `@refetchable` directive on a viewer fragment. In that case the query type must define a field named `viewer` and the type must be `Viewer`. So it actually is Relay-specific although the concept is not exclusive to Relay.\n- Why do you (or who) recommend not having a viewer, but instead independent queries? (still learning)\n- Because it's simpler, cleaner; while introducing the \"viewer\" field sounds like trying to solve some hypothetical (non-existent) problem.\n- I don't agree with this recommendation. Authenticated user and any other regular user have very different concerns and different problems to solve, in particular with what fields should be visible. You shouldn't be able to query for the SSN of any user on the platform, but you should be able to query SSN of yourself logged in.\n- @Deal permissions for individual fields are enforced inside of entity GraphQL types (it has nothing to do with the \"viewer\" top-level field). Here is an example: github.com/kriasoft/nodejs-api-starter/blob/main/api/types/…\n- I still disagree @KonstantinTarkus. Your example is trivial and over time your definition of user becomes muddy. Say now you need to introduce the concept of 'team members', which are technically users, and you should be able to query for their email addresses if you are on the same team. Your resolver is going to balloon with numerous if statements trying to figure out if the user can view that. The real solution is a User interface, and objects that implement that interface: Viewer, TeamMember, and so on.\n- @KonstantinTarkus I recommend you give \"Production Ready GraphQL\" book a read: book.productionreadygraphql.com. Written by Marc-Andre. This is briefly mentioned in the book.\n- Again, your example above has nothing to do with the \"viewer\" field concept. If you want to introduce different user types, they will be pulled from a separate top-level field, such as \"users\" or \"members\". I see no contradictions. You can satisfy the exact same business requirements in a simpler way.\n- I think I agree with @KonstantinTarkus, to me viewer merely means, implicitly get the user id from my auth token (or wherever). i.e. `Query.viewer` vs `Query.user(id: 1)`, where a user with an admin role could go via `Query.user` to get any user but non-admins would only be allowed through `Query.viewer` to get themselves...\n- Disagree with this - the viewer pattern is incredibly useful.\n- Just curious how could you seperate the members to different meaning. Like `viewer/members` means **the members of current user**, and `members` means a member list. So without viewer, we should design like `members(relatedToMe: true)`? Is it right? I think all make sense with or without `viewer`, If you take out the job from viewer, you should pay to the query, It's a fair trade.\n- Another argument or not using the viewer pattern is they don't work for mutations because mutations cannot be nested (without breaking the serial execution model) so you need to adopt a different pattern for mutations. We're going with token replacement, e.g. `Mutation.createCart({ userId: \"user_123\" })` and `Mutation.createCart({ userId: \"$me\" })` as mentioned here github.com/graphql/graphql-js/issues/571#issuecomment-949872‌​953","metadata":{"transformedAt":"2026-08-18T18:32:36.041Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":232,"estimatedTokens":1657}}242{"id":"stack-57499553","source":"stackoverflow","questionId":57499553,"title":"Is it possible to prevent `useLazyQuery` queries from being re-fetched on component state change / re-render?","tags":["graphql","apollo","react-hooks","react-apollo","apollo-client"],"text":"Title: Is it possible to prevent `useLazyQuery` queries from being re-fetched on component state change / re-render?\nTags: graphql, apollo, react-hooks, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nCurrently I have a `useLazyQuery` hook which is fired on a button press (part of a search form). \n\nThe hook behaves normally, and is only fired when the button is pressed. However, once I've fired it once, it's then fired every time the component re-renders (usually due to state changes).\n\nSo if I search once, then edit the search fields, the results appear immediately, and I don't have to click on the search button again. \n\nNot the UI I want, and it causes an error if you delete the search text entirely (as it's trying to search with `null` as the variable), is there any way to prevent the `useLazyQuery` from being refetched on re-render?\n\nThis can be worked around using `useQuery` dependent on a 'searching' state which gets toggled on when I click on the button. However I'd rather see if I can avoid adding complexity to the component.\n\n```\nconst AddCardSidebar = props => {\n const [searching, toggleSearching] = useState(false);\n const [searchParams, setSearchParams] = useState({\n name: ''\n });\n const [searchResults, setSearchResults] = useState([]);\n const [selectedCard, setSelectedCard] = useState();\n\n const [searchCardsQuery, searchCardsQueryResponse] = useLazyQuery(SEARCH_CARDS, {\n variables: { searchParams },\n onCompleted() {\n setSearchResults(searchCardsQueryResponse.data.searchCards.cards);\n }\n });\n\n ...\n\n return (\n \n \n\n### AddCardSidebar\n\n \n {searchResults.length !== 0 &&\n searchResults.map(result => {\n return (\n setSelectedCard(result.scryfall_id)}\n />\n );\n })}\n \n \n\n ...\n\n searchCardsQuery()}>\n Search\n \n \n\n ...\n\n \n );\n};\n```\n\n========================================\n\nTop Answer:\nYou don't have to use `async` with the apollo client (you can, it works). But if you want to use `useLazyQuery` you just have to pass variables on the `onClick` and not directly on the useLazyQuery call.\n\nWith the above example, the solution would be:\n\n```\nfunction DelayedQuery() {\n const [dog, setDog] = useState(null);\n const [getDogPhoto] = useLazyQuery(GET_DOG_PHOTO, {\n onCompleted: data => setDog(data.dog)\n })\n\n return (\n \n {dog && }\n getDogPhoto({ variables: { breed: 'bulldog' }})}\n >\n Click me!\n \n \n );\n}\n```\n\n========================================\n\nCode:\n```js\nconst AddCardSidebar = props => {\n const [searching, toggleSearching] = useState(false);\n const [searchParams, setSearchParams] = useState({\n name: ''\n });\n const [searchResults, setSearchResults] = useState([]);\n const [selectedCard, setSelectedCard] = useState();\n\n const [searchCardsQuery, searchCardsQueryResponse] = useLazyQuery(SEARCH_CARDS, {\n variables: { searchParams },\n onCompleted() {\n setSearchResults(searchCardsQueryResponse.data.searchCards.cards);\n }\n });\n\n ...\n\n return (\n <div>\n <h1>AddCardSidebar</h1>\n <div>\n {searchResults.length !== 0 &&\n searchResults.map(result => {\n return (\n <img\n key={result.scryfall_id}\n src={result.image_uris.small}\n alt={result.name}\n onClick={() => setSelectedCard(result.scryfall_id)}\n />\n );\n })}\n </div>\n <form>\n\n ...\n\n <button type='button' onClick={() => searchCardsQuery()}>\n Search\n </button>\n </form>\n\n ...\n\n </div>\n );\n};\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nnull\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nuseQuery\n```\n\n```text\nfunction DelayedQuery() {\n const [dog, setDog] = useState(null);\n const client = useApolloClient();\n\n return (\n <div>\n {dog && <img src={dog.displayImage} />}\n <button\n onClick={async () => {\n const { data } = await client.query({\n query: GET_DOG_PHOTO,\n variables: { breed: 'bulldog' },\n });\n setDog(data.dog);\n }}\n >\n Click me!\n </button>\n </div>\n );\n}\n```\n\n```text\nreact-apollo\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nuseApolloClient\n```\n\n```text\nfunction DelayedQuery() {\n const [dog, setDog] = useState(null);\n const [getDogPhoto] = useLazyQuery(GET_DOG_PHOTO, {\n onCompleted: data => setDog(data.dog)\n })\n\n return (\n <div>\n {dog && <img src={dog.displayImage} />}\n <button\n onClick={() => getDogPhoto({ variables: { breed: 'bulldog' }})}\n >\n Click me!\n </button>\n </div>\n );\n}\n```\n\n```text\nasync\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nonClick\n```\n\n```text\nconst AddCardSidebar = props => {\n const [searching, toggleSearching] = useState(false);\n const [searchParams, setSearchParams] = useState({\n name: ''\n });\n const [searchResults, setSearchResults] = useState([]);\n const [selectedCard, setSelectedCard] = useState();\n\n const [searchCardsQuery, searchCardsQueryResponse] = \n useLazyQuery(SEARCH_CARDS, {\n variables: { searchParams },\n fetchPolicy: 'network-only', //<-- only makes network requests\n onCompleted() {\n setSearchResults(searchCardsQueryResponse.data.searchCards.cards);\n }\n });\n ...\n\n return (\n <div>\n <h1>AddCardSidebar</h1>\n <div>\n {searchResults.length !== 0 &&\n searchResults.map(result => {\n return (\n <img\n key={result.scryfall_id}\n src={result.image_uris.small}\n alt={result.name}\n onClick={() => setSelectedCard(result.scryfall_id)}\n />\n );\n })}\n </div>\n <form>\n\n ...\n\n <button type='button' onClick={() => searchCardsQuery()}>\n Search\n </button>\n </form>\n\n ...\n\n </div>\n );\n};\n```\n\n```text\nfetchPolicy\n```\n\n```text\nnetwork-only\n```\n\n```text\ncache-and-network\n```\n\n```text\nnetwork-only\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nnextFetchPolicy\n```\n\n```text\n\"standby\"\n```\n\n========================================\n\nComments:\n- Even I am getting this problem. What I am trying to do is useLazyQuery during the component mounting `useEffect(() => refetchFunction(), [])` But whenever my state changes, the refetchFunction is called again (INTERNALLY SOMEWHERE)\n- This solution perfectly resolved the issue I had with useLazyQuery which keeps firing requests on rerendering. Thank you\n- In my opinion this should be the accepted answer, since is using the useLazyQuery hook.\n- How would you get back the error and loading states of the lazy query?\n- @AndrewEinhorn - with `const [getDogPhoto, {data, loading, error}] = useLazyQuery(GET_DOG_PHOTO...`\n- This works! useLazyQuery not getting fired again on component load/re-render. Thanks @Yann Pravo\n- ChatGPT almost convinced me into using useMutation lol, came here and tried your answer. Voila!!","metadata":{"transformedAt":"2026-08-18T18:32:36.041Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":316,"estimatedTokens":1731}}243{"id":"stack-32662437","source":"stackoverflow","questionId":32662437,"title":"GraphQL and form validation errors","tags":["validation","error-handling","graphql"],"text":"Title: GraphQL and form validation errors\nTags: validation, error-handling, graphql\nSource: Stack Overflow\n\nQuestion:\nLet's say you have a form which posts data to API server. The API server validates the input and returns JSON object. If the input is invalid an error objects like the one below is returned.\n\n```\n{errors: {field1: \"is required\"}}\n```\n\nHow do we handle and serve these kind of errors when using GraphQL? How and where should data validation be implemented (should that be part of GraphQL or should it be inside each resolve function)?\n\n========================================\n\nTop Answer:\nIt may be preferable to put the validation/capability checks into a service layer.\n\nGraphQL is just one entry point into your application. Hence it shouldn't hold validation & capability checks. \n\nIf you think of an application that has multiple access layers (REST & GraphQL). You'll be duplicating code by adding validation checks in the GraphQL layer.\n\nBest approach would be to have a code layer to handle this, e.g UserService. This would hold your logic for validation & capability checks.\n\nGraphQL & REST API would just be formatters converting the response to the acceptable format for the respective response types. An example is below for illustration purposes:\n\n```\nclass UserService {\n public function updateName(string $name) {\n // validation/capability check code here.\n // if validation fails, throw a user input exception or appropriate exception \n //return value.\n }\n}\n```\n\n```\nGraphQl Mutation\nclass UserResolver {\n public function updateUserName(array $args, context $context) {\n try {\n $user = (new UserService() )->updateName(args['name']);\n return [\n 'user' => $user\n ];\n } catch (UserInputException $exception) {\n return [\n 'error' => $exception,\n 'user' => null\n ];\n }\n }\n}\n```\n\n```\nREST API Controller\nclass UserController {\n public function updateUserName(string $name) {\n try {\n $user = (new UserService() )->updateName($name);\n\n return [\n 'user' => $user\n ];\n } catch (UserInputException $exception) {\n return [\n 'error' => $exception->message,\n ];\n }\n }\n}\n```\n\nBy using exceptions in the Service class this way, you can also select exceptions you want to be returned in your response(Can be a GraphQL or REST response).\n\nWe should only see GraphQL as an access layer. Resolver functions should be as dumb/simple as possible and not contain business logic, validations & capability checks.\n\n========================================\n\nCode:\n```text\n{errors: {field1: \"is required\"}}\n```\n\n```js\n// data/mutations/createUser.js\nimport {\n GraphQLObjectType as ObjectType,\n GraphQLNonNull as NonNull,\n GraphQLList as List,\n GraphQLString as StringType\n} from 'graphql';\nimport validator from 'validator';\nimport UserType from '../types/UserType';\n\nexport default {\n type: new ObjectType({\n name: 'CreateUserResult',\n fields: {\n user: { type: UserType },\n errors: { type: new NonNull(new List(StringType)) }\n }\n }),\n args: {\n email: { type: new NonNull(StringType) },\n password: { type: new NonNull(StringType) }\n },\n resolve(_, { email, password }) {\n let user = null;\n let errors = [];\n\n if (validator.isNull(email)) {\n errors.push(...['email', 'The email filed must not be empty.']);\n } else if (!validator.isLength(email, { max: 100})) {\n errors.push(...['email', 'The email must be at a max 100 characters long.']);\n }\n\n // etc.\n\n return { user, errors };\n }\n};\n```\n\n```text\nmutation {\n createUser(email: \"hello@tarkus.me\", password: \"Passw0rd\") {\n user { id, email },\n errors { key, message }\n }\n}\n```\n\n```text\n{\n data: {\n user: null,\n errors: [\n { key: '', message: 'Failed to create a new user account.' },\n { key: 'email', message: 'User with this email already exists.' }\n ]\n }\n}\n```\n\n```text\nresolve\n```\n\n```text\ntype UserErrorType { key: String!, message: String! }\n```\n\n```text\nconst { validator, validate } = require('graphql-validation'); // Import module\n\nconst resolver = {\n Mutation: {\n createPost: validator([ // <-- Validate here\n validate('title').not().isEmpty({ msg: 'Title is required' }),\n validate('content').isLength({ min: 10, max: 20 }),\n ], (parent, args, context, info) => {\n if (context.validateErrors.length > 0) {\n // Validate failed\n console.log(context.validateErrors); // Do anything with this errors\n\n return;\n }\n\n // Validate successfully, time to create new post\n }),\n },\n};\n```\n\n```text\nInput: { title: '', content: 'Hi!' }\n\n// console.log(context.validateErrors);\nOutput: [\n { param: 'title', msg: 'Title is required' },\n { param: 'content', msg: 'Invalid value' },\n]\n```\n\n```text\nclass UserService {\n public function updateName(string $name) {\n // validation/capability check code here.\n // if validation fails, throw a user input exception or appropriate exception \n //return value.\n }\n}\n```\n\n```text\nGraphQl Mutation\nclass UserResolver {\n public function updateUserName(array $args, context $context) {\n try {\n $user = (new UserService() )->updateName(args['name']);\n return [\n 'user' => $user\n ];\n } catch (UserInputException $exception) {\n return [\n 'error' => $exception,\n 'user' => null\n ];\n }\n }\n}\n```\n\n```text\nREST API Controller\nclass UserController {\n public function updateUserName(string $name) {\n try {\n $user = (new UserService() )->updateName($name);\n\n return [\n 'user' => $user\n ];\n } catch (UserInputException $exception) {\n return [\n 'error' => $exception->message,\n ];\n }\n }\n}\n```\n\n========================================\n\nComments:\n- This is probably the best interim solution we're going to get until/unless GraphQL opts for a separate errors object to distinguish between system errors and user field/msg validation. The only slight change I've made is to create a dedicated `ErrorType` that has `field` and `msg` keys, so it's slightly easier to work with than having to care about array insert order... but it's ultimately the same thing.\n- You could also introduce a validation endpoint to the GraphQL schema itself, or a return a validations node within the results set.","metadata":{"transformedAt":"2026-08-18T18:32:36.041Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":239,"estimatedTokens":1597}}244{"id":"stack-42937502","source":"stackoverflow","questionId":42937502,"title":"GraphQL - How to respond with different status code?","tags":["javascript","graphql","apollo","react-apollo"],"text":"Title: GraphQL - How to respond with different status code?\nTags: javascript, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm having a trouble with Graphql and Apollo Client.\n\nI always created different responses like 401 code when using REST but here I don't know how to do a similar behavior.\n\nWhen I get the response, I want it to go to the catch function.\nAn example of my front-end code:\n\n```\nclient.query({\n query: gql`\n query TodoApp {\n todos {\n id\n text\n completed\n }\n }\n `,\n})\n .then(data => console.log(data))\n .catch(error => console.error(error));\n```\n\nCan anybody help me?\n\n========================================\n\nTop Answer:\nThere has been a recent addition to the spec concerning errors outputs:\n\nGraphQL services may provide an additional entry to errors with key **extensions**. This entry, if set, must have a map as its value. This entry is reserved for implementors to add additional information to errors however they see fit, and there are no additional restrictions on its contents.\n\nNow using the `extensions` field you can custom machine-readable information to your `errors` entries:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Name for character with ID 1002 could not be fetched.\",\n \"locations\": [ { \"line\": 6, \"column\": 7 } ],\n \"path\": [ \"hero\", \"heroFriends\", 1, \"name\" ],\n \"extensions\": {\n \"code\": \"CAN_NOT_FETCH_BY_ID\",\n \"timestamp\": \"Fri Feb 9 14:33:09 UTC 2018\"\n }\n }\n ]\n}\n```\n\nLatest version of Apollo-Server is spec-compliant with this feature check it out, Error Handling.\n\n========================================\n\nCode:\n```text\nclient.query({\n query: gql`\n query TodoApp {\n todos {\n id\n text\n completed\n }\n }\n `,\n})\n .then(data => console.log(data))\n .catch(error => console.error(error));\n```\n\n```text\nage: (person, args) => {\n try {\n return fetchAge(person.id);\n } catch (e) {\n throw new Error(\"Could not connect to age service\");\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"name\": \"John\",\n \"age\": null\n },\n \"errors\": [\n { \"message\": \"Could not connect to age service\" }\n ]\n}\n```\n\n```text\napp.use('/graphql', bodyParser.json(), graphqlExpress({ \n schema: myGraphQLSchema,\n formatError: (err) => ({ message: err.message, status: err.status }),\n}));\n```\n\n```text\nformatError\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Name for character with ID 1002 could not be fetched.\",\n \"locations\": [ { \"line\": 6, \"column\": 7 } ],\n \"path\": [ \"hero\", \"heroFriends\", 1, \"name\" ],\n \"extensions\": {\n \"code\": \"CAN_NOT_FETCH_BY_ID\",\n \"timestamp\": \"Fri Feb 9 14:33:09 UTC 2018\"\n }\n }\n ]\n}\n```\n\n```text\nextensions\n```\n\n```text\nerrors\n```\n\n```text\napp.use('/graphql', auth.verifyAccess, graphqlHTTP((req, res) => {\n return {\n schema: makeExecutableSchema({\n typeDefs: typeDefs,\n resolvers: rootResolver\n }),\n graphiql: true,\n formatError: (err) => ({\n message: err.originalError.message || err.message,\n code: err.originalError.code || 500\n }),\n }\n }));\n```\n\n```text\nclass APIError extends Error {\n constructor({ code, message }) {\n const fullMsg = `${code}: ${message}`;\n\n super(fullMsg);\n this.code = code;\n this.message = message;\n }\n}\n\nexport default APIError;\n```\n\n```text\nconst e = new APIError({\n code: 500,\n message: 'Internal server error'\n });\n```\n\n```text\nError\n```\n\n```text\nformatError\n```\n\n```text\noriginalError\n```\n\n```text\noriginalError\n```\n\n```text\nget\n```\n\n```text\nAPIError\n```\n\n========================================\n\nComments:\n- Thanks helfer, it's very useful.\n- `formatError` is deprecated and replaced by `customFormatErrorFn`. It will be removed in version 1.0.0.`","metadata":{"transformedAt":"2026-08-18T18:32:36.041Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":199,"estimatedTokens":928}}245{"id":"stack-62893664","source":"stackoverflow","questionId":62893664,"title":"How can I handle long Int with GraphQL?","tags":["javascript","node.js","graphql","bigint"],"text":"Title: How can I handle long Int with GraphQL?\nTags: javascript, node.js, graphql, bigint\nSource: Stack Overflow\n\nQuestion:\nAs you know that GraphQL has no data type like long int. So, whenever the number is something big like `10000000000`, it throws an error like this: `Int cannot represent non 32-bit signed integer value: 1000000000000`\n\nFor that I know two solutions:\n\n- Use scalars.\n\n```\nimport { GraphQLScalarType } from 'graphql';\nimport { makeExecutableSchema } from '@graphql-tools/schema';\n\nconst myCustomScalarType = new GraphQLScalarType({\n name: 'MyCustomScalar',\n description: 'Description of my custom scalar type',\n serialize(value) {\n let result;\n return result;\n },\n parseValue(value) {\n let result;\n return result;\n },\n parseLiteral(ast) {\n switch (ast.kind) {\n }\n }\n});\n\nconst schemaString = `\n\nscalar MyCustomScalar\n\ntype Foo {\n aField: MyCustomScalar\n}\n\ntype Query {\n foo: Foo\n}\n\n`;\n\nconst resolverFunctions = {\n MyCustomScalar: myCustomScalarType\n};\n\nconst jsSchema = makeExecutableSchema({\n typeDefs: schemaString,\n resolvers: resolverFunctions,\n});\n```\n\n- Use apollo-type-bigint package.\n\nBoth of those solutions convert the big int to `string`, and I'd rather not use string (I prefer a number type).\n\n========================================\n\nTop Answer:\nGraphql has introduced Scalars. I am using Java and so I can provide some solution in Java. You can achieve the same by following the below steps.\n\nin your .graphqls file please define scalar\n\n```\nscalar Long\n\ntype Movie{\nmovieId: String\nmovieName: String\nproducer: String\ndirector: String\ndemoId : Long\n}\n```\n\nNow you have to register this scalar in your wiring.\n\n```\nreturn RuntimeWiring.newRuntimeWiring().type(\"Query\", typeWiring -> typeWiring\n .dataFetcher(\"allMovies\", allMoviesDataFetcher).dataFetcher(\"movie\", movieDataFetcher)\n .dataFetcher(\"getMovie\", getMovieDataFetcher)).scalar(ExtendedScalars.GraphQLLong).build();\n```\n\nNow you have to define the Scalar configuration for Long as below.\n\n```\n@Configuration\npublic class LongScalarConfiguration {\n @Bean\n public GraphQLScalarType longScalar() {\n return GraphQLScalarType.newScalar()\n .name(\"Long\")\n .description(\"Java 8 Long as scalar.\")\n .coercing(new Coercing() {\n @Override\n public String serialize(final Object dataFetcherResult) {\n if (dataFetcherResult instanceof Long) {\n return dataFetcherResult.toString();\n } else {\n throw new CoercingSerializeException(\"Expected a Long object.\");\n }\n }\n\n @Override\n public Long parseValue(final Object input) {\n try {\n if (input instanceof String) {\n return new Long((String) input);\n } else {\n throw new CoercingParseValueException(\"Expected a String\");\n }\n } catch (Exception e) {\n throw new CoercingParseValueException(String.format(\"Not a valid Long: '%s'.\", input), e\n );\n }\n }\n\n @Override\n public Long parseLiteral(final Object input) {\n if (input instanceof StringValue) {\n try {\n return new Long(((StringValue) input).getValue());\n } catch (Exception e) {\n throw new CoercingParseLiteralException(e);\n }\n } else {\n throw new CoercingParseLiteralException(\"Expected a StringValue.\");\n }\n }\n }).build();\n }\n\n}\n```\n\nIt should solve your problem. Please give it a try for Java related application.\n\n========================================\n\nCode:\n```js\nimport { GraphQLScalarType } from 'graphql';\nimport { makeExecutableSchema } from '@graphql-tools/schema';\n\nconst myCustomScalarType = new GraphQLScalarType({\n name: 'MyCustomScalar',\n description: 'Description of my custom scalar type',\n serialize(value) {\n let result;\n return result;\n },\n parseValue(value) {\n let result;\n return result;\n },\n parseLiteral(ast) {\n switch (ast.kind) {\n }\n }\n});\n\nconst schemaString = `\n\nscalar MyCustomScalar\n\ntype Foo {\n aField: MyCustomScalar\n}\n\ntype Query {\n foo: Foo\n}\n\n`;\n\nconst resolverFunctions = {\n MyCustomScalar: myCustomScalarType\n};\n\nconst jsSchema = makeExecutableSchema({\n typeDefs: schemaString,\n resolvers: resolverFunctions,\n});\n```\n\n```text\n10000000000\n```\n\n```text\nInt cannot represent non 32-bit signed integer value: 1000000000000\n```\n\n```text\nstring\n```\n\n```text\nbigInt\n```\n\n```text\ngraphQL\n```\n\n```text\nFloat\n```\n\n```text\nInt\n```\n\n```text\nnumber\n```\n\n```text\nstring\n```\n\n```text\nString\n```\n\n```text\nBigInt\n```\n\n```text\nstring\n```\n\n```text\nscalar Long\n\ntype Movie{\nmovieId: String\nmovieName: String\nproducer: String\ndirector: String\ndemoId : Long\n}\n```\n\n```text\nreturn RuntimeWiring.newRuntimeWiring().type(\"Query\", typeWiring -> typeWiring\n .dataFetcher(\"allMovies\", allMoviesDataFetcher).dataFetcher(\"movie\", movieDataFetcher)\n .dataFetcher(\"getMovie\", getMovieDataFetcher)).scalar(ExtendedScalars.GraphQLLong).build();\n```\n\n```text\n@Configuration\npublic class LongScalarConfiguration {\n @Bean\n public GraphQLScalarType longScalar() {\n return GraphQLScalarType.newScalar()\n .name(\"Long\")\n .description(\"Java 8 Long as scalar.\")\n .coercing(new Coercing<Long, String>() {\n @Override\n public String serialize(final Object dataFetcherResult) {\n if (dataFetcherResult instanceof Long) {\n return dataFetcherResult.toString();\n } else {\n throw new CoercingSerializeException(\"Expected a Long object.\");\n }\n }\n\n @Override\n public Long parseValue(final Object input) {\n try {\n if (input instanceof String) {\n return new Long((String) input);\n } else {\n throw new CoercingParseValueException(\"Expected a String\");\n }\n } catch (Exception e) {\n throw new CoercingParseValueException(String.format(\"Not a valid Long: '%s'.\", input), e\n );\n }\n }\n\n @Override\n public Long parseLiteral(final Object input) {\n if (input instanceof StringValue) {\n try {\n return new Long(((StringValue) input).getValue());\n } catch (Exception e) {\n throw new CoercingParseLiteralException(e);\n }\n } else {\n throw new CoercingParseLiteralException(\"Expected a StringValue.\");\n }\n }\n }).build();\n }\n\n}\n```\n\n```text\nconst typeDef = gql`\n scalar BigInt\n type Mutation {\n .....\n }\n`\n```\n\n```text\ndeclare global {\n interface BigInt {\n toJSON: () => number;\n fromJSON: () => BigInt;\n }\n}\n\nBigInt.prototype.toJSON = function () {\n const int = Number.parseInt(this.toString());\n return int ?? this.toString();\n};\n\nBigInt.prototype.fromJSON = function () {\n return BigInt(this.toString());\n};\n```\n\n```text\nscalar BigInt\n```\n\n```text\nimport { GraphQLScalarType } from \"graphql\";\n\nconst resolver = {\n BigInt: new GraphQLScalarType({\n name: \"BigInt\",\n description: \"BigInt custom scalar type\",\n serialize(value) {\n return Number(value);\n },\n parseValue(value) {\n return BigInt(value);\n },\n parseLiteral(ast) {\n return ast.kind === Kind.INT ? BigInt(ast.value) : null;\n },\n }),\n};\n\nexport default resolver;\n```\n\n```text\ntype Record {\n count: BigInt!\n}\n```\n\n```text\nyour-schema.graphql\n```\n\n========================================\n\nComments:\n- What do you mean by \"*convert the big int to string*\"?\n- Means if i use this method then the data should be like `{ \"a\": \"10000000000\" }` but it should be. `{\"a\" : 1000000000}`\n- It's pretty hard to parse JSON with too-long numbers, so it's easier to put them in strings. Given any integer type with more than 32 bits will be a custom scalar anyway, it should hardly matter.\n- So, my first approach will be fine for the implementation? or do you have any other options?\n- Well, the code snippet you posted doesn't yet actually do anything, but yes all approaches will be based on using a custom scalar type.\n- can you show me an example? that would be helpful. thanks\n- Take a look at the sources of any of the bigint-graphql js libraries out there\n- How is this better than/different from the apollo-type-bigint package that the OP considered to use?\n- apollo-type-bigint has two implementions. The first one works with only with 53 bit integers. The second implementation allows you to work with 63 bit integers using a new data type in JavaScript - BigInt. graphql-bigint is simplier, and if I understood the question correctly, it should do the work that OP needs. Though there is nothing wrong with using apollo-type-bigint\n- will check the float thing.\n- \"*`Float` will handle all large int values*\" - until 53 bits, that is.\n- @HarshPatel Not really that bit, though. 64 and 128 bit integers are common as well.\n- I notice one thing that if I make data type as float it will handle any big number, I don't understand why. but its strange behavior. like I check for `1B` and `10B`\n- If you are using a `BigInt` type, you should provide real big integers not ones that are serialised to a floating point number. People would expect to be able to pass values with more than 64 bit.\n- What do u mean? You can that way? This has nothing to do with a floating point number?\n- Your `serialise` method mangles the bigint so that it looses precision\n- Yes, what of it. If your GraphQL Server returns a BigInt which there is no built-in way to return BigInt values it's just converting a BigInt value to a Number. And the opposite, converts value from the client to BigInt. I don't understand what's your point. That's the point of having `BigInt`. If you want precision, you should use Float anyways.\n- Without JSON source text access, you could at least serialise to a string, instead of using lossy serialiation. \"*If you want precision, you should use Float anyways.*\" - absolutely not!\n- Ok I think now I got your point. But I don't want to return string to the client. It needs to be number. I have my values as `BigInt` but they're not real BigInts, not greater than 32 bits. That's my use case. What i mean about float is that, you can just create another scalar for >32bits floats.\n- Then please edit your answer so that it points out clearly it's only supposed to work with small big ints.","metadata":{"transformedAt":"2026-08-18T18:32:36.041Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":391,"estimatedTokens":2652}}246{"id":"stack-46022405","source":"stackoverflow","questionId":46022405,"title":"GraphQL string concatenation or interpolation","tags":["string","graphql"],"text":"Title: GraphQL string concatenation or interpolation\nTags: string, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm using GitHub API v 4 to learn GraphQL. Here is a broken query to fetch blobs (files) and their text content for a given branch:\n\n```\nquery GetTree($branch: String = \"master\") {\n repository(name: \"blog-content\", owner: \"lzrski\") {\n branch: ref(qualifiedName: \"refs/heads/${branch}\") {\n name\n target {\n ... on Commit {\n tree {\n entries {\n name\n object {\n ... on Blob {\n isBinary\n text\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\nAs you see on line 3 there is my attempt of guessing interpolation syntax, but it does not work - I leave it as an illustration of my intention.\n\nI could provide a fully qualified name for a revision, but that doesn't seem particularly elegant. Is there any GraphQL native way of manipulating strings?\n\n========================================\n\nCode:\n```text\nquery GetTree($branch: String = \"master\") {\n repository(name: \"blog-content\", owner: \"lzrski\") {\n branch: ref(qualifiedName: \"refs/heads/${branch}\") {\n name\n target {\n ... on Commit {\n tree {\n entries {\n name\n object {\n ... on Blob {\n isBinary\n text\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- can you give an example referring to the one of the OP? I cannot imagine how to use JSON with variables? Should `qualifiedName: \"refs/heads/${branch}\"` be a json object which is then used in graphql as a variable?\n- Referring to my comment one hour ago, I got it with this example with a `request` with `query` and `variables` as `data`.","metadata":{"transformedAt":"2026-08-18T18:32:36.041Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":69,"estimatedTokens":437}}247{"id":"stack-56433743","source":"stackoverflow","questionId":56433743,"title":"AWS Amplify - AppSync & Multiple DynamoDB Tables","tags":["amazon-web-services","amazon-dynamodb","graphql","aws-amplify","aws-appsync"],"text":"Title: AWS Amplify - AppSync & Multiple DynamoDB Tables\nTags: amazon-web-services, amazon-dynamodb, graphql, aws-amplify, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nWhen initializing a new GraphQL backend via the Amplify CLI, the sample schema defines multiple types with the @model annotation. For example...\n\n```\ntype Blog @model {\n id: ID!\n name: String!\n posts: [Post] @connection(name: \"BlogPosts\")\n}\ntype Post @model {\n id: ID!\n title: String!\n blog: Blog @connection(name: \"BlogPosts\")\n comments: [Comment] @connection(name: \"PostComments\")\n}\ntype Comment @model {\n id: ID!\n content: String\n post: Post @connection(name: \"PostComments\")\n}\n```\n\nWhen pushed, this results in the creation of multiple DynamoDB tables (one per model). So in this example, three separate DynamoDB tables are created (Blogs, Posts, and Comments)\n\nIn our case we have a `Users` model and we're going to have twenty or so small collections associated to the user. I feel uneasy about having to manage twenty different DynamoDB tables when it feels like these small collections all belong with the User object in a single table.\n\nFrom everything I'm reading it seems like AppSync is encouraging the use of multiple tables. For example, the **Note** in the screenshot below from the AWS AppSync documentation specifically calls out that the blog comments should go into a separate table in a production environment.\n\nhttps://i.sstatic.net/AsMD7.png\n\nThis contradicts the best practice laid out in the DynamoDB documentation:\n\n You should maintain as few tables as possible in a DynamoDB application. Most well designed applications require only one table.\n\nIs it truly the case that when using AppSync each type belongs in a separate DynamoDB table?\n\n========================================\n\nTop Answer:\nIs it truly the case that when using AppSync each type belongs in a separate DynamoDB table?\n\nNo, you can use a single table to store different types (or entities) required for your service. As long as you have well defined access patterns for the data you will be using in your service, you may get away with only using one table. However, this approach might be a bit inflexible since you have to think about your access patterns beforehand and might be hard do add new ones in the future.\n\nThere is currently no way of taking advantage of the @model directive in Amplify to have such configuration. You will have to manually create the table and then set up your resolvers accordingly for each Appsync type to query/mutate accordingly.\n\nThis is a good article that explains the approach:\nFrom relational DB to single DynamoDB table: a step-by-step exploration\n\n========================================\n\nCode:\n```text\ntype Blog @model {\n id: ID!\n name: String!\n posts: [Post] @connection(name: \"BlogPosts\")\n}\ntype Post @model {\n id: ID!\n title: String!\n blog: Blog @connection(name: \"BlogPosts\")\n comments: [Comment] @connection(name: \"PostComments\")\n}\ntype Comment @model {\n id: ID!\n content: String\n post: Post @connection(name: \"PostComments\")\n}\n```\n\n```text\nUsers\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.041Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":77,"estimatedTokens":768}}248{"id":"stack-58780119","source":"stackoverflow","questionId":58780119,"title":"Why I am getting the error \"cannot determine GraphQL output type\"?","tags":["node.js","typescript","graphql","nestjs"],"text":"Title: Why I am getting the error \"cannot determine GraphQL output type\"?\nTags: node.js, typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to create simple appliaction with **Nest.js**, **GraphQL** and **MongoDB**. I wnated to use **TypeORM** and **TypeGraphql** to generate my schema and make a connection with localhost databasebut but i can not run my server with `nest start` becouse I am getting this error:\n\n UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL output type for getArticles\n\nI have no idea why i am getting this error. My class `ArticleEntity` does't has any not primary types, so there should not be any problem. I tried to remove `() => ID` from `@Field()` decorator of filed `_id` of `ArticleEntity` class but it didn't helped\n\n**ArticleResolver**\n\n```\n@Resolver(() => ArticleEntity)\nexport class ArticlesResolver {\n constructor(\n private readonly articlesService: ArticlesService) {}\n\n @Query(() => String)\n async hello(): Promise {\n return 'Hello world';\n }\n\n @Query(() => [ArticleEntity])\n async getArticles(): Promise {\n return await this.articlesService.findAll();\n }\n\n}\n```\n\n**ArticleService**\n\n```\n@Injectable()\nexport class ArticlesService {\n constructor(\n @InjectRepository(ArticleEntity)\n private readonly articleRepository: MongoRepository,\n ) {}\n\n async findAll(): Promise {\n return await this.articleRepository.find();\n }\n}\n```\n\n**ArticleEntity**\n\n```\n@Entity()\nexport class ArticleEntity {\n @Field(() => ID)\n @ObjectIdColumn()\n _id: string;\n\n @Field()\n @Column()\n title: string;\n\n @Field()\n @Column()\n description: string;\n}\n```\n\n**ArticleDTO**\n\n```\n@InputType()\nexport class CreateArticleDTO {\n @Field()\n readonly title: string;\n\n @Field()\n readonly description: string;\n}\n```\n\nIf you need anything else comment\n\n========================================\n\nTop Answer:\nFor anyone who gets this error and uses enums, you may be missing a call to `registerEnumType`.\n\n========================================\n\nCode:\n```js\n@Resolver(() => ArticleEntity)\nexport class ArticlesResolver {\n constructor(\n private readonly articlesService: ArticlesService) {}\n\n @Query(() => String)\n async hello(): Promise<string> {\n return 'Hello world';\n }\n\n @Query(() => [ArticleEntity])\n async getArticles(): Promise<ArticleEntity[]> {\n return await this.articlesService.findAll();\n }\n\n}\n```\n\n```js\n@Injectable()\nexport class ArticlesService {\n constructor(\n @InjectRepository(ArticleEntity)\n private readonly articleRepository: MongoRepository<ArticleEntity>,\n ) {}\n\n async findAll(): Promise<ArticleEntity[]> {\n return await this.articleRepository.find();\n }\n}\n```\n\n```js\n@Entity()\nexport class ArticleEntity {\n @Field(() => ID)\n @ObjectIdColumn()\n _id: string;\n\n @Field()\n @Column()\n title: string;\n\n @Field()\n @Column()\n description: string;\n}\n```\n\n```js\n@InputType()\nexport class CreateArticleDTO {\n @Field()\n readonly title: string;\n\n @Field()\n readonly description: string;\n}\n```\n\n```text\nnest start\n```\n\n```text\nArticleEntity\n```\n\n```text\n() => ID\n```\n\n```text\n@Field()\n```\n\n```text\n_id\n```\n\n```text\nArticleEntity\n```\n\n```text\n@Entity()\n@ObjectType()\nexport class ArticleEntity {\n ...\n}\n```\n\n```text\nArticleEntity\n```\n\n```text\n@ObjectType\n```\n\n```js\n@ObjectType()\n@Schema({ versionKey: `version` })\nexport class User {\n @Field()\n _id: string\n\n @Prop({ required: true })\n @Field()\n email: string\n\n @Prop({ required: true })\n password: string\n}\n\nexport const UserSchema = SchemaFactory.createForClass(User)\n```\n\n```js\n@Query((returns) => User)\nasync user(): Promise<UserDocument> {\n const newUser = new this.userModel({\n id: ``,\n email: `test@test.com`,\n password: `abcdefg`,\n })\n return await newUser.save()\n}\n```\n\n```text\nQuery\n```\n\n```text\n@Query((returns) => UserSchema)\n```\n\n```text\n@Query((returns) => User)\n```\n\n```js\nimport { ObjectType } from '@nestjs/graphql';\n```\n\n```text\n@ObjectType\n```\n\n```text\ntype-graphql\n```\n\n```text\n@nestjs/graphql\n```\n\n```text\nregisterEnumType\n```\n\n```text\nexport class A{\nid: number;\nname:string;\nchildProperty: B\n. . . . .\n}\n\n\nexport class B{\n prop1:string;\n prop2:string;\n}\n```\n\n```text\nObjectType()\nexport class User {\n```\n\n```text\n@ObjectType()\nexport class User {\n```\n\n```text\n@\n```\n\n```text\nObjectType\n```\n\n```text\ntype-graphql\n```\n\n========================================\n\nComments:\n- Yes i forgot about this decorator, such a small thing, such a big mistake. Thank you mate\n- Excellent insight; this is what I was missing!","metadata":{"transformedAt":"2026-08-18T18:32:36.041Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":295,"estimatedTokens":1131}}249{"id":"stack-60831980","source":"stackoverflow","questionId":60831980,"title":"I don't understand the GraphQL N+1 problem","tags":["graphql"],"text":"Title: I don't understand the GraphQL N+1 problem\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI found this example of the GraphQL N+1 problem:\n\n### Query\n\n```\n# getting the top 100 reviews\n\n{\n top100Reviews {\n body\n author {\n name\n }\n }\n}\n```\n\n### Schema\n\n```\nconst typeDefs = gql`\n type User {\n id: ID!\n name: String\n }\n\n type Review {\n id: ID!\n body: String\n author: User\n product: Product\n }\n\n type Query {\n top100Reviews: [Review]\n }\n`\n```\n\n### Resolvers\n\n```\nconst resolver = {\n Query: {\n top100Reviews: () => get100Reviews(),\n },\n Review: {\n author: (review) => getUser(review.authorId),\n },\n}\n```\n\nWhen we execute the following query to get the top 100 reviews and the corresponding author names, we first make a single call to retrieve 100 records of review from database and then for each review, we make another call to the database to fetch the user details given the author ID.\n\nCan't you just remove the `Review` resolver and just do a simple `JOIN` in the `get100Reviews` method in the `Query` resolver?\n\nI don't understand why you would create the `Review` resolver it causes the GraphQL N+1 problem, when you could just do a simple `JOIN` in the `Query` resolver.\n\nDo I understand GraphQL correctly?\n\n========================================\n\nTop Answer:\nI just wrote a package that I believe can solve N+1 problems in most cases on GraphQL on Nodejs.\nCheck it out!\nhttps://github.com/oney/sequelize-proxy\n\nIt basically uses data loaders to batch multiple queries to single one but it further leverages features and association definitions in sequelize to make it more accurate and efficient.\n\n========================================\n\nCode:\n```text\n# getting the top 100 reviews\n\n{\n top100Reviews {\n body\n author {\n name\n }\n }\n}\n```\n\n```text\nconst typeDefs = gql`\n type User {\n id: ID!\n name: String\n }\n\n type Review {\n id: ID!\n body: String\n author: User\n product: Product\n }\n\n type Query {\n top100Reviews: [Review]\n }\n`\n```\n\n```text\nconst resolver = {\n Query: {\n top100Reviews: () => get100Reviews(),\n },\n Review: {\n author: (review) => getUser(review.authorId),\n },\n}\n```\n\n```text\nReview\n```\n\n```text\nJOIN\n```\n\n```text\nget100Reviews\n```\n\n```text\nQuery\n```\n\n```text\nReview\n```\n\n```text\nJOIN\n```\n\n```text\nQuery\n```\n\n```text\n{\n reviews {\n author {\n reviews {\n author\n }\n }\n }\n}\n```\n\n```text\nJOIN\n```\n\n```text\nGraphQLResolveInfo\n```\n\n```text\ninfo\n```\n\n```text\ndataloader\n```\n\n========================================\n\nComments:\n- each type can be asked separately - each one [usually] has own resolver ... in parent resolver you don't know if/how many child [fields] you should read/return beside current object [level] ... search about `dataloader` project\n- Hasura actually has great documentation on how they solve this problem through compiling graphQL queries to SQL. hasura.io/blog/graphql-in-production-hasura-cloud/#performan‌​ce github.com/hasura/graphql-engine/blob/master/architecture/…","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":182,"estimatedTokens":762}}250{"id":"stack-43306989","source":"stackoverflow","questionId":43306989,"title":"Relay vs Redux vs Apollo with GraphQL and React-Native","tags":["reactjs","react-native","redux","graphql","relayjs"],"text":"Title: Relay vs Redux vs Apollo with GraphQL and React-Native\nTags: reactjs, react-native, redux, graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nI have to start a new (web + native) project (mid-size app) from scratch. Due to the plethora of JS frameworks and implementation out there especially in the last couple of years, I have been having a second doubt on my usual stack.\n\nI have been using react + redux on the front-end along with Node and MongoDB on the backend communicating through REST API's.\n\nFor this new project, I have decided to go with React-Native + React Native for Web + Node + PostgreSQL. However, I am wondering which framework I should use to the data fetching and state/store management.\n\nSo far, redux worked for me nicely. However, due to the nature of JS evolution. I am a bit skeptical with go the same stack I have been using in the past.\n\nWhat are the pros and cons if I go with the following stack\n\n```\nReact-Native + React-Native-For-Web + Redux + GraphQL + Node + PostgreSQL\n\nReact-Native + React-Native-For-Web + Relay + GraphQL + Node + PostgreSQL\n\nReact-Native + React-Native-For-Web + Apollo + GraphQL + Node + PostgreSQL\n```\n\nI have read many articles stating the benefits of using each framework, but the amount of content and articles are a bit scary. I understand that there is no right or wrong answer. However, it would be nice to know which aforementioned stack goes nicely together keeping in mind - less learning curve, good documentation, maintainability, fewer workarounds.\n\n========================================\n\nCode:\n```text\nReact-Native + React-Native-For-Web + Redux + GraphQL + Node + PostgreSQL\n\n\nReact-Native + React-Native-For-Web + Relay + GraphQL + Node + PostgreSQL\n\n\nReact-Native + React-Native-For-Web + Apollo + GraphQL + Node + PostgreSQL\n```\n\n```text\nupdateQueries\n```\n\n========================================\n\nComments:\n- Thanks for the detailed answer. Could you please tell me what is the major difference between (graphql-server and Graphcool) in terms of speeding up the development cycle. How graphql-server and GraphCool are different from each other.\n- without knowing too much about `graphql-server`, I think the major difference is that Graphcool provides a full-blown and hosted solution whereas `graphql-server` is a tool that helps you build your own GraphQL server. so depending on what your goals are, one or the other might be better suited :) if you're interested into learning more about how GraphQL works on the server, then `graphql-server` will surely serve you better! if you just want to build an app as fast as possible Graphcool might be more helpful since you don't have to do any server-related work.\n- Thanks. I need to go through the Graphcool docs in depth. At the moment I'm wondering what data do you store on your servers. For e.g, if my application is hosted on Heroku. How does my hosted app is communicating with Graphcool and what data is actually stored on your servers.\n- I guess it's time to edit this answer. Relay API changes has made it really simple to use.","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":49,"estimatedTokens":769}}251{"id":"stack-65764361","source":"stackoverflow","questionId":65764361,"title":"How can I get more error details or logging, when an exception is thrown in a HotChocolate GraphQL server?","tags":["c#","asp.net-core","graphql","hotchocolate"],"text":"Title: How can I get more error details or logging, when an exception is thrown in a HotChocolate GraphQL server?\nTags: c#, asp.net-core, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nIβm building out a simple HotChocolate GraphQl server and HotChocolate throws an `Unexpected Execution Error`, but doesn't expose any information about the error, as soon as I post a request against it.\nIt doesn't matter how I post the request against the backend (BananaCakePop, Postman, Insomnia, ...).\n\nThe reponse looks like this:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Unexpected Execution Error\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"pong\"\n ]\n }\n ],\n \"data\": {\n \"pong\": null\n }\n}\n```\n\nThe request response contains no further information and nothing is logged to the applications console.\nWhat would be a reasonable next step to try and figure out what went wrong?\n\n========================================\n\nTop Answer:\nI'm in the same boat, also needing exception details\n\nand nothing is logged to the applications console\n\nI suggest this is where we should add error logging, as opposed to the response returned to the GraphQL client.\n\nSetting up proper logging will help us in Production as well as Development envs, if we run into an issue there.\n\nWe'll need to hook into Hot Chocolate's Diagnostics. There are several types of diagnostic events, I'm just going to set up one for execution events, as that's where the error is in my case. I was only able to test ResolverError, but the rest should work.\n\n```\npublic class ErrorLoggingDiagnosticsEventListener : ExecutionDiagnosticEventListener\n {\n private readonly ILogger log;\n\n public ErrorLoggingDiagnosticsEventListener(\n ILogger log)\n {\n this.log = log;\n }\n\n public override void ResolverError(\n IMiddlewareContext context,\n IError error)\n {\n log.LogError(error.Exception, error.Message);\n }\n\n public override void TaskError(\n IExecutionTask task,\n IError error)\n {\n log.LogError(error.Exception, error.Message);\n }\n\n public override void RequestError(\n IRequestContext context,\n Exception exception)\n {\n log.LogError(exception, \"RequestError\");\n }\n\n public override void SubscriptionEventError(\n SubscriptionEventContext context,\n Exception exception)\n {\n log.LogError(exception, \"SubscriptionEventError\");\n }\n\n public override void SubscriptionTransportError(\n ISubscription subscription,\n Exception exception)\n {\n log.LogError(exception, \"SubscriptionTransportError\");\n }\n }\n```\n\nNow wire that up in startup config.\n\n```\npublic void ConfigureServices(IServiceCollection services)\n {\n services\n .AddGraphQLServer()\n .AddDiagnosticEventListener()\n ...\n ;\n }\n```\n\nExceptions are now logged to your configured sink for ILogger.\n\n========================================\n\nCode:\n```json\n{\n \"errors\": [\n {\n \"message\": \"Unexpected Execution Error\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"pong\"\n ]\n }\n ],\n \"data\": {\n \"pong\": null\n }\n}\n```\n\n```text\nUnexpected Execution Error\n```\n\n```cs\npublic class Startup\n{\n private readonly IWebHostEnvironment _env;\n\n public Startup(IWebHostEnvironment env)\n {\n _env = env;\n }\n\n public void ConfigureServices(IServiceCollection services)\n {\n services\n .AddGraphQLServer()\n ...\n // You can change _env.IsDevelopment() to whatever condition you want.\n // If the condition evaluates to true, the server will expose it's exceptions details\n // within the reponse.\n .ModifyRequestOptions(opt => opt.IncludeExceptionDetails = _env.IsDevelopment()); \n }\n}\n```\n\n```cs\npublic class Startup\n{\n private readonly IWebHostEnvironment _env;\n\n public Startup(IWebHostEnvironment env)\n {\n _env = env;\n }\n\n public void ConfigureServices(IServiceCollection services)\n {\n services.AddGraphQL(\n Schema.Create(builder =>\n {\n ...\n }),\n // You can change _env.IsDevelopment() to whatever condition you want.\n // If the condition evaluates to true, the server will expose it's exceptions details\n // within the reponse.\n new QueryExecutionOptions {IncludeExceptionDetails = _env.IsDevelopment()}\n );\n }\n}\n```\n\n```cs\npublic class ErrorLoggingDiagnosticsEventListener : ExecutionDiagnosticEventListener\n {\n private readonly ILogger<ErrorLoggingDiagnosticsEventListener> log;\n\n public ErrorLoggingDiagnosticsEventListener(\n ILogger<ErrorLoggingDiagnosticsEventListener> log)\n {\n this.log = log;\n }\n\n public override void ResolverError(\n IMiddlewareContext context,\n IError error)\n {\n log.LogError(error.Exception, error.Message);\n }\n\n public override void TaskError(\n IExecutionTask task,\n IError error)\n {\n log.LogError(error.Exception, error.Message);\n }\n\n public override void RequestError(\n IRequestContext context,\n Exception exception)\n {\n log.LogError(exception, \"RequestError\");\n }\n\n public override void SubscriptionEventError(\n SubscriptionEventContext context,\n Exception exception)\n {\n log.LogError(exception, \"SubscriptionEventError\");\n }\n\n public override void SubscriptionTransportError(\n ISubscription subscription,\n Exception exception)\n {\n log.LogError(exception, \"SubscriptionTransportError\");\n }\n }\n```\n\n```cs\npublic void ConfigureServices(IServiceCollection services)\n {\n services\n .AddGraphQLServer()\n .AddDiagnosticEventListener<ErrorLoggingDiagnosticsEventListener>()\n ...\n ;\n }\n```\n\n========================================\n\nComments:\n- What you say is simply wrong. Please check: stackoverflow.com/help/self-answer\n- That *doesn't* change what I said. You can and are encouraged to answer your own questions, but those questions *need* to be valid too. Please read How to Ask\n- @JayChase which is what the answer says (except for IsDev instead of true).","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":254,"estimatedTokens":1572}}252{"id":"stack-40901845","source":"stackoverflow","questionId":40901845,"title":"How to create a nested resolver in apollo graphql server","tags":["graphql","apollostack","apollo-server"],"text":"Title: How to create a nested resolver in apollo graphql server\nTags: graphql, apollostack, apollo-server\nSource: Stack Overflow\n\nQuestion:\nGiven the following apollo server graphql schema\nI wanted to break these down into separate modules so I don't want the author query under the root Query schema.. and want it separated. So i added another layer called authorQueries before adding it to the Root Query\n\n```\ntype Author {\n id: Int,\n firstName: String,\n lastName: String\n} \ntype authorQueries {\n author(firstName: String, lastName: String): Author\n}\n\ntype Query {\n authorQueries: authorQueries\n}\n\nschema {\n query: Query\n}\n```\n\nI tried the following.. you can see that authorQueries was added as another layer before the author function is specified.\n\n```\nQuery: {\n authorQueries :{\n author (root, args) {\n return {}\n }\n }\n}\n```\n\nWhen querying in Graphiql, I also added that extra layer.. \n\n```\n{\n authorQueries {\n author(firstName: \"Stephen\") {\n id\n }\n }\n}\n```\n\nI get the following error.\n\n`\"message\": \"Resolve function for \\\"Query.authorQueries\\\" returned undefined\",`\n\n========================================\n\nTop Answer:\n`Query.libraries()` > `Library.books()` > `Book.author()` > `Author.name()`\n\nApollo Official related docs (**Great** example inside):\n\n### Resolver chains\n\nhttps://www.apollographql.com/docs/apollo-server/data/resolvers/#resolver-chains\n\n```\n/* code from:\nhttps://www.apollographql.com/docs/apollo-server/data/resolvers/#resolver-chains\n*/\n\nconst { ApolloServer, gql } = require('apollo-server');\n\nconst libraries = [\n {\n branch: 'downtown'\n },\n {\n branch: 'riverside'\n },\n];\n\n// The branch field of a book indicates which library has it in stock\nconst books = [\n {\n title: 'The Awakening',\n author: 'Kate Chopin',\n branch: 'riverside'\n },\n {\n title: 'City of Glass',\n author: 'Paul Auster',\n branch: 'downtown'\n },\n];\n\n// Schema definition\nconst typeDefs = gql`\n\n# A library has a branch and books\n type Library {\n branch: String!\n books: [Book!]\n }\n\n # A book has a title and author\n type Book {\n title: String!\n author: Author!\n }\n\n # An author has a name\n type Author {\n name: String!\n }\n\n # Queries can fetch a list of libraries\n type Query {\n libraries: [Library]\n }\n`;\n\n// Resolver map\nconst resolvers = {\n Query: {\n libraries() {\n\n // Return our hardcoded array of libraries\n return libraries;\n }\n },\n Library: {\n books(parent) {\n\n // Filter the hardcoded array of books to only include\n // books that are located at the correct branch\n return books.filter(book => book.branch === parent.branch);\n }\n },\n Book: {\n\n // The parent resolver (Library.books) returns an object with the\n // author's name in the \"author\" field. Return a JSON object containing\n // the name, because this field expects an object.\n author(parent) {\n return {\n name: parent.author\n };\n }\n }\n\n // Because Book.author returns an object with a \"name\" field,\n // Apollo Server's default resolver for Author.name will work.\n // We don't need to define one.\n};\n\n// Pass schema definition and resolvers to the\n// ApolloServer constructor\nconst server = new ApolloServer({ typeDefs, resolvers });\n\n// Launch the server\nserver.listen().then(({ url }) => {\n console.log(`π Server ready at ${url}`);\n});\n```\n\n========================================\n\nCode:\n```text\ntype Author {\n id: Int,\n firstName: String,\n lastName: String\n} \ntype authorQueries {\n author(firstName: String, lastName: String): Author\n}\n\ntype Query {\n authorQueries: authorQueries\n}\n\nschema {\n query: Query\n}\n```\n\n```text\nQuery: {\n authorQueries :{\n author (root, args) {\n return {}\n }\n }\n}\n```\n\n```text\n{\n authorQueries {\n author(firstName: \"Stephen\") {\n id\n }\n }\n}\n```\n\n```text\n\"message\": \"Resolve function for \\\"Query.authorQueries\\\" returned undefined\",\n```\n\n```text\n{\n Query: { authorQueries: () => ({}) },\n authorQueries: {\n author(root, args) {\n return \"Hello, world!\";\n }\n }\n}\n```\n\n```text\nauthorQueries\n```\n\n```text\nauthorQueries\n```\n\n```text\nimport {\n graphql,\n} from 'graphql';\n\nimport {\n makeExecutableSchema, IResolverObject\n} from 'graphql-tools';\n\nconst types = `\ntype Query {\n person: User\n}\n\ntype User {\n id: ID\n name: String,\n dog(showCollar: Boolean): Dog\n}\n\ntype Dog {\n name: String\n}\n`;\n\nconst User: IResolverObject = {\n dog(obj, args, ctx) {\n console.log('Dog Arg 1', obj);\n return {\n name: 'doggy'\n };\n }\n};\n\nconst resolvers = {\n User,\n Query: {\n person(obj) {\n console.log('Person Arg 1', obj);\n return {\n id: 'foo',\n name: 'bar',\n };\n }\n }\n};\n\nconst schema = makeExecutableSchema({\n typeDefs: [types],\n resolvers\n});\n\nconst query = `{ \n person {\n name,\n dog(showCollar: true) {\n name\n }\n }\n }`;\n\n\ngraphql(schema, query).then(result => {\n console.log(JSON.stringify(result, null, 2));\n});\n\n// Person Arg 1 undefined\n// Dog Arg 1 { id: 'foo', name: 'bar' }\n// {\n// \"data\": {\n// \"person\": {\n// \"name\": \"bar\",\n// \"dog\": {\n// \"name\": \"doggy\"\n// }\n// }\n// }\n// }\n```\n\n```text\nthis\n```\n\n```text\naddResolveFunctionsToSchema\n```\n\n```js\n/* code from:\nhttps://www.apollographql.com/docs/apollo-server/data/resolvers/#resolver-chains\n*/\n\nconst { ApolloServer, gql } = require('apollo-server');\n\nconst libraries = [\n {\n branch: 'downtown'\n },\n {\n branch: 'riverside'\n },\n];\n\n// The branch field of a book indicates which library has it in stock\nconst books = [\n {\n title: 'The Awakening',\n author: 'Kate Chopin',\n branch: 'riverside'\n },\n {\n title: 'City of Glass',\n author: 'Paul Auster',\n branch: 'downtown'\n },\n];\n\n// Schema definition\nconst typeDefs = gql`\n\n# A library has a branch and books\n type Library {\n branch: String!\n books: [Book!]\n }\n\n # A book has a title and author\n type Book {\n title: String!\n author: Author!\n }\n\n # An author has a name\n type Author {\n name: String!\n }\n\n # Queries can fetch a list of libraries\n type Query {\n libraries: [Library]\n }\n`;\n\n// Resolver map\nconst resolvers = {\n Query: {\n libraries() {\n\n // Return our hardcoded array of libraries\n return libraries;\n }\n },\n Library: {\n books(parent) {\n\n // Filter the hardcoded array of books to only include\n // books that are located at the correct branch\n return books.filter(book => book.branch === parent.branch);\n }\n },\n Book: {\n\n // The parent resolver (Library.books) returns an object with the\n // author's name in the \"author\" field. Return a JSON object containing\n // the name, because this field expects an object.\n author(parent) {\n return {\n name: parent.author\n };\n }\n }\n\n // Because Book.author returns an object with a \"name\" field,\n // Apollo Server's default resolver for Author.name will work.\n // We don't need to define one.\n};\n\n// Pass schema definition and resolvers to the\n// ApolloServer constructor\nconst server = new ApolloServer({ typeDefs, resolvers });\n\n// Launch the server\nserver.listen().then(({ url }) => {\n console.log(`π Server ready at ${url}`);\n});\n```\n\n```text\nQuery.libraries()\n```\n\n```text\nLibrary.books()\n```\n\n```text\nBook.author()\n```\n\n```text\nAuthor.name()\n```\n\n========================================\n\nComments:\n- Related Apollo docs: apollographql.com/docs/apollo-server/data/resolvers/…\n- Just wondering If It's good for designing gql like this. `authorQueires`, `productQueries`...etc or by authorization meaning. I think It's not bad, but less seen.\n- Is there not an better way, like defining a resolver for the author type, which uses some values of the overgiven root parameter? When i do it like this i have make a resolver for everytime a auther is used in an other type\n- Yep, you need to define a resolver for every field that returns an Author, at least in current GraphQL implementations. Could be better in the future.\n- I like your angle about GraphQL not having \"nested\" resolvers. I had struggled through quite a lot of documentations until I realized that..\n- This does not work for depth > 1. Resolvers can only be defined for properties on the type returned from the query, they cannot be defined for properties on these properties. Unless i'm missing something, this is a major performance issue as you end up performing computations that aren't necessary on every request.\n- I have tested `authorQueries: () => ({})` returning the empty object actually worked. If TypeScript complains, you can simply do the casting: `authorQueries: () => ({} as authorQueries)`\n- This doesn't work if `authorQueries` isn't nullable. And it would be very reasonable for `authorQueries` to be non-nullable - why would we ever return `null` for `authorQuery`?","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":446,"estimatedTokens":2184}}253{"id":"stack-57040429","source":"stackoverflow","questionId":57040429,"title":"How to split a long GraphQL schema","tags":["javascript","graphql"],"text":"Title: How to split a long GraphQL schema\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a Schema, however is going to get too long and confusing, what are the best practices to split the different queries, mutations and inputs so I can just require them and organize them to make it easy to read.\n\nI have tried to find information online but there is nothing clear at all and I am trying not to use Apollo.\n\n```\nconst { buildSchema } = require('graphql');\n\nmodule.exports = buildSchema(`\ntype Region {\n _id: ID!\n name: String!\n countries: [Country!]\n}\n\ntype Country {\n _id: ID!\n name: String!\n region: [Region!]!\n}\n\ntype City {\n _id: ID!\n name: String!\n country: [Country!]!\n}\n\ntype Attraction {\n _id: ID!\n name: String!\n price: Float!\n description: String!\n city: [City!]!\n}\n\ntype Eatery {\n _id: ID!\n name: String!\n cuisine: String!\n priceRange: String!\n location: [Location!]!\n typeOfEatery: String!\n city: [City!]!\n}\n\ntype Location {\n _id: ID!\n latitude: String!\n longitude: String!\n address: Float\n}\n\ntype User {\n _id: ID!\n email: String!\n password: String!\n}\n\ntype AuthData {\n userId: ID!\n token: String!\n tokenExpiration: String!\n}\n\ntype RegionInput {\n name: String!\n}\n\ntype CountryInput {\n name: String!\n}\n\ntype CityInput {\n name: String!\n}\n\ntype RootQuery {\n regions: [Region!]!\n countries: [Country!]!\n login(email: String!, password: String!): AuthData!\n}\n\ntype RootMutation {\n createRegion(regionInput: RegionInput): Region\n createCountry(countryInput: CountryInput): Country\n createCity(cityInput: CityInput): City\n}\n\nschema {\n query: RootQuery\n mutation: RootMutation\n}\n`);\n```\n\nI need something that is very organized and allows me to get everything in order and clear, merge all files in one index is the best solution.\n\n========================================\n\nTop Answer:\nMake it separate folder and structure as well to make codes maintainable I do the following:\n\nGraphQL Example Repository\n\nFile Structure Screenshot\n\n\r\n\r\n\n```\nconst express = require('express');\nconst glob = require(\"glob\");\nconst {graphqlHTTP} = require('express-graphql');\nconst {makeExecutableSchema, mergeResolvers, mergeTypeDefs} = require('graphql-tools');\nconst app = express();\n//iterate through resolvers file in the folder \"graphql/folder/folder/whatever*-resolver.js\"\nlet resolvers = glob.sync('graphql/*/*/*-resolver.js')\nlet registerResolvers = [];\nfor (const resolver of resolvers){\n// add resolvers to array\n registerResolvers = [...registerResolvers, require('./'+resolver),]\n}\n//iterate through resolvers file in the folder \"graphql/folder/folder/whatever*-type.js\"\nlet types = glob.sync('graphql/*/*/*-type.js')\nlet registerTypes = [];\nfor (const type of types){\n// add types to array\n registerTypes = [...registerTypes, require('./'+type),]\n}\n//make schema from typeDefs and Resolvers with \"graphql-tool package (makeExecutableSchema)\"\nconst schema = makeExecutableSchema({\n typeDefs: mergeTypeDefs(registerTypes),//merge array types\n resolvers: mergeResolvers(registerResolvers,)//merge resolver type\n})\n// mongodb connection if you prefer mongodb\nrequire('./helpers/connection');\n// end mongodb connection\n//Make it work with express \"express and express-graphql packages\"\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n graphiql: true,//test your query or mutation on browser (Development Only)\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at http://localhost:4000/graphql');\n```\n\n========================================\n\nCode:\n```text\nconst { buildSchema } = require('graphql');\n\nmodule.exports = buildSchema(`\ntype Region {\n _id: ID!\n name: String!\n countries: [Country!]\n}\n\ntype Country {\n _id: ID!\n name: String!\n region: [Region!]!\n}\n\ntype City {\n _id: ID!\n name: String!\n country: [Country!]!\n}\n\ntype Attraction {\n _id: ID!\n name: String!\n price: Float!\n description: String!\n city: [City!]!\n}\n\ntype Eatery {\n _id: ID!\n name: String!\n cuisine: String!\n priceRange: String!\n location: [Location!]!\n typeOfEatery: String!\n city: [City!]!\n}\n\ntype Location {\n _id: ID!\n latitude: String!\n longitude: String!\n address: Float\n}\n\ntype User {\n _id: ID!\n email: String!\n password: String!\n}\n\ntype AuthData {\n userId: ID!\n token: String!\n tokenExpiration: String!\n}\n\ntype RegionInput {\n name: String!\n}\n\ntype CountryInput {\n name: String!\n}\n\ntype CityInput {\n name: String!\n}\n\ntype RootQuery {\n regions: [Region!]!\n countries: [Country!]!\n login(email: String!, password: String!): AuthData!\n}\n\ntype RootMutation {\n createRegion(regionInput: RegionInput): Region\n createCountry(countryInput: CountryInput): Country\n createCity(cityInput: CityInput): City\n}\n\nschema {\n query: RootQuery\n mutation: RootMutation\n}\n`);\n```\n\n```text\nconst countryType = `\ntype Country {\n _id: ID!\n name: String!\n region: [Region!]!\n}\n`\n\nconst regionType = `\ntype Region {\n _id: ID!\n name: String!\n countries: [Country!]\n}\n`\n\nconst schema = `\n${countryType}\n${regionType}\n\n# ... more stuff ...\n`\n\nmodule.exports = buildSchema(schema);\n```\n\n```js\nconst express = require('express');\nconst glob = require(\"glob\");\nconst {graphqlHTTP} = require('express-graphql');\nconst {makeExecutableSchema, mergeResolvers, mergeTypeDefs} = require('graphql-tools');\nconst app = express();\n//iterate through resolvers file in the folder \"graphql/folder/folder/whatever*-resolver.js\"\nlet resolvers = glob.sync('graphql/*/*/*-resolver.js')\nlet registerResolvers = [];\nfor (const resolver of resolvers){\n// add resolvers to array\n registerResolvers = [...registerResolvers, require('./'+resolver),]\n}\n//iterate through resolvers file in the folder \"graphql/folder/folder/whatever*-type.js\"\nlet types = glob.sync('graphql/*/*/*-type.js')\nlet registerTypes = [];\nfor (const type of types){\n// add types to array\n registerTypes = [...registerTypes, require('./'+type),]\n}\n//make schema from typeDefs and Resolvers with \"graphql-tool package (makeExecutableSchema)\"\nconst schema = makeExecutableSchema({\n typeDefs: mergeTypeDefs(registerTypes),//merge array types\n resolvers: mergeResolvers(registerResolvers,)//merge resolver type\n})\n// mongodb connection if you prefer mongodb\nrequire('./helpers/connection');\n// end mongodb connection\n//Make it work with express \"express and express-graphql packages\"\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n graphiql: true,//test your query or mutation on browser (Development Only)\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at http://localhost:4000/graphql');\n```\n\n```text\ngraphql-tools\n```\n\n```text\napollo-server\n```\n\n```js\nimport { readFileSync } from \"fs\";\nimport path from \"path\";\n\nfunction getTypeDefs(filename: string) {\n return gql(readFileSync(path.join(process.cwd(), 'resources', filename), 'utf8'));\n}\n```\n\n```text\n.\nβββ src\nβΒ βββ server.ts\nβββ resources\n Β Β βββ other.graphql\n Β Β βββ schema.graphql\n```\n\n```js\nimport { ApolloServer, gql } from \"apollo-server-express\";\nimport { makeExecutableSchema } from \"graphql-tools\";\n\nconst server = new ApolloServer({\n schema: makeExecutableSchema({\n typeDefs: [getTypeDefs('schema.graphql'), getTypeDefs('other.graphql')],\n resolvers: YourResolvers\n })\n});\n```\n\n```text\nexport interface IGraphqlSchema {\n type?: string,\n query?: string,\n input?: string,\n mutation?: string,\n\n\n}\n```\n\n```text\nexport const sharedGraphqlSchema = {\n scalar: `\n scalar Void\n scalar Any\n `,\n\n rootSchema:\n `\nschema {\nquery: RootQuery\nmutation: RootMutation\n}`\n ,\n rootQuery: \"\\ntype RootQuery {\",\n\n rootMutation: \"\\ntype RootMutation {\",\n\n\n};\n```\n\n```text\nimport { IGraphqlSchema } from \"core/interfaces/graphql.schema\";\nimport { sharedGraphqlSchema } from \"./shared.graphql.schema\";\n\n\nexport function combineSchemaGraphql(schemas: IGraphqlSchema[]): string {\n\n let combine: string = \"\";\n combine = combine.concat(sharedGraphqlSchema.scalar);\n let temp: string = \"\";\n\n\n for (let index = 0; index < 4; index++) {\n for (let j = 0; j < schemas.length; j++) {\n const item = schemas[j];\n switch (index) {\n case 0:\n combine = combine.concat(item.type);\n break;\n case 1:\n combine = combine.concat(item.input);\n break;\n case 2:\n temp = temp.concat(item.query);\n\n break;\n\n default:\n temp = temp.concat(item.mutation);\n break;\n }\n\n }\n\n if (index == 2) {\n combine = combine.concat(sharedGraphqlSchema.rootQuery);\n combine = combine.concat(temp);\n combine = combine.concat(\"\\n}\");\n temp = \"\";\n }\n if (index == 3) {\n combine = combine.concat(sharedGraphqlSchema.rootMutation);\n combine = combine.concat(temp);\n combine = combine.concat(\"\\n}\");\n }\n\n }\n\n combine = combine.concat(sharedGraphqlSchema.rootSchema);\n\n return combine;\n}\n```\n\n```text\nimport { IGraphqlSchema } from \"../../../core/interfaces/graphql.schema\";\n\nexport const profileSchema: IGraphqlSchema = {\n\n type:\n `\n type Profile {\n _id: ID!\n firstName: String\n lastName: String\n userName: String\n password: String\n email: String\n phone: String\n image: String\n address: String\n gender: Boolean\n country: String\n city: String\n active: Boolean\n status: Boolean\n statusMessage: String\n createdAt: String\n updatedAt: String\n deletedAt: String\n }\n `,\n input:\n `\n input ProfileInputData {\n image: String\n firstName: String\n lastName: String\n country: String\n city: String\n password: String\n passConfirm: String\n }`,\n query:\n `\n profile: Profile!\n`,\n mutation: `\n profileUpdate(inputs: ProfileInputData): Void\n `\n};\n```\n\n```text\nimport { NextFunction, Request, Response } from \"express\";\nimport { StatusCodes } from \"http-status-codes\";\nimport { default as i18n } from \"i18next\";\nimport { RequestWithUser } from \"../../auth/interfaces/reqeust.with.user.interface\";\nimport ProfileService from \"../services/profile.service\";\nimport { UserEntity } from \"../entities/user.entity\";\nimport { IUser } from \"../../auth/interfaces/user.interface\";\nimport { isEmpty } from \"./../../shared/utils/is.empty\";\nimport { IMulterFile } from \"./../../shared/interfaces/multer.file.interface\";\nimport { optimizeImage } from \"./../../shared/utils/optimize.image\";\nimport { commonConfig } from \"./../../common/configs/common.config\";\nimport { IUserLogIn } from \"@/modules/auth/interfaces/Log.in.interface\";\nimport { ProfileValidation } from \"@/modules/common/validations/profile.validation\";\nimport { HttpException } from \"@/core/exceptions/HttpException\";\nimport { validateOrReject, Validator } from \"class-validator\";\nimport { warpValidationError } from \"@/core/utils/validator.checker\";\nimport { sharedConfig } from \"@/modules/shared/configs/shared.config\";\n\nexport const ProfileResolver = {\n\n profile: async function({ inputs }, req: RequestWithUser): Promise<void | any> {\n\n\n const user: IUserLogIn = req.user;\n\n const profileService = new ProfileService();\n const findOneData: IUser = await profileService.show(user._id);\n\n return {\n ...findOneData._doc\n };\n\n },\n\n\n profileUpdate: async function({ inputs }, req: RequestWithUser): Promise<void | Object> {\n\n const profileValidation = new ProfileValidation(inputs);\n\n try {\n await validateOrReject(profileValidation);\n\n } catch (e) {\n warpValidationError(e);\n }\n\n const user: IUserLogIn = req.user;\n const userEntity = new UserEntity(inputs);\n await userEntity.updateNow().generatePasswordHash();\n const profileService = new ProfileService();\n if (!isEmpty(req.file)) {\n\n const file: IMulterFile = req.file;\n // userEntity.image = commonConfig.profileDirectory + file.filename;\n userEntity.image = sharedConfig.publicRoot + file.filename;\n await optimizeImage(file.destination + file.filename, 200, 200, 60);\n }\n\n const updateData: IUser = await profileService.update(user._id, userEntity);\n\n\n\n }\n\n\n};\n```\n\n```text\nimport { settingSchema } from \"@/modules/common/schemas/setting.schema\";\n\nprocess.env[\"NODE_CONFIG_DIR\"] = __dirname + \"/core/configs\";\nimport \"dotenv/config\";\nimport App from \"./app\";\nimport { merge } from \"lodash\";\nimport { combineSchemaGraphql } from \"./core/utils/merge.graphql.type\";\nimport { authSchema } from \"@/modules/auth/schemas/auth.schema\";\nimport { profileSchema } from \"@/modules/common/schemas/profile.schema\";\nimport { AuthResolver } from \"@/modules/auth/resolvers/auth.resolver\";\nimport { ProfileResolver } from \"@/modules/common/resolvers/profile.resolver\";\nimport { SettingResolver } from \"@/modules/common/resolvers/setting.resolver\";\nimport { sharedSchema } from \"@/modules/shared/schemas/shared.schema\";\n\nconst rootQuery = combineSchemaGraphql(\n [\n sharedSchema,\n authSchema,\n profileSchema,\n settingSchema]);\n\nconst mutation = merge(\n AuthResolver,\n ProfileResolver,\n SettingResolver);\n\nconst app = new App(rootQuery, mutation);\napp.listen();\n```\n\n```text\nimport { AppInterface } from \"./core/interfaces/app.interface\";\n\nprocess.env[\"NODE_CONFIG_DIR\"] = __dirname + \"/core/configs\";\n\nimport compression from \"compression\";\nimport cookieParser from \"cookie-parser\";\nimport config from \"config\";\nimport express from \"express\";\nimport helmet from \"helmet\";\nimport hpp from \"hpp\";\nimport morgan from \"morgan\";\nimport { connect, set } from \"mongoose\";\nimport swaggerJSDoc from \"swagger-jsdoc\";\nimport swaggerUi from \"swagger-ui-express\";\nimport * as path from \"path\";\nimport * as fs from \"fs\";\nimport i18nMiddleware from \"i18next-express-middleware\";\nimport { default as i18n } from \"i18next\";\nimport Backend from \"i18next-node-fs-backend\";\nimport { LanguageDetector } from \"i18next-express-middleware\";\nimport { dbConnection } from \"./core/databases/database.config\";\nimport errorMiddleware from \"./core/middlewares/error.middleware\";\nimport { logger, stream } from \"./core/utils/logger\";\nimport contentNegotiationMiddleware from \"./modules/common/middlewares/content.negotiation.middleware\";\nimport corsMiddleware from \"./modules/common/middlewares/cors.middleware\";\nimport userAgent from \"express-useragent\";\nimport { graphqlHTTP } from \"express-graphql\";\nimport { buildSchema } from \"graphql\";\nimport authMiddleware from \"@/modules/auth/middlewares/auth.middleware\";\nimport multer from \"multer\";\nimport { multerFunctions, multerFileFilter } from \"@/modules/shared/utils/multer.functions\";\nimport { sharedConfig } from \"@/modules/shared/configs/shared.config\";\n\nclass App implements AppInterface {\n public app: express.Application;\n public port: string | number;\n public env: string;\n\n constructor(schema: string, resolver: object) {\n this.app = express();\n this.port = process.env.PORT || 4000;\n this.env = process.env.NODE_ENV || \"development\";\n this.initializeI18n();\n this.connectToDatabase();\n this.initializeMiddlewares();\n this.initializeSwagger();\n this.initializeErrorHandling();\n this.initGraphql(schema, resolver);\n\n }\n\n public listen(): void {\n this.app.listen(this.port, () => {\n logger.info(`==== typescript express.js modular graphql kick starter ====`);\n logger.info(`===== by ===== `);\n logger.info(`https://github.com/yasinpalizban`);\n logger.info(`======= ENV: ${this.env} =======`);\n logger.info(`π App listening on the port ${this.port}`);\n\n });\n }\n\n public getServer(): express.Application {\n return this.app;\n }\n\n private connectToDatabase(): void {\n if (this.env !== \"production\") {\n set(\"debug\", true);\n }\n\n connect(dbConnection.url, dbConnection.options);\n\n }\n\n private initializeMiddlewares(): void {\n this.app.use(morgan(config.get(\"log.format\"), { stream }));\n this.app.use(corsMiddleware);\n this.app.use(hpp());\n this.app.use(helmet());\n this.app.use(compression());\n this.app.use(express.json());\n this.app.use(express.urlencoded({ extended: true }));\n this.app.use(cookieParser());\n this.app.use(userAgent.express());\n\n this.app.use(\"/public\", express.static(path.join(__dirname, \"public\")));\n this.app.use(authMiddleware);\n\n this.app.use(contentNegotiationMiddleware);\n\n\n const storage = multer.diskStorage({\n destination: sharedConfig.publicRoot,\n filename: multerFunctions\n });\n const maxSize = 4 * 1000 * 1000;\n const upload = multer({ storage: storage, fileFilter: multerFileFilter, limits: { fileSize: maxSize } });\n this.app.use(upload.array(\"image\"));\n\n }\n\n\n private initializeSwagger(): void {\n const options = {\n swaggerDefinition: {\n info: {\n title: \"REST API\",\n version: \"1.0.0\",\n description: \"Example docs\"\n }\n },\n apis: [\"swagger.yaml\"]\n };\n\n const specs = swaggerJSDoc(options);\n this.app.use(\"/api-docs\", swaggerUi.serve, swaggerUi.setup(specs));\n }\n\n\n private initializeI18n(): void {\n\n i18n\n .use(Backend)\n .use(LanguageDetector)\n .init({\n lng: \"en\",\n whitelist: [\"en\", \"fa\"],\n fallbackLng: \"en\",\n // have a common namespace used around the full app\n ns: [\"translation\"],\n debug: false,\n backend: {\n loadPath: path.join(__dirname + \"/locales/{{lng}}/{{ns}}.json\")\n // jsonIndent: 2\n },\n preload: [\"en\", \"fa\"]\n });\n this.app.use(i18nMiddleware.handle(i18n));\n\n }\n\n private initializeErrorHandling(): void {\n this.app.use(errorMiddleware);\n }\n\n private initGraphql(schema: string, resolver: object): void {\n\n this.app.use(\n \"/graphql\",\n graphqlHTTP({\n schema: buildSchema(schema),\n rootValue: resolver,\n graphiql: true,\n customFormatErrorFn: (error) => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack ? error.stack.split('\\n') : [],\n path: error.path,\n })\n // customFormatErrorFn(err) {\n // if (!err.originalError) {\n // return err;\n // }\n //\n // // @ts-ignore\n // const data = err.originalError.data;\n // const message = err.message || \"An error occurred.\";\n // // @ts-ignore\n // const code = err.originalError.status || 500;\n //\n // return { message: message, status: code, data: data };\n\n\n // }\n })\n );\n }\n\n}\n\nexport default App;\n```\n\n```bash\n#!/bin/bash\necho \"\" >schema.graphql\nfind schema -name \"*.graphql\" -exec cat {} \\; >>schema.graphql\n```\n\n```text\n.graphql\n```\n\n```text\nschema\n```\n\n```text\nschema.graphql\n```\n\n========================================\n\nComments:\n- So I can just create multiple files and them embed them into an index correct? I'll look into Apollo in the future because I rather learn first to do it without using any other library. I need to understand the whole process first, thanks for your help!\n- Yes, but I love the Apollo approach though\n- Make sure you have at least one test where you call \"buildSchema\" since there can be duplicates, and \"buildSchema\" should throw an error at you if any duplicates exist.\n- So do we need to use this command line every time we make a change to an existing schema or adding a new schema?\n- Without a watcher of some sort, yes, @shortduck. You could add this as an `npm script` target: docs.npmjs.com/cli/v9/using-npm/scripts","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":792,"estimatedTokens":4849}}254{"id":"stack-52816623","source":"stackoverflow","questionId":52816623,"title":"GraphQL post request in axios","tags":["reactjs","graphql","axios"],"text":"Title: GraphQL post request in axios\nTags: reactjs, graphql, axios\nSource: Stack Overflow\n\nQuestion:\nI have a problem with GraphQL. I want to send axios.post request to my server. I can do it in postman:\n\n```\n{\n \"query\":\"mutation{updateUserCity(userID: 2, city:\\\"test\\\"){id name age city knowledge{language frameworks}}} \"\n}\n```\n\nand in graphiql: \n\n```\nmutation {\n updateUserCity(userID: 2, city: \"test\") {\n id\n name\n age\n city\n knowledge {\n language\n frameworks\n }\n }\n}\n```\n\nbut can't do it in my code:(( here is my code snippet:\n\n```\nconst data = await axios.post(API_URL, {\n query: mutation updateUserCity(${ id }: Int!, ${ city }: String!) {\n updateUserCity(userID: ${ id }, city: ${ city }){\n id\n name\n age\n city\n knowledge{\n language\n frameworks\n }\n }\n }\n}, {\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n```\n\nwhat's wrong in my code?\n\n========================================\n\nTop Answer:\nI enjoy using the following syntax, which is similar to the accepted answer, but more explicit.\n\nNote that the `variables` object is nested inside of the `data` object, and is a sibling of the `query` object.\n\n```\nconst data = await axios({\n url: API_URL,\n method: 'post',\n headers: {\n 'Content-Type': 'application/json',\n // ...other headers\n },\n data: {\n query: `\n mutation updateUserCity($id: Int!, $city: String!) {\n updateUserCity(userID: $id, city: $city) {\n id\n name\n age\n city\n knowledge {\n language\n frameworks\n }\n }\n }\n `,\n variables: {\n id: 2,\n city: 'Test'\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\n{\n \"query\":\"mutation{updateUserCity(userID: 2, city:\\\"test\\\"){id name age city knowledge{language frameworks}}} \"\n}\n```\n\n```text\nmutation {\n updateUserCity(userID: 2, city: \"test\") {\n id\n name\n age\n city\n knowledge {\n language\n frameworks\n }\n }\n}\n```\n\n```text\nconst data = await axios.post(API_URL, {\n query: mutation updateUserCity(${ id }: Int!, ${ city }: String!) {\n updateUserCity(userID: ${ id }, city: ${ city }){\n id\n name\n age\n city\n knowledge{\n language\n frameworks\n }\n }\n }\n}, {\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n```\n\n```text\nconst data = await axios.post(API_URL, {\n query: `mutation updateUserCity($id: Int!, $city: String!) {\n updateUserCity(userID: $id, city: $city){\n id\n name\n age\n city\n knowledge{\n language\n frameworks\n }\n }\n }`,\n variables: {\n id: 2,\n city: 'Test'\n }\n}, {\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n```\n\n```text\nquery\n```\n\n```text\n$\n```\n\n```text\nvariables\n```\n\n```text\nconst data = await axios.post(API_URL, {\n query: `\n updateUserCity(userID: ${id}, city:${city}){\n id\n name\n age\n city\n knowledge{\n language\n frameworks\n }\n }\n `\n}, {\n headers: {\n 'Content-Type': 'application/json'\n }\n});\n```\n\n```text\nid\n```\n\n```text\ncity\n```\n\n```text\nlet id = \"5c9beed4a34c1303f3371a39\";\n let body = { \n query: `\n query {\n game(id:\"${id}\") {\n _id\n title\n }\n }\n `, \n variables: {}\n }\n let options = {\n headers: {\n 'Content-Type': 'application/json'\n }\n }\n axios.post('http://localhost:3938/api/v1/graphql',body, options)\n .then((response)=>{\n console.log(response);\n });\n```\n\n```js\nconst data = await axios({\n url: API_URL,\n method: 'post',\n headers: {\n 'Content-Type': 'application/json',\n // ...other headers\n },\n data: {\n query: `\n mutation updateUserCity($id: Int!, $city: String!) {\n updateUserCity(userID: $id, city: $city) {\n id\n name\n age\n city\n knowledge {\n language\n frameworks\n }\n }\n }\n `,\n variables: {\n id: 2,\n city: 'Test'\n }\n }\n});\n```\n\n```text\nvariables\n```\n\n```text\ndata\n```\n\n```text\nquery\n```\n\n```text\nasync asyncData() {\nconst data = {\n query: `query GET_POSTS($first: Int) {\n posts(first: $first) {\n edges {\n node {\n postId\n title\n excerpt\n date\n content\n author {\n node {\n username\n }\n }\n }\n }\n }\n }`,\n variables: {\n first: 5\n }\n}\n\nconst options = {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n data: data,\n url: 'http://localhost/graphql'\n};\n \ntry {\n const response = await axios(options);\n\n console.log(response.data.data.posts.edges);\n console.log(response.data.data.posts.edges.length);\n} catch (error) {\n console.error(error);\n}\n```\n\n```js\nconst email = \"test@gmail.com\";\nconst password = \"123\";\n\nconst data = await axios.post(\n API_URL.Loging,\n {\n query: `query{\n login(\n email:\"${email}\", \n password:\"${password}\"\n )\n {\n userId\n token\n }\n }`,\n }\n);\n```\n\n========================================\n\nComments:\n- Probably good reference, looks like the query string does not have data in it. medium.com/@stubailo/…\n- no, I tried that method, but it didn't help\n- graphql.org/graphql-js/passing-arguments\n- This is not how it's supposed to be done. GraphQL has a dedicated variable interface and this can easily break when input contains quotes.\n- I had to wrap the curly braces in variables in backticks to make it work\n- What if arguments is of custom type? then how to do it?\n- @DevAKS: I did not understand what you meant by custom type. Can you please example?\n- @Raeesaa you are accepting argument in your mutation as Int and String variable, so instead let's say you have user defined type for example - Location {lat: Int, lng: Int}\n- @DevAKS graphql.org/learn/queries/#variables graphql.org/learn/schema/#input-types\n- `axios.post()` has three args if `headers` are needed, otherwise 2.\n- This is not how it's supposed to be done. GraphQL has a dedicated variable interface and this can easily break when input contains quotes.\n- This worked for me, with a few modifications. Thank you!\n- using string literals for variables is abusing graphql, far less safe/readable/manageable\n- Is there `JSON.stringify()` needed for `data`?\n- @Timo there is no need to `JSON.stringify()` the `data` with axios. For reference: axios-http.com/docs/api_intro","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":353,"estimatedTokens":1651}}255{"id":"stack-58889341","source":"stackoverflow","questionId":58889341,"title":"What should be the GraphQL mutation return type when there is no data to return?","tags":["javascript","rest","graphql","apollo","apollo-server"],"text":"Title: What should be the GraphQL mutation return type when there is no data to return?\nTags: javascript, rest, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI have an Apollo GraphQL server and I have a mutation that deletes a record. This mutation receives the UUID of the resource, calls a REST (Ruby on Rails) API and that API just returns an HTTP code of success and an empty body (204 No Content) when the deletion was successful and an HTTP error code with an error message when the deletion does not work (404 or 500, typical REST delete endpoint).\n\nWhen defining a GraphQL mutation I have to define the mutation return type. What should be the mutation return type?\n\n```\ninput QueueInput {\n \"The queue uuid\"\n uuid: String!\n}\n\ndeleteQueue(input: QueueInput!): ????????\n```\n\nI can make it work with a couple of different types of returns (Boolean, String, ...) but I want to know what is the best practice because none of the returns types I tried felt right. I think it is important that on client-side after calling the mutation I have some information about what happened if things went well (API returns 204 not content) or if some error occurred (API returns 404 or 500) and ideally have some information about the error.\n\n========================================\n\nTop Answer:\nI use graphql server with prisma and when deleting something prisma return info about the something that did get deleted. That's good because when you preform the deletion from the client and get back a response about it that help you to make the ui change by updating the cache\n\n========================================\n\nCode:\n```text\ninput QueueInput {\n \"The queue uuid\"\n uuid: String!\n}\n\n\ndeleteQueue(input: QueueInput!): ????????\n```\n\n```text\ntype Mutation {\n deleteQueue(input: QueueInput!): Boolean #or any other type\n}\n```\n\n```text\nconst { GraphQLScalarType } = require('graphql')\n\nconst Void = new GraphQLScalarType({\n description: 'Void custom scalar',\n name: 'Void',\n parseLiteral: (ast) => null,\n parseValue: (value) => null,\n serialize: (value) => null,\n})\n```\n\n```text\ntype Mutation {\n deleteQueue(input: QueueInput!): Void\n}\n```\n\n```text\ntype Mutation {\n deleteQueue(input: QueueInput!): DeleteQueuePayload\n}\n\ntype DeleteQueuePayload {\n # the id of the deleted queue\n queueId: ID\n\n # the queue itself\n queue: Queue\n\n # a status string\n status: String\n\n # or a status code\n status: Int\n\n # or even an enum\n status: Status\n\n # or just include the client error\n # with an appropriate code, internationalized message, etc.\n error: ClientError\n\n # or an array of errors, if you want to support validation, for example\n errors: [ClientError!]!\n}\n```\n\n```text\n__typename\n```\n\n========================================\n\nComments:\n- Yes, I think that is a good option. In my case, I do not control the API so I cannot make that change. I have to deal with the http 204.\n- Hasura does the same - it returns the deleted object: hasura.io/docs/latest/graphql/core/databases/postgres/mutati‌​ons/…\n- Hi Daniel! Thanks for the answer! Yes, I agree that returning null or void would be an option but in that case, I have no idea about what happened in the API, meaning if the mutation was successful (http 204) or not (http 404, 500). I think it is important to return something that would allow me to give some good feedback to the client, something that could be used in FE to show some error message for example.\n- Returning a boolean solves the issue about knowing if it was successful or not, but I think a string is probably even better. I can return \"ok\" or the resource \"ID\" (as you suggested), and in case of error, I can return the error message. What do you think?\n- @Mario edited my answer to provide additional clarification\n- I see your point now. I took a look at the videos, they are really nice, thanks for sharing. Yes, I think a payload mutation type works really well, I didn't know it was common to define such types. Currently, in our app, our types are only objects that are part of our business logic (user, queue, client, metric, ...)","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":105,"estimatedTokens":1027}}256{"id":"stack-54744066","source":"stackoverflow","questionId":54744066,"title":"Graphql merge (combine) multiple queries into one?","tags":["javascript","graphql"],"text":"Title: Graphql merge (combine) multiple queries into one?\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to combine multiple GraphQL queries into one query using JavaScript.\n\nI am looking for something like this:\n\n```\nlet query3 = mergeQueries(query1, query2);\n```\n\nWe won't know beforehand which queries will be combined.\n\nSuppose I have queries like this:\n\ninput query1:\n\n```\n{\n post(id: 1234) {\n title\n description\n }\n}\n```\n\ninput query2:\n\n```\n{\n post(id: 1234) {\n tags\n author {\n name\n }\n }\n}\n```\n\nThen I would like the result query3 to be:\n\nresult query3:\n\n```\n{\n post(id: 1234) {\n title\n tags\n description\n author {\n name\n }\n }\n}\n```\n\nThis would be the same functionality as lodash `_.merge()` does for JSON objects, but then with GraphQL queries instead of JSON objects.\n\n========================================\n\nTop Answer:\nThanks to parameterized fragments you can take variables into account! Assuming `post` is a field of the root query type the combined query referring to the above example would be:\n\n```\nfragment PostHeader on RootQueryType {\n post(id: $id) {\n tags\n author {\n name\n }\n }\n}\n\nfragment PostMeta on RootQueryType {\n post(id: $id) {\n tags\n author {\n name\n }\n }\n}\n\n# ID being the id type\nquery($id: ID! = 1234) {\n ...PostHeader\n ...PostMeta\n}\n```\n\nor rather in a real-world scenario you'd be passing in the id dynamically (e.g. in your post request), see: https://graphql.org/learn/queries/#variables\n\n========================================\n\nCode:\n```js\nlet query3 = mergeQueries(query1, query2);\n```\n\n```text\n{\n post(id: 1234) {\n title\n description\n }\n}\n```\n\n```text\n{\n post(id: 1234) {\n tags\n author {\n name\n }\n }\n}\n```\n\n```text\n{\n post(id: 1234) {\n title\n tags\n description\n author {\n name\n }\n }\n}\n```\n\n```text\n_.merge()\n```\n\n```text\nfragment PostHeader on Post {\n title\n description\n}\n\nfragment PostMeta on Post {\n tags\n author {\n name\n }\n}\n\nquery {\n post(id: 1234) {\n ...PostHeader\n ...PostMeta\n }\n}\n```\n\n```text\nfragment PostHeader on RootQueryType {\n post(id: $id) {\n tags\n author {\n name\n }\n }\n}\n\nfragment PostMeta on RootQueryType {\n post(id: $id) {\n tags\n author {\n name\n }\n }\n}\n\n# ID being the id type\nquery($id: ID! = 1234) {\n ...PostHeader\n ...PostMeta\n}\n```\n\n```text\npost\n```\n\n```js\nimport comineQuery from 'graphql-combine-query'\n\nimport gql from 'graphql-tag'\n\nconst fooQuery = gql`\n query FooQuery($foo: String!) {\n getFoo(foo: $foo)\n }\n`\n\nconst barQuery = gql`\n query BarQuery($bar: String!) {\n getBar(bar: $bar)\n }\n`\n\nconst { document, variables } = combineQuery('FooBarQuery')\n .add(fooQuery, { foo: 'some value' })\n .add(barQuery, { bar: 'another value' })\n\nconsole.log(variables)\n// { foo: 'some value', bar: 'another value' }\n\nprint(document)\n/*\nquery FooBarQuery($foo: String!, $bar: String!) {\n getFoo(foo: $foo)\n getBar(bar: $bar)\n}\n*/\n```\n\n```text\nimport { batchRequests, gql } from 'graphql-request';\n\nconst bookQuery = gql`\n query book($title: String!) {\n book(title: $title) {\n title\n }\n }\n`;\n\nconst endpoint = 'localhost/graphql/api/';\n\nconst books = await batchRequests(endpoint, [\n { document: bookQuery, variables: { title: 'Book 1' } },\n { document: bookQuery, variables: { title: 'Book 2' } },\n ]);\n```\n\n```text\ngraphql-request\n```\n\n```text\nbooks\n```\n\n```text\n{ data: book: { title } }\n```\n\n```js\nimport { gql } from '@apollo/client'\n\nconst fieldsOnBook = gql`\n fragment fieldsOnBook on Book {\n id\n author\n }\n`\n\nconst fieldsOnCar = gql`\n fragment fieldsOnCar on Car {\n id\n name\n }\n`\n\nconst bookQuery = gql`\n query ($bookId: ID!) {\n book(id: $bookId) {\n .... fieldsOnBook\n }\n }\n ${fieldsOnBook}\n`\nconst carQuery = gql`\n query ($carId: ID!) {\n car(id: $carId) {\n ...fieldsOnCar\n }\n }\n ${fieldsOnCar}\n`\n\nconst oneQuery = gql`\n query ($bookId: ID! $carId: ID!) {\n book(id: $bookId) {\n .... fieldsOnBook\n }\n car(id: $carId) {\n ... fieldsOnCar\n }\n }\n ${fieldsOnBook}\n ${fieldsOnCar}\n`\n```\n\n========================================\n\nComments:\n- are you trying to minimize the number of HTTP requests? if yes this might help blog.apollographql.com/query-batching-in-apollo-63acfd859862\n- You can't do this through simple textual manipulation; you need to parse the GraphQL queries and join them together. That can get complicated in the presence of dynamic type matching and fragments.\n- This looks like a very useful solution in many cases. I expect a lot of overlap between the input queries which will make this solution less ideal, so I will look into building my own merge function.\n- We wrote some code for combining fragments, with automatic naming of the fragments and removing duplicate fragments, and released it here: github.com/SVT/graphql-defragmentizer\n- This seemed hopeful, but it's really fresh and has bugs. Not the least of which is the package name being misspelled in package.json.\n- @ivanjonas, what was the bug, other than package name?\n- @DomasLapinskas Does this limit the network calls as well to just one ?","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":310,"estimatedTokens":1285}}257{"id":"stack-61445185","source":"stackoverflow","questionId":61445185,"title":"how to implement user guards in nestjs graphql","tags":["javascript","graphql","jwt","nestjs","graphql-js"],"text":"Title: how to implement user guards in nestjs graphql\nTags: javascript, graphql, jwt, nestjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get the current user but in the resolver I get undefined, in the jwt strategy I get the user object using the token but in the resolver the user is undefined\n\n*auth guard*\n\n```\nimport { ExecutionContext, Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { AuthenticationError } from 'apollo-server-core';\nimport { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n\n canActivate(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const { req } = ctx.getContext();\n\n return super.canActivate(\n new ExecutionContextHost([req]),\n );\n }\n\n handleRequest(err: any, user: any) {\n if (err || !user) {\n throw err || new AuthenticationError('GqlAuthGuard');\n }\n return user;\n }\n\n}\n```\n\n*user decorator*\n\n```\nimport {createParamDecorator} from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n (data, req) => req.user )\n;\n```\n\n*app module*\n\n```\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n signOptions: {\n expiresIn: 3600,\n },\n }),\n SharedModule,\n AuthModule,\n GraphQLModule.forRoot({\n autoSchemaFile: 'schema.gql',\n context: ({ req }) => ({ req })\n }),\n MongooseModule.forRoot(process.env.MONGO_URI,\n {\n useNewUrlParser: true ,\n useUnifiedTopology: true\n }),\n // RewardsModule,\n OrdersModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n*resolver*\n\n```\nimport {User} from \"src/types/user\";\nimport {GqlAuthGuard} from \"../guards/graphql.auth.guard\";\n\n@Resolver()\nexport class OrdersResolver {\n constructor(\n private orderService: OrdersService\n ) {\n }\n\n @Query(returns => [Order])\n @UseGuards(GqlAuthGuard)\n listOrders(@CurrentUser() user: User): Promise {\n console.log(user)\n return this.orderService.listOrdersByUser(user.id);\n }\n\n}\n```\n\nI also tried to implement the solution explained here NestJS Get current user in GraphQL resolver authenticated with JWT and still, I got the same error\n\n========================================\n\nTop Answer:\nThis is what I'm using for `GraphqlJwtAuthGuard` based on documentaion:\n\n```\n@Injectable()\nexport class GqlJwtAuthGuard extends AuthGuard('jwt') {\n constructor(private reflector: Reflector) {\n super();\n }\n\n canActivate(ctx: ExecutionContext) {\n const context = GqlExecutionContext.create(ctx);\n const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [\n context.getHandler(),\n context.getClass(),\n ]);\n if (isPublic) {\n return true;\n }\n const { req } = context.getContext();\n return super.canActivate(new ExecutionContextHost([req])); // NOTE\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimport { ExecutionContext, Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\nimport { GqlExecutionContext } from '@nestjs/graphql';\nimport { AuthenticationError } from 'apollo-server-core';\nimport { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';\n\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n\n canActivate(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const { req } = ctx.getContext();\n\n return super.canActivate(\n new ExecutionContextHost([req]),\n );\n }\n\n handleRequest(err: any, user: any) {\n if (err || !user) {\n throw err || new AuthenticationError('GqlAuthGuard');\n }\n return user;\n }\n\n}\n```\n\n```text\nimport {createParamDecorator} from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n (data, req) => req.user )\n;\n```\n\n```text\n@Module({\n imports: [\n PassportModule.register({ defaultStrategy: 'jwt' }),\n JwtModule.register({\n signOptions: {\n expiresIn: 3600,\n },\n }),\n SharedModule,\n AuthModule,\n GraphQLModule.forRoot({\n autoSchemaFile: 'schema.gql',\n context: ({ req }) => ({ req })\n }),\n MongooseModule.forRoot(process.env.MONGO_URI,\n {\n useNewUrlParser: true ,\n useUnifiedTopology: true\n }),\n // RewardsModule,\n OrdersModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nimport {User} from \"src/types/user\";\nimport {GqlAuthGuard} from \"../guards/graphql.auth.guard\";\n\n@Resolver()\nexport class OrdersResolver {\n constructor(\n private orderService: OrdersService\n ) {\n }\n\n @Query(returns => [Order])\n @UseGuards(GqlAuthGuard)\n listOrders(@CurrentUser() user: User): Promise<Order> {\n console.log(user)\n return this.orderService.listOrdersByUser(user.id);\n }\n\n}\n```\n\n```js\nexport const CurrentUser = createParamDecorator(\n (data, req) => req.user )\n;\n```\n\n```js\nexport const User = createParamDecorator(\n (data: unknown, ctx: ExecutionContext) => {\n const gqlCtx = GqlExecutionContext.create(ctx);\n const request = gqlCtx.getContext().req;\n return request.user;\n },\n);\n```\n\n```text\ncontext: ({req}) => ({req})\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\nGraphqlModule\n```\n\n```text\n@Injectable()\nexport class RolesGuard_ implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n canActivate(context: ExecutionContext): boolean {\n const ctx = GqlExecutionContext.create(context);\n\n const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [\n context.getHandler(),\n context.getClass(),\n ]);\n\n if (!requiredRoles) {\n return true;\n }\n\n const { user } = ctx.getContext().req;\n return requiredRoles.some((role) => user.role?.includes(role));\n }\n}\n```\n\n```text\n@Injectable()\nexport class GqlJwtAuthGuard extends AuthGuard('jwt') {\n constructor(private reflector: Reflector) {\n super();\n }\n\n canActivate(ctx: ExecutionContext) {\n const context = GqlExecutionContext.create(ctx);\n const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [\n context.getHandler(),\n context.getClass(),\n ]);\n if (isPublic) {\n return true;\n }\n const { req } = context.getContext();\n return super.canActivate(new ExecutionContextHost([req])); // NOTE\n }\n}\n```\n\n```text\nGraphqlJwtAuthGuard\n```\n\n========================================\n\nComments:\n- Quick question: what's your Nest version? There was a change to the `createParamDecorator` function between v6 and v7.\n- These are the nestjs versions \"@nestjs/common\": \"^7.0.0\", \"@nestjs/core\": \"^7.0.0\", \"@nestjs/graphql\": \"^7.3.4\", \"@nestjs/jwt\": \"^7.0.0\", \"@nestjs/mongoose\": \"^6.4.0\", \"@nestjs/passport\": \"^7.0.0\", \"@nestjs/platform-express\": \"^7.0.0\", \"@nestjs/swagger\": \"^4.5.1\",","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":303,"estimatedTokens":1740}}258{"id":"stack-54313128","source":"stackoverflow","questionId":54313128,"title":"Querying NOT NULL GraphQL with Prisma","tags":["graphql","apollo","prisma"],"text":"Title: Querying NOT NULL GraphQL with Prisma\nTags: graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nSchema:\n\n```\ntype TrackUser {\n id: ID! @unique\n createdAt: DateTime!\n user: User #note there is no `!`\n}\ntype User {\n id: ID! @unique\n name: String! @unique\n}\n```\n\nI want to get Alls `TrackUser` where `User` is not null. What would be the query?\n\n========================================\n\nTop Answer:\nthis works, but I guess it is just a hack..\n\n```\nquery TrackUsersQuery($orderBy: TrackUserOrderByInput!, $where: TrackUserWhereInput, $first: Int, $skip: Int) {\n trackUsers(where: $where, orderBy: $orderBy, first: $first, skip: $skip) {\n id\n createdAt\n user {\n id\n name\n }\n }\n}\n\nvariables = {\n where: {\n user: {\n name_contains: ''\n }\n }\n}\n```\n\nUPDATE:\n\nFor Prisma2, here you have the possibilities:\n\nFor products that have no invoice, you can use the following:\n\n```\nconst data = await prisma.product.findMany({\n where: {\n invoices: {\n none: {\n id: undefined,\n },\n },\n },\n})\n```\n\nAnd for Invoices that do not have a product associated:\n\n```\nconst data = await prisma.invoice.findMany({\n where: {\n productId: null,\n },\n})\n```\n\nmore details here: https://github.com/prisma/prisma/discussions/3461\n\n========================================\n\nCode:\n```text\ntype TrackUser {\n id: ID! @unique\n createdAt: DateTime!\n user: User #note there is no `!`\n}\ntype User {\n id: ID! @unique\n name: String! @unique\n}\n```\n\n```text\nTrackUser\n```\n\n```text\nUser\n```\n\n```text\nquery c {\n trackUsers(where: { NOT: [{ user: null }] }) {\n name\n }\n}\n```\n\n```text\nquery TrackUsersQuery($orderBy: TrackUserOrderByInput!, $where: TrackUserWhereInput, $first: Int, $skip: Int) {\n trackUsers(where: $where, orderBy: $orderBy, first: $first, skip: $skip) {\n id\n createdAt\n user {\n id\n name\n }\n }\n}\n\n\nvariables = {\n where: {\n user: {\n name_contains: ''\n }\n }\n}\n```\n\n```text\nconst data = await prisma.product.findMany({\n where: {\n invoices: {\n none: {\n id: undefined,\n },\n },\n },\n})\n```\n\n```text\nconst data = await prisma.invoice.findMany({\n where: {\n productId: null,\n },\n})\n```\n\n========================================\n\nComments:\n- You have no way to filter (at least you haven't shown us any) so it's not possible.\n- Is this question specific to `prisma`?\n- Right it is with prisma.\n- Thanks for editing the question Alan :)\n- It is with prisma. Prisma is generated a chema for you.\n- And how were we supposed to know that before you gave us that information?","metadata":{"transformedAt":"2026-08-18T18:32:36.042Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":159,"estimatedTokens":634}}259{"id":"stack-48942175","source":"stackoverflow","questionId":48942175,"title":"Apollo - update() method getting called twice, both times with optimistic/fake data","tags":["vue.js","graphql","apollo","aws-appsync","vue-apollo"],"text":"Title: Apollo - update() method getting called twice, both times with optimistic/fake data\nTags: vue.js, graphql, apollo, aws-appsync, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm completely stuck on an Apollo problem, for which I've opened a GitHub issue and had zero response on.\n\nI'm calling an Apollo mutation, using `optimisticResponse`. The way it's supposed to work, as I understand it, is that `update()` gets called twice: first with the optimistic data, then again with the actual data coming in from the network.\n\nBut for some reason, my code is not working like this. I'm getting two `update()` calls, both with the optimistic data.\n\nHere's a repo that demonstrates this behavior: https://github.com/ffxsam/apollo-update-bug\n\n- yarn && yarn dev\n\n- Open in browser, open console\n\n- Enter some text and hit enter\n\n- Repeat above\nNotice the error in the console about duplicate keys. This is happening because the temporary ID \"??\" is not being replaced with the real UUID\n(optional) You can open Vue DevTools if available and inspect the data to see it's incorrect\n\n========================================\n\nCode:\n```text\noptimisticResponse\n```\n\n```text\nupdate()\n```\n\n```text\nupdate()\n```\n\n```text\nOfflineLink\n```\n\n```text\naws-appsync\n```\n\n```text\naws-appsync\n```\n\n```text\nOfflineLink\n```\n\n```text\nrequest\n```\n\n```text\n$apollo.mutate(...)\n```\n\n```text\nApolloClient.QueryManager\n```\n\n```text\nupdate\n```\n\n```text\nOfflineLink\n```\n\n```text\nOfflineLink\n```\n\n```text\nOfflineLink\n```\n\n```text\nnext\n```\n\n```text\noptimisticResponse\n```\n\n```text\nupdate\n```\n\n```text\noptimisticResponse\n```\n\n```text\nOfflineLink\n```\n\n```text\ncomplete\n```\n\n```text\nconsole.log('done!'...\n```\n\n```text\nOfflineLink\n```\n\n========================================\n\nComments:\n- Can you see if this PR, merged today, resolves your issue: github.com/awslabs/aws-mobile-appsync-sdk-js/pull/43\n- I know this isn't really a \"solution\" but it looks like the `aws-appsync@deepdish` tag has a fix (at least it seems to work for me now. I don't believe that this is a stable branch, so buyer beware in production, but it's working for me as of now. Source: github.com/awslabs/aws-mobile-appsync-sdk-js/issues/170\n- This was totally the issue. THANK YOU.\n- Can you check the latest PR that was merged and see if the issue still exists? You can find it here: github.com/awslabs/aws-mobile-appsync-sdk-js/pull/43\n- Wonderful. This is mainly causing me a problem in create mutation - my app temporarily shows duplicate data. It was a simple workaround for me to check if the data already exists and only showing optimisticResponse for the first time. Update query's server response won't update the data but the data is re-requested from the server immediately that anyway. Hopefully this issue gets fixed soon!","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":122,"estimatedTokens":694}}260{"id":"stack-56965400","source":"stackoverflow","questionId":56965400,"title":"How to pass variables in mutation graphQL Playground?","tags":["node.js","graphql","mutation"],"text":"Title: How to pass variables in mutation graphQL Playground?\nTags: node.js, graphql, mutation\nSource: Stack Overflow\n\nQuestion:\nI am using apollo express server 2.0. And I am trying to execute mutation in the graphql playground. Here is the mutation I have attached a screenshot with another screenshot of a variable.\n\nhttps://i.sstatic.net/rGGfu.png\nhttps://i.sstatic.net/VAThX.png\n\nI am getting the following error when I am trying to execute mutation command in the graphql playground.\n\nhttps://i.sstatic.net/TmN8v.png\n\nPlease guide me where I am incorrect.\n\n========================================\n\nTop Answer:\nSeems you have to define each of the input fields separately.\n\n========================================\n\nCode:\n```text\nQUERY VARIABLES\n```\n\n```text\nHTTP HEADERS\n```\n\n```text\nQUERY VARIABLES\n```\n\n========================================\n\nComments:\n- Remove the id in the mutation or add it in the vars. Also, remove the mname in your input. GraphQL error messages all mean the same thing - \"Something is wrong, good luck!\" You may have to change your resolver param also but you didn't post the resolver, which should always be done with GraphQL. I've seen that message many times...","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":40,"estimatedTokens":300}}261{"id":"stack-52060784","source":"stackoverflow","questionId":52060784,"title":"GraphQL and CSRF protection","tags":["security","graphql","csrf","graphql-js","csrf-protection"],"text":"Title: GraphQL and CSRF protection\nTags: security, graphql, csrf, graphql-js, csrf-protection\nSource: Stack Overflow\n\nQuestion:\nI read a lot around:\n\n- https://github.com/pillarjs/understanding-csrf\n\n- https://security.stackexchange.com/questions/10227/csrf-with-json-post\n\n- Are JSON web services vulnerable to CSRF attacks?\n\n- (Nothing on the ApolloServer site: https://www.apollographql.com/docs/apollo-server/)\n\nHowever, I am not yet able to understand if our endpoint (\"/graphql\") is protected for this type of attack or if it is necessary to protect it with solutions like this: https://github.com/expressjs/csurf.\n\nThe thing that is not clear to me is that here: https://github.com/pillarjs/understanding-csrf they say:\n\n When you're using CSRF tokens incorrectly:\n ...\n Adding them to JSON AJAX calls\n As noted above, if you do not support CORS and your APIs are strictly JSON, there is absolutely no point in adding CSRF tokens to your AJAX calls.\n\nIf we restrict our endpoint to just use `Content-Type: application/json` are we safe?\n\n========================================\n\nCode:\n```text\nContent-Type: application/json\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":32,"estimatedTokens":284}}262{"id":"stack-45521040","source":"stackoverflow","questionId":45521040,"title":"How to create generics with the schema language?","tags":["graphql","graphql-js","apollo-server"],"text":"Title: How to create generics with the schema language?\nTags: graphql, graphql-js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nUsing facebook's reference library, I found a way to hack generic types like this:\n\n```\ntype PagedResource = (pagedQuery: PagedQuery) => PagedResponse\n β\ninterface PagedQuery {\n query: Query;\n take: number;\n skip: number;\n}\n β\ninterface PagedResponse {\n items: Array; \n total: number;\n}\n```\n\n```\nfunction pagedResource({type, resolve, args}) {\n return {\n type: pagedType(type),\n args: Object.assign(args, {\n page: { type: new GraphQLNonNull(pageQueryType()) }\n }),\n resolve\n };\n function pageQueryType() {\n return new GraphQLInputObjectType({\n name: 'PageQuery',\n fields: {\n skip: { type: new GraphQLNonNull(GraphQLInt) },\n take: { type: new GraphQLNonNull(GraphQLInt) }\n }\n });\n }\n function pagedType(type) {\n return new GraphQLObjectType({\n name: 'Paged' + type.toString(),\n fields: {\n items: { type: new GraphQLNonNull(new GraphQLList(type))},\n total: { type: new GraphQLNonNull(GraphQLInt) }\n }\n });\n }\n}\n```\n\nBut I like how with Apollo Server I can declaratively create the schema. So question is, how do you guys go about creating generic-like types with the schema language?\n\n========================================\n\nCode:\n```js\ntype PagedResource<Query, Item> = (pagedQuery: PagedQuery<Query>) => PagedResponse<Item>\n β\ninterface PagedQuery<Query> {\n query: Query;\n take: number;\n skip: number;\n}\n β\ninterface PagedResponse<Item> {\n items: Array<Item>; \n total: number;\n}\n```\n\n```js\nfunction pagedResource({type, resolve, args}) {\n return {\n type: pagedType(type),\n args: Object.assign(args, {\n page: { type: new GraphQLNonNull(pageQueryType()) }\n }),\n resolve\n };\n function pageQueryType() {\n return new GraphQLInputObjectType({\n name: 'PageQuery',\n fields: {\n skip: { type: new GraphQLNonNull(GraphQLInt) },\n take: { type: new GraphQLNonNull(GraphQLInt) }\n }\n });\n }\n function pagedType(type) {\n return new GraphQLObjectType({\n name: 'Paged' + type.toString(),\n fields: {\n items: { type: new GraphQLNonNull(new GraphQLList(type))},\n total: { type: new GraphQLNonNull(GraphQLInt) }\n }\n });\n }\n}\n```\n\n```text\ntype Query {\n pagedQuery(page: PageInput!): PagedResult\n}\n\ninput PageInput {\n skip: Int!\n take: Int!\n}\n\ntype PagedResult {\n items: [Pageable!]!\n total: Int\n}\n\n# Regular type definitions for Bar, Foo, Baz types...\n\nunion Pageable = Bar | Foo | Baz\n```\n\n```text\nconst resolvers = {\n Query: { ... },\n Pageable {\n __resolveType: (obj) => {\n // resolve logic here, needs to return a string specifying type\n // i.e. if (obj.__typename == 'Foo') return 'Foo'\n }\n }\n}\n```\n\n```text\nextend Query {\n nonPaginatedQuery: Result\n}\n```\n\n```text\ngraphql-tools\n```\n\n```text\n__resolveType\n```\n\n```text\ntypename\n```\n\n```text\nresolveType\n```\n\n```text\nitems\n```\n\n```text\n... on Foo\n```\n\n```text\nPagedFoo\n```\n\n```text\nFoo\n```\n\n```text\nPagedBar\n```\n\n```text\nBar\n```\n\n```text\npagedResource\n```\n\n```text\nprintSchema\n```\n\n```text\ngraphql/utilities\n```\n\n```text\nextend\n```\n\n```text\nresolve\n```\n\n```text\npagedResource\n```\n\n```text\nbuildExecutableSchema\n```\n\n========================================\n\nComments:\n- Doesn't this mean that the client will need to figure out what type is being returned?\n- Yeah, the client would have to use inline fragments. Not sure if there's a good way of doing what you're trying to accomplish without generating the schema programatically. See my edit for some additional thoughts.\n- Appreciate the effort","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":214,"estimatedTokens":898}}263{"id":"stack-43020235","source":"stackoverflow","questionId":43020235,"title":"Proxy/convert existing GraphQL API to REST","tags":["rest","proxy","graphql"],"text":"Title: Proxy/convert existing GraphQL API to REST\nTags: rest, proxy, graphql\nSource: Stack Overflow\n\nQuestion:\nWe have an existing private GraphQL server that powers our React application and would like to possibly expose a subset of the functionality as REST endpoints. This way we do not have to support 2 code bases, one for GraphQL and one for the REST APIs. \n\nHow would I take an existing GraphQL server and create a wrapper/proxy layer to expose of the schema as REST endpoints?\n\n========================================\n\nTop Answer:\nCheck out this package (**graphql2rest**): https://github.com/sisense/graphql2rest\n\nYou can use it to automatically generate a REST API from your existing GraphQL API - just what you need. \n\n\"GraphQL2REST is a Node.js library that reads your GraphQL schema and a user-provided manifest file and automatically generates an Express router with fully RESTful HTTP routesβββa full-fledged REST API.\"\n\n========================================\n\nCode:\n```text\n/posts/1\n```\n\n```text\nconst postByIdQuery = `\n query postById($postId: Int!) {\n post(id: $postId) {\n title\n description\n author {\n name\n }\n }\n }\n`;\n```\n\n```text\napp.get('/posts/:postId', function (req, res) {\n graphql(\n schema, // same schema as your graphql api\n postByIDQuery, // the query from above\n rootValue, context, // set these same way as for your graphql endpoint\n req.params // use the route params as variables!\n ).then((result) => {\n res.send(result);\n }).catch((error) => {\n // something to handle errors\n });;\n})\n```\n\n```text\nfunction addEndpointFromQuery(app, path, query) {\n // generates endpoint like the above sample\n}\n```\n\n```text\naddEndpointFromQuery(app, '/posts/:postId', `\n query postById($postId: Int!) {\n post(id: $postId) {\n title\n description\n author {\n name\n }\n }\n }\n`);\n```\n\n```text\n:postId\n```\n\n```text\n$postId\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":81,"estimatedTokens":483}}264{"id":"stack-58245183","source":"stackoverflow","questionId":58245183,"title":"GraphQL/Gatsby/Prismic - difference between 'edges.node.data' and 'nodes.data' in query","tags":["graphql","gatsby","prismic.io"],"text":"Title: GraphQL/Gatsby/Prismic - difference between 'edges.node.data' and 'nodes.data' in query\nTags: graphql, gatsby, prismic.io\nSource: Stack Overflow\n\nQuestion:\nI'm following this tutorial on Medium to get Gatsby working with Prismic.\n\nIn the GraphiQL explorer, the two queries below both yield the same result and was wondering when I should use one over the other (i.e. **edges.node.data** vs **nodes.data**):\n\n**Query #1:**\n\n```\nquery Articles {\n articles: allPrismicArticle {\n edges {\n node {\n data {\n title {\n text\n }\n image {\n url\n }\n paragraph {\n html\n }\n }\n }\n }\n }\n}\n```\n\n**Query #2:**\n\n```\nquery Articles {\n articles: allPrismicArticle {\n nodes {\n data {\n title {\n text\n }\n image {\n url\n }\n paragraph {\n html\n }\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery Articles {\n articles: allPrismicArticle {\n edges {\n node {\n data {\n title {\n text\n }\n image {\n url\n }\n paragraph {\n html\n }\n }\n }\n }\n }\n}\n```\n\n```text\nquery Articles {\n articles: allPrismicArticle {\n nodes {\n data {\n title {\n text\n }\n image {\n url\n }\n paragraph {\n html\n }\n }\n }\n }\n}\n```\n\n```text\nnodes\n```\n\n```text\nedges.map(edge => edge.node)\n```\n\n```text\nallMarkdownRemark\n```\n\n```text\nedges\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":115,"estimatedTokens":352}}265{"id":"stack-49988215","source":"stackoverflow","questionId":49988215,"title":"Call GraphQL endpoints using Cypress .request","tags":["javascript","unit-testing","graphql","graphql-js","cypress"],"text":"Title: Call GraphQL endpoints using Cypress .request\nTags: javascript, unit-testing, graphql, graphql-js, cypress\nSource: Stack Overflow\n\nQuestion:\nI have googled `cypress request with graphql` but I see lots of people mentioning `mock up server`, `stub` and so on. But I am not able to find a ful example of how to use GraphQL with cy.request.\n\n========================================\n\nTop Answer:\nThe chosen answer worked for me as soon as I added `method: \"post\"`\n\n```\nconst query = `\n query getItems {\n items {\n items {\n id\n }\n }\n }\n`;\n\ncy.request({\n method: \"post\",\n url: 'http://localhost:4000/graphql',\n body: { query },\n}).then((res) => {\n console.log(res.body);\n});\n```\n\n========================================\n\nCode:\n```text\ncypress request with graphql\n```\n\n```text\nmock up server\n```\n\n```text\nstub\n```\n\n```text\nconst query = `{\n findUser(username:\"hello\") {\n id\n }\n}`;\n \ncy.request({\n url: 'http://localhost/graphql/', // graphql endpoint\n body: { query }, // or { query: query } depending if you are writing with es6\n failOnStatusCode: false // not a must but in case the fail code is not 200 / 400\n}).then((res) => {\n cy.log(res);\n});\n```\n\n```text\ncy.request\n```\n\n```text\nrestful\n```\n\n```text\ncy.request\n```\n\n```text\nfindUser\n```\n\n```text\nusername\n```\n\n```text\nfindUser(username:\"hello\"){id, name}\n```\n\n```text\njson\n```\n\n```text\n{\"query\": findUser(username:\"hello\"){id, name}}\n```\n\n```text\nconst query = `\n query getItems {\n items {\n items {\n id\n }\n }\n }\n`;\n\ncy.request({\n method: \"post\",\n url: 'http://localhost:4000/graphql',\n body: { query },\n}).then((res) => {\n console.log(res.body);\n});\n```\n\n```text\nmethod: \"post\"\n```\n\n========================================\n\nComments:\n- nice this does work, thx a lot. I even tried using `graphql-request` which doesn't work as good as expected\n- Were you able to have this work with a mutation? I can't seem to work it out. Any ideas?\n- @jamesemanon this works with mutation too, the same as query. Do you want to make a post so I can give you sample codes?\n- Yeah, that would be great if you could! Also, I'm trying to figure out how to do a react-dropzone \"click\" image upload. This seems to be an issue with cypress, no?\n- @jamesemanon give me the URL of your question post so I can give you a sample code. As for image upload, I am not that far yet but maybe you can take a look at these two posts which I hope would help. stackoverflow.com/questions/47074225/… and github.com/cypress-io/cypress/issues/170\n- stackoverflow.com/questions/51012988/…","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":128,"estimatedTokens":649}}266{"id":"stack-62046070","source":"stackoverflow","questionId":62046070,"title":"prisma2: how to fetch nested fields?","tags":["javascript","node.js","graphql","prisma","prisma-graphql"],"text":"Title: prisma2: how to fetch nested fields?\nTags: javascript, node.js, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nIn prisma 1 I have used fragment to fetch the nested fields.\n\nFor example:\n\n```\nconst mutations = {\n async createPost(_, args, ctx) {\n const user = await loginChecker(ctx);\n const post = await prisma.post\n .create({\n data: {\n author: {\n connect: {\n id: user.id,\n },\n },\n title: args.title,\n body: args.body,\n published: args.published,\n },\n })\n .$fragment(fragment);\n\n return post;\n },\n};\n```\n\nbut seems like in prisma2 it is not supported. because by running this on playground,\n\n```\nmutation CREATEPOST {\n createPost(\n title: \"How to sleep?\"\n body: \"Eat, sleep, repaet\"\n published: true\n ) {\n title\n body\n published\n author {\n id\n }\n }\n}\n```\n\nI am getting,\n\n```\n\"prisma.post.create(...).$fragment is not a function\",\n```\n\n========================================\n\nCode:\n```text\nconst mutations = {\n async createPost(_, args, ctx) {\n const user = await loginChecker(ctx);\n const post = await prisma.post\n .create({\n data: {\n author: {\n connect: {\n id: user.id,\n },\n },\n title: args.title,\n body: args.body,\n published: args.published,\n },\n })\n .$fragment(fragment);\n\n return post;\n },\n};\n```\n\n```text\nmutation CREATEPOST {\n createPost(\n title: \"How to sleep?\"\n body: \"Eat, sleep, repaet\"\n published: true\n ) {\n title\n body\n published\n author {\n id\n }\n }\n}\n```\n\n```text\n\"prisma.post.create(...).$fragment is not a function\",\n```\n\n```text\nconst result = await prisma.user.findOne({\n where: { id: 1 },\n include: { posts: true },\n})\n```\n\n```text\nconst result = await prisma.user.findOne({\n where: { id: 1 },\n include: {\n posts: {\n include: {\n author: true,\n }\n },\n },\n})\n```\n\n========================================\n\nComments:\n- suppose I include {post and author} in createComment resolver. when running this from playground: `mutation CREATECOMMENT { createComment(text: \"yep, very bad post dude\", postId: 4) { id text post { id title author: {id} } author { name } } }` here how can I get posts {author:id} ?\n- So that has more to do with how your schema is defined than prisma itself. Assuming createComment returns a `Comment`, the `Comment` type needs to have `post` as a queryable field. And the `Post` type needs to have `author` as a queryable field.\n- you can see from my data model: gist.github.com/ashiqdev/17d96ac1db30c35ef8e7622992cab035 comment has relation with post and post has relation with author. but, when created a comment I included { author: true, post: true,}. so, I got post and authors direct queries. but when I try to get post {author {id}} I can't get it. In prisma1 by using fragment I used to got it.\n- The prisma client supports nesting includes as well `.findOne({ include: { post: { include: { author: true } } } })`\n- with nested includes, can i also add where parts so to only get those total records including all the hierarchy where a specific element deep in the tree has a specific value?","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":134,"estimatedTokens":787}}267{"id":"stack-53391097","source":"stackoverflow","questionId":53391097,"title":"Graphene Django - Mutation with one to many relation foreign key","tags":["django","django-models","graphql","graphene-python"],"text":"Title: Graphene Django - Mutation with one to many relation foreign key\nTags: django, django-models, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI would like to know how to properly create mutation for creating this django model:\n\n```\nclass Company(models.Model):\n\n class Meta:\n db_table = 'companies'\n app_label = 'core'\n default_permissions = ()\n\n name = models.CharField(unique=True, max_length=50, null=False)\n email = models.EmailField(unique=True, null=False)\n phone_number = models.CharField(max_length=13, null=True)\n address = models.TextField(max_length=100, null=False)\n crn = models.CharField(max_length=20, null=False)\n tax = models.CharField(max_length=20, null=False)\n parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE)\n currency = models.ForeignKey(Currency, null=False, on_delete=models.CASCADE)\n country = models.ForeignKey(Country, null=False, on_delete=models.CASCADE)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n```\n\nAs you see, there are three Foreign keys. For model **Currency**, **Country** and **Parent(self)**. **Company DjangoObjectType** looks very simple like this:\n\n```\nclass CompanyType(DjangoObjectType):\n class Meta:\n model = Company\n```\n\nAnd finally my mutation class **CreateCompany** have **Currency**, **Country** and **Self(Parent)** defined like `graphene.Field()`:\n\n```\nclass CompanyInput(graphene.InputObjectType):\n name = graphene.String(required=True)\n email = graphene.String(required=True)\n address = graphene.String(required=True)\n crn = graphene.String(required=True)\n tax = graphene.String(required=True)\n currency = graphene.Field(CurrencyType)\n country = graphene.Field(CountryType)\n parent = graphene.Field(CompanyType)\n phone_number = graphene.String()\n\nclass CreateCompany(graphene.Mutation):\n company = graphene.Field(CompanyType)\n\n class Arguments:\n company_data = CompanyInput(required=True)\n\n @staticmethod\n def mutate(root, info, company_data):\n company = Company.objects.create(**company_data)\n return CreateCompany(company=company)\n```\n\nWhen i want to start django server, Assertion error will be raised.\n\n```\nAssertionError: CompanyInput.currency field type must be Input Type but got: CurrencyType.\n```\n\nI was finding some good tutorial for one to many foreign key for a long time, so if someone know how to implement this solution nice and clear I would be very glad. \n\nPS: Please can you also show me example of GraphQL query, so I would know how to call that mutation? Thank you very much.\n\n========================================\n\nCode:\n```text\nclass Company(models.Model):\n\n class Meta:\n db_table = 'companies'\n app_label = 'core'\n default_permissions = ()\n\n name = models.CharField(unique=True, max_length=50, null=False)\n email = models.EmailField(unique=True, null=False)\n phone_number = models.CharField(max_length=13, null=True)\n address = models.TextField(max_length=100, null=False)\n crn = models.CharField(max_length=20, null=False)\n tax = models.CharField(max_length=20, null=False)\n parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE)\n currency = models.ForeignKey(Currency, null=False, on_delete=models.CASCADE)\n country = models.ForeignKey(Country, null=False, on_delete=models.CASCADE)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n```\n\n```text\nclass CompanyType(DjangoObjectType):\n class Meta:\n model = Company\n```\n\n```text\nclass CompanyInput(graphene.InputObjectType):\n name = graphene.String(required=True)\n email = graphene.String(required=True)\n address = graphene.String(required=True)\n crn = graphene.String(required=True)\n tax = graphene.String(required=True)\n currency = graphene.Field(CurrencyType)\n country = graphene.Field(CountryType)\n parent = graphene.Field(CompanyType)\n phone_number = graphene.String()\n\n\nclass CreateCompany(graphene.Mutation):\n company = graphene.Field(CompanyType)\n\n class Arguments:\n company_data = CompanyInput(required=True)\n\n @staticmethod\n def mutate(root, info, company_data):\n company = Company.objects.create(**company_data)\n return CreateCompany(company=company)\n```\n\n```text\nAssertionError: CompanyInput.currency field type must be Input Type but got: CurrencyType.\n```\n\n```text\ngraphene.Field()\n```\n\n```text\nclass CompanyInput(graphene.InputObjectType):\n name = graphene.String(required=True)\n email = graphene.String(required=True)\n address = graphene.String(required=True)\n crn = graphene.String(required=True)\n tax = graphene.String(required=True)\n currency = graphene.Field(CurrencyInput)\n country = graphene.Field(CountryInput)\n parent = graphene.Field(CompanyInput)\n phone_number = graphene.String()\n\nclass CurrencyInput(graphene.InputObjectType):\n name = graphene.String()\n code = graphene.String()\n character = graphene.String()\n\nclass CountryInput(graphene.InputObjectType):\n name = graphene.String()\n code = graphene.String()\n\n\nclass CreateCompany(graphene.Mutation):\n company = graphene.Field(CompanyType)\n\n class Arguments:\n company_data = CompanyInput(required=True)\n\n @staticmethod\n def mutate(root, info, company_data):\n company = Company.objects.create(**company_data)\n return CreateCompany(company=company)\n```\n\n========================================\n\nComments:\n- Have you found a solution to this issue?\n- @KeykoYume Yes. To graphene.Field goes InputType not Type object. As you see class CompanyInput. All you need to do is change for example graphene.Field(CurrencyType) to graphene.Field(CurrencyInput). The same class for currency like CompanyInput for company.\n- Could you please write up the answer along with what you defined for `CurrencyInput` and the associated graphql query? I am having trouble with a create mutation because of a foreign-key field, I've tried implementing your above approach but obviously, I am short of something important.\n- Did any of you manage to get this working? Would love to see an example of it.\n- Could you, please, show the example of your query? I'm wondering how did you provide the ForeignKey input in the mutation query\n- Hi. Foreign keys can be handled two ways. Firstly like example above currency, country and parent are in model foreign keys, but in that example you will create new record in table and assign that record to Company object as FK. Second example (which I hope you want) is that object which is FK is already created in table and you just want to assign it to Company object. It is very similar. For example with currency as FK it will be in input like: currency_id = graphene.Int() and in mutation you will simply provide that number corresponding to FK of currency object.\n- Yeah, thanks. I was thinking about the passing the whole foreign object into the mutation query instead the ID only, regarding GraphQL InputType (thought to keep them consistent) but later I decided to avoid such weird thing and used the ID only.\n- Oh so even when using InputObjectType we just have to provide the ID of the desired object and then somehow it fetches it to be able to assign it ?","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":180,"estimatedTokens":1816}}268{"id":"stack-40687045","source":"stackoverflow","questionId":40687045,"title":"apollostack/graphql-server - how to get the fields requested in a query from resolver","tags":["mongodb","hapi.js","graphql","apollo-server"],"text":"Title: apollostack/graphql-server - how to get the fields requested in a query from resolver\nTags: mongodb, hapi.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am trying to figure out a clean way to work with queries and mongdb projections so I don't have to retrieve excessive information from the database. \nSo assuming I have:\n\n```\n// the query\ntype Query {\n getUserByEmail(email: String!): User\n}\n```\n\nAnd I have a `User` with an `email` and a `username`, to keep things simple. If I send a query and I only want to retrieve the email, I can do the following:\n\n```\nquery { getUserByEmail(email: \"test@test.com\") { email } }\n```\n\nBut in the resolver, my DB query still retrieves both `username` and `email`, but only one of those is passed back by apollo server as the query result. \n\nI only want the DB to retrieve what the query asks for:\n\n```\n// the resolver\ngetUserByEmail(root, args, context, info) {\n // check what fields the query requested\n // create a projection to only request those fields\n return db.collection('users').findOne({ email: args.email }, { /* projection */ });\n}\n```\n\nOf course the problem is, getting information on what the client is requesting isn't so straightforward.\n\nAssuming I pass in request as context - I considered using `context.payload` (hapi.js), which has the query string, and searching it through various `.split()`s, but that feels kind of dirty. As far as I can tell, `info.fieldASTs[0].selectionSet.selections` has the list of fields, and I could check for it's existence in there. I'm not sure how reliable this is. Especially when I start using more complex queries.\n\nIs there a simpler way?\n\nIn case you don't use mongDB, a projection is an additional argument you pass in telling it explicitly what to retrieve:\n\n```\n// telling mongoDB to not retrieve _id\ndb.collection('users').findOne({ email: 'test@test.com' }, { _id: 0 })\n```\n\nAs always, thanks to the amazing community.\n\n========================================\n\nTop Answer:\n### 2020-Jan answer\n\nThe current answer to getting the fields requested in a GraphQL query, is to use the `graphql-parse-resolve-info` library for parsing the `info` parameter.\n\nThe library is \"a pretty complete solution and is actually used under the hood by postgraphile\", and is recommended going forward by the author of the other top library for parsing the `info` field, `graphql-fields`.\n\n========================================\n\nCode:\n```text\n// the query\ntype Query {\n getUserByEmail(email: String!): User\n}\n```\n\n```text\nquery { getUserByEmail(email: \"test@test.com\") { email } }\n```\n\n```text\n// the resolver\ngetUserByEmail(root, args, context, info) {\n // check what fields the query requested\n // create a projection to only request those fields\n return db.collection('users').findOne({ email: args.email }, { /* projection */ });\n}\n```\n\n```text\n// telling mongoDB to not retrieve _id\ndb.collection('users').findOne({ email: 'test@test.com' }, { _id: 0 })\n```\n\n```text\nUser\n```\n\n```text\nemail\n```\n\n```text\nusername\n```\n\n```text\nusername\n```\n\n```text\nemail\n```\n\n```text\ncontext.payload\n```\n\n```text\n.split()\n```\n\n```text\ninfo.fieldASTs[0].selectionSet.selections\n```\n\n```text\ninfo\n```\n\n```text\ninfo\n```\n\n```text\nconst rootSchema = [`\n\n type Person {\n id: String!\n name: String!\n email: String!\n picture: String!\n type: Int!\n status: Int!\n createdAt: Float\n updatedAt: Float\n }\n\n schema {\n query: Query\n mutation: Mutation\n }\n\n`];\n\nconst rootResolvers = {\n\n\n Query: {\n\n users(root, args, context, info) {\n const topLevelFields = Object.keys(graphqlFields(info));\n return fetch(`/api/user?fields=${topLevelFields.join(',')}`);\n }\n }\n};\n\nconst schema = [...rootSchema];\nconst resolvers = Object.assign({}, rootResolvers);\n\n// Create schema\nconst executableSchema = makeExecutableSchema({\n typeDefs: schema,\n resolvers,\n});\n```\n\n```text\ngraphql-parse-resolve-info\n```\n\n```text\ninfo\n```\n\n```text\ninfo\n```\n\n```text\ngraphql-fields\n```\n\n```text\n/**\n * @description - Gets MongoDB projection from graphql query\n *\n * @return { object }\n * @param { object } info\n * @param { model } model - MongoDB model for referencing\n */\n\nfunction getDBProjection(info, model) {\n const {\n schema: { obj }\n } = model;\n const keys = Object.keys(obj);\n const projection = {};\n\n const { selections } = info.fieldNodes[0].selectionSet;\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n const isSelected = selections.some(\n selection => selection.name.value === key\n );\n\n projection[key] = isSelected;\n }\n\n console.log(projection);\n}\n\nmodule.exports = getDBProjection;\n```\n\n```text\ninfo\n```\n\n```text\nimport { parceGqlInfo, query } from \"@backend\";\nimport { GraphQLResolveInfo } from \"graphql\";\n\nexport const user = async (parent: unknown, args: unknown, ctx: unknown, info: GraphQLResolveInfo): Promise<User | null> => {\n const { dbQueryStr } = parceGqlInfo(info, userFields, \"id\");\n\n const [user] = await query(`SELECT ${dbQueryStr} FROM users WHERE id=$1;`, [1]);\n\n return user;\n};\n```\n\n```text\nconst userFields = [\n \"gql_uid\",\n \"id\",\n \"email\"\n ]\n\n // merge arrays and delete duplicates\n export const mergeDedupe = <T>(arr: any[][]): T => {\n // @ts-ignore\n return ([...new Set([].concat(...arr))] as unknown) as T;\n };\n\n import { parse, simplify, ResolveTree } from \"graphql-parse-resolve-info\";\n import { GraphQLResolveInfo } from \"graphql\";\n\n export const getQueryFieldsFromInfo = <Required = string>(info: GraphQLResolveInfo, options: { required?: Required[] } = {}): string[] => {\n const { fields } = simplify(parse(info) as ResolveTree, info.returnType) as { fields: { [key: string]: { name: string } } };\n\n let astFields = Object.entries(fields).map(([, v]) => v.name);\n\n if (options.required) {\n astFields = mergeDedupe([astFields, options.required]);\n }\n\n return astFields;\n };\n\n export const onlyAllowedFields = <T extends string | number>(raw: T[] | readonly T[], allowed: T[] | readonly T[]): T[] => {\n return allowed.filter((f) => raw.includes(f));\n };\n\n export const parceGqlInfo = (\n info: GraphQLResolveInfo,\n allowedFields: string[] | readonly string[],\n gqlUidDbAlliasField: string,\n options: { required?: string[]; queryPrefix?: string } = {}\n ): { pureDbFields: string[]; gqlUidRequested: boolean; dbQueryStr: string } => {\n const fieldsWithGqlUid = onlyAllowedFields(getQueryFieldsFromInfo(info, options), allowedFields);\n\n return {\n pureDbFields: fieldsWithGqlUid.filter((i) => i !== \"gql_uid\"),\n gqlUidRequested: fieldsWithGqlUid.includes(\"gql_uid\"),\n dbQueryStr: fieldsWithGqlUid\n .map((f) => {\n const dbQueryStrField = f === \"gql_uid\" ? `${gqlUidDbAlliasField}::Text AS gql_uid` : f;\n\n return options.queryPrefix ? `${options.queryPrefix}.${dbQueryStrField}` : dbQueryStrField;\n })\n .join(),\n };\n```\n\n```text\nselect u.id from users u\n```\n\n========================================\n\nComments:\n- OK. So now it's still not clear what you are asking. That query says \"please return an `email`\". What do you mean by \"But in the resolver, my DB query still retrieves both, but only passes back one. I only want the DB to retrieve what the query asks for\"? You should the resolver code for this query.\n- That is also my fault. I should have been a bit more clear. I am trying to find out what fields the query is looking for so I can make my database queries only request the information that the query requested. I'll edit my question to better reflect this.\n- Sorry to be dense. It is still not clear what you mean by \"the fields that the query requested\". What are these fields? How did the query request them? Is your question actually \"How do I make a query that contains information about a projection I want to perform\"? Reading this question it sound like you think the query is already telling the resolver what \"fields to project\". You said that \"getting information on what the client requested isn't straightforwards\". Actually it is. Everything the client requested is in the query. If you want to request more, put it in the query.\n- In order use projections, I need to know which fields the query asked for: `getUserByEmail(email: \"someemail\") { field }`. The same query could also be made: `getUserByEmail(email: \"someemail\") { field1 field2 field3 }`. If I run the first query, I need to do `db.collection('test').findOne({ args }, { field: 1 })` but for the second query I need to do `db.collection('test').findOne({ args }, { field1: 1, field2: 1, field3: 1 })`. My issue is how to get that list of fields from the resolver.\n- At last I understand the question :) I don't think you can do it. It is probably implementation dependent, but with `apollo-server`, you've defined the query schema. Your `getUserByEmail` returns a `User`: that's all there is to it. It seems that asking the DB for less information than that is premature optimisation. Why not just fetch the user and be done with it. On the client side `apollo-client` will cache the results so next time if you has for just the email, it will give it to you.\n- Link is broken.\n- What is the actual answer? 'sure you can', or 'info.fieldASTs[0].selectionSet.selections' can be relied upon\n- This answer could be drastically improved with a code sample.\n- Note that the author of graphql-fields has just recommended using `graphql-parse-resolve-info` going forward.","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":304,"estimatedTokens":2380}}269{"id":"stack-69178586","source":"stackoverflow","questionId":69178586,"title":"NestJS GraphQL subscriptions not working with `graphql-ws`","tags":["graphql","nestjs","graphql-subscriptions"],"text":"Title: NestJS GraphQL subscriptions not working with `graphql-ws`\nTags: graphql, nestjs, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nI'm trying to upgrade our NestJS GraphQL subscriptions server to utilize `graphql-ws` rather than the current `subscriptions-transport-ws` (as suggested by the NestJS documentation).\nI upgraded the NestJS version to\n\n```\n\"@nestjs/core\": \"^8.0.6\",\n \"@nestjs/graphql\": \"^9.0.4\",\n \"@nestjs/platform-express\": \"^8.0.6\",\n \"graphql\": \"^15.5.3\",\n \"graphql-tools\": \"^8.2.0\",\n \"apollo-server-express\": \"^3.3.0\",\n```\n\nAnd after, I added the `subscriptions` option to the `App.Module`:\n\n```\nGraphQLModule.forRoot({\n autoSchemaFile: true,\n sortSchema: true,\n playground: true,\n installSubscriptionHandlers: true,\n subscriptions: {\n 'graphql-ws': true\n },\n }),\n```\n\nHowever when I subscribe (in playground) to a previously working subscription, I get:\n\n```\n{\n \"error\": \"Could not connect to websocket endpoint ws://localhost:8880/graphql. Please check if the endpoint url is correct.\"\n}\n```\n\nAnd in the console I get:\n\n```\nWebSocket protocol error occured. It was most likely caused due to an unsupported subprotocol \"graphql-ws\" requested by the client. graphql-ws implements exclusively the \"graphql-transport-ws\" subprotocol, please make sure that the client implements it too.\n```\n\nThings I have tried:\n\n- Adding the `graphql-ws` package\n\n- Upgrading the NestJS version again\n\n- Removing the `installSubscriptionHandlers` option from config\n\n- Setting `graphql-ws` configs instead of passing `true`\n\n- Using the `WebSocket Test Client` Google Chrome extension instead of Playground\n\nBut none have worked. Sorry for the long post. How can I fix this?\n\n========================================\n\nTop Answer:\nThis will do the job:\n\n```\nsubscriptions: {\n 'graphql-ws': true,\n 'subscriptions-transport-ws': true,\n },\n```\n\nAs mentionned in the doc:\n\nHINT\n\nYou can also use both packages (subscriptions-transport-ws and graphql-ws) at > the same time, for example, for backward compatibility.\n\n========================================\n\nCode:\n```text\n\"@nestjs/core\": \"^8.0.6\",\n \"@nestjs/graphql\": \"^9.0.4\",\n \"@nestjs/platform-express\": \"^8.0.6\",\n \"graphql\": \"^15.5.3\",\n \"graphql-tools\": \"^8.2.0\",\n \"apollo-server-express\": \"^3.3.0\",\n```\n\n```text\nGraphQLModule.forRoot({\n autoSchemaFile: true,\n sortSchema: true,\n playground: true,\n installSubscriptionHandlers: true,\n subscriptions: {\n 'graphql-ws': true\n },\n }),\n```\n\n```text\n{\n \"error\": \"Could not connect to websocket endpoint ws://localhost:8880/graphql. Please check if the endpoint url is correct.\"\n}\n```\n\n```text\nWebSocket protocol error occured. It was most likely caused due to an unsupported subprotocol \"graphql-ws\" requested by the client. graphql-ws implements exclusively the \"graphql-transport-ws\" subprotocol, please make sure that the client implements it too.\n```\n\n```text\ngraphql-ws\n```\n\n```text\nsubscriptions-transport-ws\n```\n\n```text\nsubscriptions\n```\n\n```text\nApp.Module\n```\n\n```text\ngraphql-ws\n```\n\n```text\ninstallSubscriptionHandlers\n```\n\n```text\ngraphql-ws\n```\n\n```text\ntrue\n```\n\n```text\nWebSocket Test Client\n```\n\n```text\nsubscriptions: {\n 'graphql-ws': true,\n 'subscriptions-transport-ws': true,\n },\n```\n\n========================================\n\nComments:\n- Oh well, that's disappointing. So the Google Chrome extension failed for the same reason as well?","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":158,"estimatedTokens":856}}270{"id":"stack-69778679","source":"stackoverflow","questionId":69778679,"title":"NestJS - Expected undefined to be a GraphQL schema","tags":["javascript","node.js","typescript","graphql","nestjs"],"text":"Title: NestJS - Expected undefined to be a GraphQL schema\nTags: javascript, node.js, typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup a very small GraphQL API using NestJS 8. I installed all required redepndencies from the documentation, but when I start the server, I get this error:\n\n```\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [NestFactory] Starting Nest application...\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] AppModule dependencies initialized +43ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] ConfigHostModule dependencies initialized +7ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] ConfigModule dependencies initialized +1ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] ConfigModule dependencies initialized +1ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] GraphQLSchemaBuilderModule dependencies initialized +21ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] GraphQLModule dependencies initialized +1ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +93ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] PostModule dependencies initialized +0ms\n\n/workspace/node_modules/graphql/type/schema.js:35\n throw new Error(\n ^\nError: Expected undefined to be a GraphQL schema.\n at assertSchema (/workspace/node_modules/graphql/type/schema.js:35:11)\n at validateSchema (/workspace/node_modules/graphql/type/validate.js:34:28)\n at graphqlImpl (/workspace/node_modules/graphql/graphql.js:52:64)\n at /workspace/node_modules/graphql/graphql.js:21:43\n at new Promise ()\n at graphql (/workspace/node_modules/graphql/graphql.js:21:10)\n at GraphQLSchemaFactory.create (/workspace/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:48:60)\n at GraphQLSchemaBuilder.buildSchema (/workspace/node_modules/@nestjs/graphql/dist/graphql-schema.builder.js:62:52)\n at GraphQLSchemaBuilder.build (/workspace/node_modules/@nestjs/graphql/dist/graphql-schema.builder.js:24:31)\n at GraphQLFactory.mergeOptions (/workspace/node_modules/@nestjs/graphql/dist/graphql.factory.js:33:69)\n```\n\nI don't understand this error, as I am just following the documentation...\n\n```\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { GraphqlOptions } from './config/graphql.config';\nimport { typeOrmConfigAsync } from './config/typeorm.config';\nimport { PostModule } from './post/post.module';\n\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync(typeOrmConfigAsync),\n GraphQLModule.forRootAsync({\n useClass: GraphqlOptions,\n }),\n PostModule,\n ],\n})\nexport class AppModule {}\n```\n\n```\n// graphql.config.ts\nimport { Injectable } from '@nestjs/common';\nimport { GqlModuleOptions, GqlOptionsFactory } from '@nestjs/graphql';\n\n@Injectable()\nexport class GraphqlOptions implements GqlOptionsFactory {\n createGqlOptions(): Promise | GqlModuleOptions {\n return {\n autoSchemaFile: 'schema.gql',\n sortSchema: true,\n debug: true,\n installSubscriptionHandlers: true,\n context: ({ req }) => ({ req }),\n };\n }\n}\n```\n\n```\n// post.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Post } from './post.entity';\nimport { PostResolver } from './post.resolver';\nimport { PostService } from './post.service';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Post])],\n providers: [PostService, PostResolver],\n exports: [PostService],\n})\nexport class PostModule {}\n```\n\n```\n// post.entity.ts\nimport { Field, ID, ObjectType } from '@nestjs/graphql';\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity('post')\n@ObjectType()\nexport class Post {\n @Field(() => ID)\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Field()\n @Column({ nullable: false })\n title: string;\n\n @Field()\n @Column({ nullable: false, unique: true })\n slug: string;\n\n @Field()\n @Column({ nullable: false })\n content: string;\n\n @Field()\n @Column({ type: 'timestamp' })\n createdAt: Date;\n\n @Field()\n @Column({ type: 'timestamp', nullable: true })\n updatedAt: Date;\n}\n```\n\nDoes anyone can highlight what's wrong with my project?\n\n========================================\n\nTop Answer:\nAs I got to know from the official documentation of nestjs. It's a version issue.\n\nTo avoid this issue just install\n\n```\nnpm i @nestjs/graphql graphql@^15 apollo-server-express\n```\n\nfor better understanding - refer to documentation of nestjs\n\nGraphql with nestjs\n\n========================================\n\nCode:\n```sh\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [NestFactory] Starting Nest application...\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] AppModule dependencies initialized +43ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] ConfigHostModule dependencies initialized +7ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] ConfigModule dependencies initialized +1ms\n[Nest] 22727 - 10/30/2021, 10:11:10 AM LOG [InstanceLoader] ConfigModule dependencies initialized +1ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] GraphQLSchemaBuilderModule dependencies initialized +21ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] GraphQLModule dependencies initialized +1ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +93ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms\n[Nest] 22727 - 10/30/2021, 10:11:11 AM LOG [InstanceLoader] PostModule dependencies initialized +0ms\n\n/workspace/node_modules/graphql/type/schema.js:35\n throw new Error(\n ^\nError: Expected undefined to be a GraphQL schema.\n at assertSchema (/workspace/node_modules/graphql/type/schema.js:35:11)\n at validateSchema (/workspace/node_modules/graphql/type/validate.js:34:28)\n at graphqlImpl (/workspace/node_modules/graphql/graphql.js:52:64)\n at /workspace/node_modules/graphql/graphql.js:21:43\n at new Promise (<anonymous>)\n at graphql (/workspace/node_modules/graphql/graphql.js:21:10)\n at GraphQLSchemaFactory.create (/workspace/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:48:60)\n at GraphQLSchemaBuilder.buildSchema (/workspace/node_modules/@nestjs/graphql/dist/graphql-schema.builder.js:62:52)\n at GraphQLSchemaBuilder.build (/workspace/node_modules/@nestjs/graphql/dist/graphql-schema.builder.js:24:31)\n at GraphQLFactory.mergeOptions (/workspace/node_modules/@nestjs/graphql/dist/graphql.factory.js:33:69)\n```\n\n```text\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { GraphqlOptions } from './config/graphql.config';\nimport { typeOrmConfigAsync } from './config/typeorm.config';\nimport { PostModule } from './post/post.module';\n\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync(typeOrmConfigAsync),\n GraphQLModule.forRootAsync({\n useClass: GraphqlOptions,\n }),\n PostModule,\n ],\n})\nexport class AppModule {}\n```\n\n```text\n// graphql.config.ts\nimport { Injectable } from '@nestjs/common';\nimport { GqlModuleOptions, GqlOptionsFactory } from '@nestjs/graphql';\n\n@Injectable()\nexport class GraphqlOptions implements GqlOptionsFactory {\n createGqlOptions(): Promise<GqlModuleOptions> | GqlModuleOptions {\n return {\n autoSchemaFile: 'schema.gql',\n sortSchema: true,\n debug: true,\n installSubscriptionHandlers: true,\n context: ({ req }) => ({ req }),\n };\n }\n}\n```\n\n```text\n// post.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Post } from './post.entity';\nimport { PostResolver } from './post.resolver';\nimport { PostService } from './post.service';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Post])],\n providers: [PostService, PostResolver],\n exports: [PostService],\n})\nexport class PostModule {}\n```\n\n```text\n// post.entity.ts\nimport { Field, ID, ObjectType } from '@nestjs/graphql';\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity('post')\n@ObjectType()\nexport class Post {\n @Field(() => ID)\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Field()\n @Column({ nullable: false })\n title: string;\n\n @Field()\n @Column({ nullable: false, unique: true })\n slug: string;\n\n @Field()\n @Column({ nullable: false })\n content: string;\n\n @Field()\n @Column({ type: 'timestamp' })\n createdAt: Date;\n\n @Field()\n @Column({ type: 'timestamp', nullable: true })\n updatedAt: Date;\n}\n```\n\n```text\nfunction graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {\n var _arguments = arguments;\n\n /* eslint-enable no-redeclare */\n // Always return a Promise for a consistent API.\n return new Promise(function (resolve) {\n return resolve( // Extract arguments from object args if provided.\n _arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({\n schema: argsOrSchema,\n source: source,\n rootValue: rootValue,\n contextValue: contextValue,\n variableValues: variableValues,\n operationName: operationName,\n fieldResolver: fieldResolver,\n typeResolver: typeResolver\n }));\n });\n}\n```\n\n```text\n@nestjs/graphql@9.1.1\n```\n\n```text\nGraphQL@16\n```\n\n```text\nGraphQL@16\n```\n\n```text\ngqaphql\n```\n\n```text\ngraphqlImpl\n```\n\n```text\ngraphql\n```\n\n```text\nnpm i @nestjs/graphql graphql@^15 apollo-server-express\n```\n\n========================================\n\nComments:\n- After downgrade to version 15.7.2, everything started working. You saved my day!!!\n- Also tested with 15.8.0, thanks.","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":326,"estimatedTokens":2584}}271{"id":"stack-68114615","source":"stackoverflow","questionId":68114615,"title":"GraphQL playground - sending Cookie as Http Header \"disappears\"","tags":["cookies","graphql","apollo","graphql-playground","restdatasource"],"text":"Title: GraphQL playground - sending Cookie as Http Header \"disappears\"\nTags: cookies, graphql, apollo, graphql-playground, restdatasource\nSource: Stack Overflow\n\nQuestion:\nI'm testing some implementations in the GraphQL Playground, in which I want to send a specific cookie, so that I can fetch it in my resolver. I'm using the built in Http Headers pane in the playground:\n\nhttps://i.sstatic.net/6xvtq.png\n\nHowever, when I add headers named either `Cookie` or `cookie`, it doesn't show up when I try to console.log it in my resolver. All other custom Http Headers show up with no issues.\n\nhttps://i.sstatic.net/6yvaF.png\n\nAs seen in the above screenshoot the testheader appears, but the cookie header doesn't. I'm using cookieParser, which might to blame for the `cookie` header disappearing, however I'm not sure. Here is a screenshot of my console.log section:\n\nhttps://i.sstatic.net/KWPMb.png\n\nAnd when I try to console.log the `req.cookies`, I get nothing, which is to be one of the benefits of using the cookieParser.\n\nhttps://i.sstatic.net/YNGZz.png\nhttps://i.sstatic.net/HfPlM.png\n\nMy ApolloServer implementation is as follows:\n\n```\nconst server = new ApolloServer({\n typeDefs: schema\n resolvers,\n dataSources: () => ({\n // ...\n }),\n context: ({req, res}) => ({\n models,\n session: req.session,\n req,\n res\n }),\n // ... and the rest is not important\n});\n```\n\nCreating a \"custom\" cookie header could do the trick, such as `somecookie: =`, but I don't think that's the best practice, and would prefer to avoid that. I'm hoping someone out there got an idea why my cookie `header` doesn't appear, or what I can do for it to appear?\n\n========================================\n\nCode:\n```text\nconst server = new ApolloServer({\n typeDefs: schema\n resolvers,\n dataSources: () => ({\n // ...\n }),\n context: ({req, res}) => ({\n models,\n session: req.session,\n req,\n res\n }),\n // ... and the rest is not important\n});\n```\n\n```text\nCookie\n```\n\n```text\ncookie\n```\n\n```text\ncookie\n```\n\n```text\nreq.cookies\n```\n\n```text\nsomecookie: <key>=<value>\n```\n\n```text\nheader\n```\n\n```text\n'request.credentials': 'omit', // possible values: 'omit', 'include', 'same-origin'\n```\n\n```text\n\"request.credentials\"\n```\n\n```text\n\"include\"\n```\n\n```text\nApplication\n```\n\n========================================\n\nComments:\n- I did the same, however, still not working ...\n- What about in the GraphQL Playground desktop app?\n- I had the same problem (set a cookie in dev tools, but it wasn't being sent with the request). I changed the cookie path to `/` ensures it's `HttpOnly` and `SameSite` is `Lax` then it was sent","metadata":{"transformedAt":"2026-08-18T18:32:36.043Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":109,"estimatedTokens":654}}272{"id":"stack-57445294","source":"stackoverflow","questionId":57445294,"title":"compose not exported from react-apollo","tags":["reactjs","graphql","apollo","react-apollo"],"text":"Title: compose not exported from react-apollo\nTags: reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm following a graphql tutorial on youtube (https://www.youtube.com/watch?v=ed8SzALpx1Q at about 3hr 16min) and part of it uses `compose` from \"react-apollo\". However, I'm getting an error because the new version of react-apollo does not export this. \n\nI read online that I need to replace `import { compose } from \"react-apollo\"` with `import { compose } from \"recompose\"` but doing that produces the error `TypeError: Cannot read property 'loading' of undefined` I've also read that I should replace the import from react-apollo with `import * as compose from \"lodash\"` but when I do this I get other errors, saying that `Γ TypeError: lodash__WEBPACK_IMPORTED_MODULE_2__(...) is not a function`\n\nApp.js:\n\n```\nimport React from \"react\";\nimport ApolloClient from \"apollo-boost\";\nimport { ApolloProvider } from \"react-apollo\";\n\nimport BookList from \"./components/BookList\";\nimport AddBook from \"./components/AddBook\";\n\n//apollo client setup\nconst client = new ApolloClient({\n uri: \"http://localhost:4000/graphql\"\n});\n\nfunction App() {\n return (\n \n \n \n\n### My Reading List\n\n \n \n \n \n );\n}\n\nexport default App;\n```\n\nqueries.js:\n\n```\nimport { gql } from \"apollo-boost\";\n\nconst getBooksQuery = gql`\n {\n books {\n name\n id\n }\n }\n`;\n\nconst getAuthorsQuery = gql`\n {\n authors {\n name\n id\n }\n }\n`;\n\nconst addBookMutation = gql`\n mutation {\n addBook(name: \"\", genre: \"\", authorId: \"\") {\n name\n id\n }\n }\n`;\n\nexport { getAuthorsQuery, getBooksQuery, addBookMutation };\n```\n\nAddBooks.js: \n\n```\nimport React, { Component } from \"react\";\nimport { graphql } from \"react-apollo\";\nimport { compose } from \"recompose\";\n// import * as compose from \"lodash\";\nimport { getAuthorsQuery, addBookMutation } from \"../queries/queries\";\n\nclass AddBook extends Component {\n state = {\n name: \"\",\n genre: \"\",\n authorId: \"\"\n };\n\n displayAuthors = () => {\n let data = this.props.data;\n if (data.loading) {\n return loading authors...;\n } else {\n return data.authors.map(author => {\n return (\n \n {author.name}\n \n );\n });\n }\n };\n\n submitForm(e) {\n e.preventDefault();\n console.log(this.state);\n }\n\n render() {\n return (\n \n \n Book name: \n {\n this.setState({ name: e.target.value });\n }}\n />\n \n \n Genre: \n {\n this.setState({ genre: e.target.value });\n }}\n />\n \n \n Author: \n {\n this.setState({ authorId: e.target.value });\n }}\n >\n Select author\n {this.displayAuthors()}\n \n \n +\n \n );\n }\n}\n\nexport default compose(\n graphql(getAuthorsQuery, { name: \"getAuthorsQuery\" }),\n graphql(addBookMutation, { name: \"addBookMutation\" })\n)(AddBook);\n```\n\nI expected compose to be imported from react-apollo and to take the query and mutation and make them available inside of AddBook's props, so I can use them in the displayAuthors() and submitForm() funtions, but instead I get the error that it is not exported from react-apollo, and when I try the suggested solutions I found online I get the other errors mentioned above.\n\n========================================\n\nTop Answer:\n`compose` was removed from React Apollo 3 (see the Breaking Changes). \nNow, to use compose, use lodash's flowRight.\n\nInstall flowright: \n\n`yarn add lodash.flowright`\n\nReplace in your code: \n\n`import { compose } from 'react-apollo'`\n\nby \n\n`import {flowRight as compose} from 'lodash';`\n\n========================================\n\nCode:\n```text\nimport React from \"react\";\nimport ApolloClient from \"apollo-boost\";\nimport { ApolloProvider } from \"react-apollo\";\n\nimport BookList from \"./components/BookList\";\nimport AddBook from \"./components/AddBook\";\n\n//apollo client setup\nconst client = new ApolloClient({\n uri: \"http://localhost:4000/graphql\"\n});\n\nfunction App() {\n return (\n <ApolloProvider client={client}>\n <div className=\"main\">\n <h1>My Reading List</h1>\n <BookList />\n <AddBook />\n </div>\n </ApolloProvider>\n );\n}\n\nexport default App;\n```\n\n```text\nimport { gql } from \"apollo-boost\";\n\nconst getBooksQuery = gql`\n {\n books {\n name\n id\n }\n }\n`;\n\nconst getAuthorsQuery = gql`\n {\n authors {\n name\n id\n }\n }\n`;\n\nconst addBookMutation = gql`\n mutation {\n addBook(name: \"\", genre: \"\", authorId: \"\") {\n name\n id\n }\n }\n`;\n\nexport { getAuthorsQuery, getBooksQuery, addBookMutation };\n```\n\n```text\nimport React, { Component } from \"react\";\nimport { graphql } from \"react-apollo\";\nimport { compose } from \"recompose\";\n// import * as compose from \"lodash\";\nimport { getAuthorsQuery, addBookMutation } from \"../queries/queries\";\n\nclass AddBook extends Component {\n state = {\n name: \"\",\n genre: \"\",\n authorId: \"\"\n };\n\n displayAuthors = () => {\n let data = this.props.data;\n if (data.loading) {\n return <option>loading authors...</option>;\n } else {\n return data.authors.map(author => {\n return (\n <option key={author.id} value={author.id}>\n {author.name}\n </option>\n );\n });\n }\n };\n\n submitForm(e) {\n e.preventDefault();\n console.log(this.state);\n }\n\n render() {\n return (\n <form onSubmit={this.submitForm.bind(this)}>\n <div className=\"field\">\n <label>Book name: </label>\n <input\n type=\"text\"\n onChange={e => {\n this.setState({ name: e.target.value });\n }}\n />\n </div>\n <div className=\"field\">\n <label>Genre: </label>\n <input\n type=\"text\"\n onChange={e => {\n this.setState({ genre: e.target.value });\n }}\n />\n </div>\n <div className=\"field\">\n <label>Author: </label>\n <select\n onChange={e => {\n this.setState({ authorId: e.target.value });\n }}\n >\n <option>Select author</option>\n {this.displayAuthors()}\n </select>\n </div>\n <button>+</button>\n </form>\n );\n }\n}\n\nexport default compose(\n graphql(getAuthorsQuery, { name: \"getAuthorsQuery\" }),\n graphql(addBookMutation, { name: \"addBookMutation\" })\n)(AddBook);\n```\n\n```text\ncompose\n```\n\n```text\nimport { compose } from \"react-apollo\"\n```\n\n```text\nimport { compose } from \"recompose\"\n```\n\n```text\nTypeError: Cannot read property 'loading' of undefined\n```\n\n```text\nimport * as compose from \"lodash\"\n```\n\n```text\nΓ TypeError: lodash__WEBPACK_IMPORTED_MODULE_2__(...) is not a function\n```\n\n```text\nnpm install lodash\n```\n\n```text\nimport {flowRight as compose} from 'lodash';\n```\n\n```text\ncompose\n```\n\n```text\nflowRight\n```\n\n```text\ncompose\n```\n\n```text\nyarn add lodash.flowright\n```\n\n```text\nimport { compose } from 'react-apollo'\n```\n\n```text\nimport {flowRight as compose} from 'lodash';\n```\n\n```text\nimport React, { Component } from 'react';\n//import { compose } from \"recompose\";\nimport {flowRight as compose} from 'lodash';\nimport {graphql} from 'react-apollo';\nimport {getAuthorsQuery,addBookMutation} from '../queries/queries';\n```\n\n```js\nnpm install lodash.flowright\nimport * as compose from 'lodash.flowright';\n```\n\n```text\nexport default graphql(addBookMutation)(graphql(getAuthorsQuery)(AddBook))\n```\n\n```text\nimport React, {Component} from 'react';\nimport {getAuthersQuery , AddBookMutation } from '../quearies/quearies'\n\nimport { gql } from 'apollo-boost' \n\nimport { graphql } from 'react-apollo' \nimport {flowRight as compose} from 'lodash';\n```\n\n```text\nimport {useQuery} from \"@apollo/react-hooks\";\nimport React, {useState} from \"react\";\nimport {getAuthorsQuery, addBookMutation} from \"../queries/queries.js\";\nimport { graphql } from \"react-apollo\";\n// import { flowRight as compose } from \"lodash\";\n// import {* as compose} from \"lodash.flowRight\";\n\n\nconst AddBook = (props) => {\nconst [formData, setFormData] = useState({\n name : \"\",\n genre : \"\",\n authorId : \"\"\n});\n\nconst authorsData = useQuery(getAuthorsQuery);\n\n\nfunction displayAuthors(){\n\n console.log(authorsData)\n\n if(authorsData.loading){\n return( <option disabled >Loading Authors...</option> )\n }\n else{\n return( authorsData.data.authors.map(author => {\n return( <option key={author.id} value={author.id}>{author.name}</option>)\n }))\n }\n}\n\nfunction submitForm(e){\n e.preventDefault();\n console.log(formData);\n}\n \nreturn(\n <form id=\"add-book\" onSubmit={(e) => submitForm(e)}>\n <div className=\"field\" > \n <label>Book Name:</label>\n <input type=\"text\" onChange={(e) => setFormData({name : \ne.target.value})}/>\n </div>\n\n <div className=\"field\" > \n <label>Genre:</label>\n <input type=\"text\" onChange={(e) => setFormData({genre : \ne.target.value})}/>\n </div>\n\n <div className=\"field\" > \n <label>Author:</label>\n <select onChange={(e) => setFormData({authorId : e.target.value})}>\n <option>Select Author</option>\n {displayAuthors()}\n </select>\n </div>\n\n <button>+</button>\n </form>\n)}\nexport default graphql(addBookMutation)(AddBook);\n```\n\n========================================\n\nComments:\n- Do you have a vanilla solution?\n- I'd like to know why `composer` was removed, before start using a hack solution. if compose was removed is because is a bad practice or something, so what is the better approach.\n- compose has been removed github.com/apollographql/react-apollo/blob/…, it was just a copy of lodash's flowRight github.com/apollographql/react-apollo/issues/3330\n- Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":470,"estimatedTokens":2474}}273{"id":"stack-63123558","source":"stackoverflow","questionId":63123558,"title":"Apollo GraphQL merge cached data","tags":["javascript","reactjs","caching","graphql","apollo"],"text":"Title: Apollo GraphQL merge cached data\nTags: javascript, reactjs, caching, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI have a page that consists of 2 components and each of them has its own request for data\nfor example\n\n```\n\nconst GET_MOVIE_INFO = `gql\n query($id: String!){\n movie(id: $id){\n name\n description\n }\n}`\n```\n\nNext component\n\n```\n\nconst GET_MOVIE_ACTORS = `gql\n query($id: String!){\n movie(id: $id){\n actors\n }\n}`\n```\n\nFor each of these queries I use apollo hook\n\nconst { data, loading, error } = useQuery(GET_DATA, {variable: {id: queryParamsId}}))\n\nEverything is fine, but I got a warning message:\n\nCache data may be lost when replacing the movie field of a Query object.\nTo address this problem (which is not a bug in Apollo Client), either ensure all objects of type Movie have IDs, or define a custom merge function for the Query.movie field, so InMemoryCache can safely merge these objects: { ... }\n\nIt's works ok with google chrome, but this error affects Safari browser. Everything is crushing. I'm 100% sure it's because of this warning message. On the first request, I set Movie data in the cache, on the second request to the same query I just replace old data with new, so previous cached data is undefined. How can I resolve this problem?\n\n========================================\n\nTop Answer:\nHere is the same solution mentioned by Thomas but a bit shorter\n\n```\nconst cache = new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n YOUR_FIELD: {\n // shorthand \n merge: true,\n },\n },\n },\n },\n});\n```\n\nThis is same as the following\n\n```\nconst cache = new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n YOUR_FIELD: {\n merge(existing, incoming, { mergeObjects }) {\n return mergeObjects(existing, incoming);\n },\n },\n },\n },\n },\n});\n```\n\n========================================\n\nCode:\n```text\n<MovieInfo movieId={queryParamsId}/>\n\nconst GET_MOVIE_INFO = `gql\n query($id: String!){\n movie(id: $id){\n name\n description\n }\n}`\n```\n\n```text\n<MovieActors movieId={queryParamsId}/>\n\nconst GET_MOVIE_ACTORS = `gql\n query($id: String!){\n movie(id: $id){\n actors\n }\n}`\n```\n\n```text\ncache: new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n YOUR_FIELD: {\n merge(existing = [], incoming: any) {\n return { ...existing, ...incoming };\n // this part of code depends on what you actually need to do\n // in my case I had to save my incoming data as single object in cache\n }\n }\n }\n }\n }\n })\n});\n```\n\n```text\nconst typePolicies = {\n PROBLEM_TYPE: {\n keyFields: false as false,\n },\n PARENT_TYPE: {\n fields: {\n PROBLEM_FIELD: {\n merge: true\n }\n }\n }\n }\n```\n\n```text\nconst cache = new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n YOUR_FIELD: {\n // shorthand \n merge: true,\n },\n },\n },\n },\n});\n```\n\n```text\nconst cache = new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n YOUR_FIELD: {\n merge(existing, incoming, { mergeObjects }) {\n return mergeObjects(existing, incoming);\n },\n },\n },\n },\n },\n});\n```\n\n```js\nconst cache = new InMemoryCache({\n typePolicies: {\n YOUR_TYPE_NAME: {\n merge: true,\n }\n }\n});\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- in other words: \"your queried (requested) `movie` [type] should contain `id` property\" (beside `name`, `description` or `actors`) - otherwise it is not cache'able - [you can use other named unique field and conversion function] - cache just works this way, it wants unique objects\n- \"*ensure all objects of type Movie have IDs*\" is quite clear imo\n- using `id` in both queries does the same\n- I had a similar issue and I am retuning ids in both, but it doesn't work for me @xadm\n- @xadm My man... was about to start pulling my hair before I saw your comment.\n- Using `id` in both queries worked for me as well.\n- I'm confused; why wouldn't that be the default behavior for types with an `id` field. Apollo can tell two objects are the same object if they have the same id, so just merge them.\n- @matrixfrog it is the default behavior for types with an `id` field, this setup is only for special cases where one is not available for whatever reason (definitely preferable to design the API side such that this isn't necessary). (Just updated my answer to be clear on this)\n- Okay that makes sense, but I was still getting a warning, even with `id`s on all objects. However, since posting that comment, I think I solved it by upgrading to the latest Apollo Client version.","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":197,"estimatedTokens":1180}}274{"id":"stack-43449564","source":"stackoverflow","questionId":43449564,"title":"Why GraphQL `implements` need to duplicate the fields, is that mandatory? If yes, what is the underlying reasons?","tags":["graphql","graphql-js"],"text":"Title: Why GraphQL `implements` need to duplicate the fields, is that mandatory? If yes, what is the underlying reasons?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nWhy GraphQL `implements` keyword need to duplicate the fields, is that mandatory? Like the examples in the document:\n\n```\nenum Episode { NEWHOPE, EMPIRE, JEDI }\n\ninterface Character {\n id: String\n name: String\n friends: [Character]\n appearsIn: [Episode]\n}\n\ntype Human implements Character {\n id: String\n name: String\n friends: [Character]\n appearsIn: [Episode]\n homePlanet: String\n}\n\ntype Droid implements Character {\n id: String\n name: String\n friends: [Character]\n appearsIn: [Episode]\n primaryFunction: String\n}\n```\n\nIf yes, what is the underlying reasons?\n\nCoz If I have to duplicate, if I change then i need to change everywhere...\n\n========================================\n\nTop Answer:\nYes it's mandatory. If it helps, think of it as analogous to Java classes and interfaces. The interfaces have the type signatures, but cannot have an implementation. It is in the classes where you write out all the implementation, and the type signatures get repeated. This gives you the ability to choose subtypes or covariant types in the types signatures, so they might not be *exactly* the same.\n\nNow suppose you are creating a GraphQL schema with the JavaScript objects from graphql-js. The interfaces are simply field names and types. The Object Type definitions themselves have the \"implementation,\" or the `resolve`, `resolveType`, and other properties that actually make it an executable schema.\n\nYour example, however, uses the schema language instead, which has no \"implementation\" at all. So they pretty much are an exact repetition of one another. You don't necessarily need to spell it all out every time, you could use string interpolation to parts of the interface.\n\n```\nconst characterFields = `\n id: String\n name: String\n friends: [Character]\n appearsIn: [Episode]\n`\n\nconst typeDefs = `\n interface Character {\n ${characterFields}\n }\n\n type Human Implements Character {\n ${characterFields}\n homePlanet: String\n }\n`\n```\n\nEDIT: Analogous to the Java comparison, the fields may not be *exactly* the same type. As RomanHotsiy pointed out, you can make the types non-nullable or use subtypes of polymorphic types.\n\n========================================\n\nCode:\n```text\nenum Episode { NEWHOPE, EMPIRE, JEDI }\n\ninterface Character {\n id: String\n name: String\n friends: [Character]\n appearsIn: [Episode]\n}\n\ntype Human implements Character {\n id: String\n name: String\n friends: [Character]\n appearsIn: [Episode]\n homePlanet: String\n}\n\ntype Droid implements Character {\n id: String\n name: String\n friends: [Character]\n appearsIn: [Episode]\n primaryFunction: String\n}\n```\n\n```text\nimplements\n```\n\n```text\ninterface Character {\n id: String\n name: String\n friends: [Character]\n appearsIn: [Episode]\n}\n\ntype Human implements Character {\n id: String\n name: String\n friends: [Human] # <- notice Human here\n appearsIn: [Episode]\n homePlanet: String\n}\n\ntype Droid implements Character {\n id: String\n name: String\n friends: [Droid!]! # <- specified Droid here + added not null\n appearsIn: [Episode]\n primaryFunction: String\n}\n```\n\n```text\nconst characterFields = `\n id: String\n name: String\n friends: [Character]\n appearsIn: [Episode]\n`\n\nconst typeDefs = `\n interface Character {\n ${characterFields}\n }\n\n type Human Implements Character {\n ${characterFields}\n homePlanet: String\n }\n`\n```\n\n```text\nresolve\n```\n\n```text\nresolveType\n```\n\n========================================\n\nComments:\n- Thank you very much for the answer and the great comparison, but only one answer can be selected, combined would be the best.\n- @andy-carlson What would the difference be between having an external file containing the common fields for `character` and `Human`, then adding to the fields like `...characterFields`?","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":161,"estimatedTokens":980}}275{"id":"stack-53012629","source":"stackoverflow","questionId":53012629,"title":"Apollo Client sending OPTIONS instead of GET HTTP method","tags":["javascript","meteor","graphql","apollo-client"],"text":"Title: Apollo Client sending OPTIONS instead of GET HTTP method\nTags: javascript, meteor, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm having trouble understanding Apollo Client library as it does not work as intended. Instead of sending the **`GET`** HTTP method, it sends the **`OPTIONS`** HTTP method even though I've put to use **GET** only when retrieving data from GraphQL server.\n\n```\nconst client = new ApolloClient({\n link: ApolloLink.from([\n new MeteorAccountsLink(),\n new HttpLink({\n uri: 'https://selo-comments.herokuapp.com/graphql',\n useGETForQueries: true\n })\n ]),\n cache: new InMemoryCache()\n});\n```\n\nConsole log from the browser:\n`OPTIONS https://selo-comments.herokuapp.com/graphql?query=%7B%0A%20%20comments(id%3A%20%22TFpQmhrDxQqHk2ryy%22)%20%7B%0A%20%20%20%20articleID%0A%20%20%20%20content%0A%20%20%20%20userId%0A%20%20%20%20createdAt%0A%20%20%20%20commentID%0A%20%20%20%20votes%0A%20%20%20%20blockedUsers%0A%20%20%20%20__typename%0A%20%20%7D%0A%7D%0A&variables=%7B%7D 405 (Method Not Allowed)`\n\nWhich obviously means that the HTTP method is incorrect even if it has the query parameter in the url. If you query that url using Postman or simply navigating to the url using browser's address bar, you will get GraphQL data. I have to use `https://cors-anywhere.herokuapp.com/` in order to execute the query successfully.\n\nWhat am I doing wrong?\n\n========================================\n\nCode:\n```text\nconst client = new ApolloClient({\n link: ApolloLink.from([\n new MeteorAccountsLink(),\n new HttpLink({\n uri: 'https://selo-comments.herokuapp.com/graphql',\n useGETForQueries: true\n })\n ]),\n cache: new InMemoryCache()\n});\n```\n\n```text\nGET\n```\n\n```text\nOPTIONS\n```\n\n```text\nOPTIONS https://selo-comments.herokuapp.com/graphql?query=%7B%0A%20%20comments(id%3A%20%22TFpQmhrDxQqHk2ryy%22)%20%7B%0A%20%20%20%20articleID%0A%20%20%20%20content%0A%20%20%20%20userId%0A%20%20%20%20createdAt%0A%20%20%20%20commentID%0A%20%20%20%20votes%0A%20%20%20%20blockedUsers%0A%20%20%20%20__typename%0A%20%20%7D%0A%7D%0A&variables=%7B%7D 405 (Method Not Allowed)\n```\n\n```text\nhttps://cors-anywhere.herokuapp.com/\n```\n\n========================================\n\nComments:\n- Wow, that actually fixed the problem haha. I wasn't even aware of this, thank you!\n- I already had a CORS module on the server but it was still giving me headaches on the client side, but thanks again.","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":64,"estimatedTokens":610}}276{"id":"stack-32551022","source":"stackoverflow","questionId":32551022,"title":"How do i create a graphql schema for a self referencing data hierarchy?","tags":["graphql","relayjs"],"text":"Title: How do i create a graphql schema for a self referencing data hierarchy?\nTags: graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nThis doesnt work because the type refers to its self in the routes field definition:\n\n```\nvar routeType = new GraphQLObjectType({\n name: 'MessageRoute',\n fields: {\n name: {\n type: GraphQLString\n },\n routes: {\n type: new GraphQLList(routeType),\n resolve: (route) => {\n return route.routes;\n }\n }\n }\n});\n```\n\nso how do I do it?\n\n========================================\n\nTop Answer:\nI'd like to point out that you can use a function for any property inside an object using Javascript getter.\n\nSo instead of wrapping the whole `fields` property within a function you can use a function just for the `type` property like this: \n\n```\nvar routeType = new GraphQLObjectType({\n name: 'MessageRoute',\n fields: {\n name: {\n type: GraphQLString\n },\n routes: {\n get type() {\n return new GraphQLList(routeType)\n },\n resolve: (route) => {\n return route.routes;\n }\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\nvar routeType = new GraphQLObjectType({\n name: 'MessageRoute',\n fields: {\n name: {\n type: GraphQLString\n },\n routes: {\n type: new GraphQLList(routeType),\n resolve: (route) => {\n return route.routes;\n }\n }\n }\n});\n```\n\n```js\nvar routeType = new GraphQLObjectType({\n name: 'MessageRoute',\n fields: function () {\n return {\n name: {\n type: GraphQLString\n },\n routes: {\n type: new GraphQLList(routeType),\n resolve: (route) => {\n return route.routes;\n }\n }\n };\n }\n});\n```\n\n```js\nvar routeType = new GraphQLObjectType({\n name: 'MessageRoute',\n fields: () => ({\n name: {\n type: GraphQLString\n },\n routes: {\n type: new GraphQLList(routeType),\n resolve: (route) => {\n return route.routes;\n }\n }\n })\n});\n```\n\n```text\nfields\n```\n\n```text\nvar routeType = new GraphQLObjectType({\n name: 'MessageRoute',\n fields: {\n name: {\n type: GraphQLString\n },\n routes: {\n get type() {\n return new GraphQLList(routeType)\n },\n resolve: (route) => {\n return route.routes;\n }\n }\n }\n});\n```\n\n```text\nfields\n```\n\n```text\ntype\n```\n\n========================================\n\nComments:\n- Cool thanks, any idea how I write the react side of things without getting a stack overflow?\n- Is there a way for the result of a graphql query to be self referencing? I understand this is possible in XML - I have quite a basic understanding of GraphQL at this point. Is it possible that the graphql engine resolves XML instead of JSON?","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":144,"estimatedTokens":663}}277{"id":"stack-34952792","source":"stackoverflow","questionId":34952792,"title":"How do I structure authenticated queries with GraphQL?","tags":["authentication","graphql"],"text":"Title: How do I structure authenticated queries with GraphQL?\nTags: authentication, graphql\nSource: Stack Overflow\n\nQuestion:\nI was thinking of writing an API that does the following things:\n\n- Sign-up and sign-in users which provide the user with an authentication token\n\n- Create maps (data example: `{ name: βQuotesβ, attributes: [βquoteβ, βauthor\"] }`)\n\n- Create map items (data example: `{ quote: \"...\", author: \"...\" }`)\n\nI would build the queries somewhat like this:\n\n```\n// return the name and id of all the user's maps\nmaps(authToken=\"β¦\") {\nΒ name,\nΒ id\n}\n\n// return all the items of a single map\nmaps(authToken=\"β¦\") {\nΒ map(name=βQuotes\") {\nΒ Β items\nΒ }\n}\n\n// OR by using the map_id\nmaps(authToken=\"β¦\") {\nΒ map(id=ββ¦\") {\nΒ Β items\nΒ }\n}\n```\n\n**So, my question is, is this correct or would I need to structure it differently?**\n\n========================================\n\nTop Answer:\nI offered an approach that structures resolvers as a composition of smaller functions to help in solving this exact problem. You can see the full answer here: How to check permissions and other conditions in GraphQL query?.\n\nThe basic concept is that if you structure your resolvers as small functions that are composed together you can layer different authorization/authenication mechanisms on top of one another and throw an error in the first one that is not satisfied. This will help keep your code clean, testable, and re-usable as well :)\n\nAlso yes, the resolver context is a great place to store authentication information as well as other goodies that might need to be used throughout your resolvers.\n\nHappy Hacking!\n\n========================================\n\nCode:\n```text\n// return the name and id of all the user's maps\nmaps(authToken=\"β¦\") {\nΒ name,\nΒ id\n}\n\n// return all the items of a single map\nmaps(authToken=\"β¦\") {\nΒ map(name=βQuotes\") {\nΒ Β items\nΒ }\n}\n\n// OR by using the map_id\nmaps(authToken=\"β¦\") {\nΒ map(id=ββ¦\") {\nΒ Β items\nΒ }\n}\n```\n\n```text\n{ name: βQuotesβ, attributes: [βquoteβ, βauthor\"] }\n```\n\n```text\n{ quote: \"...\", author: \"...\" }\n```\n\n```text\napp.use('/graphql', (request, response, next) => {\n const viewer = getViewerFromRequest(); // You provide this.\n const options = {\n rootValue: {\n viewer,\n },\n schema,\n };\n\n return graphqlHTTP(request => options)(request, response, next);\n});\n```\n\n```text\nresolve: (parent, args, {rootValue}) => {\n const viewer = {rootValue};\n\n // Code that uses viewer here...\n}\n```\n\n```text\nresolve: (parent, args, authToken, {rootValue}) => {\n // Code that uses the auth token here...\n}\n```\n\n```text\nexpress-graphql\n```\n\n```text\nrootValue\n```\n\n```text\nresolve\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":122,"estimatedTokens":660}}278{"id":"stack-49809261","source":"stackoverflow","questionId":49809261,"title":"AttributeError: type object 'User' has no attribute 'name'","tags":["django","python-3.x","django-models","graphql","graphene-python"],"text":"Title: AttributeError: type object 'User' has no attribute 'name'\nTags: django, python-3.x, django-models, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nIβm new with graphene and I have this:\n\n```\nfrom django.contrib.auth.models import User\n\nclass UserType(DjangoObjectType):\n class Meta:\n model = User\n```\n\nBasically, using Djangoβs User class is giving me this error, because before using the django User class, I was using my own User definition and it worked. Why using the User class from the django authentication framework is giving me the error mentioned in the title:\n\n File β/usr/local/lib/python3.6/site-packages/graphql/type/typemap.pyβ,\n line 60, in reducer if type.name in map: AttributeError: type object\n βUserβ has no attribute βnameβ\n\nAm I missing something?\n\nRegards\n\nPD: Iβm using Django 2.0.4\n\n**Traceback**\n\n```\nUnhandled exception in thread started by .wrapper at 0x107c49e18>\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py\", line 225, in wrapper\n fn(*args, **kwargs)\n File \"/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py\", line 120, in inner_run\n self.check(display_num_errors=True)\n File \"/usr/local/lib/python3.6/site-packages/django/core/management/base.py\", line 364, in check\n include_deployment_checks=include_deployment_checks,\n File \"/usr/local/lib/python3.6/site-packages/django/core/management/base.py\", line 351, in _run_checks\n return checks.run_checks(**kwargs)\n File \"/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py\", line 73, in run_checks\n new_errors = check(app_configs=app_configs)\n File \"/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py\", line 13, in check_url_config\n return check_resolver(resolver)\n File \"/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py\", line 23, in check_resolver\n return check_method()\n File \"/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py\", line 397, in check\n for pattern in self.url_patterns:\n File \"/usr/local/lib/python3.6/site-packages/django/utils/functional.py\", line 36, in __get__\n res = instance.__dict__[self.name] = self.func(instance)\n File \"/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py\", line 536, in url_patterns\n patterns = getattr(self.urlconf_module, \"urlpatterns\", self.urlconf_module)\n File \"/usr/local/lib/python3.6/site-packages/django/utils/functional.py\", line 36, in __get__\n res = instance.__dict__[self.name] = self.func(instance)\n File \"/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py\", line 529, in urlconf_module\n return import_module(self.urlconf_name)\n File \"/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py\", line 126, in import_module\n return _bootstrap._gcd_import(name[level:], package, level)\n File \"\", line 994, in _gcd_import\n File \"\", line 971, in _find_and_load\n File \"\", line 955, in _find_and_load_unlocked\n File \"\", line 665, in _load_unlocked\n File \"\", line 678, in exec_module\n File \"\", line 219, in _call_with_frames_removed\n File \"/Users/freddy/PycharmProjects/DYD/DYD/urls.py\", line 19, in \n from dyd_server.graphql import schema\n File \"/Users/freddy/PycharmProjects/DYD/dyd_server/graphql/__init__.py\", line 10, in \n schema = graphene.Schema(query=RootQuery, mutation=Mutations)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/schema.py\", line 57, in __init__\n self.build_typemap()\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/schema.py\", line 123, in build_typemap\n schema=self\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 69, in __init__\n super(TypeMap, self).__init__(types)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/typemap.py\", line 16, in __init__\n self.update(reduce(self.reducer, types, OrderedDict()))\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 77, in reducer\n return self.graphene_reducer(map, type)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 107, in graphene_reducer\n return GraphQLTypeMap.reducer(map, internal_type)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/typemap.py\", line 80, in reducer\n field_map = type.fields\n File \"/usr/local/lib/python3.6/site-packages/graphql/pyutils/cached_property.py\", line 16, in __get__\n value = obj.__dict__[self.func.__name__] = self.func(obj)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/definition.py\", line 180, in fields\n return define_field_map(self, self._fields)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/definition.py\", line 189, in define_field_map\n field_map = field_map()\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 250, in construct_fields_for_type\n map = self.reducer(map, field.type)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 77, in reducer\n return self.graphene_reducer(map, type)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 107, in graphene_reducer\n return GraphQLTypeMap.reducer(map, internal_type)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/typemap.py\", line 80, in reducer\n field_map = type.fields\n File \"/usr/local/lib/python3.6/site-packages/graphql/pyutils/cached_property.py\", line 16, in __get__\n value = obj.__dict__[self.func.__name__] = self.func(obj)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/definition.py\", line 180, in fields\n return define_field_map(self, self._fields)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/definition.py\", line 189, in define_field_map\n field_map = field_map()\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 250, in construct_fields_for_type\n map = self.reducer(map, field.type)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 78, in reducer\n return GraphQLTypeMap.reducer(map, type)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/typemap.py\", line 60, in reducer\n if type.name in map:\nAttributeError: type object 'User' has no attribute 'name'\n```\n\n========================================\n\nTop Answer:\nAs suggested by your error, Django's default `User` model does not have a field called `name`.\n\nInstead, it has two similar fields, `first_name`, and `last_name`.\n\nIf you would like to use the combination of the two, use the `get_full_name()` method.\n\n========================================\n\nCode:\n```text\nfrom django.contrib.auth.models import User\n\nclass UserType(DjangoObjectType):\n class Meta:\n model = User\n```\n\n```text\nUnhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x107c49e18>\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py\", line 225, in wrapper\n fn(*args, **kwargs)\n File \"/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py\", line 120, in inner_run\n self.check(display_num_errors=True)\n File \"/usr/local/lib/python3.6/site-packages/django/core/management/base.py\", line 364, in check\n include_deployment_checks=include_deployment_checks,\n File \"/usr/local/lib/python3.6/site-packages/django/core/management/base.py\", line 351, in _run_checks\n return checks.run_checks(**kwargs)\n File \"/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py\", line 73, in run_checks\n new_errors = check(app_configs=app_configs)\n File \"/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py\", line 13, in check_url_config\n return check_resolver(resolver)\n File \"/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py\", line 23, in check_resolver\n return check_method()\n File \"/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py\", line 397, in check\n for pattern in self.url_patterns:\n File \"/usr/local/lib/python3.6/site-packages/django/utils/functional.py\", line 36, in __get__\n res = instance.__dict__[self.name] = self.func(instance)\n File \"/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py\", line 536, in url_patterns\n patterns = getattr(self.urlconf_module, \"urlpatterns\", self.urlconf_module)\n File \"/usr/local/lib/python3.6/site-packages/django/utils/functional.py\", line 36, in __get__\n res = instance.__dict__[self.name] = self.func(instance)\n File \"/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py\", line 529, in urlconf_module\n return import_module(self.urlconf_name)\n File \"/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py\", line 126, in import_module\n return _bootstrap._gcd_import(name[level:], package, level)\n File \"<frozen importlib._bootstrap>\", line 994, in _gcd_import\n File \"<frozen importlib._bootstrap>\", line 971, in _find_and_load\n File \"<frozen importlib._bootstrap>\", line 955, in _find_and_load_unlocked\n File \"<frozen importlib._bootstrap>\", line 665, in _load_unlocked\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n File \"/Users/freddy/PycharmProjects/DYD/DYD/urls.py\", line 19, in <module>\n from dyd_server.graphql import schema\n File \"/Users/freddy/PycharmProjects/DYD/dyd_server/graphql/__init__.py\", line 10, in <module>\n schema = graphene.Schema(query=RootQuery, mutation=Mutations)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/schema.py\", line 57, in __init__\n self.build_typemap()\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/schema.py\", line 123, in build_typemap\n schema=self\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 69, in __init__\n super(TypeMap, self).__init__(types)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/typemap.py\", line 16, in __init__\n self.update(reduce(self.reducer, types, OrderedDict()))\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 77, in reducer\n return self.graphene_reducer(map, type)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 107, in graphene_reducer\n return GraphQLTypeMap.reducer(map, internal_type)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/typemap.py\", line 80, in reducer\n field_map = type.fields\n File \"/usr/local/lib/python3.6/site-packages/graphql/pyutils/cached_property.py\", line 16, in __get__\n value = obj.__dict__[self.func.__name__] = self.func(obj)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/definition.py\", line 180, in fields\n return define_field_map(self, self._fields)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/definition.py\", line 189, in define_field_map\n field_map = field_map()\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 250, in construct_fields_for_type\n map = self.reducer(map, field.type)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 77, in reducer\n return self.graphene_reducer(map, type)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 107, in graphene_reducer\n return GraphQLTypeMap.reducer(map, internal_type)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/typemap.py\", line 80, in reducer\n field_map = type.fields\n File \"/usr/local/lib/python3.6/site-packages/graphql/pyutils/cached_property.py\", line 16, in __get__\n value = obj.__dict__[self.func.__name__] = self.func(obj)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/definition.py\", line 180, in fields\n return define_field_map(self, self._fields)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/definition.py\", line 189, in define_field_map\n field_map = field_map()\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 250, in construct_fields_for_type\n map = self.reducer(map, field.type)\n File \"/usr/local/lib/python3.6/site-packages/graphene/types/typemap.py\", line 78, in reducer\n return GraphQLTypeMap.reducer(map, type)\n File \"/usr/local/lib/python3.6/site-packages/graphql/type/typemap.py\", line 60, in reducer\n if type.name in map:\nAttributeError: type object 'User' has no attribute 'name'\n```\n\n```text\nuser = graphene.Field(UserType)\n```\n\n```text\nuser = graphene.Field(User)\n```\n\n```text\nUser\n```\n\n```text\nname\n```\n\n```text\nfirst_name\n```\n\n```text\nlast_name\n```\n\n```text\nget_full_name()\n```\n\n========================================\n\nComments:\n- I think you'd used `user_obj.name` in your code. Replace that with `user_obj.username`\n- @JerinPeterGeorge no I'm not, the obj.name call i have in my project is country_gql = CountryType(id=country_db.id, code=country_db.code, name=country_db.name), where country_db is another model class. Thanks for you answer my friend.\n- The `User` model in `django.contrib.auth.models` has a name field. Try using `first_name` or `last_name`\n- But my question is mor related to where the issue is? In my model or in my schema? because it doesnβt make any sense that User model doesnβt have any name attribute when en my entire project Iβm not using obj.name because I donβt have it only for my country model which only has two field: name and code. :(\n- I made this same mistake a bunch of times -- maybe I'll make a pull request to make the error friendlier, e.g. \"Object \"User\" is not a \"DjangoObjectType\"\n- Thankyou, Problem solved, I am new to django, but have a php laravel background and i sometimes can not understand the errors that django throw at us.\n- Well, it doesn't look like I'm ever going to get around to making that pull request. Be my guest, dear reader.","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":251,"estimatedTokens":3448}}279{"id":"stack-45083756","source":"stackoverflow","questionId":45083756,"title":"How to resolve nested types in GraphQL?","tags":["javascript","graphql"],"text":"Title: How to resolve nested types in GraphQL?\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm having trouble resolving graphql nested types. I can successfully get the `UserMetrics` nested resolver to fire, but the parent resolver object (user) is null. Am I misunderstanding the GraphQL resolver map?\n\nSchema:\n\n```\ntype User {\n id: String!\n metrics: UserMetrics\n}\n\ntype UserMetrics {\n lastLogin: String!\n}\n```\n\nResolver:\n\n```\nQuery: {\n user(_, { id }, ctx) {\n return { id }; \n }\n},\n\nUser: {\n metrics(): ({}), // UserMetrics.lastLogin doesn't fire without this\n},\n\nUserMetrics: {\n lastLogin(user) {\n console.log(user); // null\n }\n},\n```\n\n========================================\n\nCode:\n```text\ntype User {\n id: String!\n metrics: UserMetrics\n}\n\ntype UserMetrics {\n lastLogin: String!\n}\n```\n\n```text\nQuery: {\n user(_, { id }, ctx) {\n return { id }; \n }\n},\n\nUser: {\n metrics(): ({}), // UserMetrics.lastLogin doesn't fire without this\n},\n\nUserMetrics: {\n lastLogin(user) {\n console.log(user); // null\n }\n},\n```\n\n```text\nUserMetrics\n```\n\n```text\nUser\n```\n\n```text\nmetrics\n```\n\n```text\nmetrics\n```\n\n```text\n{ id }\n```\n\n```text\n{ id, metrics: { lastLogin: 'foo' }}\n```\n\n```text\nlastLogin\n```\n\n```text\n{ lastLogin: 'foo' }\n```\n\n```text\nuser\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nid\n```\n\n```text\nmetrics\n```\n\n```text\nmetrics\n```\n\n```text\n{ lastLogin: 'foo' }\n```\n\n```text\n{ lastLogin: 'foo' }\n```\n\n```text\nlastLogin\n```\n\n========================================\n\nComments:\n- Also, there's a typo in the sample you provided. `metrics() => ({}),` will throw a syntax error\n- Is it a common pattern to then pass the result of the query to connect resolvers for nested types? So `metrics: obj => obj` for above would then pass `id` down the `UserMetrics.lastLogin`.","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":145,"estimatedTokens":455}}280{"id":"stack-48476154","source":"stackoverflow","questionId":48476154,"title":"Make one of two fields required in GraphQL schema?","tags":["graphql","graphcool"],"text":"Title: Make one of two fields required in GraphQL schema?\nTags: graphql, graphcool\nSource: Stack Overflow\n\nQuestion:\nIm using Graphcool but this may be a general GraphQL question. Is there a way to make one of two fields required? \n\nFor instance say I have a Post type. Posts must be attached to either a Group or to an Event. Can this be specified in the schema? \n\n```\ntype Post {\n body: String!\n author: User!\n event: Event // This or group is required\n group: Group // This or event is required\n}\n```\n\nMy actual requirements are a bit more complicated. Posts can either be attached to an event, or must be attached to a group and a location.\n\n```\ntype Post {\n body: String!\n author: User!\n event: Event // Either this is required, \n group: Group // Or both Group AND Location are required \n location: Location \n}\n```\n\nSo this is valid:\n\n```\nmutation {\n createPost(\n body: \"Here is a comment\",\n authorId: \"\",\n eventId: \"\"\n ){\n id\n }\n}\n```\n\nAs is this:\n\n```\nmutation {\n createPost(\n body: \"Here is a comment\",\n authorId: \"\",\n groupID: \"\",\n locationID: \"\"\n ){\n id\n }\n}\n```\n\nBut this is not:\n\nAs is this:\n\n```\nmutation {\n createPost(\n body: \"Here is a comment\",\n authorId: \"\",\n groupID: \"\",\n ){\n id\n }\n}\n```\n\n========================================\n\nTop Answer:\nOne way to represent this in the schema is to use unions , in your case it could be something like this:\n\n```\ntype LocatedGroup {\n group: Group!\n location: Location!\n}\n\nunion Attachable = Event | LocatedGroup\n\ntype Post {\n body: String!\n author: User!\n attachable: Attachable!\n}\n```\n\n========================================\n\nCode:\n```text\ntype Post {\n body: String!\n author: User!\n event: Event // This or group is required\n group: Group // This or event is required\n}\n```\n\n```text\ntype Post {\n body: String!\n author: User!\n event: Event // Either this is required, \n group: Group // Or both Group AND Location are required \n location: Location \n}\n```\n\n```text\nmutation {\n createPost(\n body: \"Here is a comment\",\n authorId: \"<UserID>\",\n eventId: \"<EventID>\"\n ){\n id\n }\n}\n```\n\n```text\nmutation {\n createPost(\n body: \"Here is a comment\",\n authorId: \"<UserID>\",\n groupID: \"<GroupID>\",\n locationID: \"<LocationID>\"\n ){\n id\n }\n}\n```\n\n```text\nmutation {\n createPost(\n body: \"Here is a comment\",\n authorId: \"<UserID>\",\n groupID: \"<GroupID>\",\n ){\n id\n }\n}\n```\n\n```text\n(obj, {eventId, groupID, locationID}) => {\n if (\n (eventID && !groupID && !locationID) ||\n (groupID && locationID && !eventID)\n ) {\n // resolve normally\n }\n throw new Error('Invalid inputs')\n}\n```\n\n```text\ntype LocatedGroup {\n group: Group!\n location: Location!\n}\n\nunion Attachable = Event | LocatedGroup\n\ntype Post {\n body: String!\n author: User!\n attachable: Attachable!\n}\n```\n\n========================================\n\nComments:\n- You can use an union type, however this question is not solved. My preference goes to the @oneOf directive and the related TS equivalent","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":185,"estimatedTokens":740}}281{"id":"stack-51695337","source":"stackoverflow","questionId":51695337,"title":"refetchQueries in Mutation Component of React Apollo Client is not working?","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: refetchQueries in Mutation Component of React Apollo Client is not working?\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have a `` in my `Home.js` file\n\n### Home.js\n\n```\n\n {({ data: { product } }) => {\n return ;\n }}\n\n```\n\nIn my `Main.js` file I have `` component -\n\n### Main.js\n\n```\n {\n console.log(\"refetchQueries\", product.id);\n return {\n query: GET_TODOS_BY_PRODUCT,\n variables: { id: product.id }\n };\n }}\n>\n{switchSelectedProduct => (\n {\n switchSelectedProduct({\n variables: { id: product.id, name: product.name }\n });\n }}\n highlight={\n data.selectedProduct\n ? product.name === data.selectedProduct.name\n : i === 0\n }\n >\n {product.name}\n \n )}\n\n```\n\nWhen `switchSelectedProduct` is called inside `` component, it runs `refetchQueries` as I see the `console.log(\"refetchQueries\", product.id);` statement but I don't see the updated results in the `` component in `Home.js` file.\n\nHow do I tell `` component in `Home.js` to get notified when `refetchQueries` is run in `Main.js` file? \n\nAny suggestions?\n\n========================================\n\nTop Answer:\nFrom docs: `refetchQueries: (mutationResult: FetchResult) => Array`, so probably you need to return an array instead of just the object\n\n```\n {\n console.log(\"refetchQueries\", product.id)\n return [{\n query: GET_TODOS_BY_PRODUCT,\n variables: { id: product.id }\n }];\n}}\n>\n```\n\n========================================\n\nCode:\n```text\n<Query\n query={GET_TODOS_BY_PRODUCT}\n variables={{ id: state.get(\"selectedProduct.id\"), completed: true }}\n >\n {({ data: { product } }) => {\n return <Main todos={product.todos} hashtag={product.hashtag} />;\n }}\n</Query>\n```\n\n```text\n<Mutation\n key={v4()}\n mutation={SWITCH_SELECTED_PRODUCT}\n refetchQueries={() => {\n console.log(\"refetchQueries\", product.id);\n return {\n query: GET_TODOS_BY_PRODUCT,\n variables: { id: product.id }\n };\n }}\n>\n{switchSelectedProduct => (\n <Product\n onClick={() => {\n switchSelectedProduct({\n variables: { id: product.id, name: product.name }\n });\n }}\n highlight={\n data.selectedProduct\n ? product.name === data.selectedProduct.name\n : i === 0\n }\n >\n <Name>{product.name}</Name>\n </Product>\n )}\n</Mutation>\n```\n\n```text\n<Query />\n```\n\n```text\nHome.js\n```\n\n```text\nMain.js\n```\n\n```text\n<Mutation />\n```\n\n```text\nswitchSelectedProduct\n```\n\n```text\n<Mutation />\n```\n\n```text\nrefetchQueries\n```\n\n```text\nconsole.log(\"refetchQueries\", product.id);\n```\n\n```text\n<Query />\n```\n\n```text\nHome.js\n```\n\n```text\n<Query />\n```\n\n```text\nHome.js\n```\n\n```text\nrefetchQueries\n```\n\n```text\nMain.js\n```\n\n```text\n<Query\n query={GET_ALL_PRODUCTS}\n variables={{ id: state.get(\"user.id\") }}\n>\n {({ data: { user } }) => {\n const { id, name } = user.products ? user.products[0] : [];\n return <Main id={id} name={name} />;\n }}\n</Query>\n```\n\n```text\n<Query query={GET_SELECTED_PRODUCT}>\n <Mutation\n key={v4()}\n mutation={SWITCH_SELECTED_PRODUCT}\n >\n {switchSelectedProduct => (\n <Product\n onClick={() => {\n switchSelectedProduct({\n variables: { id: product.id, name: product.name }\n });\n }}\n highlight={\n data.selectedProduct\n ? product.name === data.selectedProduct.name\n : i === 0\n }\n >\n <Name>{product.name}</Name>\n </Product>\n )}\n </Mutation>\n</Query>\n```\n\n```text\nrefetchQueries\n```\n\n```text\nrefetchQueries\n```\n\n```text\nHome\n```\n\n```text\nQuery\n```\n\n```text\nMain\n```\n\n```text\nQuery\n```\n\n```text\nrefetchQueries\n```\n\n```text\nMutation\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\n<Mutation\n key={v4()}\n mutation={SWITCH_SELECTED_PRODUCT}\n refetchQueries={() => {\n console.log(\"refetchQueries\", product.id)\n return [{\n query: GET_TODOS_BY_PRODUCT,\n variables: { id: product.id }\n }];\n}}\n>\n```\n\n```text\nrefetchQueries: (mutationResult: FetchResult) => Array<{ query: DocumentNode, variables?: TVariables} | string>\n```\n\n```text\n<Mutation refetchQueries={[{query:YOUR_QUERY}>\n ...code\n</Mutation>\n```\n\n========================================\n\nComments:\n- Hey @alexhenkel so this worked I tried it again with some other parameters but I still can't see my `` component being re-rendered. That's my other question.\n- Works great. Thanks. Also see its documentation: apollographql.com/docs/react/essentials/mutations.html","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":278,"estimatedTokens":1242}}282{"id":"stack-53215803","source":"stackoverflow","questionId":53215803,"title":"Missing selection set for object GraphQL+Apollo error","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: Missing selection set for object GraphQL+Apollo error\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have a set of mutations that trigger the local state of certain types of popups. They're generally set up like this:\n\n```\nopenDialog: (_, variables, { cache }) => {\n const data = {\n popups: {\n ...popups,\n dialog: {\n id: 'dialog',\n __typename: 'Dialog',\n type: variables.type\n }\n }\n };\n\n cache.writeData({\n data: data\n });\n return null;\n }\n```\n\nAnd the defaults I pass in look like:\n\n```\nconst defaults = {\n popups: {\n __typename: TYPENAMES.POPUPS,\n id,\n message: null,\n modal: null,\n menu: null,\n dialog: null\n }\n};\n```\n\nThe way they're used in my React code is with a Mutation wrapper component, like so:\n\n```\nconst OPEN_ALERT_FORM = gql`\n mutation AlertOpenDialog($type: String!) {\n openDialog(type: $type) @client\n }\n`;\n\nclass Alert extends Component {\n render() {\n return (\n \n {openDialog => {\n return (\n \n );\n }}\n \n );\n }\n}\n```\n\nFor my various popups (I have 3 or 4 different ones, like `menu` and `modal`), the mutations to open and close them all look the same, just different typenames and content etc. But, for Dialogs, I get this error when I click on them:\n\n*Network error: Missing selection set for object of type Dialog returned for query field dialog*\n\n...and then the triggering component disappears from the page. Plus, once that happens, all other popup types disappear when you try clicking on them, and either re-throw that error, or say:\n\n*Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.*\n\nI've tried re-writing dialogs to match up with other popup types, and re-writing the components as well, but I'm still getting this error. It does appear to be dialog+Apollo specific.\nWhat could be the root of this issue? It can't be a backend thing, because this is only dealing with local Apollo. I haven't seen this error before and I'm not sure where to go from here.\n\n========================================\n\nTop Answer:\nSolution is to add fields to the query (vs. declaring the top-level object you want to fetch without specifying the fields to fetch). If you have something like:\n\n```\n{\n popups @client {\n id\n dialog\n }\n}\n```\n\nyou must declare some fields to fetch inside `dialog`, for example `id`:\n\n```\n{\n popups @client {\n id\n dialog {\n id\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nopenDialog: (_, variables, { cache }) => {\n const data = {\n popups: {\n ...popups,\n dialog: {\n id: 'dialog',\n __typename: 'Dialog',\n type: variables.type\n }\n }\n };\n\n cache.writeData({\n data: data\n });\n return null;\n }\n```\n\n```text\nconst defaults = {\n popups: {\n __typename: TYPENAMES.POPUPS,\n id,\n message: null,\n modal: null,\n menu: null,\n dialog: null\n }\n};\n```\n\n```text\nconst OPEN_ALERT_FORM = gql`\n mutation AlertOpenDialog($type: String!) {\n openDialog(type: $type) @client\n }\n`;\n\nclass Alert extends Component {\n render() {\n return (\n <Mutation mutation={OPEN_ALERT_FORM} variables={{ type: ALERT_FORM }}>\n {openDialog => {\n return (\n <Button\n classes=\"alert-button\"\n onClick={openDialog}\n label=\"Trigger Alert\"\n />\n );\n }}\n </Mutation>\n );\n }\n}\n```\n\n```text\nmenu\n```\n\n```text\nmodal\n```\n\n```text\nopenDialog: (_, variables, { cache }) => {\n const data = {\n popups: {\n ...popups,\n dialog: variables.type\n }\n };\n\n cache.writeData({\n data: data\n });\n return null;\n }\n```\n\n```text\ndialog\n```\n\n```text\n{\n popups @client {\n id\n dialog\n }\n}\n```\n\n```text\n{\n popups @client {\n id\n dialog {\n id\n }\n }\n}\n```\n\n```text\ndialog\n```\n\n```text\nid\n```\n\n```text\nmutation AlertOpenDialog($type: String!) {\n openDialog(type: $type) @client\n}\n```\n\n```text\nmutation AlertOpenDialog($type: String!) {\n openDialog(type: $type) @client {\n dialog {\n id\n }\n }\n}\n```\n\n```text\n@client\n```\n\n========================================\n\nComments:\n- What does the `defaults` object you pass to `withClientState` look like?\n- @DanielRearden just updated question with the defaults!\n- Hmm. It looks like that error gets thrown whenever the cache has some object (as opposed to just a scalar value) and you try to read that object from the cache without specifying a selection set (i.e. which fields on the type). You can take a look at the test here. Do you have a query that requests the `dialog` field on `popups` without specifying the fields on `dialog`?\n- i.e. something like `query { popups { dialog } }` ?\n- @DanielRearden I'll check that out, thanks! I do have a query that checks that, and it appears to be working correctly.\n- If you do have a query that's missing a selection set like that one, I suspect it's working when your cached value is null (i.e. the default), but then breaks once you populate the cache with a mutation.\n- well it does not solve the original question but rather changing data model to avoid the error. You're lucky being free to alter the model ;)","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":252,"estimatedTokens":1301}}283{"id":"stack-51517363","source":"stackoverflow","questionId":51517363,"title":"graphql, how to design input type when there are \"add\" and \"update\" mutation?","tags":["graphql","graphql-js","apollo-server"],"text":"Title: graphql, how to design input type when there are \"add\" and \"update\" mutation?\nTags: graphql, graphql-js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nHere are my requirements: \n\n\"add\" mutation, every field(or called scalar) of `BookInput` input type should have additional type modifiers \"!\" to validate the non-null value. Which means when I add a book, the argument must have `title` and `author` field, like `{title: \"angular\", author: \"novaline\"}`\n\n\"update\" mutation, I want to update a part of fields of the book, don't want to update whole book(MongoDB document, And, I don't want front-end to pass graphql server a whole big book mutation argument for saving bandwidth). Which means the book argument can be `{title: \"angular\"}` or `{title: \"angular\", author: \"novaline\"}`.\n\nHere are my type definitions:\n\n```\nconst typeDefs = `\n input BookInput {\n title: String!\n author: String!\n }\n\n type Book {\n id: ID!\n title: String!\n author: String!\n }\n\n type Query {\n books: [Book!]!\n }\n\n type Mutation{\n add(book: BookInput!): Book\n update(id: String!, book: BookInput!): Book\n }\n`;\n```\n\nFor now, \"add\" mutation works fine. But \"update\" mutation cannot pass the non-null check if I pass `{title: \"angular\"}` argument\n\nHere is a mutation which does not pass the non-null check, lack of \"author\" field for `BookInput` input type.\n\n```\nmutation {\n update(id: \"1\", book: {title: \"angular\"}) {\n id\n title\n author\n }\n}\n```\n\nSo, graphql will give me an error: \n\n```\n{\n \"errors\": [\n {\n \"message\": \"Field BookInput.author of required type String! was not provided.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 24\n }\n ]\n }\n ]\n}\n```\n\nHow do I design the `BookInput` input type? Don't want to define `addBookInput` and `updateBookInput`. It's duplicated.\n\n========================================\n\nTop Answer:\nHere is my solution, I write a helper function to generate \"create\" `input` type and \"update\" `input` type.\n\n```\nconst { parse } = require('graphql');\n\n/**\n * schema definition helper function - dynamic generate graphql input type\n *\n * @author https://github.com/mrdulin\n * @param {string} baseSchema\n * @param {object} options\n * @returns {string}\n */\nfunction generateInputType(baseSchema, options) {\n const inputTypeNames = Object.keys(options);\n const schema = inputTypeNames\n .map(inputTypeName => {\n const { validator } = options[inputTypeName];\n const validatorSchema = Object.keys(validator)\n .map(field => `${field}: ${validator[field]}\\n`)\n .join(' ');\n\n return `\n input ${inputTypeName} {\n ${baseSchema}\n ${validatorSchema}\n }\n `;\n })\n .join(' ')\n .replace(/^\\s*$(?:\\r\\n?|\\n)/gm, '');\n\n parse(schema);\n return schema;\n}\n```\n\n`schema.js`:\n\n```\n${generateInputType(\n `\n campaignTemplateNme: String\n`,\n {\n CreateCampaignTemplateInput: {\n validator: {\n channel: 'ChannelUnionInput!',\n campaignTemplateSharedLocationIds: '[ID]!',\n campaignTemplateEditableFields: '[String]!',\n organizationId: 'ID!',\n },\n },\n UpdateCampaignTemplateInput: {\n validator: {\n channel: 'ChannelUnionInput',\n campaignTemplateSharedLocationIds: '[ID]',\n campaignTemplateEditableFields: '[String]',\n organizationId: 'ID',\n },\n },\n },\n)}\n```\n\n========================================\n\nCode:\n```js\nconst typeDefs = `\n input BookInput {\n title: String!\n author: String!\n }\n\n type Book {\n id: ID!\n title: String!\n author: String!\n }\n\n type Query {\n books: [Book!]!\n }\n\n type Mutation{\n add(book: BookInput!): Book\n update(id: String!, book: BookInput!): Book\n }\n`;\n```\n\n```text\nmutation {\n update(id: \"1\", book: {title: \"angular\"}) {\n id\n title\n author\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Field BookInput.author of required type String! was not provided.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 24\n }\n ]\n }\n ]\n}\n```\n\n```text\nBookInput\n```\n\n```text\ntitle\n```\n\n```text\nauthor\n```\n\n```text\n{title: \"angular\", author: \"novaline\"}\n```\n\n```text\n{title: \"angular\"}\n```\n\n```text\n{title: \"angular\", author: \"novaline\"}\n```\n\n```text\n{title: \"angular\"}\n```\n\n```text\nBookInput\n```\n\n```text\nBookInput\n```\n\n```text\naddBookInput\n```\n\n```text\nupdateBookInput\n```\n\n```text\nconst typeDefs = `\n input AddBookInput {\n title: String!\n author: String!\n }\n\n input UpdateBookInput {\n # NOTE: all fields are optional for the update input \n title: String\n author: String\n }\n\n type Book {\n id: ID!\n title: String!\n author: String!\n }\n\n type Query {\n books: [Book!]!\n }\n\n type Mutation{\n addBook(input: AddBookInput!): Book\n updateBook(id: String!, input: UpdateBookInput!): Book\n }\n`;\n```\n\n```text\nconst typeDefs = `\n input AddBookInput {\n title: String!\n author: String!\n }\n\n input UpdateBookInput {\n # NOTE: all fields, except the 'id' (the selector), are optional for the update input \n id: String!\n title: String\n author: String\n }\n\n type Book {\n id: ID!\n title: String!\n author: String!\n }\n\n type Query {\n books: [Book!]!\n }\n\n type Mutation{\n addBook(input: AddBookInput!): Book\n updateBook(input: UpdateBookInput!): Book\n }\n`;\n```\n\n```text\nconst typeDefs = `\n input AddBookInput {\n title: String!\n author: String!\n }\n\n input UpdateBookInput {\n # NOTE: all fields, except the 'id' (the selector), are optional for the update input \n id: String!\n title: String\n author: String\n }\n\n type Book {\n id: ID!\n title: String!\n author: String!\n }\n\n type AddBookPayload {\n book: Book!\n }\n\n type UpdateBookPayload {\n book: Book!\n }\n\n type Query {\n books: [Book!]!\n }\n\n type Mutation{\n addBook(input: AddBookInput!): AddBookPayload!\n updateBook(input: UpdateBookInput!): UpdateBookPayload!\n }\n`;\n```\n\n```js\nconst { parse } = require('graphql');\n\n/**\n * schema definition helper function - dynamic generate graphql input type\n *\n * @author https://github.com/mrdulin\n * @param {string} baseSchema\n * @param {object} options\n * @returns {string}\n */\nfunction generateInputType(baseSchema, options) {\n const inputTypeNames = Object.keys(options);\n const schema = inputTypeNames\n .map(inputTypeName => {\n const { validator } = options[inputTypeName];\n const validatorSchema = Object.keys(validator)\n .map(field => `${field}: ${validator[field]}\\n`)\n .join(' ');\n\n return `\n input ${inputTypeName} {\n ${baseSchema}\n ${validatorSchema}\n }\n `;\n })\n .join(' ')\n .replace(/^\\s*$(?:\\r\\n?|\\n)/gm, '');\n\n parse(schema);\n return schema;\n}\n```\n\n```js\n${generateInputType(\n `\n campaignTemplateNme: String\n`,\n {\n CreateCampaignTemplateInput: {\n validator: {\n channel: 'ChannelUnionInput!',\n campaignTemplateSharedLocationIds: '[ID]!',\n campaignTemplateEditableFields: '[String]!',\n organizationId: 'ID!',\n },\n },\n UpdateCampaignTemplateInput: {\n validator: {\n channel: 'ChannelUnionInput',\n campaignTemplateSharedLocationIds: '[ID]',\n campaignTemplateEditableFields: '[String]',\n organizationId: 'ID',\n },\n },\n },\n)}\n```\n\n```text\ninput\n```\n\n```text\ninput\n```\n\n```text\nschema.js\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.044Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":408,"estimatedTokens":1785}}284{"id":"stack-42400207","source":"stackoverflow","questionId":42400207,"title":"Relay Mutations: Mutating Paginated Associations","tags":["graphql","relayjs"],"text":"Title: Relay Mutations: Mutating Paginated Associations\nTags: graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nIn a lot of cases we have mutations where there is a one-to-many or many-to-many association we need to mutate, and where the association is exposed to queries as a paginated list.\n\nThere are a handful of critical requirements:\n\n- Clients must be able to delete, add, and update elements of the association\n\n- In some cases, the ordering of the association is important in which case clients must be able to reorder the elements as well\n\nLess critical:\n\n- Clients should be able to specify the association at the creation of the parent (e.g. create an ordered set of variants at the same time as creating the product)\n\n- Clients should be able to delete, add, update, and reorder elements of the association at once with some form of transactional atomicity\n\n- Clients should not have to paginate through the entire current association in order to add or remove a single element\n\nThere's a number of possible solutions to this problem:\n\n### Option 1 - Single Input Field, No Additional Mutations\n\nThe input type has a single array input field which represents the total truth of the association (new elements are added, existing elements are updated, missing elements are deleted, and order is preserved when necessary).\n\nCons: Deletion is very implicit. Clients have to paginated through the entire current state of the association. Not granular.\n\n### Option 2 - Single Input Field with Positions, Delete Mutation\n\nThe input type has a single array input field which is used to update existing elements and add new ones (missing elements are ignored). A position or index value can be specified on elements to reorder them. A separate mutation is used to delete elements.\n\nCons: It is inconsistent for deletion to be off on its own in a mutation while all other operations are on the parent. Not very granular.\n\n### Option 3 - Single Input Field, Delete and Reorder Mutations\n\nThe input type has a single array input field which is used to update existing elements and add new ones (missing elements are ignored). Separate mutations are used to delete and re-order elements.\n\nCons: Clients cannot add new elements to specific locations in the association, they would have to be added and then reordered separately. Not very granular.\n\n### Option 4 - Single Input Field, Add/Delete/Reorder Mutations\n\nLike option 3 except the input field is only used for updates; a separate mutation is used for adding new elements.\n\nCons: Clients have to make multiple mutations to perform complex updates. Clients cannot create the parent with initial associations.\n\n### Option 5 - Entirely Separate Mutations\n\nThe parent input type has no related fields, everything is done via four separate mutations for add/remove/update/reorder.\n\nPros: Very explicit and granular, keeps different data model objects separate.\nCons: Clients have to make multiple mutations to perform complex updates. Clients cannot create the parent with initial associations.\n\n### Option 6 - Two Input Fields with Positions\n\nThe input type has two array fields: one used to update, add, and reorder elements (see option 2) and the other to delete.\n\nCons: Feels like we're polluting the parent mutation; not granular.\n\n### Option 7 - Two Input Fields, Reorder Mutations\n\nLike option 6, except a separate re-order mutation is used instead of position arguments.\n\nCons: Inconsistent for reorder to be off on its own. Also see cons for option 6.\n\nAll these options seem to have drawbacks. Option 5 seems to be to most explicit, but requires the user to use multiple mutations at the same time, where the operation is not really atomic anymore.\n\nWhat is Facebook's way of handling those types of mutations? What is your way ? Thanks!\n\n========================================\n\nCode:\n```text\ncommentCreate\n```\n\n```text\ncommentEdit\n```\n\n```text\ncommentDelete\n```\n\n```text\ncreate\n```\n\n```text\nedit\n```\n\n```text\nupdate\n```\n\n```text\ndelete\n```\n\n```text\ncommentCreate(input: {text:\"Hello World\", replies:[{text:\"Reply 1\"}, {text:\"Reply 2\"}]})\n```\n\n```text\ncommentCreate\n```\n\n```text\nreplies\n```\n\n```text\nfavoritePhotosUpdate({operations: {operation:ADD, addedId:1234}, {operation:REMOVE, addedId:5678}, {operation:UPDATE, oldId:4321, newId:8765}, {operation:SWAP, oldId:32, newId:76}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":116,"estimatedTokens":1087}}285{"id":"stack-56054038","source":"stackoverflow","questionId":56054038,"title":"GitHub GraphQL query not returning last commit","tags":["github","graphql"],"text":"Title: GitHub GraphQL query not returning last commit\nTags: github, graphql\nSource: Stack Overflow\n\nQuestion:\nEverywhere I read, I see I can get the latest commit for a GitHub repository using this GraphQL query:\n\n```\n{\nrepository(owner: \"petermorlion\", name: \"RedStar.Amounts\") {\n defaultBranchRef {\n name\n target {\n ... on Commit {\n history(first: 1) {\n edges {\n node {\n committedDate\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\nAnd this works. For this repository. As you can see (at the time I'm writing this), both the GraphQL explorer and the GitHub UI say 7th May is the latest commit:\n\nhttps://i.sstatic.net/D5LV5.png\n\nhttps://i.sstatic.net/Y0qmX.png\n\nHowever, if I run this on another repository, I'm getting the first commit. Change the owner to `ystk` and the repository name to `debian-libidn`. GraphQL tells me the latest commit is 13th October 2009:\n\nhttps://i.sstatic.net/ZFM0N.png\n\nBut the GitHub UI shows it is in fact 13th May 2011:\n\nhttps://i.sstatic.net/m53ac.png\n\nIs my query wrong? Should I be adding an `orderby` somewhere (I saw that it can't be added to `history`)?\n\n========================================\n\nCode:\n```text\n{\nrepository(owner: \"petermorlion\", name: \"RedStar.Amounts\") {\n defaultBranchRef {\n name\n target {\n ... on Commit {\n history(first: 1) {\n edges {\n node {\n committedDate\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nystk\n```\n\n```text\ndebian-libidn\n```\n\n```text\norderby\n```\n\n```text\nhistory\n```\n\n```text\nCommit\n```\n\n```text\ncommittedDate\n```\n\n```text\nauthoredDate\n```\n\n```text\ncommittedDate\n```\n\n```text\n--date\n```\n\n```text\npushedDate\n```\n\n```text\npushedDate\n```\n\n========================================\n\nComments:\n- have you tried adding orderby create date maybe like orderBy: {field: CREATED_AT, direction: ASC}\n- For a reproducible demo you may look at the repository I created for this purpose: author `SiavasFiroozbakht` and repo `TestRepo`. *New commit* is shown as older though it was pushed after the *Initial commit*\n- Interesting. Searching a bit further, I tried replacing the commit block in my query with `... on Commit { committedDate }` Would that give me the lastest commit? It seems to.\n- @Peter I have elaborated on these timestamp-related fields of `Commit`. You could use `pushedDate` to get the actual date of when the commit was pushed. Note changing or adding fields in the query does not actually apply any filter by them. `history` will give the same order as `git log` apparently","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":119,"estimatedTokens":636}}286{"id":"stack-48490312","source":"stackoverflow","questionId":48490312,"title":"Apollo Server timeout while waiting for stream data","tags":["node.js","graphql","braintree","apollo","apollo-server"],"text":"Title: Apollo Server timeout while waiting for stream data\nTags: node.js, graphql, braintree, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to wait for the result of a stream with my Apollo Server. My resolver looks like this.\n\n```\nasync currentSubs() {\n try {\n const stream = gateway.subscription.search(search => {\n search.status().is(braintree.Subscription.Status.Active);\n });\n const data = await stream.pipe(new CollectObjects()).collect();\n return data;\n } catch (e) {\n console.log(e);\n throw new Meteor.Error('issue', e.message);\n }\n},\n```\n\nThis resolver works just fine when the data stream being returned is small, but when the data coming in is larger, I'm getting a `503 (Service Unavailable)`. I looks like the timeout is happening around 30 seconds. I've tried increasing the timeout of my Express server with `graphQLServer.timeout = 240000;` but that hasn't made a difference.\n\nHow can I troubleshoot this & where is the 30 second timeout coming from? It only fails when the results take longer.\n\nI'm using https://github.com/mrdaniellewis/node-stream-collect to collect the results from the stream.\n\nError coming in from the try catch:\n\n```\nI20180128-13:09:26.872(-7)? { proxy:\nI20180128-13:09:26.872(-7)? { error: 'Post http://127.0.0.1:26474/graphql: net/http: request canceled (Client.Timeout exceeded while awaiting headers)',\nI20180128-13:09:26.872(-7)? level: 'error',\nI20180128-13:09:26.873(-7)? msg: 'Error sending request to origin.',\nI20180128-13:09:26.873(-7)? time: '2018-01-28T13:09:26-07:00',\nI20180128-13:09:26.873(-7)? url: 'http://127.0.0.1:26474/graphql' } }\n```\n\n========================================\n\nCode:\n```text\nasync currentSubs() {\n try {\n const stream = gateway.subscription.search(search => {\n search.status().is(braintree.Subscription.Status.Active);\n });\n const data = await stream.pipe(new CollectObjects()).collect();\n return data;\n } catch (e) {\n console.log(e);\n throw new Meteor.Error('issue', e.message);\n }\n},\n```\n\n```text\nI20180128-13:09:26.872(-7)? { proxy:\nI20180128-13:09:26.872(-7)? { error: 'Post http://127.0.0.1:26474/graphql: net/http: request canceled (Client.Timeout exceeded while awaiting headers)',\nI20180128-13:09:26.872(-7)? level: 'error',\nI20180128-13:09:26.873(-7)? msg: 'Error sending request to origin.',\nI20180128-13:09:26.873(-7)? time: '2018-01-28T13:09:26-07:00',\nI20180128-13:09:26.873(-7)? url: 'http://127.0.0.1:26474/graphql' } }\n```\n\n```text\n503 (Service Unavailable)\n```\n\n```text\ngraphQLServer.timeout = 240000;\n```\n\n```text\nexport function startApolloEngine() {\n const engine = new Engine({\n engineConfig: {\n stores: [\n {\n name: \"publicResponseCache\",\n memcache: {\n url: [environmentSettings.memcache.server],\n keyPrefix: environmentSettings.memcache.keyPrefix\n }\n }\n ],\n queryCache: {\n publicFullQueryStore: \"publicResponseCache\"\n },\n reporting: {\n disabled: true\n }\n },\n // GraphQL port\n graphqlPort: 9001,\n origin: {\n requestTimeout: \"50s\"\n },\n\n // GraphQL endpoint suffix - '/graphql' by default\n endpoint: \"/my_api_graphql\",\n // Debug configuration that logs traffic between Proxy and GraphQL server\n dumpTraffic: true\n });\n\n engine.start();\n app.use(engine.expressMiddleware());\n}\n```\n\n```text\n503s\n```\n\n```text\norigin: {\n requestTimeout: \"50s\"\n}\n```\n\n========================================\n\nComments:\n- Can you say more about your infrastructure? Is the Apollo server being connected to directly, or is it behind a load balancer or proxy or reverse proxy or anything like that?\n- The way you're increasing the timeout is incorrect. how are you starting your server are you using apollo-engine or apollo-server or apolloExpress ect :)\n- @JoeWarner I am using apollo-server v1 via github.com/apollographql/meteor-integration","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":127,"estimatedTokens":986}}287{"id":"stack-42903666","source":"stackoverflow","questionId":42903666,"title":"How to connect GraphQL to MySQL","tags":["node.js","graphql"],"text":"Title: How to connect GraphQL to MySQL\nTags: node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI've used express cli to set up a simple express project, And followed tutorials to create the `db.js` and `schema.js` but at this point I cant think of anyway to debug this error / to view any part of the schema in `graphiql` documentation. \n\n```\n{\n \"errors\": [\n {\n \"message\": \"Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory.\"\n }\n ]\n}\n```\n\n**App.js**\n\n```\nvar express = require('express');\nvar path = require('path');\nvar favicon = require('serve-favicon');\nvar logger = require('morgan');\nvar cookieParser = require('cookie-parser');\nvar bodyParser = require('body-parser');\n\nvar index = require('./routes/index');\nvar users = require('./routes/users');\n\nvar schema = require('./schema');\nvar graphqlHTTP = require('express-graphql');\n\nvar app = express();\n\n// view engine setup\napp.set('views', path.join(__dirname, 'views'));\napp.set('view engine', 'pug');\n\n// uncomment after placing your favicon in /public\n//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));\napp.use(logger('dev'));\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({extended: false}));\napp.use(cookieParser());\napp.use(express.static(path.join(__dirname, 'public')));\n\napp.use('/', index);\napp.use('/users', users);\n\napp.use('/api', graphqlHTTP({schema, graphiql: true}));\n\n// catch 404 and forward to error handler\napp.use(function(req, res, next) {\n var err = new Error('Not Found');\n err.status = 404;\n next(err);\n});\n\n// error handler\napp.use(function(err, req, res, next) {\n // set locals, only providing error in development\n res.locals.message = err.message;\n res.locals.error = req.app.get('env') === 'development'\n ? err\n : {};\n\n // render the error page\n res.status(err.status || 500);\n res.render('error');\n});\n\nmodule.exports = app;\n```\n\n**db.js**\n\n```\nvar Sequelize = require('sequelize');\nvar mysql = require('mysql');\nvar _ = require('lodash');\n\nvar Conn = new Sequelize('DB', 'Username', 'password', {\n host: 'DB IP',\n dialect: 'mysql'\n});\n\nvar Sectors = Conn.define('sectors', {\n name: {\n type: Sequelize.STRING,\n allowNull: false\n }\n});\n\nSectors.sync({force: true}).then(function () {\n // Table created\n return Sectors.create({\n name: 'test'\n });\n});\n\nexports.default = Conn;\n```\n\n**Schema.js**\n\n```\nvar {\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLID,\n GraphQLString,\n GraphQLInt,\n GraphQLBoolean,\n GraphQLList,\n GraphQLNonNull\n} = require('graphql');\n\nvar Db = require('./db');\n\nvar Sectors = new GraphQLObjectType({\n name: 'sectors',\n description: 'list of all the sectors',\n fields: () => {\n return {\n id: {\n type: GraphQLInt,\n resolve (sectors) {\n return sectors.id;\n }\n },\n name: {\n type: GraphQLString,\n resolve (sectors) {\n return sectors.name;\n }\n }\n };\n }\n});\n\nvar Query = new GraphQLObjectType({\n name: 'Query',\n description: 'Root query object',\n fields: () => {\n return {\n sectors: {\n type: new GraphQLList(Sectors),\n args: {\n id: {\n type: GraphQLInt\n },\n name: {\n type: GraphQLString\n }\n },\n resolve (root, args) {\n return Db.models.sectors.findAll({ where: args });\n }\n }\n };\n }\n});\n\nvar Schema = new GraphQLSchema({query: Query});\nexports.default = Schema;\n```\n\n========================================\n\nCode:\n```text\n{\n \"errors\": [\n {\n \"message\": \"Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory.\"\n }\n ]\n}\n```\n\n```text\nvar express = require('express');\nvar path = require('path');\nvar favicon = require('serve-favicon');\nvar logger = require('morgan');\nvar cookieParser = require('cookie-parser');\nvar bodyParser = require('body-parser');\n\nvar index = require('./routes/index');\nvar users = require('./routes/users');\n\nvar schema = require('./schema');\nvar graphqlHTTP = require('express-graphql');\n\nvar app = express();\n\n// view engine setup\napp.set('views', path.join(__dirname, 'views'));\napp.set('view engine', 'pug');\n\n// uncomment after placing your favicon in /public\n//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));\napp.use(logger('dev'));\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({extended: false}));\napp.use(cookieParser());\napp.use(express.static(path.join(__dirname, 'public')));\n\napp.use('/', index);\napp.use('/users', users);\n\napp.use('/api', graphqlHTTP({schema, graphiql: true}));\n\n// catch 404 and forward to error handler\napp.use(function(req, res, next) {\n var err = new Error('Not Found');\n err.status = 404;\n next(err);\n});\n\n// error handler\napp.use(function(err, req, res, next) {\n // set locals, only providing error in development\n res.locals.message = err.message;\n res.locals.error = req.app.get('env') === 'development'\n ? err\n : {};\n\n // render the error page\n res.status(err.status || 500);\n res.render('error');\n});\n\nmodule.exports = app;\n```\n\n```text\nvar Sequelize = require('sequelize');\nvar mysql = require('mysql');\nvar _ = require('lodash');\n\nvar Conn = new Sequelize('DB', 'Username', 'password', {\n host: 'DB IP',\n dialect: 'mysql'\n});\n\nvar Sectors = Conn.define('sectors', {\n name: {\n type: Sequelize.STRING,\n allowNull: false\n }\n});\n\nSectors.sync({force: true}).then(function () {\n // Table created\n return Sectors.create({\n name: 'test'\n });\n});\n\nexports.default = Conn;\n```\n\n```text\nvar {\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLID,\n GraphQLString,\n GraphQLInt,\n GraphQLBoolean,\n GraphQLList,\n GraphQLNonNull\n} = require('graphql');\n\nvar Db = require('./db');\n\nvar Sectors = new GraphQLObjectType({\n name: 'sectors',\n description: 'list of all the sectors',\n fields: () => {\n return {\n id: {\n type: GraphQLInt,\n resolve (sectors) {\n return sectors.id;\n }\n },\n name: {\n type: GraphQLString,\n resolve (sectors) {\n return sectors.name;\n }\n }\n };\n }\n});\n\nvar Query = new GraphQLObjectType({\n name: 'Query',\n description: 'Root query object',\n fields: () => {\n return {\n sectors: {\n type: new GraphQLList(Sectors),\n args: {\n id: {\n type: GraphQLInt\n },\n name: {\n type: GraphQLString\n }\n },\n resolve (root, args) {\n return Db.models.sectors.findAll({ where: args });\n }\n }\n };\n }\n});\n\nvar Schema = new GraphQLSchema({query: Query});\nexports.default = Schema;\n```\n\n```text\ndb.js\n```\n\n```text\nschema.js\n```\n\n```text\ngraphiql\n```\n\n```text\nexports.default = Schema\n```\n\n```text\nmodule.exports = Schema\n```\n\n========================================\n\nComments:\n- Do you have multiple versions of graphql installed, in node_modules... whilst I think :) it might be worth clearing node_modules and resinstalling if you havent already\n- Are you exporting and importing Schema correctly?\n- Node Module didnt work and regarding Schema I don't know I just followed Lee Benson, except I used vanilla Js and mysql. No errors !\n- Do you think you might need to install graphql-sequelize?\n- I just used this question as a one-page tutorial on how to wire up MySQL for GraphQL! Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":354,"estimatedTokens":1823}}288{"id":"stack-46669560","source":"stackoverflow","questionId":46669560,"title":"Github GraphQL to recursively list all files in the directory","tags":["github","graphql","github-api"],"text":"Title: Github GraphQL to recursively list all files in the directory\nTags: github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nI want to use the GraphQL Github API to recursively list all files contained in the directory. Right now my query looks like this:\n\n```\n{\n search(first:1, type: REPOSITORY, query: \"language:C\") {\n edges {\n node {\n ... on Repository {\n name\n descriptionHTML\n stargazers {\n totalCount\n }\n forks {\n totalCount\n }\n object(expression: \"master:\") {\n ... on Tree {\n entries {\n name\n type\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\nHowever, this only gives me only the first level of directory contents, in particular some of the resulting objects are again trees. Is there a way to adjust the query, such that it recursively list the contents of tree again?\n\n========================================\n\nTop Answer:\nworking example\n\nMore info: https://docs.sourcegraph.com/api/graphql/examples\n\nBut probably this will change in the near feature. For example latest github version is v4 https://developer.github.com/v4/explorer/\n\n========================================\n\nCode:\n```text\n{\n search(first:1, type: REPOSITORY, query: \"language:C\") {\n edges {\n node {\n ... on Repository {\n name\n descriptionHTML\n stargazers {\n totalCount\n }\n forks {\n totalCount\n }\n object(expression: \"master:\") {\n ... on Tree {\n entries {\n name\n type\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nquery TestQuery($branch: GitObjectID) {\n search(first: 1, type: REPOSITORY, query: \"language:C\") {\n edges {\n node {\n ... on Repository {\n object(expression: \"master:\", oid: $branch) {\n ... on Tree {\n entries {\n oid\n name\n type\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nnull\n```\n\n```text\n{\n search(first: 1, type: REPOSITORY, query: \"language:C\") {\n edges {\n node {\n ... on Repository {\n name\n descriptionHTML\n stargazers {\n totalCount\n }\n forks {\n totalCount\n }\n object(expression: \"master:\") {\n ... on Tree {\n entries {\n name\n object {\n ... on Tree {\n entries {\n name\n object {\n ... on Tree {\n entries {\n name\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- I was excited to see your question, both because your example solved an issue I was having with GraphQL AND because I thought I knew of a solution. Sadly, when I attempted to use a \"fragment,\" it threw an error about \"Fragment [fragment name] contains an infinite loop. So now I'm anxiously awaiting an answer to this question, too.\n- Please add a few words explaining what you are doing, to me it does not look recursive. It looks like you only go a few more levels deep\n- It still works, however in the Github GraphQl Explorer I get two errors with your example: `\"Field 'repository' is missing required arguments: owner\"` and `\"Field 'commit' doesn't exist on type 'Repository'\"`\n- The first error from my comment one hour ago can be solved by using `owner`, but the second one seems not to be cleared. Another query is needed to work with the explorer?","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":154,"estimatedTokens":941}}289{"id":"stack-51977753","source":"stackoverflow","questionId":51977753,"title":"Apollo 2.0.0 Graphql cookie session","tags":["graphql","session-cookies","apollo-server","express-graphql"],"text":"Title: Apollo 2.0.0 Graphql cookie session\nTags: graphql, session-cookies, apollo-server, express-graphql\nSource: Stack Overflow\n\nQuestion:\nCan someone help me on this, My setup was as follows prior to Apollo 2.0, I had a server.js in which i used express and graphql-server-express\nI had a http only cookie session, when a user logs in I set the jwt token as a cookie and it is set in browser as http only.\nOn subsequent request I validate the cookie that the browser passes back. It was all working fine and I could access\nthe token from req.session.token in any other resolver and validate the jwt token saved in the cookie session.\n\nserver.js \n\n```\nimport express from 'express';\nimport { graphqlExpress, graphiqlExpress } from 'graphql-server-express';\nimport { ApolloEngine } from 'apollo-engine';\nimport bodyParser from 'body-parser';\nimport cors from 'cors';\nimport cookieSession from 'cookie-session';\nimport schema from './schema/';\nβ\nconst server = express();\nβ\nserver.use(\n cookieSession({\n name: 'session',\n keys: 'k1,k2',\n maxAge: 30 * 60 * 1000,\n domain: '.mydomain.com',\n path: '/',\n }),\n);\nβ\nconst corsOptions = {\n origin: 'http://local.mydomain.com:3000',\n credentials: true,\n methods: ['GET', 'PUT', 'POST', 'OPTIONS'],\n};\nβ\nserver.use(cors(corsOptions));\nβ\nserver.use(\n '/graphql',\n bodyParser.json(),\n graphqlExpress(req => ({\n schema,\n tracing: true,\n context: { req },\n })),\n);\nβ\nif (process.env.NODE_ENV !== 'production') {\n server.use('/graphiql',graphiqlExpress({endpointURL: '/graphql'}));\n}\nβ\nconst engine = new ApolloEngine({\n apiKey: engineConfig.apiKey,\n});\nβ\nengine.listen(\n {\n port: 3000,\n graphqlPaths: ['/graphql'],\n expressApp: server,\n },\n () => {console.log('GraphiQL is now running');},\n);\n```\n\nauthenticateResolver.js\n\n```\nconst authenticateResolver = {\n Query: {\n authenticate: async (root, args, context) => {\n const { req } = context;\nβ\n const auth = `Basic ${Buffer.from(`${args.username}:${args.password}`).toString('base64')}`;\nβ\n const axiosResponse = await axios.post(\"localhot:8080/login, 'true', \n {\n headers: {\n Authorization: auth,\n },\n });\nβ\n if (axiosResponse.status === 200 && axiosResponse.data.token) {\n req.session.token = axiosResponse.data.token;\n }\n return {\n status: 200,\n };\n },\n```\n\nBut when I upgraded to Apollo 2.0 my server.js code changed, authenticateResolver was as is.\nI am now unable to access req.session.token in any subsequent requests since the cookie session is not getting set.\nWhen I open Developer tools in chrome I cannot see the cookie being set when Authentication is called.\nWhat am I doing wrong here ? \n\nserver.js # After Apollo 2.0 upgrade \nβ\n\n```\nimport express from 'express';\nimport { ApolloServer, gql } from 'apollo-server-express';\nimport cors from 'cors';\nimport cookieSession from 'cookie-session';\nimport { mergedTypes, resolvers } from './schema/';\nβ\nconst server = express();\nβ\nserver.use(\n cookieSession({\n name: 'session',\n keys: 'k1,k2',\n maxAge: 30 * 60 * 1000,\n domain: '.mydomain.com',\n path: '/',\n }),\n);\nβ\nconst corsOptions = {\n origin: 'http://local.mydomain.com:3000',\n credentials: true,\n methods: ['GET', 'PUT', 'POST', 'OPTIONS'],\n};\nβ\nserver.use(cors(corsOptions));\nβ\nserver.listen({ port: 3000 }, () => { \n console.log('Server ready');\n console.log('Try your health check at: .well-known/apollo/app-health');\n});\nβ\nconst apollo = new ApolloServer({\n typeDefs: gql`\n ${mergedTypes}\n `,\n resolvers,\n engine: false,\n context: ({ req }) => ({ req }),\n});\nβ\napollo.applyMiddleware({\n server\n});\n```\n\n========================================\n\nCode:\n```text\nimport express from 'express';\nimport { graphqlExpress, graphiqlExpress } from 'graphql-server-express';\nimport { ApolloEngine } from 'apollo-engine';\nimport bodyParser from 'body-parser';\nimport cors from 'cors';\nimport cookieSession from 'cookie-session';\nimport schema from './schema/';\nβ\nconst server = express();\nβ\nserver.use(\n cookieSession({\n name: 'session',\n keys: 'k1,k2',\n maxAge: 30 * 60 * 1000,\n domain: '.mydomain.com',\n path: '/',\n }),\n);\nβ\nconst corsOptions = {\n origin: 'http://local.mydomain.com:3000',\n credentials: true,\n methods: ['GET', 'PUT', 'POST', 'OPTIONS'],\n};\nβ\nserver.use(cors(corsOptions));\nβ\nserver.use(\n '/graphql',\n bodyParser.json(),\n graphqlExpress(req => ({\n schema,\n tracing: true,\n context: { req },\n })),\n);\nβ\nif (process.env.NODE_ENV !== 'production') {\n server.use('/graphiql',graphiqlExpress({endpointURL: '/graphql'}));\n}\nβ\nconst engine = new ApolloEngine({\n apiKey: engineConfig.apiKey,\n});\nβ\nengine.listen(\n {\n port: 3000,\n graphqlPaths: ['/graphql'],\n expressApp: server,\n },\n () => {console.log('GraphiQL is now running');},\n);\n```\n\n```text\nconst authenticateResolver = {\n Query: {\n authenticate: async (root, args, context) => {\n const { req } = context;\nβ\n const auth = `Basic ${Buffer.from(`${args.username}:${args.password}`).toString('base64')}`;\nβ\n const axiosResponse = await axios.post(\"localhot:8080/login, 'true', \n {\n headers: {\n Authorization: auth,\n },\n });\nβ\n if (axiosResponse.status === 200 && axiosResponse.data.token) {\n req.session.token = axiosResponse.data.token;\n }\n return {\n status: 200,\n };\n },\n```\n\n```text\nimport express from 'express';\nimport { ApolloServer, gql } from 'apollo-server-express';\nimport cors from 'cors';\nimport cookieSession from 'cookie-session';\nimport { mergedTypes, resolvers } from './schema/';\nβ\nconst server = express();\nβ\nserver.use(\n cookieSession({\n name: 'session',\n keys: 'k1,k2',\n maxAge: 30 * 60 * 1000,\n domain: '.mydomain.com',\n path: '/',\n }),\n);\nβ\nconst corsOptions = {\n origin: 'http://local.mydomain.com:3000',\n credentials: true,\n methods: ['GET', 'PUT', 'POST', 'OPTIONS'],\n};\nβ\nserver.use(cors(corsOptions));\nβ\nserver.listen({ port: 3000 }, () => { \n console.log('Server ready');\n console.log('Try your health check at: .well-known/apollo/app-health');\n});\nβ\nconst apollo = new ApolloServer({\n typeDefs: gql`\n ${mergedTypes}\n `,\n resolvers,\n engine: false,\n context: ({ req }) => ({ req }),\n});\nβ\napollo.applyMiddleware({\n server\n});\n```\n\n```js\nconst app = express()\n\napp.use(\n cookieSession({\n name: 'session',\n keys: corsConfig.cookieSecret.split(','),\n maxAge: 60 * 60 * 1000,\n domain: corsConfig.cookieDomain,\n path: '/',\n })\n)\n\nconst corsOptions = {\n origin: corsConfig.corsWhitelist.split(','),\n credentials: true,\n methods: ['GET', 'PUT', 'POST', 'OPTIONS'],\n}\n\napp.use(cors(corsOptions))\n\nconst apollo = new ApolloServer({\n typeDefs: gql`\n ${mergedTypes}\n `,\n resolvers,\n engine: false,\n context: ({ req }) => ({ req }),\n tracing: true,\n debug: !process.env.PRODUCTION,\n introspection: !process.env.PRODUCTION,\n})\n\napollo.applyMiddleware({\n app,\n path: '/',\n cors: corsOptions,\n})\n\napp.listen({ port: engineConfig.port }, () => {\n console.log('π - Server ready')\n console.log('Try your health check at: .well-known/apollo/app-health')\n})\n```\n\n```text\n\"request.credentials\": \"omit\"\n```\n\n```text\n\"request.credentials\": \"include\"\n```\n\n========================================\n\nComments:\n- Did you get this working? We are having the same issue.\n- Did you find a solution for this?\n- Legend. I've no idea why default is set to omit. It did not occur for me to check that. Thanks !\n- Can you your code for `corsConfig`?","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":339,"estimatedTokens":1825}}290{"id":"stack-54026744","source":"stackoverflow","questionId":54026744,"title":"GraphQL: Nested queries vs root queries","tags":["graphql","apollo"],"text":"Title: GraphQL: Nested queries vs root queries\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm using Apollo GraphQL on my server, and I'm trying to design my GraphQL API. One question I have is whether or not I should prefer nested queries over root queries.\n\nLet's examine both in this example where the current user, `me`, has many `invitations`.\n\n**Root queries**\n\n```\nme {\n id\n name\n}\n\ninvitations {\n id\n message\n}\n```\n\nThe resolver for `invitations` returns invitations for the current user.\n\n**Nested query**\n\n```\nme {\n id\n name\n invitations {\n id\n message\n }\n}\n```\n\nThese should achieve the same result, except in the latter approach invitations are nested inside the user object `me`. My concern is whether this will work smoothly with Apollo Client and keep the cache consistent.\n\nWhat is the recommended way to design GraphQL queries?\n\n========================================\n\nTop Answer:\nOne of the GraphQL selling point is to allow client to have very much flexibility to define the shape of the data they want to query in a minimised number of requests. They also encourage developers to \"Think in Graphs\" when designing the schema. \n\nSo, I would go for nested query which looks more like a graph. Furthermore, it is much more flexible. If user want to get their user profile data with their invitations, they can get them in a single request only. If they only want to get the profile data, they just ignore the invitation part in the query and server will not waste any resources to get the invitation data due to the design nature of the GraphQL.\n\n========================================\n\nCode:\n```text\nme {\n id\n name\n}\n\ninvitations {\n id\n message\n}\n```\n\n```text\nme {\n id\n name\n invitations {\n id\n message\n }\n}\n```\n\n```text\nme\n```\n\n```text\ninvitations\n```\n\n```text\ninvitations\n```\n\n```text\nme\n```\n\n```text\nme { notifications { ... } }\n```\n\n```text\nnotifications { ... }\n```\n\n```text\nme\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nuser(id: ...) { ... }\n```\n\n```text\nme { ... }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":118,"estimatedTokens":514}}291{"id":"stack-66185620","source":"stackoverflow","questionId":66185620,"title":"GraphQL, Shopify Get All products or totalcount of products","tags":["graphql","shopify"],"text":"Title: GraphQL, Shopify Get All products or totalcount of products\nTags: graphql, shopify\nSource: Stack Overflow\n\nQuestion:\nI am brand new to graphQL and I have to retrieve all of the products. I have been looking around, watching tutorials and reading and people seem to return all of a certain type of data they want but I cannot. For example it will throw an error saying you must provide first or last but I want them all or it will say totalCount or count does not exist.\n\n```\n{\n products {\n id\n title\n price\n \n }\n}\n\n// or get total count of products\n\n {\n products {\n totalCount\n }\n}\n```\n\nI was basically trying to do something like that. I understand I may not receive any help because no one has access to my shopify admin api but maybe even an example or anything that I could see. This is from my graphQL query root of options I have for products.\nList of products.\n\n```\nProductConnection!\nfirst: Int\nReturns up to the first n elements from the list.\n\nafter: String\nReturns the elements that come after the specified cursor.\n\nlast: Int\nReturns up to the last n elements from the list.\n\nbefore: String\nReturns the elements that come before the specified cursor.\n\nreverse: Boolean = false\nReverse the order of the underlying list.\n\nsortKey: ProductSortKeys = ID\nSort the underlying list by the given key.\n\nquery: String\nSupported filter parameters:\n\nbarcode\ncreated_at\ndelivery_profile_id\nerror_feedback\ngift_card\ninventory_total\nis_price_reduced\nout_of_stock_somewhere\nprice\nproduct_type\npublishable_status\npublished_status\nsku\nstatus\ntag\ntitle\nupdated_at\nvendor\nSee the detailed search syntax for more information about using filters.\n\nsavedSearchId: ID\nID of an existing saved search. The searchβs query string is used as the query argument.\n```\n\n========================================\n\nTop Answer:\nYou can get all products using BULK API with conjunction to GRAPHQL\n\n========================================\n\nCode:\n```text\n{\n products {\n id\n title\n price\n \n }\n}\n\n// or get total count of products\n\n {\n products {\n totalCount\n }\n}\n```\n\n```text\nProductConnection!\nfirst: Int\nReturns up to the first n elements from the list.\n\nafter: String\nReturns the elements that come after the specified cursor.\n\nlast: Int\nReturns up to the last n elements from the list.\n\nbefore: String\nReturns the elements that come before the specified cursor.\n\nreverse: Boolean = false\nReverse the order of the underlying list.\n\nsortKey: ProductSortKeys = ID\nSort the underlying list by the given key.\n\nquery: String\nSupported filter parameters:\n\nbarcode\ncreated_at\ndelivery_profile_id\nerror_feedback\ngift_card\ninventory_total\nis_price_reduced\nout_of_stock_somewhere\nprice\nproduct_type\npublishable_status\npublished_status\nsku\nstatus\ntag\ntitle\nupdated_at\nvendor\nSee the detailed search syntax for more information about using filters.\n\nsavedSearchId: ID\nID of an existing saved search. The searchβs query string is used as the query argument.\n```\n\n```text\n[\n{% paginate collection.products by 9999 %}\n {% for product in collection.products %}\n {{product | json}}{% unless forloop.last %},{% endunless %}\n {% endfor %}\n{% endpagination %}\n]\n```\n\n```text\nfetch('/collections/all?view=ajax').then((response) => handle the response)\n```\n\n```text\nfirst: 250\n```\n\n```text\ncollection.ajax.liquid\n```\n\n```text\n{{ collection.all_products_count }}\n```\n\n```text\nManyToMany\n```\n\n========================================\n\nComments:\n- You can use Rest API endpoint: shopify.dev/api/admin-rest/2022-04/resources/…","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":184,"estimatedTokens":879}}292{"id":"stack-48787135","source":"stackoverflow","questionId":48787135,"title":"Should I write two times each objects as 'input' and 'type' in a graphql schema file","tags":["graphql","graphql-java"],"text":"Title: Should I write two times each objects as 'input' and 'type' in a graphql schema file\nTags: graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI have to use a Java object in GraphQL in response as well as in request. \n\nShould I have to write two times each objects as 'input' and 'type' in a GraphQL schema file? For getting that object in request as well as in response.\n\nShould I define the same object two times with input and type?\n\nfile: `test.graphqls`\n\n```\ninput Employee {\n id: Integer\n name: String\n dept: String\n active: String\n}\n\ntype Employee {\n id: Integer\n name: String\n dept: String\n active: String\n}\n```\n\n========================================\n\nCode:\n```text\ninput Employee {\n id: Integer\n name: String\n dept: String\n active: String\n}\n\ntype Employee {\n id: Integer\n name: String\n dept: String\n active: String\n}\n```\n\n```text\ntest.graphqls\n```\n\n```text\nEmployee\n```\n\n```text\nEmployeeInput\n```\n\n========================================\n\nComments:\n- thank you.. how would we impliment two different names in schema for a single object ?\n- @Pranav I'm confused by the question. How are you making the schema? There's no relation between the Java class and the GraphQL type unless you make it. When defining the types simply give them different names. Whether the DataFetchers are backed by the same class or not has no bearing on the name.\n- @Pranav e.g. in your schema just have `type Employee` and `input EmployeeInput`, and wire them both in a similar way when making an executable schema.\n- Can `input` encapsulate `type` to avoid duplicate member definition?\n- @KokHowTeh An input type can only refer to scalars, other input types and lists of those. If they could refer to output types what would the purpose of separating them in the first place be? You'd still end up with potential infinite recursion, interfaces etc (which are all allowed for output types but not inputs).","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":68,"estimatedTokens":479}}293{"id":"stack-45625548","source":"stackoverflow","questionId":45625548,"title":"How to upload an image to AWS S3 using GraphQL?","tags":["javascript","reactjs","amazon-s3","graphql","aws-appsync"],"text":"Title: How to upload an image to AWS S3 using GraphQL?\nTags: javascript, reactjs, amazon-s3, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI'm uploading a base64 string but the GraphQL gets hung. If I slice the string to less than 50,000 characters it works. After 50,000 characters, graphQL never makes it to the resolve function, yet does not give an error. On the smaller strings, it works just fine.\n\n```\nconst file = e.target.files[0];\nconst reader = new FileReader();\nreader.readAsDataURL(file);\nreader.onloadend = () => {\n const imageArray = reader.result;\n this.context.fetch('/graphql', {\n body: JSON.stringify({\n query: `mutation s3Upload($img: String!) {\n s3Upload(file: $img) {\n logo,\n }\n }`,\n variables: {\n img: imageArray,\n },\n }),\n }).then(response => response.json())\n .then(({ data }) => {\n console.log(data);\n });\n}\n\nconst s3Upload = {\n type: S3Type,\n args: {\n file: { type: new NonNull(StringType) },\n },\n resolve: (root, args, { user }) => upload(root, args, user),\n};\n\nconst S3Type = new ObjectType({\n name: 'S3',\n fields: {\n logo: { type: StringType },\n },\n});\n```\n\n========================================\n\nTop Answer:\nAWS AppSync (https://aws.amazon.com/appsync/) provides this with functionality known as \"Complex Objects\" where you can have a types for the S3 Object and the input:\n\n```\ntype S3Object {\n bucket: String!\n key: String!\n region: String!\n}\n\ninput S3ObjectInput {\n bucket: String!\n key: String!\n region: String!\n localUri: String\n mimeType: String\n}\n```\n\nYou could then do something like this to define this object as part of another type:\n\n```\ntype UserProfile {\n id: ID!\n name: String\n file: S3Object\n}\n```\n\nAnd then specify a mutation to add it:\n\n```\ntype Mutation {\n addUser(id: ID! name: String file: S3ObjectInput): UserProfile!\n}\n```\n\nYour client operations would need to specify the appropriate bucket, key (with file extension), region, etc.\n\nMore here: https://docs.aws.amazon.com/appsync/latest/devguide/building-a-client-app-react.html#complex-objects\n\n========================================\n\nCode:\n```text\nconst file = e.target.files[0];\nconst reader = new FileReader();\nreader.readAsDataURL(file);\nreader.onloadend = () => {\n const imageArray = reader.result;\n this.context.fetch('/graphql', {\n body: JSON.stringify({\n query: `mutation s3Upload($img: String!) {\n s3Upload(file: $img) {\n logo,\n }\n }`,\n variables: {\n img: imageArray,\n },\n }),\n }).then(response => response.json())\n .then(({ data }) => {\n console.log(data);\n });\n}\n\nconst s3Upload = {\n type: S3Type,\n args: {\n file: { type: new NonNull(StringType) },\n },\n resolve: (root, args, { user }) => upload(root, args, user),\n};\n\nconst S3Type = new ObjectType({\n name: 'S3',\n fields: {\n logo: { type: StringType },\n },\n});\n```\n\n```text\nenum Visibility {\n public\n private\n}\n\ninput S3ObjectInput {\n bucket: String!\n region: String!\n localUri: String\n visibility: Visibility\n key: String\n mimeType: String\n}\n\ntype S3Object {\n bucket: String!\n region: String!\n key: String!\n}\n```\n\n```text\n{\n \"version\": \"2017-02-28\",\n \"operation\": \"PutItem\",\n \"key\": {\n \"id\": $util.dynamodb.toDynamoDBJson($ctx.args.input.id),\n },\n\n #set( $attribs = $util.dynamodb.toMapValues($ctx.args.input) )\n #set( $file = $ctx.args.input.file )\n #set( $attribs.file = $util.dynamodb.toS3Object($file.key, $file.bucket, $file.region, $file.version) )\n\n \"attributeValues\": $util.toJson($attribs)\n}\n```\n\n```text\n## Request Resolver ##\n{\n \"version\": \"2017-02-28\",\n \"payload\": {}\n}\n\n## Response Resolver ##\n$util.toJson($util.dynamodb.fromS3ObjectJson($context.source.file))\n```\n\n```text\nconst client = new AWSAppSyncClient({\n url: AppSync.graphqlEndpoint,\n region: AppSync.region,\n auth: {\n type: AUTH_TYPE.AWS_IAM,\n credentials: () => Auth.currentCredentials()\n },\n complexObjectsCredentials: () => Auth.currentCredentials(),\n});\n```\n\n```text\nfile\n```\n\n```text\nString!\n```\n\n```text\nS3ObjectInput\n```\n\n```text\nS3ObjectInput\n```\n\n```text\n$utils.dynamodb.toS3Object()\n```\n\n```text\nfile\n```\n\n```text\nS3ObjectInput\n```\n\n```text\nS3Object\n```\n\n```text\nfile\n```\n\n```text\nfile\n```\n\n```text\nS3Object\n```\n\n```text\nfile\n```\n\n```text\nbucket\n```\n\n```text\nregion\n```\n\n```text\nkey\n```\n\n```text\ncomplexObjectCredentials\n```\n\n```text\ntype S3Object {\n bucket: String!\n key: String!\n region: String!\n}\n\ninput S3ObjectInput {\n bucket: String!\n key: String!\n region: String!\n localUri: String\n mimeType: String\n}\n```\n\n```text\ntype UserProfile {\n id: ID!\n name: String\n file: S3Object\n}\n```\n\n```text\ntype Mutation {\n addUser(id: ID! name: String file: S3ObjectInput): UserProfile!\n}\n```\n\n========================================\n\nComments:\n- Thank you @Richard. The tutorial you referenced does not show how `NewPostMutation.js` has to be changed. I have tried to this tutorial but so far no luck to make a file to upload on s3 :-(","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":290,"estimatedTokens":1254}}294{"id":"stack-43675933","source":"stackoverflow","questionId":43675933,"title":"in GraphQL, Can I send variables with Content-Type: application/graphql?","tags":["graphql"],"text":"Title: in GraphQL, Can I send variables with Content-Type: application/graphql?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI've tried to use variables with graphql, \nbut it seems impossible to send variables with 'application/graphql'.\n\nShould i have to move on to Content-Type: 'application/json'?\n\n========================================\n\nTop Answer:\nWhat prevents you from passing the variables in the query string and the query in the body?\n\n```\nPOST /graphql?variables={\"id\":1234}\nContent-Type: application/graphql\nquery ($id: ID!) {\n Post(id: $id) {\n id\n title\n body\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n \"query\": \"...\",\n \"operationName\": \"...\",\n \"variables\": { \"myVariable\": \"someValue\", ... }\n}\n```\n\n```text\nContent-Type: \"application/graphql\"\n```\n\n```text\nContent-Type: \"application/json\"\n```\n\n```text\nPOST /graphql?variables={\"id\":1234}\nContent-Type: application/graphql\nquery ($id: ID!) {\n Post(id: $id) {\n id\n title\n body\n }\n}\n```\n\n```text\n/graphql?query=query+getUser($id:ID){user(id:$id){name}}&variables={\"id\":\"4\"}\n```\n\n```text\napplication/json\n```\n\n```text\napplication/graphql\n```\n\n```text\nvariables={...}\n```\n\n========================================\n\nComments:\n- can you please provide some more precise information about your approach to send variables? what does the http request look like? \"it seems impossible to send variables with 'application/graphql'.\" --> what exactly do you mean by that? why does it seem impossible? are you getting an error? what does it say?\n- Oh, variables can works with the queryString? I didn't get it. I'll try that. Thanks!\n- POST requests do not usually have a query string. Doing some basic web searches, this is acceptable per the web standards, but is not conventional.","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":80,"estimatedTokens":449}}295{"id":"stack-55598213","source":"stackoverflow","questionId":55598213,"title":"Enums not working with nestjs and graphql","tags":["typescript","enums","graphql","nestjs","typeorm"],"text":"Title: Enums not working with nestjs and graphql\nTags: typescript, enums, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have recently moved from using typegraphql and typeorm directly to using them with nestjs. Mostly this has been a straightforward experience. I however have one issue with respect to enums.\n\nI have a set of custom decorators that I have combined together so that I can easily decorate up my models without having both typeorm, typegraphql and class validator decorators. This worked great before and works fine now in all cases other than enums.\n\nAs an example here is an @OptionalDecimal decorator:\n\n```\nimport { IsNumber } from 'class-validator'\nimport { Field, Float } from 'type-graphql'\nimport { Column } from 'typeorm'\n\nexport function OptionalDecimal() {\n const typeDecorator = IsNumber()\n const fieldDecorator = Field(type => Float, { nullable: true })\n const columnDecorator = Column('decimal', { nullable: true })\n\n return (target: any, key: string) => {\n typeDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\nMy @Enum decorator is as so:\n\n```\nimport { IsEnum } from 'class-validator'\nimport { Field } from 'type-graphql'\nimport { Column } from 'typeorm'\nimport { IEnumOptions } from './IEnumOptions'\n\nexport function Enum(\n typeFunction: (type?: any) => object,\n options: IEnumOptions = {}\n) {\n const isEnumDecorator = IsEnum(typeFunction())\n const fieldDecorator = Field(typeFunction)\n const columnDecorator = Column({\n default: options.default,\n enum: typeFunction(),\n type: 'enum',\n })\n\n return (target: any, key: string) => {\n isEnumDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\nI define my enums in separate files like so:\n\n```\nimport { registerEnumType } from 'type-graphql'\n\nexport enum AccountState {\n ACTIVE,\n SUSPENDED,\n CLOSED,\n}\n\nregisterEnumType(AccountState, { name: 'AccountState' })\n```\n\nAnd is used thusly:\n\n```\n@EntityType()\nexport class Member extends VersionedEntity {\n @IdentifierNewGuid()\n public readonly id: string\n\n @Enum(type => AccountState, { default: AccountState.ACTIVE })\n public accountState: AccountState\n...\n```\n\nMy database is returning numeric ids for the enumerations and the field type in the database (mysql) is `enum`. As an example where my database is returning 1 for accountState which should be SUSPENDED I receive a graphql error:\n\n```\n\"errors\": [\n {\n \"message\": \"Expected a value of type \\\"AccountState\\\" but received: 1\",\n \"locations\": [\n {\n \"line\": 3,\n \"column\": 5\n }\n ],\n \"path\": [\n \"searchMembers\",\n 0,\n \"accountState\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Expected a value of type \\\"AccountState\\\" but received: 1\",\n \" at completeLeafValue\n```\n\nSo to recap this approach worked fine with typeorm and typegraphql directly but sadly fails to work now. All the other decorators I have appear to work fine (50+) so it's just something that's up specifically with enums.\n\nThis is a major blocker for me and any help would be greatly appreciated as I am currently out of ideas.\n\nEdit - In response to Shusson, when I add the decorators manually it also does not work actually:\n\n```\n@Column({\n default: AccountState.ACTIVE,\n enum: AccountState,\n type: 'enum',\n })\n@Field(type => AccountState)\npublic accountState: AccountState\n```\n\nCheers,\nMark\n\n========================================\n\nTop Answer:\nSince this is still an issue in 2022, here is a solution I came up with that does not require you to change your integer enums to string ones with the keys exactly matching the values. You can use the `@Transform` decorator from the `class-transformer` package.\n\n```\n@ArgsType()\nexport class SomeArgs {\n @Field(() => SomeEnum, {\n nullable: true,\n defaultValue: SomeEnum.SOME_KEY,\n })\n @Transform(({ value }) => \n typeof value === 'string' ? SomeEnum[value] : value\n )\n someEnumProp?: SomeEnum = SomeEnum.SOME_KEY;\n}\n```\n\nWhere SomeEnum is like:\n\n```\nexport enum SomeEnum {\n SOME_KEY = 1, \n SOME_OTHER_KEY = 2, \n}\n\nregisterEnumType(SomeEnum, {name: 'SomeEnum'})\n```\n\n========================================\n\nCode:\n```text\nimport { IsNumber } from 'class-validator'\nimport { Field, Float } from 'type-graphql'\nimport { Column } from 'typeorm'\n\nexport function OptionalDecimal() {\n const typeDecorator = IsNumber()\n const fieldDecorator = Field(type => Float, { nullable: true })\n const columnDecorator = Column('decimal', { nullable: true })\n\n return (target: any, key: string) => {\n typeDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\n```text\nimport { IsEnum } from 'class-validator'\nimport { Field } from 'type-graphql'\nimport { Column } from 'typeorm'\nimport { IEnumOptions } from './IEnumOptions'\n\nexport function Enum(\n typeFunction: (type?: any) => object,\n options: IEnumOptions = {}\n) {\n const isEnumDecorator = IsEnum(typeFunction())\n const fieldDecorator = Field(typeFunction)\n const columnDecorator = Column({\n default: options.default,\n enum: typeFunction(),\n type: 'enum',\n })\n\n return (target: any, key: string) => {\n isEnumDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\n```text\nimport { registerEnumType } from 'type-graphql'\n\nexport enum AccountState {\n ACTIVE,\n SUSPENDED,\n CLOSED,\n}\n\nregisterEnumType(AccountState, { name: 'AccountState' })\n```\n\n```text\n@EntityType()\nexport class Member extends VersionedEntity {\n @IdentifierNewGuid()\n public readonly id: string\n\n @Enum(type => AccountState, { default: AccountState.ACTIVE })\n public accountState: AccountState\n...\n```\n\n```text\n\"errors\": [\n {\n \"message\": \"Expected a value of type \\\"AccountState\\\" but received: 1\",\n \"locations\": [\n {\n \"line\": 3,\n \"column\": 5\n }\n ],\n \"path\": [\n \"searchMembers\",\n 0,\n \"accountState\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Expected a value of type \\\"AccountState\\\" but received: 1\",\n \" at completeLeafValue\n```\n\n```text\n@Column({\n default: AccountState.ACTIVE,\n enum: AccountState,\n type: 'enum',\n })\n@Field(type => AccountState)\npublic accountState: AccountState\n```\n\n```text\nenum\n```\n\n```text\nexport enum AccountState {\n ACTIVE='ACTIVE',\n SUSPENDED='SUSPENDED',\n CLOSED='CLOSED',\n}\n```\n\n```text\n@ArgsType()\nexport class SomeArgs {\n @Field(() => SomeEnum, {\n nullable: true,\n defaultValue: SomeEnum.SOME_KEY,\n })\n @Transform(({ value }) => \n typeof value === 'string' ? SomeEnum[value] : value\n )\n someEnumProp?: SomeEnum = SomeEnum.SOME_KEY;\n}\n```\n\n```text\nexport enum SomeEnum {\n SOME_KEY = 1, \n SOME_OTHER_KEY = 2, \n}\n\nregisterEnumType(SomeEnum, {name: 'SomeEnum'})\n```\n\n```text\n@Transform\n```\n\n```text\nclass-transformer\n```\n\n```text\nexport enum AccountState {\n ACTIVE,\n SUSPENDED,\n CLOSED,\n}\n\n// Make to register before creating resolver\nregisterEnumType(AccountState, { name: 'AccountState' })\n\nexport const accountStateResolver: Record<keyof typeof AccountState, any> = {\n ACTIVE: 0,\n SUSPENDED: 1,\n CLOSED: 2\n};\n```\n\n```text\n@Module({\n ...\n imports:[\n ...\n GraphQLModule.forRoot({\n ...\n resolvers: {\n AccountState: accountStateResolver,\n }\n }),\n ...\n ]\n ...\n})\n```\n\n```text\nexport function createGQLEnumType<T>(enumType: T): { [key: string]: string } {\n const result = {} as { [key: string]: string }\n for (const key in enumType) {\n if (Object.prototype.hasOwnProperty.call(enumType, key)) {\n const value = enumType[key as keyof T] as string\n result[value] = value\n }\n }\n return result\n}\n```\n\n```text\nconst AccountStateGQLEnum = createGQLEnumType(AccountState)\nregisterEnumType(AccountStateGQLEnum, { name: 'AccountState' })\n\n@InputType({ description: 'Sample input type' })\nexport class SampleInput {\n\n @Field(() => AccountStateGQLEnum!)\n accountState: AccountState\n}\n```\n\n========================================\n\nComments:\n- Have you tried replacing the custom enum decorator with the standard typeorm declaration?\n- I have updated my question, thanks for your response @shusson\n- You're awesome man.. I just missed the registerEnumType(), I was using the string Enums, however it was not working, I saw your code and BAM.... I got the hint... In my case enum with Numeric value also working.. Just declare mongoose document using interface with int enum.\n- Thanks, glad I could be of help :)\n- i'm using the @Field decorator in nestjs/graphql pkg. Tried setting the defaultValue as an array containing an enum member...graphql playground threw an error stating `\"each value in ... must be a valid enum value\"`. It was only after setting the enum member to equal its string equivalent was there no longer an error... Your solution helped solve my problem. Thank you.","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":371,"estimatedTokens":2250}}296{"id":"stack-55620542","source":"stackoverflow","questionId":55620542,"title":"Is it a bad practice to use an Input Type for a graphql Query?","tags":["graphql"],"text":"Title: Is it a bad practice to use an Input Type for a graphql Query?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI have seen that inserting an Input Type is recommended in the context of mutations but does not say anything about queries.\n\nFor instance, in learn tutorial just say:\n\n This is particularly valuable in the case of mutations, where you might want to pass in a whole object to be created\n\nI have this query:\n\n```\ntype query {\n person(personID: ID!): Person\n brazilianPerson(rg: ID!): BrazilizanPerson\n foreignerPerson(passport: ID!): ForeignerPerson\n}\n```\n\nInstead of having a different type just because of the name (rg, passport) of the fields, or put one more argument like type in query, I could not just have the `Person` with an documentNr field and do an Input type like that?\n\n```\ninput PersonInput {\n documentNr : ID!\n type: PersonType # this type is Foreign or Brazilian and with this I k \n}\n```\n\n`PersonType` is a enum and with him I know if the document is a rg or a passport.\n\n========================================\n\nCode:\n```text\ntype query {\n person(personID: ID!): Person\n brazilianPerson(rg: ID!): BrazilizanPerson\n foreignerPerson(passport: ID!): ForeignerPerson\n}\n```\n\n```text\ninput PersonInput {\n documentNr : ID!\n type: PersonType # this type is Foreign or Brazilian and with this I k \n}\n```\n\n```text\nPerson\n```\n\n```text\nPersonType\n```\n\n```text\nquery {\n person(id: 1) {\n powers(onlyMutant: true) {\n name\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":67,"estimatedTokens":371}}297{"id":"stack-52111467","source":"stackoverflow","questionId":52111467,"title":"GraphQL schema with nested objects","tags":["express","graphql"],"text":"Title: GraphQL schema with nested objects\nTags: express, graphql\nSource: Stack Overflow\n\nQuestion:\nHow to write schema for this kind of response.\n\n```\n{\n \"adult\": false,\n \"backdrop_path\": \"/dnaitaoCh8MftfYEVnprcuYExZp.jpg\",\n \"belongs_to_collection\": {\n \"id\": 256322,\n \"name\": \"The Purge Collection\",\n \"poster_path\": \"/nP3c8mTSxlis4vfg0UjlkK8LRG9.jpg\",\n \"backdrop_path\": \"/quFWGOA4I5KCTsyDbvLh6PHNZwv.jpg\"\n },\n \"budget\": 13000000,\n \"genres\": [\n {\n \"id\": 28,\n \"name\": \"Action\"\n },\n {\n \"id\": 27,\n \"name\": \"Horror\"\n },\n {\n \"id\": 878,\n \"name\": \"Science Fiction\"\n },\n {\n \"id\": 53,\n \"name\": \"Thriller\"\n }\n ]\n}\n```\n\n========================================\n\nTop Answer:\n```\nconst typeDefs = `\n type BelongsToCollectionType {\n id: ID!\n name: String\n poster_path: String\n backdrop_path: String\n }\n\n type GenreType {\n id: ID!\n name: String\n }\n\n type SomeType {\n adult: Boolean\n backdrop_path: String\n belongs_to_collection: BelongsToCollectionType\n budget: Int\n genres: [GenreType]!\n }\n`;\n```\n\n========================================\n\nCode:\n```js\n{\n \"adult\": false,\n \"backdrop_path\": \"/dnaitaoCh8MftfYEVnprcuYExZp.jpg\",\n \"belongs_to_collection\": {\n \"id\": 256322,\n \"name\": \"The Purge Collection\",\n \"poster_path\": \"/nP3c8mTSxlis4vfg0UjlkK8LRG9.jpg\",\n \"backdrop_path\": \"/quFWGOA4I5KCTsyDbvLh6PHNZwv.jpg\"\n },\n \"budget\": 13000000,\n \"genres\": [\n {\n \"id\": 28,\n \"name\": \"Action\"\n },\n {\n \"id\": 27,\n \"name\": \"Horror\"\n },\n {\n \"id\": 878,\n \"name\": \"Science Fiction\"\n },\n {\n \"id\": 53,\n \"name\": \"Thriller\"\n }\n ]\n}\n```\n\n```js\nconst MovieType = new GraphQLObjectType({\n name: 'Movie',\n fields: () => ({\n id: { type: GraphQLString },\n adult: { type: GraphQLBoolean },\n backdrop_path: { type: GraphQLString },\n belongs_to_collection: { type: BelongsToCollection },\n budget: { type: GraphQLInt },\n overview: { type: GraphQLString },\n popularity: { type: GraphQLInt },\n poster_path: { type: GraphQLString },\n production_companies: {\n type: new GraphQLList(CompaniesType)\n },\n genres: {\n type: new GraphQLList(GenreType)\n },\n release_date: { type: GraphQLString },\n tagline: { type: GraphQLString },\n title: { type: GraphQLString },\n vote_average: { type: GraphQLInt },\n vote_count: { type: GraphQLInt }\n })\n});\n\nconst CompaniesType = new GraphQLObjectType({\n name: 'ProductionCompanies',\n fields: {\n id: { type: GraphQLInt },\n name: { type: GraphQLString },\n logo_path: { type: GraphQLString },\n original_country: { type: GraphQLString }\n }\n});\n\nconst GenreType = new GraphQLObjectType({\n name: 'Genre',\n fields: () => ({\n id: { type: GraphQLInt },\n name: { type: GraphQLString }\n })\n})\n\nconst BelongsToCollection = new GraphQLObjectType({\n name: 'BelongsToCollection',\n fields: () => ({\n id: { type: GraphQLInt },\n name: { type: GraphQLString },\n poster_path: { type: GraphQLString },\n backdrop_path: { type: GraphQLString } \n })\n});\n```\n\n```js\nconst typeDefs = `\n type BelongsToCollectionType {\n id: ID!\n name: String\n poster_path: String\n backdrop_path: String\n }\n\n type GenreType {\n id: ID!\n name: String\n }\n\n type SomeType {\n adult: Boolean\n backdrop_path: String\n belongs_to_collection: BelongsToCollectionType\n budget: Int\n genres: [GenreType]!\n }\n`;\n```\n\n========================================\n\nComments:\n- Was there a specific part of the schema you found difficult to write? Or were you just wondering how to write a schema in general?\n- well done, very good for those referencing old method\n- thank you, but everytime i learn more about gql i hate it twice as much. typing everything to death is the death of programing.","metadata":{"transformedAt":"2026-08-18T18:32:36.045Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":186,"estimatedTokens":933}}298{"id":"stack-51525516","source":"stackoverflow","questionId":51525516,"title":"how to use .graphql in a typescript node project without webpack","tags":["typescript","graphql"],"text":"Title: how to use .graphql in a typescript node project without webpack\nTags: typescript, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a node, express server using expressGraphql. I am trying to declare a type definition for graphql in a `.graphql` or `.gql` file, because as the type gets larger, it becomes difficult to read the `string`. \n\n**Here is what I have:** \n\n```\nimport testQuery from './test.graphql';\n\nimport routes from \"./routes\";\n\nimport { buildSchema } from \"graphql\";\n\nconst schema = buildSchema(testQuery);\n\n// Root resolver\nconst root = {\n message: () => \"Hello World!\",\n};\n\napp.use(\n \"/api/graphql\",\n expressGraphQL({\n schema,\n graphiql: true,\n })\n);\n```\n\nMy graphql file. //test.graphql\n\n```\ntype Book {\n message: String\n}\n```\n\nI get an error because Typescript\n\n Cannot find module './test.graphql'.\n\nI have seen people doing this:\n\n```\nconst { makeExecutableSchema } = require('graphql-tools');\n\nconst schemaFile = path.join(__dirname, 'schema.graphql');\nconst typeDefs = fs.readFileSync(schemaFile, 'utf8');\n\nconst schema = makeExecutableSchema({ typeDefs });\n```\n\nIs this the way of doing it? \n\nSo what do I need to to config typescript to be able to import, and build the schema\n\n========================================\n\nTop Answer:\nYou can use https://github.com/ardatan/graphql-import-node to solve this without webpack.\n\nInstall with `yarn add graphql-import-node` or `npm install --save graphql-import-node` and then either use the `graphql-import-node/register` hook (if you're using ts-node):\n\n`ts-node -r graphql-import-node/register index.ts`\n\nOr import it in your file right at the top like this:\n\n```\nimport \"graphql-import-node\";\n```\n\nI chose the later in my case because I already used `ts-node/register` with `mocha -r` for my tests.\n\nYou also may need to add `\"esModuleInterop\": true` to your compilerOptions in `tsconfig.json`.\n\n========================================\n\nCode:\n```text\nimport testQuery from './test.graphql';\n\nimport routes from \"./routes\";\n\nimport { buildSchema } from \"graphql\";\n\nconst schema = buildSchema(testQuery);\n\n// Root resolver\nconst root = {\n message: () => \"Hello World!\",\n};\n\napp.use(\n \"/api/graphql\",\n expressGraphQL({\n schema,\n graphiql: true,\n })\n);\n```\n\n```text\ntype Book {\n message: String\n}\n```\n\n```text\nconst { makeExecutableSchema } = require('graphql-tools');\n\nconst schemaFile = path.join(__dirname, 'schema.graphql');\nconst typeDefs = fs.readFileSync(schemaFile, 'utf8');\n\nconst schema = makeExecutableSchema({ typeDefs });\n```\n\n```text\n.graphql\n```\n\n```text\n.gql\n```\n\n```text\nstring\n```\n\n```text\n// bookSchema.ts <- note the file extension is .ts instead of .graphql\nexport default `\n type Book {\n message: String\n }\n`\n\n// anotherSchema.ts <- note the file extension is .ts instead of .graphql\nexport default `\n type User {\n name: String\n }\n`\n\n// main.ts\nimport bookSchema from 'bookSchema';\nimport anotherSchema from 'anotherSchema';\n\nconst schema = makeExecutableSchema({ typeDefs: [\n bookSchema,\n anotherSchema,\n] });\n```\n\n```text\nsrc\n - graphql\n - schema.ts\n - bar\n - barResolver.ts\n - schema.graphql\n - foo\n - fooResolver.ts\n - schema.graphql\n```\n\n```text\nimport { mergeSchemas, makeExecutableSchema } from \"graphql-tools\";\n import { readdirSync, lstatSync, existsSync } from \"fs\";\n import * as path from \"path\";\n import { importSchema } from 'graphql-import'\n import { GraphQLSchema } from 'graphql';\n\n const schemas: GraphQLSchema[] = [];\n\n const isDirectory = dirPath => existsSync(dirPath) && lstatSync(dirPath).isDirectory();\n const getDirectories = source =>\n readdirSync(source).map( name => path.join(source, name) ).filter(isDirectory)\n\n const folders = getDirectories( path.resolve(__dirname, './') )\n\n folders.forEach(folder => {\n folder = folder.substr( folder.lastIndexOf(\"\\\\\")+1 )\n const {resolvers} = require(`./${folder}/${folder}Resolver`);\n const typeDefs = importSchema( path.join(__dirname, `./${folder}/schema.graphql`) );\n schemas.push(makeExecutableSchema({resolvers, typeDefs}))\n });\n\n const mergedSchemas = mergeSchemas({ schemas })\n\n export default mergedSchemas;\n```\n\n```text\nimport schema from './graphql/schema';\nconst server = new GraphQLServer({schema: schema})\n```\n\n```text\n.graphql\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nschema.graphql\n```\n\n```text\nschema.ts\n```\n\n```text\nschema.ts\n```\n\n```text\nmergeSchemas\n```\n\n```js\nimport \"graphql-import-node\";\n```\n\n```text\nyarn add graphql-import-node\n```\n\n```text\nnpm install --save graphql-import-node\n```\n\n```text\ngraphql-import-node/register\n```\n\n```text\nts-node -r graphql-import-node/register index.ts\n```\n\n```text\nts-node/register\n```\n\n```text\nmocha -r\n```\n\n```text\n\"esModuleInterop\": true\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- Reading the file as pure text, as you mentioned, is the best way to do it if you are not using any bundler (like webpack). This way you also have the benefit to lint and auto-format gql files easier\n- Possible duplicate of Error compiling Typescript with graphql files\n- and is that really the best of doing it? That means i will have to use that methods for every type file I define\n- I did not see the error message you posted. Did you remove it again?\n- Not sure this is the best way of doing it. I've been going between these two methods over a few apps I've been working on. In my current project I use .graphql files and read them with fs.readFile. It's a matter of preference I'd say. Some devtools are bettter at dealing with plain .graphql text files so that might weight in that direction.\n- This is not the answer on how to use .graphql files in typescript without webpack as it suggest to use .ts instead.\n- It was so hard to find this answer, somehow for me `import \"graphql-import-node\";\"`in the index file does not work. But `ts-node -r graphql-import-node/register index.ts` does the trick","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":270,"estimatedTokens":1503}}299{"id":"stack-70752976","source":"stackoverflow","questionId":70752976,"title":"GraphQL - retrieves only maximum 10 items from Strapi","tags":["reactjs","graphql","strapi"],"text":"Title: GraphQL - retrieves only maximum 10 items from Strapi\nTags: reactjs, graphql, strapi\nSource: Stack Overflow\n\nQuestion:\nI am using React with Strapi and GrapqQL in order to retreive my data from Strapi.\nSeems that my query retrieves only maximum 10 items. The API is changed with this new version and I am not allowed to use `first:100` in the query.\nhttps://i.sstatic.net/8CjBU.png\n\nThis link 1 is obsolete. I don't know if this is a policy from Strapi's or GraphQL's new version.\n1 https://graphql.org/learn/pagination/\n\n```\nconst REVIEWS = gql`\n query GetReviews {\n reviews (sort: \"createdAt:desc\") {\n data{\n id\n attributes{\n title\n rating\n body\n createdAt\n categories{\n data{\n id\n attributes\n {\n name\n }\n }\n }\n }\n }\n }\n }\n`\n```\n\n========================================\n\nCode:\n```text\nconst REVIEWS = gql`\n query GetReviews {\n reviews (sort: \"createdAt:desc\") {\n data{\n id\n attributes{\n title\n rating\n body\n createdAt\n categories{\n data{\n id\n attributes\n {\n name\n }\n }\n }\n }\n }\n }\n }\n`\n```\n\n```text\nfirst:100\n```\n\n```js\nconst REVIEWS = gql`\n query GetReviews {\n reviews (sort: \"createdAt:desc\", pagination: { limit: 100 }) {\n data{\n id\n attributes{\n title\n rating\n body\n createdAt\n categories{\n data{\n id\n attributes\n {\n name\n }\n }\n }\n }\n }\n }\n }\n`\n```\n\n```text\npagination[limit]\n```\n\n```text\n./config/plugins.js\n```\n\n```text\ngraphql.config.defaultLimit\n```\n\n```text\ngraphql.config.maxLimit\n```\n\n========================================\n\nComments:\n- great tip, Pierre! these is one of those things that you spend a lot of time debugging.\n- Great, thank you! Kept wondering why I only ever received ten items and not more, no matter what I had configured. There are even a couple of PRs that address problems with limit/amountLimit, but they are quite old and didn't help with my queries.\n- This works, but it doesn't allow for flexibility sadly. Let's hope this is fixed in strapiv5. It seems like a basic thing.","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":122,"estimatedTokens":606}}300{"id":"stack-41953815","source":"stackoverflow","questionId":41953815,"title":"GraphQL nested query definition","tags":["javascript","schema","graphql","graphql-js"],"text":"Title: GraphQL nested query definition\nTags: javascript, schema, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create tree-like structure for my queries, to get rid off queries like \n\n```\npeopleList, peopleSingle, peopleEdit, peopleAdd, peopleDelete companyList, companySingle, companyEdit, companyAdd, companyDelete etc.\n```\n\nIn the end I would like to send query like this:\n\n```\nquery test {\n people {\n list {\n id\n name\n }\n single(id: 123) {\n id\n name\n }\n }\n company {\n list {\n id\n name\n }\n single(id: 456) {\n id\n name\n }\n }\n}\n\nmutation test2 {\n people {\n create(data: $var) {\n id\n name\n }\n }\n people {\n edit(id: 123, data: $var) {\n id\n name\n }\n }\n}\n```\n\nThis is part of my query object on people module:\n\n```\npeople: {\n type: //What type this should be?\n name: 'Root of People queries',\n fields: () => ({\n list: {\n type: peopleType,\n description: 'Returns all people in DB.',\n resolve: () => {\n // resolve method implementation\n }\n },\n single: {\n type: peopleType,\n description: 'Single row from people table. Requires ID argument.',\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n resolve: () => {\n // resolve method implementation\n }\n }\n })\n}\n```\n\nI have tried to put this snippet into GraphQLObjectType and then combine them together in RootQuery (using GraphQLObjectType again) - didn't work.\n\nAlternative method could be to create new Type - like peopleQueriesType, inside this type specify all my queries as fields and then create single query for this object. But this seems odd to me - polluting my code with unnecessary objects just to merge my queries in tree-like shape.\n\nI have tried to look at Apollo server implementation, if it can do this kind of query structure, but couldn't find any help in documentation.\n\nI'm using node.js + express + graphql-js on my server.\n\n========================================\n\nCode:\n```text\npeopleList, peopleSingle, peopleEdit, peopleAdd, peopleDelete companyList, companySingle, companyEdit, companyAdd, companyDelete etc.\n```\n\n```text\nquery test {\n people {\n list {\n id\n name\n }\n single(id: 123) {\n id\n name\n }\n }\n company {\n list {\n id\n name\n }\n single(id: 456) {\n id\n name\n }\n }\n}\n\nmutation test2 {\n people {\n create(data: $var) {\n id\n name\n }\n }\n people {\n edit(id: 123, data: $var) {\n id\n name\n }\n }\n}\n```\n\n```text\npeople: {\n type: //What type this should be?\n name: 'Root of People queries',\n fields: () => ({\n list: {\n type: peopleType,\n description: 'Returns all people in DB.',\n resolve: () => {\n // resolve method implementation\n }\n },\n single: {\n type: peopleType,\n description: 'Single row from people table. Requires ID argument.',\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n resolve: () => {\n // resolve method implementation\n }\n }\n })\n}\n```\n\n```text\ntype: new GraphQLObjectType({ name: 'patientQuery', fields: { find, findOne } })\n```\n\n```text\n{\n patient {\n find {\n id\n active\n }\n findOne(id: \"pat3\") {\n id\n active\n }\n }\n}\n```\n\n```text\nimport findOne from './find-one.js';\nimport find from './find.js';\nimport { GraphQLObjectType } from 'graphql';\n\nexport default {\n patient: {\n type: new GraphQLObjectType({ name: 'patientQuery', fields: { find, findOne } }),\n resolve(root, params, context, ast) {\n return true;\n }\n }\n};\n```\n\n```text\nimport patient from './patient/queries/index.js';\nexport default {\n ...patient\n};\n```\n\n```text\nimport {\n GraphQLObjectType,\n GraphQLSchema\n} from 'graphql';\n\nimport queries from './queries';\nimport mutations from './mutations';\n\nexport default new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: queries\n }),\n mutation: new GraphQLObjectType({\n name: 'Mutation',\n fields: mutations\n })\n});\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\npatient/queries/index.js\n```\n\n```text\nqueries.js\n```\n\n```text\nschema.js\n```\n\n========================================\n\nComments:\n- Returning true in the Object base resolver was something I had overlooked. Great help!","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":244,"estimatedTokens":1047}}301{"id":"stack-56494526","source":"stackoverflow","questionId":56494526,"title":"Can I use Guzzle for GraphQL API consumption?","tags":["php","graphql","guzzle"],"text":"Title: Can I use Guzzle for GraphQL API consumption?\nTags: php, graphql, guzzle\nSource: Stack Overflow\n\nQuestion:\nThere isn't a lot of information in the google-verse about consuming GraphQL API's in PHP. There are several packages that from my perspective, are mostly about creating your own GraphQL API, but nothing specific to consuming. It's possible that I'm over complicating things or that the solution to my question is obvious. I've solved my problem and will post the answer.\n\n========================================\n\nTop Answer:\nJust make normal post request from guzzle. Add form params as query and variables. Put your query in query form param and and variables as array of key value.\n\n```\n$response = $this->client->post('https://grapqlEndPoint', [\n 'form_params' => [\n 'query' => '\n query($username: String!) {\n users(username: $username) {\n username \n }\n }',\n 'variables' => json_encode([\n 'username' => $username\n ])\n ]\n ]);\n \n echo $response->getBody()->getContents();\n```\n\n========================================\n\nCode:\n```text\n$graphQLquery = '{\"query\": \"query { viewer { repositories(last: 100) { nodes { name id isPrivate nameWithOwner } } } } \"}';\n\nuse GuzzleHttp\\Client;\n\n$response = (new Client)->request('post', '{graphql-endpoint}', [\n 'headers' => [\n 'Authorization' => 'bearer ' . $token,\n 'Content-Type' => 'application/json'\n ],\n 'body' => $graphQLquery\n]);\n```\n\n```text\n{\"query\": \"query {\n```\n\n```text\n\"query { }\"\n```\n\n```text\n$response = $this->client->post('https://grapqlEndPoint', [\n 'form_params' => [\n 'query' => '\n query($username: String!) {\n users(username: $username) {\n username \n }\n }',\n 'variables' => json_encode([\n 'username' => $username\n ])\n ]\n ]);\n \n echo $response->getBody()->getContents();\n```\n\n```text\n$graphQLquery = '{\"query\": \"query { viewer { repositories(last: 100) { nodes { name id isPrivate nameWithOwner } } } } \"}, \"variables\": { \"isPrivate\": \"True\", \"name\": \"JohnDoe\", ... }';\n```\n\n```text\nuse GuzzleHttp\\Client;\n\n$name = 'JohnDoe';\n$graphQLquery = '{'.\n '\"query\": \"query viewer {'.\n 'repositories(last: 100) {'.\n 'nodes {'.\n 'name'. \n 'id'. \n 'isPrivate'. \n 'nameWithOwner'. \n '}'.\n '}'. \n '}\",'.\n '\"variables\": { \"name\": \"'.$name.'\", \"id\": \"1\", \"isPrivate \": \"True\", \"nameWithOwner\": \"VimDiesel\"}'.\n '}';'\n\n\n\n$response = (new Client)->request('post', '{graphql-endpoint}', [\n 'headers' => [\n 'Authorization' => $token,\n 'Content-Type' => 'application/json'\n ],\n 'body' => $graphQLquery\n]);\n```\n\n```text\nquery { }\n```\n\n```text\n'\"query\": \"query queryName{ }\"'\n```\n\n```text\n'\n```\n\n```text\n.\n```\n\n```text\n$graphQLBody = [\n 'query' => 'mutation ($name: String!) {\n create(\n input:{\n name: $name,\n }\n ) {\n user {\n id,\n name,\n }\n errors {\n messages\n }\n }\n }',\n 'variables' => [\n 'name' => $name,\n ]\n];\n\n$response = $this->client->request('post', $this->apiEndpoint, [\n 'headers' => [\n 'Authorization' => 'bearer ' . $token,\n 'Content-Type' => 'application/json'\n ],\n 'body' => json_encode($graphQLBody)\n]);\n```\n\n========================================\n\nComments:\n- Any idea why some data is missing the response? When same `graphql` endpoint is hit using CURL or python, all required data exists in the response. Due to confidential reasons, graphql query and endpoint cannot be shared here.\n- I don't think so ... where is json encoding (required by graphql API)? some magic?\n- Have added the missing `json_encode()`","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":159,"estimatedTokens":996}}302{"id":"stack-53947508","source":"stackoverflow","questionId":53947508,"title":"How to do filteration in AWS Amplify GraphQL Client","tags":["reactjs","react-native","graphql","aws-appsync","aws-amplify"],"text":"Title: How to do filteration in AWS Amplify GraphQL Client\nTags: reactjs, react-native, graphql, aws-appsync, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement GraphQL filter using Amplify GraphQL Client. I got a list of todos and wanted to retrieve list of todos that has status complete. \n\nThe Documentation only show how to get all items and single item\n\n```\nconst allTodos = await API.graphql(graphqlOperation(queries.listTodos));\nconsole.log(allTodos);\n```\n\nCould someone please point me how to apply filter to the listTodos so that it return todos with status complete only.\n\nI tried to do the following but it is wrong.\n\n```\nAPI.graphql(graphqlOperation(queries.listTodos(filter: {\n status: {\n eq: \"completed\"\n }\n})));\n```\n\n========================================\n\nTop Answer:\n- In your terminal, run amplify console and open the link it returns\n\n- Scroll down and click on the `API` tab. `AWS AppSync` will open up.\n\n- On the `AWS AppSync` menu, select `Queries`\n\n- Create and test your queries. There is a filtering option depending on your schema.\nWhen you have your query working, copy it and paste it into your `js` code using backticks ``\nHere is an example:\n\n```\nconst friendNames = await API.graphql(graphqlOperation(`query MyQuery {\n listFriends(filter: {userId: {eq: \"randomID123456\"}}) {\n items {\n firstname\n othername\n }\n }\n }`));\n```\n\nI can't seem to get stackoverflow to show the backticks `` in the code section above. You need to open backtick before the word query and put a closing backtick after the last curly bracket.\n\nEdit - Edited answer with backticks\n\n========================================\n\nCode:\n```text\nconst allTodos = await API.graphql(graphqlOperation(queries.listTodos));\nconsole.log(allTodos);\n```\n\n```text\nAPI.graphql(graphqlOperation(queries.listTodos(filter: {\n status: {\n eq: \"completed\"\n }\n})));\n```\n\n```text\nexport const listOrganizations = `query ListOrganizations(\n $filter: ModelOrganizationFilterInput\n $limit: Int\n $nextToken: String\n) {\n listOrganizations(filter: $filter, limit: $limit, nextToken: $nextToken) {\n items {\n id\n name\n address\n }\n nextToken\n }\n}\n`;\n```\n\n```text\nAPI.graphql(graphqlOperation(queries.listTodos, {\n filter: {\n status: {\n eq: \"completed\"\n }\n }\n})));\n```\n\n```text\ncodegen\n```\n\n```text\n~/graphql\n```\n\n```text\nListOrganizations\n```\n\n```text\nListTodos\n```\n\n```text\nfilter: $filter\n```\n\n```text\nstatus\n```\n\n```text\ncompleted\n```\n\n```text\nAdmin\n```\n\n```text\n@model\n```\n\n```text\n@owner\n```\n\n```text\n@auth\n```\n\n```text\nowner\n```\n\n```text\nAdmin\n```\n\n```text\n@filter\n```\n\n```text\nModelOrganizationFilterInput\n```\n\n```text\nowner\n```\n\n```text\naws-amplify\n```\n\n```text\nAPI\n```\n\n```text\ngraphqlOperation\n```\n\n```text\nconst friendNames = await API.graphql(graphqlOperation(`query MyQuery {\n listFriends(filter: {userId: {eq: \"randomID123456\"}}) {\n items {\n firstname\n othername\n }\n }\n }`));\n```\n\n```text\nAPI\n```\n\n```text\nAWS AppSync\n```\n\n```text\nAWS AppSync\n```\n\n```text\nQueries\n```\n\n```text\njs\n```\n\n========================================\n\nComments:\n- What does your schema and request mapping template look like? Does listTodos query take in a filter input or something? I know that AppSync generates these filter inputs for you if you choose to start with a sample schema\n- yes, the code was auto generate by the amplify codegen. so it take filter, limit and next token\n- Keep in mind that the filter is applied in the front-end (at least at the time being). You'll have to set a higher limit of todos to filter them correctly\n- Hi @SuperVeetz, did you managed to solve your issue? As for the filter you suggested it work well for field with string type but how about for field with JSON object type.\n- Hi @MohammadHarith , To be honest, i'm not entirely sure, I would assume that if your object time was nested, then you may be able to do something like `filter: { myObj { someProp { eq: \"somevalue\" } } }` , this may work, may not. I have run into a bigger problem, which is how to enforce group based security, and now, how to filter by group based security.. ie. `@auth` transform declares dynamic or static security groups, can I filter results by a group name or by if a given username is contained inside a user group.\n- yeah, its not working, the field has AWSJSON type and it return as one long string, so I just added a new field to specify the item from the object and use the filtration suggested earlier which work well in my case. Thanks!!\n- Hi @SuperVeetz, I'm stuck again, this time I need to filter todos with status of completed and pending. How can I achieve that? I tried `status: { eq: [\"completed\",\"pending\"] }`, but not working.\n- Hi Mohammed, I'll be honest, I haven't run into this problem yet myself, but I believe that you can do use `AND` { `eq`: \"completed\" .. }, { `eq`: \"pending\" } .. I believe there is syntax to do this, but I am not 100% sure yet what it is.. Check the graphql amplify documenation","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":216,"estimatedTokens":1264}}303{"id":"stack-62765178","source":"stackoverflow","questionId":62765178,"title":"Graphql error: \"using last without before is not supported\"","tags":["javascript","ecmascript-6","graphql","shopify"],"text":"Title: Graphql error: \"using last without before is not supported\"\nTags: javascript, ecmascript-6, graphql, shopify\nSource: Stack Overflow\n\nQuestion:\nI am using Gatsby + GraphQL + Shopify. I am having an issue retrieving my orders by the last 10.\n\nMy query looks like this:\n\n```\nquery {\n customer(customerAccessToken: \"${customerAccessToken}\") {\n orders(last: 10) {...}\n }\n}\n```\n\nAnd it returns this:\n\n\"message\": \"using last without before is not supported\"\n\nI noticed this issue happening to some other devs: https://community.shopify.com/c/Shopify-Discussion/How-to-get-customer-s-orders-and-sort-by-date-in-descending/m-p/629133/highlight/false#M151241\n\nIf you check the docs it says nothing about using `before` with `last`:\nhttps://shopify.dev/docs/admin-api/graphql/reference/object/order?api[version]=2020-07\n\nThere is a playground at the bottom where you can test queries.\n\nAnybody else has seen this issue before?\n\n========================================\n\nCode:\n```text\nquery {\n customer(customerAccessToken: \"${customerAccessToken}\") {\n orders(last: 10) {...}\n }\n}\n```\n\n```text\nbefore\n```\n\n```text\nlast\n```\n\n```text\n{\n orders(first: 10, reverse:true) {\n edges {\n node {\n id\n createdAt\n }\n }\n }\n}\n```\n\n```text\nreverse\n```\n\n```text\nfirst\n```\n\n========================================\n\nComments:\n- Hi, but `first:10, reverse:true` is not equal to `last:10`, imagine you have 20 data `[1,2,3....17,18,19,20]` The 1st approach will return `[10,9,8,7...3,2,1]` while the 2nd will return `[20,19,18....12,11,10]`.\n- Have you tested it?\n- It work but without the `sortKey`. The `sortKey` gives an error. You can remove it from there so I can click the check.\n- strange ... as it worked in playground embedded in docs\n- @xadm Provided the correct answer, if we user \"first with reverse\" then it will send you the last orders. GREAT!!!!\n- that is the correct answer","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":79,"estimatedTokens":477}}304{"id":"stack-61615755","source":"stackoverflow","questionId":61615755,"title":"Why Express (or other integration) with Apollo GraphQL Sever?","tags":["graphql","apollo"],"text":"Title: Why Express (or other integration) with Apollo GraphQL Sever?\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI am struggling to understand the added value of Express (or Koa, Hapi, etc) integration with Apollo GraphQL server. \n\nI see it can work in stand alone mode very well (an example: https://medium.com/codingthesmartway-com-blog/apollo-server-2-introduction-efc4026f5654).\n\nIn which case should we use it with (or without) integration? What should drive this decision?\n\n========================================\n\nCode:\n```text\napollo-server\n```\n\n```text\napollo-server-express\n```\n\n========================================\n\nComments:\n- Thank you Daniel, very clear answer, I get it. Just one small thing - your last statement. Why do you say the integration is necessary to deploy to AWS? It should be easy to build just a stand alone Apollo server, no integrations, and deploy it to Lambda or Fargate. Did I understand you well?\n- I haven't used Lambda extensively, but my understanding was that you no longer use listen when running an HTTP server since there is effectively no port to listen to and everything runs through the handler function itself. Under the hood, the standalone library just sets up an Express server for you and then calls `listen` when you call `listen` on the server instance.\n- The greater point is that when using serverless solutions like Azure Functions, Google Cloud Functions, etc. the architecture is different enough compared to a regular Express app to warrant using the appropriate integration.","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":28,"estimatedTokens":388}}305{"id":"stack-56232820","source":"stackoverflow","questionId":56232820,"title":"How to update ApolloClient authorization header after successful login?","tags":["javascript","reactjs","session","local-storage","graphql"],"text":"Title: How to update ApolloClient authorization header after successful login?\nTags: javascript, reactjs, session, local-storage, graphql\nSource: Stack Overflow\n\nQuestion:\nBasically, we have this in our `index.js` file to set-up the `ApolloProvider` authorization to make queries / mutations.\n\n```\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n\nimport App from './App';\n\nimport ApolloClient from \"apollo-boost\";\nimport { ApolloProvider } from \"react-apollo\";\n\nlet session = localStorage.getItem(\"session\");\nlet authorization = \"\";\nif(session) {\n let sessionObj = JSON.parse(session);\n authorization = sessionObj.access_token\n}\n\nconst graphQLServerURL = process.env.REACT_APP_API_URL;\nconst client = new ApolloClient({\n uri: graphQLServerURL + \"/graphql\",\n headers: {\n authorization,\n }\n});\n\nReactDOM.render(\n \n \n \n , document.getElementById('root'));\n```\n\nWhen the app first loads, the `authorization` header would be `null`. However, within the `` component, we have a `` component which basically does a post request with a `username` and `password`. Upon successful request in the `.then()` method, we have:\n\n```\n.then(res => {\nif (res === 200) {\n localStorage.setItem(\"session\", JSON.stringify(res.data));\n history.push(\"/dashboard\");\n});\n```\n\nSo what happens is the user is redirected to a `` component which has a `` component (to list some data). However, the `authorization` in `ApolloClient` is still `null` until I hit refresh. Using `push` doesn't reload the `` component (so that it gets the updated `session` from localstorage).\n\nHow should I do this in a way that after successful post request on login, the authorization from `index.js` gets the latest `session` object without having to reload the entire application?\n\n========================================\n\nTop Answer:\nYou will have to use a link. Ref\n\n```\nconst httpLink = createHttpLink({\n uri: '/graphql',\n});\n\nconst authLink = setContext((_, { headers }) => {\n // get the authentication token from local storage if it exists\n const token = localStorage.getItem('token');\n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n});\n```\n\n========================================\n\nCode:\n```text\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n\nimport App from './App';\n\nimport ApolloClient from \"apollo-boost\";\nimport { ApolloProvider } from \"react-apollo\";\n\nlet session = localStorage.getItem(\"session\");\nlet authorization = \"\";\nif(session) {\n let sessionObj = JSON.parse(session);\n authorization = sessionObj.access_token\n}\n\nconst graphQLServerURL = process.env.REACT_APP_API_URL;\nconst client = new ApolloClient({\n uri: graphQLServerURL + \"/graphql\",\n headers: {\n authorization,\n }\n});\n\nReactDOM.render(\n <ApolloProvider client={client}>\n <App />\n </ApolloProvider>\n , document.getElementById('root'));\n```\n\n```text\n.then(res => {\nif (res === 200) {\n localStorage.setItem(\"session\", JSON.stringify(res.data));\n history.push(\"/dashboard\");\n});\n```\n\n```text\nindex.js\n```\n\n```text\nApolloProvider\n```\n\n```text\nauthorization\n```\n\n```text\nnull\n```\n\n```text\n<App>\n```\n\n```text\n<Login>\n```\n\n```text\nusername\n```\n\n```text\npassword\n```\n\n```text\n.then()\n```\n\n```text\n<Dashboard>\n```\n\n```text\n<Query>\n```\n\n```text\nauthorization\n```\n\n```text\nApolloClient\n```\n\n```text\nnull\n```\n\n```text\npush\n```\n\n```text\n<App>\n```\n\n```text\nsession\n```\n\n```text\nindex.js\n```\n\n```text\nsession\n```\n\n```text\nconst getToken = () => {\n const token = localStorage.getItem('token');\n return token ? `Bearer ${token}` : '';\n};\n\nconst client = new ApolloClient({\n uri: `${graphQLServerURL}/graphql`,\n request: (operation) => {\n operation.setContext({\n headers: {\n authorization: getToken(),\n },\n });\n },\n});\n```\n\n```text\nrequest\n```\n\n```text\napollo-boost\n```\n\n```text\nconst httpLink = createHttpLink({\n uri: '/graphql',\n});\n\nconst authLink = setContext((_, { headers }) => {\n // get the authentication token from local storage if it exists\n const token = localStorage.getItem('token');\n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n});\n```\n\n```js\nimport {\n ApolloClient, InMemoryCache, HttpLink, split,\n} from '@apollo/client';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { getMainDefinition } from 'apollo-utilities';\nimport { useEffect, useState } from 'react';\nimport config from './index';\n\nexport const useConfigClient = () => {\n const [authTokenStorage, setAuthTokenStorage] = useState(localStorage.getItem('token')); // by default it is null\n\n const cache = new InMemoryCache();\n\n const httpLink = new HttpLink({\n uri: config.GRAPHQL_URL,\n headers: {\n authorization: `Bearer ${authTokenStorage}`,\n },\n });\n\n const wsLink = new WebSocketLink({\n uri: config.GRAPHQL_WS,\n options: {\n reconnect: true,\n connectionParams: {\n headers: {\n authorization: `Bearer ${authTokenStorage}`,\n },\n },\n },\n });\n\n const link = split(\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition'\n && definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink,\n );\n\n useEffect(() => {\n setAuthTokenStorage(localStorage.getItem('token')); // as soon as it is available just update the token\n }, []);\n\n const client = new ApolloClient({\n cache,\n link,\n });\n\n return client;\n};\n```\n\n```js\nimport { ApolloProvider } from '@apollo/client';\nimport { useConfigClient } from '../config/apolloConfig'; // import the hooks\n\n<ApolloProvider client={useConfigClient()}>\n // ... add your component\n</ ApolloProvider>\n```\n\n```text\ntoken\n```\n\n```text\nApolloProvider\n```\n\n```text\nlocalStorage\n```\n\n```text\nuseEffect\n```\n\n```text\nuseState\n```\n\n```js\nimport {ApolloClient, InMemoryCache, HttpLink} from '@apollo/client';\nimport {setContext} from '@apollo/client/link/context';\n\nconst httpLink = new HttpLink({uri: '/graphql'});\n\nlet config = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n});\n\nexport function setGraphqlHeaders() {\n const token = localStorage.getItem(AUTH_TOKEN);\n const authLink = setContext((_, {headers}) => {\n return {\n headers: {\n ...headers,\n authorization: token || null,\n },\n };\n });\n\n config.setLink(authLink.concat(httpLink));\n}\n```\n\n```text\nsetLink\n```\n\n```text\nconst userTokenKey = 'userToken'\n\nexport const getUserToken = () => {\n try {\n return localStorage.getItem(userTokenKey) \n } catch (error) {\n ...\n }\n}\n\nexport const setUserToken = (token: string) => {\n try {\n localStorage.setItem(userTokenKey, token)\n } catch (error) {\n ...\n }\n}\n```\n\n```text\nimport { ApolloClient, createHttpLink, InMemoryCache } from \"@apollo/client\";\nimport { setContext } from \"@apollo/client/link/context\";\nimport { getUserToken } from \"./userToken\";\n\nconst httpLink = createHttpLink({\n uri: process.env.NEXT_PUBLIC_GRAPHQL_URL\n})\n\nlet client = new ApolloClient({\n // link: authLink.concat(httpLink),\n link: httpLink,\n cache: new InMemoryCache(),\n});\n\nexport function updateGraphqlHeaders() {\n const authLink = setContext((_, { headers }) => {\n const token = getUserToken();\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n })\n client.setLink(authLink.concat(httpLink))\n}\nupdateGraphqlHeaders() // Init\n\nexport default client;\n```\n\n```text\n...\nimport { ApolloProvider } from \"@apollo/client\";\nimport client from \"../auth/apolloClient\";\n\nfunction MyApp({ Component, pageProps }: AppProps) {\n return (\n <ApolloProvider client={client}>\n <Component {...pageProps} />\n </ApolloProvider>\n );\n}\n\nexport default MyApp;\n```\n\n```text\npraveen-me\n```\n\n```text\nncabral\n```\n\n```text\npraveen-me\n```\n\n```text\nimport { ApolloProvider } from \"@apollo/client\"; \n \nexport default function RootLayout({ children }:any) {\n\n const client = createApolloClient();\n \n return (\n <html lang=\"en\">\n <ApolloProvider client={client}> \n \n </ApolloProvider> \n </html>\n )\n}\n```\n\n```text\nimport { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';\nimport { setContext } from '@apollo/client/link/context';\nimport { getUserToken } from \"./userToken\";\n\nconst API_URL = process.env.API_URL;\n\nconst httpLink = createHttpLink({\n uri: API_URL,\n});\n\n\nconst authLink = setContext(async (_, { headers }) => {\n \n // get the authentication token from local storage if it exists \n const userToken = await getUserToken() \n const token = userToken || null;\n \n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n\nconst createApolloClient = () => {\n \n let client = ''; \n client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n }); \n return client \n};\n\nexport default createApolloClient;\n```\n\n```text\nexport const getUserToken = () => { \n try {\n return JSON.parse(localStorage.getItem('token')); \n } catch (error) {\n console.log(error)\n }\n}\n```\n\n========================================\n\nComments:\n- It appears that the Apollo Client 3 docs show how to include a header on each call. apollographql.com/docs/react/networking/authentication/#head‌​er ncabral below has the answer\n- However, our app is using `ApolloClient` from `apollo-boost` and it doesn't recognise the `link` option.\n- Dang, wish this wouldn't have been downvoted. With new Apollo Client 3 this is the preferred path and would have saved me time. Totally skipped this answer due to down votes >.>\n- @afreeland agreed, this answer is highly underated.\n- This answer doesn't explain how to \"**update** ApolloClient authorization header after successful login\". This answer assumes you are already logged in. What this question is asking for is that you have already created `ApolloClient` **without** a token. Then you login and somehow pass that token to the existing `ApolloClient`\n- If you're using Apollo Client 3 you should check out the answer below by ncabral that uses Apollo Client's setContext. That answer is referenced in the latest Apollo Client API docs (see the REF link in ncabral's answer).\n- When I use this, I get an Invalid Hook Error. \"Hooks can only be called inside of the body of a function component.\" which makes sense as the function being used here is not a component.\n- Thanks @praveen-me. This is the simplest solution. I added an argument \"setGraphqlHeaders(token:string)\" since the caller provides the token.","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":43,"totalLines":520,"estimatedTokens":2771}}306{"id":"stack-44641553","source":"stackoverflow","questionId":44641553,"title":"GraphQL: How to restrict fields server-side across queries?","tags":["graphql"],"text":"Title: GraphQL: How to restrict fields server-side across queries?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nLet's say I have a User type that contains the following fields:\n\n```\ntype User {\n name: String\n username: String\n someOtherField1: String\n someOtherField2: String\n someOtherField3: String\n someOtherField4: String\n creditCardNumber: String\n}\n```\n\nIf I am querying for myself, it's okay to return all fields, because the information is mine. So returning `creditCardNumber` to the client is no biggie. But if I am querying for someone else, I should only be able to access the public info on the returned user. Returning `creditCardNumber` would be terrible. And even if I don't code the query on the client to do so, what would prevent a malicious user from digging into the code, updating the client-side query to include `creditCardNumber`, and executing it?\n\nWhat is the best way to achieve this level of field restriction across queries in GraphQL? My only thought on this so far is to create a separate `UserSearch` type, i.e.\n\n```\ntype UserSearch {\n name: String\n username: String\n someOtherField1: String\n someOtherField2: String\n someOtherField3: String\n someOtherField4: String\n}\n```\n\nwhich excludes the private fields, however this does not feel DRY as you'd be creating many types that are 90% similar in structure form each other.\n\nIs there a cleaner way to implement this, that doesn't create unnecessary types or duplicate fields?\n\n========================================\n\nCode:\n```text\ntype User {\n name: String\n username: String\n someOtherField1: String\n someOtherField2: String\n someOtherField3: String\n someOtherField4: String\n creditCardNumber: String\n}\n```\n\n```text\ntype UserSearch {\n name: String\n username: String\n someOtherField1: String\n someOtherField2: String\n someOtherField3: String\n someOtherField4: String\n}\n```\n\n```text\ncreditCardNumber\n```\n\n```text\ncreditCardNumber\n```\n\n```text\ncreditCardNumber\n```\n\n```text\nUserSearch\n```\n\n```text\ngraphql(schema, query, rootValue, context) // <-- the last parameter\n```\n\n```text\n...\nresolve: (object, args, context) => {\n // Third argument is your object\n},\n....\n```\n\n```text\ngraphql(schema, query, rootValue, { user: getCurrentLoggedUser() })\n```\n\n```text\ncreditCardNumber: {\n ...\n resolve: (user, args, context) => {\n if (user.id === context.user.id)\n return user.creditCardNumber;\n\n return null;\n },\n ...\n}\n```\n\n```text\nresolve\n```\n\n```text\ncreditCardNumber\n```\n\n```text\ncontext\n```\n\n```text\nresolve\n```\n\n```text\nUser\n```\n\n```text\ncreditCardNumber\n```\n\n```text\ngraphql-express\n```\n\n========================================\n\nComments:\n- I can't believe this has to be handled in resolve of every field that needs to be filtered.\n- you can use directives to limit access to limit access to specific field github.com/LawJolla/prisma-auth0-example/issues/12","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":142,"estimatedTokens":718}}307{"id":"stack-68264025","source":"stackoverflow","questionId":68264025,"title":"How to customize SQL query according to GraphQL request using HotChocolate and Dapper?","tags":[".net","asp.net-core","graphql","hotchocolate"],"text":"Title: How to customize SQL query according to GraphQL request using HotChocolate and Dapper?\nTags: .net, asp.net-core, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI'm using HotChocolate as my GraphQL server and Dapper to access the database in my project. Currently With each graphql query requesting \"some\" fields of an entity, the whole row is queried from database and this is wasting resources especially when querying lists of data. I want to customize the sql query according to the requested fields in the graphql query.\nSo, this\n\n```\n{\n product(id: 3) {\n title,\n price\n }\n}\n```\n\nbecomes:\n\n```\nSELECT title, price FROM products WHERE id = 3;\n```\n\nThere is a feature in HotChocolate called projection that I think is related to my problem. But unfortunately the documentation is uncomplete and just shows some examples of using projection with entity framework. Is there a way to implement this feature using Dapper? How?\n\n========================================\n\nTop Answer:\nWell, I managed it (honestly, I used it because of aggregation field feature), but via another package NReco.GraphQL - it takes exactly those fields that you set in the GraphQL query.\n\n========================================\n\nCode:\n```text\n{\n product(id: 3) {\n title,\n price\n }\n}\n```\n\n```text\nSELECT title, price FROM products WHERE id = 3;\n```\n\n```text\npublic static class IResolverContextSelectionExtensions\n{\n /// <summary>\n /// Similar to CollectFields in v10, this uses GetSelections but safely validates that the current context\n /// has selections before returning them, it will safely return null if unable to do so.\n /// This is a variation of the helper method provided by HotChocolate team here: \n /// https://github.com/ChilliCream/hotchocolate/issues/1527#issuecomment-596175928\n /// </summary>\n /// <param name=\"context\"></param>\n /// <returns></returns>\n public static IReadOnlyList<PreProcessingSelection> GetPreProcessingSelections(this IResolverContext? context)\n {\n if (context == null)\n return null!;\n\n var selectionResults = new List<PreProcessingSelection>();\n\n var selections = GatherChildSelections(context!);\n if (selections.Any())\n {\n //BBernard\n //Determine if the Selection is for a Connection, and dive deeper to get the real\n // selections from the node {} field.\n var lookup = selections.ToLookup(s => s.SelectionName.ToString().ToLower());\n\n //Handle paging cases; current Node is a Connection so we have to look for selections inside\n // ->edges->nodes, or inside the ->nodes (shortcut per Relay spec); both of which may exist(?)\n if (lookup.Contains(SelectionNodeName.Nodes) || lookup.Contains(SelectionNodeName.Edges) || lookup.Contains(SelectionNodeName.Items))\n {\n //Cursor & Offset Paging are mutually exclusive so this small optimization prevents unnecessary processing...\n var searchOffsetPagingEnabled = true;\n\n //CURSOR PAGING SUPPORT - results are in either a 'Nodes' or 'Edges' Node!\n //NOTE: nodes and edges are not mutually exclusive per Relay spec so\n // we gather from all if they are defined...\n if (lookup.Contains(SelectionNodeName.Nodes))\n {\n var nodesSelectionField = lookup[SelectionNodeName.Nodes].FirstOrDefault();\n var childSelections = GatherChildSelections(context, nodesSelectionField);\n selectionResults.AddRange(childSelections);\n\n searchOffsetPagingEnabled = false;\n }\n\n if (lookup.Contains(SelectionNodeName.Edges))\n {\n var edgesSelectionField = lookup[SelectionNodeName.Edges].FirstOrDefault();\n //If Edges are specified then Selections are actually inside a nested 'Node' (singular, not plural) that we need to traverse...\n var nodesSelectionField = FindChildSelectionByName(context, SelectionNodeName.EdgeNode, edgesSelectionField);\n var childSelections = GatherChildSelections(context, nodesSelectionField);\n selectionResults.AddRange(childSelections);\n \n searchOffsetPagingEnabled = false;\n }\n\n //OFFSET PAGING SUPPORT - results are in an 'Items' Node!\n if (searchOffsetPagingEnabled && lookup.Contains(SelectionNodeName.Items))\n {\n var nodesSelectionField = lookup[SelectionNodeName.Items].FirstOrDefault();\n var childSelections = GatherChildSelections(context, nodesSelectionField);\n selectionResults.AddRange(childSelections);\n }\n }\n //Handle Non-paging cases; current Node is an Entity...\n else\n {\n selectionResults.AddRange(selections);\n }\n }\n\n return selectionResults;\n }\n\n /// <summary>\n /// Find the selection that matches the specified name.\n /// For more info. on Node parsing logic see here:\n /// https://github.com/ChilliCream/hotchocolate/blob/a1f2438b74b19e965b560ca464a9a4a896dab79a/src/Core/Core.Tests/Execution/ResolverContextTests.cs#L83-L89\n /// </summary>\n /// <param name=\"context\"></param>\n /// <param name=\"baseSelection\"></param>\n /// <param name=\"selectionFieldName\"></param>\n /// <returns></returns>\n private static PreProcessingSelection FindChildSelectionByName(IResolverContext? context, string selectionFieldName, PreProcessingSelection? baseSelection)\n {\n if (context == null)\n return null!;\n\n var childSelections = GatherChildSelections(context!, baseSelection);\n var resultSelection = childSelections?.FirstOrDefault(\n s => s.SelectionName.Equals(selectionFieldName, StringComparison.OrdinalIgnoreCase)\n )!;\n\n return resultSelection!;\n }\n\n /// <summary>\n /// Gather all child selections of the specified Selection\n /// For more info. on Node parsing logic see here:\n /// https://github.com/ChilliCream/hotchocolate/blob/a1f2438b74b19e965b560ca464a9a4a896dab79a/src/Core/Core.Tests/Execution/ResolverContextTests.cs#L83-L89\n /// </summary>\n /// <param name=\"context\"></param>\n /// <param name=\"baseSelection\"></param>\n /// <returns></returns>\n private static List<PreProcessingSelection> GatherChildSelections(IResolverContext? context, PreProcessingSelection? baseSelection = null)\n {\n if (context == null)\n return null!;\n\n var gathered = new List<PreProcessingSelection>();\n\n //Initialize the optional base field selection if specified...\n var baseFieldSelection = baseSelection?.GraphQLFieldSelection;\n \n //Dynamically support re-basing to the specified baseSelection or fallback to current Context.Field\n var field = baseFieldSelection?.Field ?? context.Field;\n\n //Initialize the optional SelectionSet to rebase processing as the root for GetSelections()\n // if specified (but is optional & null safe)...\n SelectionSetNode? baseSelectionSetNode = baseFieldSelection is ISelection baseISelection\n ? baseISelection.SelectionSet\n : null!;\n\n //Get all possible ObjectType(s); InterfaceTypes & UnionTypes will have more than one...\n var objectTypes = GetObjectTypesSafely(field.Type, context.Schema);\n\n //Map all object types into PreProcessingSelection (adapter classes)...\n foreach (var objectType in objectTypes)\n {\n //Now we can process the ObjectType with the correct context (selectionSet may be null resulting\n // in default behavior for current field.\n var childSelections = context.GetSelections(objectType, baseSelectionSetNode);\n var preprocessSelections = childSelections.Select(s => new PreProcessingSelection(objectType, s));\n gathered.AddRange(preprocessSelections);\n }\n\n return gathered;\n }\n\n /// <summary>\n /// ObjectType resolver function to get the current object type enhanced with support\n /// for InterfaceTypes & UnionTypes; initially modeled after from HotChocolate source:\n /// HotChocolate.Data -> SelectionVisitor`1.cs\n /// </summary>\n /// <param name=\"type\"></param>\n /// <param name=\"objectType\"></param>\n /// <param name=\"schema\"></param>\n /// <returns></returns>\n private static List<ObjectType> GetObjectTypesSafely(IType type, ISchema schema)\n {\n var results = new List<ObjectType>();\n switch (type)\n {\n case NonNullType nonNullType:\n results.AddRange(GetObjectTypesSafely(nonNullType.NamedType(), schema));\n break;\n case ObjectType objType:\n results.Add(objType);\n break;\n case ListType listType:\n results.AddRange(GetObjectTypesSafely(listType.InnerType(), schema));\n break;\n case InterfaceType interfaceType:\n var possibleInterfaceTypes = schema.GetPossibleTypes(interfaceType);\n var objectTypesForInterface = possibleInterfaceTypes.SelectMany(t => GetObjectTypesSafely(t, schema));\n results.AddRange(objectTypesForInterface);\n break;\n case UnionType unionType:\n var possibleUnionTypes = schema.GetPossibleTypes(unionType);\n var objectTypesForUnion = possibleUnionTypes.SelectMany(t => GetObjectTypesSafely(t, schema));\n results.AddRange(objectTypesForUnion);\n break;\n }\n\n return results;\n }\n}\n```\n\n```text\n[GraphQLName(\"products\")]\n public async Task<IEnumerable<Products> GetProductsByIdAsync(\n IResolverContext context,\n [Service] ProductsService productsService,\n CancellationToken cancellationToken,\n int id\n )\n {\n //Per the Annotation based Resolver signature here HC will inject the 'id' argument for us!\n //Otherwise this is just normal Resolver stuff...\n var productId = id;\n\n //Also you could get the argument from the IResolverContext...\n var productId = context.Argument<int>(\"id\");. . . \n }\n```\n\n```text\npublic static class IResolverContextSortingExtensions\n{\n /// <summary>\n /// Safely process the GraphQL context to retrieve the Order argument;\n /// matches the default name used by HotChocolate Sorting middleware (order: {{field1}: ASC, {field2}: DESC).\n /// Will return null if the order arguments/info is not available.\n /// </summary>\n /// <returns></returns>\n public static List<ISortOrderField>? GetSortingArgsSafely(this IResolverContext context, string sortOrderArgName = null!)\n {\n var results = new List<ISortOrderField>();\n\n //Unfortunately the Try/Catch is required to make this safe for easier coding when the argument is not specified,\n // because the ResolverContext doesn't expose a method to check if an argument exists...\n try\n {\n var sortArgName = sortOrderArgName ?? SortConventionDefinition.DefaultArgumentName;\n\n //Get Sort Argument Fields and current Values...\n //NOTE: In order to correctly be able to Map names from GraphQL Schema to property/member names\n // we need to get both the Fields (Schema) and the current order values...\n //NOTE: Not all Queries have Fields (e.g. no Selections, just a literal result), so .Field may\n // throw internal NullReferenceException, hence we have the wrapper Try/Catch.\n IInputField sortArgField = context.Field.Arguments[sortArgName];\n ObjectValueNode sortArgValue = context.ArgumentLiteral<ObjectValueNode>(sortArgName);\n\n //Validate that we have some sort args specified and that the Type is correct (ListType of SortInputType values)...\n //NOTE: The Following processing logic was adapted from 'QueryableSortProvider' implementation in HotChocolate.Data core.\n //FIX: The types changed in v11.0.1/v11.0.2 the Sort Field types need to be checked with IsNull() method, and\n // then against NonNullType.NamedType() is ISortInputType instead.\n if (!sortArgValue.IsNull()\n && sortArgField.Type is ListType lt\n && lt.ElementType is NonNullType nn \n && nn.NamedType() is ISortInputType sortInputType)\n {\n //Create a Lookup for the Fields...\n var sortFieldLookup = sortInputType.Fields.OfType<SortField>().ToLookup(f => f.Name.ToString().ToLower());\n\n //Now only process the values provided, but initialize with the corresponding Field (metadata) for each value...\n var sortOrderFields = sortArgValue.Fields.Select(\n f => new SortOrderField(\n sortFieldLookup[f.Name.ToString().ToLower()].FirstOrDefault(), \n f.Value.ToString()\n )\n );\n\n results.AddRange(sortOrderFields);\n }\n\n return results;\n }\n catch\n {\n //Always safely return at least an Empty List to help minimize Null Reference issues.\n return results;\n }\n }\n}\n```\n\n```text\nIResolverContext.GetSelctions()\n```\n\n```text\nIResolverContext\n```\n\n========================================\n\nComments:\n- What code do you currently have?\n- @Nick.McDermaid The SQL for product by id is ` SELECT * FROM products WHERE id = 3; `. What I want is a way to know which fields the user has queried so that I build my SQL string based upon it inside my resolver function. In particular replacing \" * \" by \" title, price, ... \" or whatever the user has specified.\n- Can you integrate this package with Hot Chocolate?","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":318,"estimatedTokens":3525}}308{"id":"stack-55188636","source":"stackoverflow","questionId":55188636,"title":"GraphQL.NET: How to separate the root query into multiple parts","tags":["asp.net",".net-core","graphql"],"text":"Title: GraphQL.NET: How to separate the root query into multiple parts\nTags: asp.net, .net-core, graphql\nSource: Stack Overflow\n\nQuestion:\nI currently have a small application which is using GraphQL to communicate with the .net core backend. I currently have one one root query as is mandatory for GraphQL and am looking for a way to break this up into multiple pieces for organization's sake. My Query looks as follows:\n\n```\npublic class ReactToFactsQuery : ObjectGraphType\n{\n public ReactToFactsQuery(IArticleService articleService,\n INewsItemService newsItemService)\n {\n Field(\n name: \"article\",\n arguments: new QueryArguments(new QueryArgument { Name = \"id\" }),\n resolve: context =>\n {\n var id = context.GetArgument(\"id\");\n return articleService.Get(id);\n }\n );\n\n Field>(\n name: \"articles\",\n arguments: new QueryArguments(new QueryArgument() { Name = \"count\" }),\n resolve: context =>\n {\n var count = context.GetArgument(\"count\");\n if (count.HasValue)\n {\n return articleService.GetAll(count.Value);\n }\n else\n {\n return articleService.GetAll();\n }\n\n }\n );\n\n Field>(\n name: \"newsItems\",\n arguments: new QueryArguments(\n new QueryArgument() { Name = \"count\" },\n new QueryArgument() { Name = \"newsType\" }),\n resolve: context =>\n {\n var count = context.GetArgument(\"count\");\n var category = context.GetArgument(\"newsType\");\n var newsType = (NewsType)category;\n\n if (count.HasValue)\n {\n return newsItemService.GetMostRecent(newsType, count.Value);\n }\n else\n {\n return newsItemService.GetMostRecent(newsType);\n }\n }\n );\n }\n}\n```\n\nCurrently the query is pretty small and manageable but as the application grows, I can easily see there being a huge number of queries defined in this class. THe current query names that exist are `article`, `articles`, and `newsItems`. Preferably, I'd like to create a query class to represent each model type (i.e one query class for article related queries, one for news item related queries, etc).\n\nI've read the documentation here however I for whatever reason am struggling to understand the example here and how to apply it to my code. \n\nAll help is appreciated.\n\n========================================\n\nCode:\n```text\npublic class ReactToFactsQuery : ObjectGraphType\n{\n public ReactToFactsQuery(IArticleService articleService,\n INewsItemService newsItemService)\n {\n Field<ArticleType>(\n name: \"article\",\n arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = \"id\" }),\n resolve: context =>\n {\n var id = context.GetArgument<int>(\"id\");\n return articleService.Get(id);\n }\n );\n\n Field<ListGraphType<ArticleType>>(\n name: \"articles\",\n arguments: new QueryArguments(new QueryArgument<IntGraphType>() { Name = \"count\" }),\n resolve: context =>\n {\n var count = context.GetArgument<int?>(\"count\");\n if (count.HasValue)\n {\n return articleService.GetAll(count.Value);\n }\n else\n {\n return articleService.GetAll();\n }\n\n }\n );\n\n Field<ListGraphType<NewsItemType>>(\n name: \"newsItems\",\n arguments: new QueryArguments(\n new QueryArgument<IntGraphType>() { Name = \"count\" },\n new QueryArgument<IntGraphType>() { Name = \"newsType\" }),\n resolve: context =>\n {\n var count = context.GetArgument<int?>(\"count\");\n var category = context.GetArgument<int>(\"newsType\");\n var newsType = (NewsType)category;\n\n if (count.HasValue)\n {\n return newsItemService.GetMostRecent(newsType, count.Value);\n }\n else\n {\n return newsItemService.GetMostRecent(newsType);\n }\n }\n );\n }\n}\n```\n\n```text\narticle\n```\n\n```text\narticles\n```\n\n```text\nnewsItems\n```\n\n```text\npublic class RootQuery : ObjectGraphType\n{\n public RootQuery()\n {\n Name = \"RootQuery\";\n // defines the articles sub query and returns an empty anonymous type object\n // whose only purpose is to allow making queries on the subtype (ArticlesQueryType)\n Field<ArticlesQueryType>(\"articles\", resolve: context => new {});\n }\n}\n\n// defines the articles specific queries\npublic class ArticlesQueryType: ObjectGraphType\n{\n public ArticlesQueryType(IArticleService articleService)\n {\n Name = \"ArticlesQuery\";\n Field<ArticleType>(\n name: \"article\",\n arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = \"id\" }),\n resolve: context =>\n {\n var id = context.GetArgument<int>(\"id\");\n return articleService.Get(id);\n });\n }\n}\n```\n\n```text\ntype RootQuery {\n articles: ArticlesQuery\n news: NewsQuery\n}\n\ntype ArticlesQuery {\n article(id: ID): Article\n articles: [Article]\n}\n...\n```\n\n```text\npublic partial class RootQuery: ObjectGraphType\n{\n private IArticleService ArticleService { get; }\n\n public RootQuery()\n {\n Name = \"RootQuery\";\n\n InitializeArticlesQueries()\n }\n}\n```\n\n```text\npublic partial class RootQuery\n{\n protected InitializeArticlesQuery()\n {\n Field<ArticleType>(\n name: \"article\",\n arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = \"id\" }),\n resolve: context =>\n {\n var id = context.GetArgument<int>(\"id\");\n return articleService.Get(id);\n });\n }\n}\n```\n\n```text\ntype RootQuery {\n articles: [Article]\n ....\n}\n```\n\n========================================\n\nComments:\n- Is it a correct assumption that you create all the Article Queries. One for GetOne, GetAll etc... within ArticlesQueryType?\n- I would add that the disadvantage of using partial classes is the RootQuery file still gets bloated with a long list of dependencies if you're using constructor injection. e.g. if you have 100+ services or repositories then thats going to be a long list\n- And with schema first approach? I only see that the partial method is the only option here...","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":233,"estimatedTokens":1575}}309{"id":"stack-55336923","source":"stackoverflow","questionId":55336923,"title":"sending Date using moment to graphql","tags":["javascript","reactjs","graphql","momentjs"],"text":"Title: sending Date using moment to graphql\nTags: javascript, reactjs, graphql, momentjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to send a mutation to my graphql server to update a date. My mutation schema looks like this:\n\n```\nmutation CreateReminderMutation(\n $birthday: Date\n) {\n createReminder(\n birthday: $birthday\n ) {\n id\n }\n}\n```\n\nThen in my react component I am sending the date like this using `moment`.\n\n```\nconst Calendar = () => {\n // component and mutation implementation\n birthday: moment(birthday).toDate()\n}\n```\n\nI am getting the following error message:\n\n [GraphQL error]: Message: Variable \"$birthday\" got invalid value\n \"2019-03-15T12:00:00.000Z\"; Expected type Date; Value is not a valid\n Date: 2019-03-15T12:00:00.000Z, unparsable, Location: [object Object],\n Path: undefined\n\ncan anyone advise how to get the correct `Date` format with moment to send to graphql?\n\n========================================\n\nTop Answer:\nNo moment.js solution but this works for me using graphql prisma\n\n```\nnew Date().toISOString()\n```\n\n========================================\n\nCode:\n```text\nmutation CreateReminderMutation(\n $birthday: Date\n) {\n createReminder(\n birthday: $birthday\n ) {\n id\n }\n}\n```\n\n```text\nconst Calendar = () => {\n // component and mutation implementation\n birthday: moment(birthday).toDate()\n}\n```\n\n```text\nmoment\n```\n\n```text\nDate\n```\n\n```text\nmutation {\n createReminder(birthday: \"1990-01-01\") {\n id\n }\n}\n```\n\n```text\nDate\n```\n\n```text\nYYYY-MM-DD\n```\n\n```text\nnew Date().toISOString()\n```\n\n```text\nnew Date().toUTCString()\n```\n\n```text\nnew Date().toISOString()\n```\n\n```text\nnew Date().toISOString().split(\"T\")[0],\n```\n\n```text\ntoISOString()\n```\n\n```text\nYYYY-MM-DDTHH:mm:ss.sssZ\n```\n\n```text\nYYYY-MM-DD\n```\n\n========================================\n\nComments:\n- why has this been downvoted without any explanation? If it was an obvious easy solution I would have found it\n- well, toDate seems to be exactly what you should be doing, that's for sure, as toDate returns a copy of the native Date object - it's odd that the error also states that date string is unparsable - I mean, that is THE guaranteed parsable string format for a date\n- thanks @JaromandaX at least I am not going completely crazy. can't find much in the graphql docs about this","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":126,"estimatedTokens":580}}310{"id":"stack-39114417","source":"stackoverflow","questionId":39114417,"title":"GraphQL Args error: argument type must be Input Type but got: function GraphQLObjectType(config) {","tags":["javascript","node.js","graphql"],"text":"Title: GraphQL Args error: argument type must be Input Type but got: function GraphQLObjectType(config) {\nTags: javascript, node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nOn server start (`node index.js`) I am getting the following error with my GraphQL NodeJS server:\n\n Error: Query.payment(data:) argument type must be Input Type but got:\n function GraphQLObjectType(config) {\n _classCallCheck(this, GraphQLObjectType);\n\nThis error happened when I changed my original args from a string\n\n```\nargs: {\n data: { type: graphQL.GraphQLString }\n },\n```\n\nTo an object type:\n\n```\nargs: {\n data: { type: graphQL.GraphQLObjectType }\n },\n```\n\nI need an object type as I need to send several fields as params.\n\n**GraphQL Server:**\n\n```\nvar Query = new graphQL.GraphQLObjectType({\n name: 'Query',\n fields: {\n payment: {\n type: graphQL.GraphQLString,\n args: {\n data: { type: graphQL.GraphQLObjectType }\n },\n resolve: function (_, args) {\n // There will be more data here, \n // but ultimately I want to return a string\n return 'success!';\n }\n }\n }\n});\n```\n\nHow can I allow it to accept an object?\n\n**Frontend** (if needed. But the error is happening before I even send this):\n\n```\nvar userQuery = encodeURIComponent('{ payment ( data: { user : \"test\" } )}');\n\n$.get('http://localhost:4000/graphql?query=' + userQuery, function (res) {\n //stuff\n});\n```\n\n========================================\n\nCode:\n```text\nargs: {\n data: { type: graphQL.GraphQLString }\n },\n```\n\n```text\nargs: {\n data: { type: graphQL.GraphQLObjectType }\n },\n```\n\n```text\nvar Query = new graphQL.GraphQLObjectType({\n name: 'Query',\n fields: {\n payment: {\n type: graphQL.GraphQLString,\n args: {\n data: { type: graphQL.GraphQLObjectType }\n },\n resolve: function (_, args) {\n // There will be more data here, \n // but ultimately I want to return a string\n return 'success!';\n }\n }\n }\n});\n```\n\n```text\nvar userQuery = encodeURIComponent('{ payment ( data: { user : \"test\" } )}');\n\n$.get('http://localhost:4000/graphql?query=' + userQuery, function (res) {\n //stuff\n});\n```\n\n```text\nnode index.js\n```\n\n```text\n// your arg input object\nvar inputType = new GraphQLInputObjectType({\n name: 'paymentInput',\n fields: {\n user: {\n type: new GraphQLNonNull(GraphQLString)\n },\n order: {\n type: GraphQLString\n },\n ...another fields\n }\n});\n\nvar Query = new graphQL.GraphQLObjectType({\n name: 'Query',\n fields: {\n payment: {\n type: graphQL.GraphQLString,\n args: {\n data: { type: new GraphQLNonNull(inputType) }\n },\n resolve: function (_, args) {\n // There will be more data here,\n // but ultimately I want to return a string\n return 'success!';\n }\n }\n }\n});\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nGraphQLObjectType\n```\n\n========================================\n\nComments:\n- Thanks Lord Dave. I ended up changing it to a `mutation` and specifying fields. Btw, two more questions: `1)` Is there a better way to write my POST query than `encodeURIComponent('{ payment ( data: { user : \"test\" } )}');` ? This gets unwieldy manually specifying each field if the object is large. `2)` GraphQL seems to required a `Query`, even though I only need a `Mutation`. Am I required to always have a query or is there an options somewhere?\n- `1)` I presume you are using a jquery ajax to make a graphql calls according to your given example. Unfortunately I can't help you with this since in my project I am using a `Relay` on `ReactJS` frontend, which is responsible for this. `2)` Apparently, `Query` is always required in schema. Take a look at the `graphql-js` source code I hope I've helped you with at least something\n- Thank you!!! Two years since this post and the documentation still doesn't make it clear. I wasted an entire day until I saw this post. Thanks for the solution @lorddave!","metadata":{"transformedAt":"2026-08-18T18:32:36.046Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":159,"estimatedTokens":1038}}311{"id":"stack-42531322","source":"stackoverflow","questionId":42531322,"title":"GraphQL circular dependency","tags":["javascript","node.js","graphql","circular-dependency"],"text":"Title: GraphQL circular dependency\nTags: javascript, node.js, graphql, circular-dependency\nSource: Stack Overflow\n\nQuestion:\nI am fairly new to javascript and am currently learning to implement a graphQL API with a MongoDB backend using Node.js. I am running into a problem with a circular dependency between two types.\n\nBasically, I have a classic blog post/blog author situation. A post only has one author and therefore the mongoose schema holds a reference to that author.\n\nIn my graphQL type \"Author\" I want to add a field \"posts\" which allows me to navigate from authors to all the posts they have written. The reference is not coded in the database models but retrieved through the controllers. Here's my blog post code.\n\n```\nvar graphql = require(\"graphql\");\nvar AuthorResolvers = require(\"../resolvers/author\");\nvar PostResolvers = require(\"../resolvers/post\");\nvar AuthorType = require(\"./author\").AuthorType;\n\nvar PostType = new graphql.GraphQLObjectType({\n name: \"PostType\",\n fields: {\n _id: {\n type: graphql.GraphQLID\n },\n title: {\n type: graphql.GraphQLString\n },\n author: {\n type: AuthorType,\n description: \"Author of this post\",\n resolve: (post) => AuthorResolvers.retwArgs(post)\n }\n }\n});\n\nmodule.exports = {PostType};\n```\n\nThe resolvers.js file only exports functions to address the controllers.\n\nMy authors type is defined as follows:\n\n```\nvar graphql = require (\"graphql\");\nvar AuthorResolvers = require(\"../resolvers/author\");\nvar PostResolvers = require(\"../resolvers/post\");\n\nvar AuthorType = new graphql.GraphQLObjectType({\n name: \"AuthorType\",\n fields: () => {\n var PostType = require(\"./post\");\n return {\n _id: {\n type: graphql.GraphQLID\n },\n name: {\n type: graphql.GraphQLString\n },\n posts: {\n type: new graphql.GraphQLList(PostType),\n description: \"Posts written by this author\",\n resolve: (author) => PostResolvers.retwArgs(author)\n }\n }\n }\n});\n```\n\nThere're two things in here which I already tried:\n\n- I used a function to return the fields field. I think this is called a thunk or a closure.\n\n- I require the PostType in the function returning the fields. When i required the file ./post together with the other requires, the error was already thrown at the top of the file.\n\nwhen i try to run this server example, i recieve the error:\n\n```\nCan only create List of a GraphQLType but got: [object Object].\n```\n\nwhich points to the line\n\n```\ntype: new graphql.GraphQLList(PostType)\n```\n\nin authors.\n\nThe files containing the type definitions posted above also export queries like this:\n\n```\nvar PostQuery = {\n posts: {\n type: new graphql.GraphQLList(PostType),\n description: \"Posts of this Blog\",\n resolve: PostResolvers.ret\n }\n};\n```\n\nfor the post and like this\n\n```\nvar AuthorQuery = {\n authors: {\n type: new graphql.GraphQLList(AuthorType),\n description: \"The authors working on this Blog\",\n resolve: AuthorResolvers.ret\n }\n};\n```\n\nfor the author respectively. Everything is brought together in a Schema file like this:\n\n```\nvar graphql = require(\"graphql\");\nvar Author = require(\"./types/author\").AuthorQuery;\nvar Post = require(\"./types/post\").PostQuery;\n\nvar root_query = new graphql.GraphQLObjectType({ \n name: \"root_query\",\n fields: {\n posts: Post.posts,\n authors: Author.authors\n }\n});\n\nmodule.exports = new graphql.GraphQLSchema({\n query: root_query\n});\n```\n\nand finally the server:\n\n```\nvar graphql = require ('graphql').graphql \nvar express = require('express') \nvar graphQLHTTP = require('express-graphql')\nvar Schema = require('./api/schema')\n\nvar app = express()\n .use(\"/\", graphQLHTTP(\n {\n schema: Schema,\n pretty: true,\n graphiql: true,\n }\n ))\n .listen(4000, function(err) {\n console.log('Running a GraphQL API server at localhost:4000');\n })\n```\n\nI really don't see any way to resolve this circular dependency. If i simply comment out the references to the PostType in the AuthorType definitions, The server starts without problems. Any help here would be greatly appreciated.\n\nMaybe for better understanding. The directory structure looks like this:\n\n```\nβ package.json\nβ server.js\nβ\nββββapi\nβ β schema.js\nβ β\nβ ββββcontrollers\nβ β author.js\nβ β post.js\nβ β\nβ ββββmodels\nβ β author.js\nβ β post.js\nβ β\nβ ββββresolvers\nβ β author.js\nβ β post.js\nβ β\nβ ββββtypes\nβ author.js\nβ post.js\nβ\nββββconfig\n db.js\n```\n\n========================================\n\nTop Answer:\npiotrbienias' response led me to the correct thread. I've read it before but didn't understand completely. It is necessary to define the exports before you require the class. In my case, i was able to fix it like this:\n\n```\nmodule.exports.AuthorType = new graphql.GraphQLObjectType({\n name: \"AuthorType\",\n fields: () => {\n var PostType = require(\"./post\").PostType;\n return {\n _id: {\n type: graphql.GraphQLID\n },\n name: {\n type: graphql.GraphQLString\n },\n posts: {\n type: new graphql.GraphQLList(PostType),\n description: \"Posts written by this author\",\n resolve: (author) => PostResolvers.retwArgs(author)\n }\n }\n }\n});\n```\n\nand similarly for the PostType. This way, the export is defined before the require is called.\n\nThanks so much!\n\n========================================\n\nCode:\n```js\nvar graphql = require(\"graphql\");\nvar AuthorResolvers = require(\"../resolvers/author\");\nvar PostResolvers = require(\"../resolvers/post\");\nvar AuthorType = require(\"./author\").AuthorType;\n\nvar PostType = new graphql.GraphQLObjectType({\n name: \"PostType\",\n fields: {\n _id: {\n type: graphql.GraphQLID\n },\n title: {\n type: graphql.GraphQLString\n },\n author: {\n type: AuthorType,\n description: \"Author of this post\",\n resolve: (post) => AuthorResolvers.retwArgs(post)\n }\n }\n});\n\nmodule.exports = {PostType};\n```\n\n```js\nvar graphql = require (\"graphql\");\nvar AuthorResolvers = require(\"../resolvers/author\");\nvar PostResolvers = require(\"../resolvers/post\");\n\nvar AuthorType = new graphql.GraphQLObjectType({\n name: \"AuthorType\",\n fields: () => {\n var PostType = require(\"./post\");\n return {\n _id: {\n type: graphql.GraphQLID\n },\n name: {\n type: graphql.GraphQLString\n },\n posts: {\n type: new graphql.GraphQLList(PostType),\n description: \"Posts written by this author\",\n resolve: (author) => PostResolvers.retwArgs(author)\n }\n }\n }\n});\n```\n\n```text\nCan only create List of a GraphQLType but got: [object Object].\n```\n\n```text\ntype: new graphql.GraphQLList(PostType)\n```\n\n```js\nvar PostQuery = {\n posts: {\n type: new graphql.GraphQLList(PostType),\n description: \"Posts of this Blog\",\n resolve: PostResolvers.ret\n }\n};\n```\n\n```js\nvar AuthorQuery = {\n authors: {\n type: new graphql.GraphQLList(AuthorType),\n description: \"The authors working on this Blog\",\n resolve: AuthorResolvers.ret\n }\n};\n```\n\n```js\nvar graphql = require(\"graphql\");\nvar Author = require(\"./types/author\").AuthorQuery;\nvar Post = require(\"./types/post\").PostQuery;\n\nvar root_query = new graphql.GraphQLObjectType({ \n name: \"root_query\",\n fields: {\n posts: Post.posts,\n authors: Author.authors\n }\n});\n\nmodule.exports = new graphql.GraphQLSchema({\n query: root_query\n});\n```\n\n```js\nvar graphql = require ('graphql').graphql \nvar express = require('express') \nvar graphQLHTTP = require('express-graphql')\nvar Schema = require('./api/schema')\n\nvar app = express()\n .use(\"/\", graphQLHTTP(\n {\n schema: Schema,\n pretty: true,\n graphiql: true,\n }\n ))\n .listen(4000, function(err) {\n console.log('Running a GraphQL API server at localhost:4000');\n })\n```\n\n```text\nβ package.json\nβ server.js\nβ\nββββapi\nβ β schema.js\nβ β\nβ ββββcontrollers\nβ β author.js\nβ β post.js\nβ β\nβ ββββmodels\nβ β author.js\nβ β post.js\nβ β\nβ ββββresolvers\nβ β author.js\nβ β post.js\nβ β\nβ ββββtypes\nβ author.js\nβ post.js\nβ\nββββconfig\n db.js\n```\n\n```text\nmodule.exports = { PostType }\n```\n\n```text\nAuthorType\n```\n\n```text\nvar PostType = require('./post')\n```\n\n```text\nvar PostType = require('./post').PostType\n```\n\n```text\nCan only create List of a GraphQLType but got: [object Object].\n```\n\n```text\nPostType\n```\n\n```text\n{ PostType: ... }\n```\n\n```text\nGraphQLObjectType\n```\n\n```js\nmodule.exports.AuthorType = new graphql.GraphQLObjectType({\n name: \"AuthorType\",\n fields: () => {\n var PostType = require(\"./post\").PostType;\n return {\n _id: {\n type: graphql.GraphQLID\n },\n name: {\n type: graphql.GraphQLString\n },\n posts: {\n type: new graphql.GraphQLList(PostType),\n description: \"Posts written by this author\",\n resolve: (author) => PostResolvers.retwArgs(author)\n }\n }\n }\n});\n```\n\n```text\ntype User {\n id: ID\n posts: [Post]\n}\ntype Post {\n id: ID\n user: User\n}\n```\n\n```text\ntype User {\n id: ID \n // no reference to [Post] !\n}\ntype Post {\n id: ID\n user: User // this stays - single direction\n}\nextend type User {\n posts: [Post]\n}\n```\n\n```text\nextend type\n```\n\n```text\nextend\n```\n\n========================================\n\nComments:\n- What happens if you try defining fields like `fields: () => ({ _id: ..., author: ... })`?\n- Then I'll have to put the `var PostType = require(\"./post\");` at the top of the file and instead get the error in a different class. The output is then `PostType.author field type must be Output Type but got: undefined.` and strangely points to the generation of the GraphQL schema.\n- If i then add another function to also retrieve the fields in PostType with a function as you defined, the same error is thrown.\n- Thank you very much. The PostType was indeed a type which i fixed. It wasn't the problem, though. Your link led me to the correct answer which is: make sure your exports are defined before any require statements import anything. (I'm paraphrasing) Thanks a lot.\n- This is the solution for me -- the key is to use a callback function for the `fields` parameter and put your require() in that function\n- This is a pattern known as a \"thunk\".","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":457,"estimatedTokens":2565}}312{"id":"stack-50134500","source":"stackoverflow","questionId":50134500,"title":"Does GraphQL negate the need for Graph Databases","tags":["neo4j","relational-database","graphql","graph-databases"],"text":"Title: Does GraphQL negate the need for Graph Databases\nTags: neo4j, relational-database, graphql, graph-databases\nSource: Stack Overflow\n\nQuestion:\nMost of the reasons for using a graph database seem to be that relational databases are slow when making graph like queries.\n\nHowever, if I am using GraphQL with a data loader, all my queries are flattened and combined using the data loader, so you end up making simpler `SELECT * FROM X` type queries instead of doing any heavy joins. I might even be using a No-SQL database which is usually pretty fast at these kinds of flat queries.\n\nIf this is the case, is there a use case for Graph databases anymore when combined with GraphQL? Neo4j seems to be promoting GraphQL. I'd like to understand the advantages if any.\n\n========================================\n\nTop Answer:\nYes GraphQL allows you to make some kind of graph queries, you can start from one entity, and then explore its neighborhood, and so on.\n\nBut, if you need performances in graph queries, you need to have a **native** graph database. \n\nWith GraphQL you give a lot of power to the end-user. He can make a deep GraphQL query.\n\nIf you have an SQL database, you will have two choices:\n\n- to compute a big SQL query with a lot of joins (really bad idea)\n\n- make a lot of SQL queries to retrieve the neighborhood of the neighborhood, ...\n\nIf you have a native graph database, it will be just one query with good performance! It's a graph traversal, and native graph database are made for this.\n\nMoreover, if you use GraphQL, you consider your data model as a graph. So to store it as graph seems obvious and gives you less headache :) \n\nI recommend you to read this post: The Motivation for Native Graph Databases\n\n### Answer for Graph Loader\n\nWith Graph loader you will do a lot of small queries (it's the second choice on my above answer) but wait no, ... there is a cache record. \n\nGraph loaders just do `batch` and `cache`.\n\nFor comparaison:\n\n- you need to add another library and implement the logic (more code)\n\n- you need to manage the cache. There is a lot of documentation about this topic. (more memory and complexity)\n\n- due to `SELECT *` in loaders, you will always get more data than needed Example: I only want the `id` and `name` of a user not his `email`, `birthday`, ... (less performant)\n\n- ...\n\n========================================\n\nCode:\n```text\nSELECT * FROM X\n```\n\n```text\nSELECT * FROM X\n```\n\n```text\nbatch\n```\n\n```text\ncache\n```\n\n```text\nSELECT *\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\nemail\n```\n\n```text\nbirthday\n```\n\n========================================\n\nComments:\n- If you use a GraphQL data loader, you don't need any joins. It also reduces the number of SQL queries. This is the reason I am asking the question.","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":91,"estimatedTokens":693}}313{"id":"stack-50559580","source":"stackoverflow","questionId":50559580,"title":"Creating Dynamic Schema on Runtime Graphene","tags":["python","graphql","graphene-python"],"text":"Title: Creating Dynamic Schema on Runtime Graphene\nTags: python, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI almost spent 3 days to find a way for creating a dynamic schema in python graphene.\nthe only related result I could find is the below link:\nhttps://github.com/graphql-python/graphene/blob/master/graphene/types/dynamic.py\nBut I couldn't find any documentation for it.\n\nThe whole idea is to create a dynamic schema. I want to provide a GraphQL compatible API that makes users able to query my contents even if Models are not defined in the code. In other words, I want to create Models on the fly. I have no idea about what shall I do.\n\nIt would be a great favor if you can provide an example for that.\n\n**Update :**\n\nMy Project is a Headless CMS which has a feature that users can create their own content types and I want to provide a GraphQL interface to make everything easier and more flexible.\n\nHere is example of my Content Types in DB :\n\n```\n{\n \"id\": \"author\",\n \"name\": \"Book Author\",\n \"desc\": \"\",\n \"options\":[\n {\n \"id\": \"author_faname\",\n \"label\": \"Sample Sample\",\n \"type\": \"text\",\n \"required\": true,\n \"placeholder\":\"One Two Three Four\"\n },\n {\n \"id\": \"author_enname\",\n \"label\": \"Sample label\",\n \"type\": \"text\",\n \"required\": true,\n \"placeholder\":\"Sample Placeholder\"\n }\n ]\n}\n```\n\nAnd Here is Stored content in DB based on that content type :\n\n```\n{\n \"id\": \"9rqgbrox10\",\n \"content_type\": \"author\",\n \"data\":{\n \"author_fname\":\"Jimmy\",\n \"author_ename\":\"Hello\"\n }\n}\n```\n\nNow as my Models are not declared in Code and they are completely in DB, I want to make my schemas on the fly and I don't know what is best the solution for this. I know there should be a way because the other Headless CMS Projects are providing this.\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nI'd like to another neat method.\n\nSo, the issue is that the graphene.ObjectType is not a regular Python class. It has a special metaclass that you can see implemented here. At the moment Python takes care of the inheritance process (when the class itself is initalized), graphene does some operations to register the type. I didn't find a way to change types after the inheritance happens. However, if you just want to generate the schema out of a predefined boilerplate (like me) or some other source, you can do something like this. I first define a handy inherit method:\n\n```\ndef inherit_from(Child, Parent, persist_meta=False):\n \"\"\"Return a class that is equivalent to Child(Parent) including Parent bases.\"\"\"\n PersistMeta = copy(Child.Meta) if hasattr(Child, 'Meta') else None\n\n if persist_meta:\n Child.Meta = PersistMeta\n\n # Prepare bases\n child_bases = inspect.getmro(Child)\n parent_bases = inspect.getmro(Parent)\n bases = tuple([item for item in parent_bases if item not in child_bases]) + child_bases\n\n # Construct the new return type\n try:\n Child = type(Child.__name__, bases, Child.__dict__.copy())\n except AttributeError as e:\n if str(e) == 'Meta':\n raise AttributeError('Attribute Error in graphene library. Try setting persist_meta=True in the inherit_from method call.')\n raise e\n\n if persist_meta:\n Child.Meta = PersistMeta\n\n return Child\n```\n\nNow the key is to perform the inheritance when the type's class is not about to change anymore.\n\n```\ndef context_resolver_factory(attr):\n \"\"\"Create a simple resolver method with default return value None.\"\"\"\n\n def resolver(obj, info):\n return info.context.get(attr, None)\n\n return resolver\n\nclass User:\n id = graphene.ID()\n name = graphene.String(resolver=lambda user, info: user.name)\n\nclass Query: pass\n me = graphene.Field(User)\n\n def resolve_me(self, info):\n return info.context[\"user\"]\n\ninherit_from(User, graphene.ObjectType) # no changes to User class are possible after this line\n\n# method 1: sometimes it's really neat and clean to include a resolver in the field definition\nsetattr(Query, 'user', graphene.User(resolver=context_resolver_factory('user'))\n# or even use lambda if a factory is still overkill\nsetattr(Query, 'user', graphene.User(resolver=lambda query, info: info.context[\"user\"]))\n\n# method 2: if you want to set the resolver separately, you can do it this way\nsetattr(Query, 'user', graphene.User())\nsetattr(Query, 'resolve_user', context_resolver_factory('user'))\n\n# any changes to `Query.Meta` can be done here too\n\ninherit_from(Query, graphene.ObjectType) # no changes to Query class are possible after this line\n\nschema = graphene.Schema(query=Query)\n```\n\nWhere I got with my little library was generating everything from a boilerplate class like this:\n\n```\n@register_type('Product')\nclass ProductType:\n class Meta:\n model = Product\n fields = '__all__'\n related_fields = {\n NestedField('tags', TagType),\n NestedField('related_products', 'self'),\n }\n lookups = {\n 'id': graphene.ID(),\n 'name': graphene.String(description=\"Name\"),\n 'ean': graphene.String(),\n 'brand': graphene.String()\n }\n filters = {\n 'ids': IDFilter,\n 'django_filter': DjangoFilter,\n 'pagination': PaginationFilter,\n 'search_name': ProductMLNSearchFilter\n }\n```\n\nBiggest challenge were the NestedFields and figuring out automatic Django ORM query select/prefetch when a request comes in, but I won't go into detail unless that's something relevant.\n\n========================================\n\nCode:\n```json\n{\n \"id\": \"author\",\n \"name\": \"Book Author\",\n \"desc\": \"\",\n \"options\":[\n {\n \"id\": \"author_faname\",\n \"label\": \"Sample Sample\",\n \"type\": \"text\",\n \"required\": true,\n \"placeholder\":\"One Two Three Four\"\n },\n {\n \"id\": \"author_enname\",\n \"label\": \"Sample label\",\n \"type\": \"text\",\n \"required\": true,\n \"placeholder\":\"Sample Placeholder\"\n }\n ]\n}\n```\n\n```json\n{\n \"id\": \"9rqgbrox10\",\n \"content_type\": \"author\",\n \"data\":{\n \"author_fname\":\"Jimmy\",\n \"author_ename\":\"Hello\"\n }\n}\n```\n\n```text\nclass MyType(graphene.ObjectType):\n something = graphene.String()\n\nclass Query(graphene.ObjectType):\n value = graphene.Field(MyType)\n\nschema = graphene.Schema(query=Query, types=[MyType])\n```\n\n```text\ndef create_schema():\n MyType = type('MyType', (graphene.ObjectType,), {\n 'something': graphene.String(),\n })\n\n Query = type('Query', (graphene.ObjectType,), {\n 'value': graphene.Field(MyType),\n })\n\n return graphene.Schema(query=Query, types=[MyType])\n```\n\n```text\ndef make_resolver(record_name, record_cls):\n def resolver(self, info):\n data = ...\n return record_cls(...)\n resolver.__name__ = 'resolve_%s' % record_name\n return resolver\n\ndef create_schema(db):\n record_schemas = {}\n for record_type in db.get_record_types():\n classname = record_type['id'].title() # 'Author'\n fields = {}\n for option in record_type['options']:\n field_type = {\n 'text': graphene.String,\n ...\n }[option['type']\n fields[option['id']] = field_type() # maybe add label as description?\n rec_cls = type(\n classname,\n (graphene.ObjectType,), \n fields,\n name=record_type['name'],\n description=record_type['desc'],\n )\n record_schemas[record_type['id']] = rec_cls\n\n # create Query in similar way\n fields = {}\n for key, rec in record_schemas:\n fields[key] = graphene.Field(rec)\n fields['resolve_%s' % key] = make_resolver(key, rec)\n Query = type('Query', (graphene.ObjectType,), fields)\n\n return graphene.Schema(query=Query, types=list(record_schemas.values()))\n```\n\n```text\ncreate_schema()\n```\n\n```text\nMyType.another_field = graphene.String()\n```\n\n```text\ngraphene.ObjectType\n```\n\n```text\nself._meta.fields\n```\n\n```text\nMyType._meta.fields['another_field'] = thefield\n```\n\n```text\ngraphene.ObjectType.__init_subclass_with_meta__\n```\n\n```text\ndef inherit_from(Child, Parent, persist_meta=False):\n \"\"\"Return a class that is equivalent to Child(Parent) including Parent bases.\"\"\"\n PersistMeta = copy(Child.Meta) if hasattr(Child, 'Meta') else None\n\n if persist_meta:\n Child.Meta = PersistMeta\n\n # Prepare bases\n child_bases = inspect.getmro(Child)\n parent_bases = inspect.getmro(Parent)\n bases = tuple([item for item in parent_bases if item not in child_bases]) + child_bases\n\n # Construct the new return type\n try:\n Child = type(Child.__name__, bases, Child.__dict__.copy())\n except AttributeError as e:\n if str(e) == 'Meta':\n raise AttributeError('Attribute Error in graphene library. Try setting persist_meta=True in the inherit_from method call.')\n raise e\n\n if persist_meta:\n Child.Meta = PersistMeta\n\n return Child\n```\n\n```text\ndef context_resolver_factory(attr):\n \"\"\"Create a simple resolver method with default return value None.\"\"\"\n\n def resolver(obj, info):\n return info.context.get(attr, None)\n\n return resolver\n\n\nclass User:\n id = graphene.ID()\n name = graphene.String(resolver=lambda user, info: user.name)\n\n\nclass Query: pass\n me = graphene.Field(User)\n\n def resolve_me(self, info):\n return info.context[\"user\"]\n\n\ninherit_from(User, graphene.ObjectType) # no changes to User class are possible after this line\n\n# method 1: sometimes it's really neat and clean to include a resolver in the field definition\nsetattr(Query, 'user', graphene.User(resolver=context_resolver_factory('user'))\n# or even use lambda if a factory is still overkill\nsetattr(Query, 'user', graphene.User(resolver=lambda query, info: info.context[\"user\"]))\n\n\n# method 2: if you want to set the resolver separately, you can do it this way\nsetattr(Query, 'user', graphene.User())\nsetattr(Query, 'resolve_user', context_resolver_factory('user'))\n\n# any changes to `Query.Meta` can be done here too\n\ninherit_from(Query, graphene.ObjectType) # no changes to Query class are possible after this line\n\nschema = graphene.Schema(query=Query)\n```\n\n```text\n@register_type('Product')\nclass ProductType:\n class Meta:\n model = Product\n fields = '__all__'\n related_fields = {\n NestedField('tags', TagType),\n NestedField('related_products', 'self'),\n }\n lookups = {\n 'id': graphene.ID(),\n 'name': graphene.String(description=\"Name\"),\n 'ean': graphene.String(),\n 'brand': graphene.String()\n }\n filters = {\n 'ids': IDFilter,\n 'django_filter': DjangoFilter,\n 'pagination': PaginationFilter,\n 'search_name': ProductMLNSearchFilter\n }\n```\n\n```text\nimport importlib\nimport inspect\n\nimport graphene\n\nfrom django.conf import settings\n\n\ndef dynamic_inherit(name_cls: str, parent_class_list):\n \"\"\" name_cls needed to keep the standard names Mutation ΠΈ Query\"\"\"\n\n class Mutate(*parent_class_list, graphene.ObjectType):\n pass\n\n class Query(*parent_class_list, graphene.ObjectType):\n pass\n\n if name_cls.lower() == \"mutate\":\n return Mutate\n elif name_cls.lower() == \"query\":\n return Query\n else:\n raise ValueError('cls need choice [mutate,query]')\n\n\ndef collect_class(name_class_contains, path_module_from_app):\n list_cls = []\n for application in settings.INSTALLED_APPS:\n application = application.split('.')[0] # if app.AppConfig del AppConfig\n try:\n file = importlib.import_module(application + path_module_from_app)\n except ImportError:\n pass\n else:\n all_class = inspect.getmembers(file, inspect.isclass)\n for cls in all_class:\n if cls[0].find(name_class_contains) != -1:\n list_cls.append(cls[1])\n return list_cls\n```\n\n```text\n\"\"\"Global GraphQL Schema\"\"\"\nfrom graphene import Schema\n\nfrom main.dynamic_collect_graphene_scheme import dynamic_inherit, collect_class\n\nschema = Schema(query=dynamic_inherit(\"query\", collect_class(name_class_contains=\"MixinQuery\",\n path_module_from_app=\".api.queries\")),\n mutation=dynamic_inherit(\"mutate\", collect_class(name_class_contains=\"MixinMutation\",\n path_module_from_app=\".api.mutate\")))\n```\n\n========================================\n\nComments:\n- Your question is very broad and not a good fit for stackoverflow. Also GraphQl is fully typed, so not sure if what you want can be achieved without breaking the graphql standards. Please specify more exactly what you want. How should the queries work? What would be an example of a dynamic model? \"I have no idea about what shall I do\" is not really a good question, have a look at: stackoverflow.com/help/how-to-ask Don't give up, but put some more effort into formulating the problem, so people can help you.\n- Question fits stackoverflow perfectly. The main question is - how to make dynamic schema. And MarSoft answer describes it nicely.\n- i can confirm that this is working solution. It should be marked as correct answer. MarSoft thank you a lot! You saved me a ton of time!\n- in django, if a schema is alread loaded in a running process, how can I change the schema and reload it live? @MarSoft\n- Working as charm. I am begineerish Pythonee and would need a lot of time to do this. Thanx.\n- I'm getting type error `Expected Graphene type, but received`, Can anyone help me out here?\n- @NirajGautam, please the full error with traceback. Likely as a separate question.","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":441,"estimatedTokens":3369}}314{"id":"stack-54589989","source":"stackoverflow","questionId":54589989,"title":"Unexpected end of JSON on GraphQL query with React while no issue with GraphiQL","tags":["reactjs","graphql","magento2","apollo"],"text":"Title: Unexpected end of JSON on GraphQL query with React while no issue with GraphiQL\nTags: reactjs, graphql, magento2, apollo\nSource: Stack Overflow\n\nQuestion:\nI am trying to do a very basic query via React with Apollo.\n\nWhen I do this query in GraphiQL I nicely get my results back but in my app I get an undefined data object. And a error with a message: \n\n Network error: Unexpected end of JSON input\n\nThe query is:\n\n```\nquery {\n category(id: 3) {\n id\n children {\n id\n name\n }\n }\n}\n```\n\nThis is my component\n\n```\nimport React, { Component } from 'react';\nimport { Query } from 'react-apollo';\nimport gql from 'graphql-tag';\n\nconst CATEGORIES_LIST = gql`\n query CATEGORIES_LIST {\n category(id: 3) {\n id\n children {\n id\n name\n }\n }\n }\n`;\n\nclass Cat extends Component {\n render() {\n return (\n \n Items!\n\n \n {payload => {\n console.log(payload);\n return fetch done!\n\n;\n }}\n \n \n )\n }\n}\n\nexport default Cat;\n```\n\nWhile the GraphiQL response is with the exact same request\n\n```\n{\n \"data\": {\n \"category\": {\n \"id\": 3,\n \"children\": [\n {\n \"id\": 4,\n \"name\": \"Bags\"\n },\n {\n \"id\": 5,\n \"name\": \"Fitness Equipment\"\n },\n {\n \"id\": 6,\n \"name\": \"Watches\"\n }\n ]\n }\n }\n}\n```\n\nBy the way I'm querying a local Magento 2.3 graphql server.\n\nWhen inspecting the network tab this is the response i get from the graphql endpoint. So no url typo are issue in the response\n\n```\n{\n \"data\":{\n \"category\":{\n \"id\":3,\n \"children\":[\n {\n \"id\":4,\n \"name\":\"Bags\",\n \"__typename\":\"CategoryTree\"\n },\n {\n \"id\":5,\n \"name\":\"Fitness Equipment\",\n \"__typename\":\"CategoryTree\"\n },\n {\n \"id\":6,\n \"name\":\"Watches\",\n \"__typename\":\"CategoryTree\"\n }\n ],\n \"__typename\":\"CategoryTree\"\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nDid you add your backend url as Proxy to React?, that usually does the trick. Add it to the package.json\n\nthen set the uri to \"/graphql\"\n\n========================================\n\nCode:\n```text\nquery {\n category(id: 3) {\n id\n children {\n id\n name\n }\n }\n}\n```\n\n```text\nimport React, { Component } from 'react';\nimport { Query } from 'react-apollo';\nimport gql from 'graphql-tag';\n\nconst CATEGORIES_LIST = gql`\n query CATEGORIES_LIST {\n category(id: 3) {\n id\n children {\n id\n name\n }\n }\n }\n`;\n\nclass Cat extends Component {\n render() {\n return (\n <div>\n <p>Items!</p>\n <Query query={CATEGORIES_LIST}>\n {payload => {\n console.log(payload);\n return <p>fetch done!</p>;\n }}\n </Query>\n </div>\n )\n }\n}\n\nexport default Cat;\n```\n\n```text\n{\n \"data\": {\n \"category\": {\n \"id\": 3,\n \"children\": [\n {\n \"id\": 4,\n \"name\": \"Bags\"\n },\n {\n \"id\": 5,\n \"name\": \"Fitness Equipment\"\n },\n {\n \"id\": 6,\n \"name\": \"Watches\"\n }\n ]\n }\n }\n}\n```\n\n```text\n{\n \"data\":{\n \"category\":{\n \"id\":3,\n \"children\":[\n {\n \"id\":4,\n \"name\":\"Bags\",\n \"__typename\":\"CategoryTree\"\n },\n {\n \"id\":5,\n \"name\":\"Fitness Equipment\",\n \"__typename\":\"CategoryTree\"\n },\n {\n \"id\":6,\n \"name\":\"Watches\",\n \"__typename\":\"CategoryTree\"\n }\n ],\n \"__typename\":\"CategoryTree\"\n }\n }\n}\n```\n\n```text\n- $data = $this->jsonSerializer->unserialize($request->getContent());\n + $content = ($request->getContent() === '') ? '{}' : $request->getContent();\n + $data = $this->jsonSerializer->unserialize($content);\n```\n\n```text\nno-cors\n```\n\n```text\nApolloClient\n```\n\n```text\nOPTIONS\n```\n\n```text\nUnable to unserialize value\n```\n\n```text\n/vendor/magento/module-graph-ql/Controller/GraphQl.php\n```\n\n========================================\n\nComments:\n- Check the actual server response shown in the Network tab. `Unexpected end of JSON input` means the server encountered some kind of issue when processing the request and returned an error message instead of a JSON object. CORS configuration is the usual culprit, but it could be something simple like a typo in the endpoint URL. Check the message and include it with your question if you still can't diagnose the problem.\n- Thanks @DanielRearden i just updated the question with the results. Looks good to me!\n- Ok, so the next likely culprit is apollo client and/or link config.\n- Exactly. but my biggest pain is not sure where to exactly find \"the\" error im sure i can fix when i know what exactly is wrong.\n- Can you post your client config?\n- For what it's worth, it's possible that it could be because of a bad import somewhere: github.com/apollographql/react-apollo/issues/…\n- It could very well be the issue in the last comment of your link @DanielRearden i added { mode: 'no-cors' } because i had issues with that.","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":270,"estimatedTokens":1263}}315{"id":"stack-64658321","source":"stackoverflow","questionId":64658321,"title":"Variable \"$file\" got invalid value {}; Upload value invalid","tags":["javascript","node.js","file-upload","graphql","antd"],"text":"Title: Variable \"$file\" got invalid value {}; Upload value invalid\nTags: javascript, node.js, file-upload, graphql, antd\nSource: Stack Overflow\n\nQuestion:\nI am using GraphQLClient from `graphql-request` to send requests to my server. I am trying to upload a file by doing the following:\n\n```\nconst graphQLClient = new GraphQLClient('http://localhost:4000/graphql', {\n credentials: 'include',\n mode: 'cors',\n});\nconst source = gql`\n mutation uploadImage($file: Upload!) {\n uploadImage(file: $file)\n }\n`;\nconst file: RcFile = SOME_FILE; // RcFile (from antd) extends File\nawait graphQLClient.request(source, { file });\n```\n\nHowever, when I send a request to my server this way I get the following error:\n\n```\nGraphQLError: Variable \\\"$file\\\" got invalid value {}; Upload value invalid\n```\n\nThis is what my request looks like in the console:\n\n```\noperations: {\n \"query\":\"\\n mutation uploadProfileImage($file: Upload!){\\n uploadProfileImage(file: $file)\\n }\\n\", \n \"variables\":{\"file\":null}\n}\nmap: {\"1\":[\"variables.file\"]}\n1: (binary)\n```\n\nHas anyone else had this issue? I can't seem to upload a file to my backend.\n\n========================================\n\nTop Answer:\nit depends on ApolloClient that you used.\n\n1- If used import { ApolloClient } from 'apollo-client' must be used \"**createUploadLink**\" instead of \"**createHttpLink** \"means,\n\n```\nimport { createUploadLink } from 'apollo-upload-client'\nconst httpLink = createUploadLink({\n uri: httpEndpoint,\n})\n```\n\n2- if used createApolloClient, exact this package:\n\n```\nimport { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client'\nconst { apolloClient, wsClient } = createApolloClient({\n ...defaultOptions,\n ...options,\n })\n``\nYou do not need to set anything and Upload work complete.\n```\n\n========================================\n\nCode:\n```text\nconst graphQLClient = new GraphQLClient('http://localhost:4000/graphql', {\n credentials: 'include',\n mode: 'cors',\n});\nconst source = gql`\n mutation uploadImage($file: Upload!) {\n uploadImage(file: $file)\n }\n`;\nconst file: RcFile = SOME_FILE; // RcFile (from antd) extends File\nawait graphQLClient.request<{uploadImage: boolean}>(source, { file });\n```\n\n```text\nGraphQLError: Variable \\\"$file\\\" got invalid value {}; Upload value invalid\n```\n\n```text\noperations: {\n \"query\":\"\\n mutation uploadProfileImage($file: Upload!){\\n uploadProfileImage(file: $file)\\n }\\n\", \n \"variables\":{\"file\":null}\n}\nmap: {\"1\":[\"variables.file\"]}\n1: (binary)\n```\n\n```text\ngraphql-request\n```\n\n```text\nnew ApolloServer({ schema, context, uploads: false })\n```\n\n```text\napp.use(graphqlUploadExpress({ maxFileSize: 10000, maxFiles: 10 }));\n```\n\n```text\nApolloServer\n```\n\n```text\ngraphqlUploadExpress()\n```\n\n```text\ngraphql-upload\n```\n\n```text\nimport { createUploadLink } from 'apollo-upload-client'\nconst httpLink = createUploadLink({\n uri: httpEndpoint,\n})\n```\n\n```text\nimport { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client'\nconst { apolloClient, wsClient } = createApolloClient({\n ...defaultOptions,\n ...options,\n })\n``\nYou do not need to set anything and Upload work complete.\n```\n\n```text\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { createUploadLink } from 'apollo-upload-client';\n\nconst client = new ApolloClient({\n cache: new InMemoryCache(),\n link: createUploadLink({\n uri: 'http://localhost:4000/graphql'\n }),\n});\n```\n\n```text\nApolloServer\n```\n\n```text\napollo-upload-client\n```\n\n```js\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n csrfPrevention: false, // if this is set to true, uploads will fail\n uploads: false,\n cache: \"bounded\",\n plugins: [ApolloServerPluginLandingPageLocalDefault({ embed: true })],\n });\n```\n\n```text\ncsrfPrevention\n```\n\n========================================\n\nComments:\n- console.log(file) ?\n- `File { uid: \"rc-upload-1604388578610-2\", name: \"images.jpg\", lastModified: 1604388587004, lastModifiedDate: Tue Nov 03 2020 01:29:47 GMT-0600 (Central Standard Time), webkitRelativePath: \"\", name: \"images.jpg\" size: 4040 type: \"image/jpeg\" uid: \"rc-upload-1604388578610-2\" webkitRelativePath: \"\"`\n- does this server support graphql upload properly ? ... mutation should have return type/fields defined\n- I am using typegraphql and graphql-upload on my backend: `@Mutation(() => Boolean) async uploadImage( @Arg('file', () => GraphQLUpload) upload: UploadType): Promise { ... }`\n- more like ... is it working using postman?\n- It seems to be happening on postman as well! `\"Variable \\\"$file\\\" got invalid value {}; Upload value invalid.\"`. I tried changing ApolloServer to have { uploads: false } in it's configuration and now I get `POST body missing. Did you forget use body-parser middleware?`\n- I'm trying the same thing but get the error: \"POST body missing. Did you forget use body-parser middleware?\". Did you run into that?","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":182,"estimatedTokens":1227}}316{"id":"stack-39609979","source":"stackoverflow","questionId":39609979,"title":"GraphQL List or single object","tags":["javascript","graphql"],"text":"Title: GraphQL List or single object\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI got the following \"problem\". I am used to having an API like that. \n\n```\n/users\n/users/{id}\n```\n\nThe first one returns a list of users. The second just a single object. I would like the same with GraphQL but seem to fail. I got the following Schema\n\n```\nvar schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: {\n users: {\n type: new GraphQLList(userType),\n args: {\n id: {type: GraphQLString}\n },\n resolve: function (_, args) {\n if (args.id) {\n return UserService.findOne(args.id).then(user => [user]);\n } else {\n return UserService.find()\n }\n }\n }\n }\n })\n});\n```\n\nHow can I modify the type of users to either return a List OR a single object?\n\n========================================\n\nTop Answer:\nThe above answer is correct, the usual approach is to add singular and plural form of queries. However, in large schema, this can duplicate a lot of logic and can be abstracted a little bit for example with Node interface and node, nodes queries. But the nodes query is usually applied with ids as argument (in Relay viz node Fields), but you can build your own abstracted way for fetching so that you have just nodes with some argument for type and based on that you can say what type of list to fetch. However, the simpler approach is to just duplicate the logic for every type and use singular and plural form of query and do the same type of queries as above or in this code snippet for every type. For more detail explanation on implementing GraphQL list modifiers in queries or even as an input for mutations. I just published the article on that.\n\n========================================\n\nCode:\n```text\n/users\n/users/{id}\n```\n\n```text\nvar schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: {\n users: {\n type: new GraphQLList(userType),\n args: {\n id: {type: GraphQLString}\n },\n resolve: function (_, args) {\n if (args.id) {\n return UserService.findOne(args.id).then(user => [user]);\n } else {\n return UserService.find()\n }\n }\n }\n }\n })\n});\n```\n\n```text\nfields: {\n user: {\n type: userType,\n description: 'Returns a single user',\n args: {\n id: {type: GraphQLString}\n },\n resolve: function (_, args) {\n return UserService.findOne(args.id);\n }\n },\n users: {\n type: new GraphQLList(userType),\n description: 'Returns a list of users',\n resolve: function () {\n return UserService.find()\n }\n }\n}\n```\n\n========================================\n\nComments:\n- You are right, Just small correction, then then(user => [user]) is not needed anymore :)\n- I had the same solution...but under the same name `users` ain't possible?\n- I've tried to reproduce your schema and everything works correctly. Try console.log on your `[user]` result and see what you get\n- Can you tell me why this is better practice? What if you want people to be able to filter the data in several different ways (e.g. min/max age, min/max height, eye colour) - are you creating new fields for each of these, or just adding arguments to the `users` field? If you're adding arguments to the `users` field for those filters, would you still create a separate field for returning 1 user? Or in this case would you simply add `id` as another argument on `users`?\n- the both uses same endpoint the only differnce is we are passing an id, if not we need to list the items","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":105,"estimatedTokens":906}}317{"id":"stack-42634742","source":"stackoverflow","questionId":42634742,"title":"How do you define multiple query or mutation in GraphQLSchema","tags":["graphql"],"text":"Title: How do you define multiple query or mutation in GraphQLSchema\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI am new to GraphQL. Forgive me if this is obvious.\n\nBeside using `buildSchema`, is there a way to define more than one query/mutation using `new GraphQLSchema`?\n\nThis is what I have right now.\n\n```\nconst schema = new graphql.GraphQLSchema(\n {\n query: new graphql.GraphQLObjectType({\n name: 'RootQueryType',\n fields: {\n count: {\n type: graphql.GraphQLInt,\n resolve: function () {\n return count;\n }\n }\n }\n }),\n mutation: new graphql.GraphQLObjectType({\n name: 'RootMutationType',\n fields: {\n updateCount: {\n type: graphql.GraphQLInt,\n description: 'Updates the count',\n resolve: function () {\n count += 1;\n return count;\n }\n }\n }\n })\n });\n```\n\n========================================\n\nCode:\n```text\nconst schema = new graphql.GraphQLSchema(\n {\n query: new graphql.GraphQLObjectType({\n name: 'RootQueryType',\n fields: {\n count: {\n type: graphql.GraphQLInt,\n resolve: function () {\n return count;\n }\n }\n }\n }),\n mutation: new graphql.GraphQLObjectType({\n name: 'RootMutationType',\n fields: {\n updateCount: {\n type: graphql.GraphQLInt,\n description: 'Updates the count',\n resolve: function () {\n count += 1;\n return count;\n }\n }\n }\n })\n });\n```\n\n```text\nbuildSchema\n```\n\n```text\nnew GraphQLSchema\n```\n\n```text\nquery: new graphql.GraphQLObjectType({\n name: 'RootQueryType',\n fields: {\n count: {\n type: graphql.GraphQLInt,\n resolve: function () {\n return count;\n }\n },\n myNewField: {\n type: graphql.String,\n resolve: function () {\n return 'Hello world!';\n }\n }\n }\n}),\n```\n\n```text\nGraphQLObjectType\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":105,"estimatedTokens":528}}318{"id":"stack-51659099","source":"stackoverflow","questionId":51659099,"title":"How do I subscribe directly to my AWS AppSync data source?","tags":["amazon-dynamodb","graphql","aws-appsync"],"text":"Title: How do I subscribe directly to my AWS AppSync data source?\nTags: amazon-dynamodb, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI have a DynamoDB connected to step functions and I am building a UI to display changes. I connected the DB to an AppSync instance and have tried using subscriptions through AppSync, but it seems they only observe mutations within the current AppSync.\n\nHow can I subscribe to the data source changes directly?\n\n========================================\n\nComments:\n- How do I authorize the Lambda to call the AppSync instance if it requires Cognito login?\n- Depends on the auth type. For API Key, just add a header. Ditto for OIDC and Cognito user pools. If you are using AWS_IAM, there is more work to do since you have to sign the connection with the AWS AppSync SDK.\n- @AdrianHall what header would I add for connecting to Cognito pools?\n- Add an Authorization header with a bearer JWT token\n- @AdrianHall don't you require a username and password to generate this token?\n- Yes - you can either use the passed in Authorization header, which is available in the Lambda, or just log in to the Cognito pool with a backend username/password (standard OIDC stuff) to generate the JWT.\n- In step 3, from the lambda, \"call the AWS AppSync mutation\"? How do we do that? The other comments suggest marshall the endpoint, auth, query and hit it like anyone might from the outside? In which case, might this solution also be described as \"Create a mutation that calls a lambda which passes the incoming data straight out again. Send an appsync mutation to it from the stream.\"?","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":19,"estimatedTokens":403}}319{"id":"stack-32657596","source":"stackoverflow","questionId":32657596,"title":"GraphQL mutation variables","tags":["graphql","graphql-js"],"text":"Title: GraphQL mutation variables\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to do a simple mutation using GraphQL with the GraphiQL interface. My mutation looks like this:\n\n```\nmutation M($name: String) {\n addGroup(name:$name) {\n id,\n name\n }\n}\n```\n\nwith variables:\n\n```\n{\n \"name\": \"ben\"\n}\n```\n\nBut it gives me the error: `Variable $name of type \"String\" used in position expecting type \"String!\"`\n\nIf I change my mutation to `mutation M($name: String = \"default\")` it works as expected. This looks like it's related to the type system, but I can't seem to figure out what the problem is.\n\n========================================\n\nTop Answer:\nI think in you `addGroup()` mutation the args for name is of type `String!` that is `new GraphQLNonNull(GraphQLString)` but in your mutation you specify as `String` which conflicts with the type system.\n\n========================================\n\nCode:\n```graphql\nmutation M($name: String) {\n addGroup(name:$name) {\n id,\n name\n }\n}\n```\n\n```graphql\n{\n \"name\": \"ben\"\n}\n```\n\n```text\nVariable $name of type \"String\" used in position expecting type \"String!\"\n```\n\n```text\nmutation M($name: String = \"default\")\n```\n\n```text\nmutation M($name: String!) {\n addGroup(name:$name) {\n id,\n name\n }\n}\n```\n\n```text\ntype: new GraphQLNonNull(GraphQLString)\n```\n\n```text\nString!\n```\n\n```text\naddGroup()\n```\n\n```text\nString!\n```\n\n```text\nnew GraphQLNonNull(GraphQLString)\n```\n\n```text\nString\n```\n\n```text\nmutation {\n createProject(\n name:\"project two\",\n description:\"project two\"\n ) {\n name\n }\n}\n```\n\n========================================\n\nComments:\n- Incredible the the `!` was the issue... Alas it does make sense!","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":107,"estimatedTokens":429}}320{"id":"stack-48984933","source":"stackoverflow","questionId":48984933,"title":"Resolving nested data in express GraphQL","tags":["node.js","express","graphql","graphql-js","express-graphql"],"text":"Title: Resolving nested data in express GraphQL\nTags: node.js, express, graphql, graphql-js, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI am currently trying to resolve a simple recipe list that has a reference to ingredients.\n\nThe data layout looks like this:\n\n```\ntype Ingredient {\n name: String!\n amount: Int!\n unit: Unit!\n recipe: Recipe\n}\n\ntype Recipe {\n id: Int!\n name: String!\n ingredients: [Ingredient]!\n steps: [String]!\n pictureUrl: String!\n}\n```\n\nAs I understand it, my resolvers should look like this:\nThe first one resolves the recipes and second one resolves the ingredient field in the recipe. It can (from my understanding) use the argument provided by recipe. In my recipe object, the ingredient is referenced by id (int), so this should be the argument (at least that's what I think).\n\n```\nvar root = {\n recipe: (argument) => {\n return recipeList;\n },\n Recipe: {\n ingredients: (obj, args, context) => {\n //resolve ingredients\n }\n },\n```\n\nThese resolvers are passed to the app like this:\n\n```\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n graphiql: true,\n rootValue: root,\n}));\n```\n\nHowever, my resolver does not seem to be called. I would like the ingredients to be resolved on the fly when queried in my query.\n\nThe endpoint works, but as soon as I query for ingredients, an error with this message `\"message\": \"Cannot return null for non-nullable field Ingredient.name.\",` is returned.\n\nWhen trying to log the incoming arguments in my resolver, I can see that it is never executed. Unfortunately, I can't find examples on how to do this with express-graphql when using it like I am.\n\n**How do I write seperate resolvers for nested types in express-graphQL?**\n\n========================================\n\nCode:\n```text\ntype Ingredient {\n name: String!\n amount: Int!\n unit: Unit!\n recipe: Recipe\n}\n\ntype Recipe {\n id: Int!\n name: String!\n ingredients: [Ingredient]!\n steps: [String]!\n pictureUrl: String!\n}\n```\n\n```text\nvar root = {\n recipe: (argument) => {\n return recipeList;\n },\n Recipe: {\n ingredients: (obj, args, context) => {\n //resolve ingredients\n }\n },\n```\n\n```text\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n graphiql: true,\n rootValue: root,\n}));\n```\n\n```text\n\"message\": \"Cannot return null for non-nullable field Ingredient.name.\",\n```\n\n```text\nroot\n```\n\n```text\nbuildSchema\n```\n\n```text\ningredients\n```\n\n```text\nbuildSchema\n```\n\n```text\nmakeExecutableSchema\n```\n\n========================================\n\nComments:\n- Thank you so much! I used makeExecutableSchema, defined a custom resolver for Ingredient type and it worked instantly. I really found it hard to figure out what caused this, so thanks for explaining!\n- TBH I wasn't even aware that it's possible to build the schema programatically - every tutorial shows this `buildSchema` from string method. Why did they even create option to build it from string?","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":128,"estimatedTokens":726}}321{"id":"stack-48968896","source":"stackoverflow","questionId":48968896,"title":"Validation error of type FieldUndefined: Field 'register' in type 'Query' is undefined","tags":["java","spring-boot","graphql","graphql-java"],"text":"Title: Validation error of type FieldUndefined: Field 'register' in type 'Query' is undefined\nTags: java, spring-boot, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI am new to GrapQL. I am trying to use it with spring boot. I can make query successfully, it is returning the data that I need, but i want now to use mutation. I need to add a use to database when he registers.\n\nThis is my schema.graphqls file:\n\n```\ntype Token {\n token: String\n}\ntype Register {\n message: String\n}\ntype User {\n username: String!\n firstName: String!\n lastName: String!\n password: String!\n role: String!\n}\n\ntype Query {\n login(username: String, password: String): Token\n}\n\ntype Mutation {\n register(input: RegisterUserInput!): Register\n}\n\ninput RegisterUserInput {\n username: String!\n firstName: String!\n lastName: String!\n password: String!\n role: String!\n}\n\nschema {\n query: Query\n mutation: Mutation\n}\n```\n\nSo as you can see register is in Mutation type, which is added in schema as is Query. But for some reason it looks like it is not going into Mutation, it is only trying to find the types in Query.\n\nThis is my controller:\n\n```\n@Autowired\n private UserService userService;\n\n /**\n * Login the user and return generated token\n * @param query\n * @return String token\n */\n @PostMapping(\"/login\")\n public ResponseEntity login(@RequestBody String query){\n ExecutionResult executionResult = userService.getGraphQL().execute(query);\n\n // Check if there are errors\n if(!executionResult.getErrors().isEmpty()){\n return new ResponseEntity<>(executionResult.getErrors().get(0).getMessage(), HttpStatus.UNAUTHORIZED);\n }\n\n return new ResponseEntity<>(executionResult, HttpStatus.OK);\n }\n\n /**\n * Create new user and save him to database\n * @param mutation\n * @return String message\n */\n@PostMapping(\"/register\")\npublic ResponseEntity register(@RequestBody String mutation){\n ExecutionResult executionResult = userService.getGraphQL().execute(mutation);\n\n // Check if there are errors\n if(!executionResult.getErrors().isEmpty()){\n return new ResponseEntity<>(executionResult.getErrors().get(0).getMessage(), HttpStatus.UNAUTHORIZED);\n }\n\n return new ResponseEntity<>(executionResult, HttpStatus.OK);\n}\n```\n\nAs I said, login is working fine, but register is return the error I mentioned in the title.\n\nMy service class:\n\n```\n@Value(\"classpath:graphql-schema/schema.graphqls\")\n Resource resource;\n\n private GraphQL graphQL;\n\n @Autowired\n private LoginDataFetcher loginDataFetcher;\n @Autowired\n private RegisterDataFetcher registerDataFetcher;\n\n @PostConstruct\n public void loadSchema() throws IOException{\n // Get the schema\n File schemaFile = resource.getFile();\n\n // Parse schema\n TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(schemaFile);\n RuntimeWiring runtimeWiring = buildRuntimeWiring();\n GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);\n graphQL = GraphQL.newGraphQL(graphQLSchema).build();\n}\n\nprivate RuntimeWiring buildRuntimeWiring() {\n return RuntimeWiring.newRuntimeWiring()\n .type(\"Query\", typeWiring ->\n typeWiring\n .dataFetcher(\"login\", loginDataFetcher))\n .type(\"Mutation\", typeWiring ->\n typeWiring\n .dataFetcher(\"register\", registerDataFetcher))\n .build();\n}\n\npublic GraphQL getGraphQL() {\n return graphQL;\n}\n```\n\nMy LoginDataFetcher:\n\n```\n@Autowired\n private AppUserRepository appUserRepository;\n\n private JwtGenerator jwtGenerator;\n\n public LoginDataFetcher(JwtGenerator jwtGenerator) {\n this.jwtGenerator = jwtGenerator;\n }\n\n @Override\n public TokenDAO get(DataFetchingEnvironment dataFetchingEnvironment) {\n String username = dataFetchingEnvironment.getArgument(\"username\");\n String password = dataFetchingEnvironment.getArgument(\"password\");\n\n AppUser appUser = appUserRepository.findByUsername(username);\n\n // If user is not foung\n if(appUser == null){\n throw new RuntimeException(\"Username does not exist\");\n }\n\n // If the user is fount check passwords\n if(!appUser.getPassword().equals(password)){\n throw new RuntimeException(\"Incorrect password\");\n }\n\n // Generate the token\n String token = jwtGenerator.generate(appUser);\n\n return new TokenDAO(token);\n }\n```\n\nThe RegisterDataFetcher:\n\n```\n@Autowired\n private AppUserRepository appUserRepository;\n\n @Override\n public RegisterDAO get(DataFetchingEnvironment dataFetchingEnvironment) {\n String username = dataFetchingEnvironment.getArgument(\"username\");\n String firstName = dataFetchingEnvironment.getArgument(\"firstName\");\n String lastName = dataFetchingEnvironment.getArgument(\"lastName\");\n String password = dataFetchingEnvironment.getArgument(\"password\");\n String role = dataFetchingEnvironment.getArgument(\"role\");\n\n AppUser appUser = appUserRepository.findByUsername(username);\n\n // Check if username exists\n if(appUser != null){\n throw new RuntimeException(\"Username already taken\");\n }\n\n AppUser newAppUser = new AppUser(username, password, role, firstName, lastName);\n\n // Save new user\n appUserRepository.save(newAppUser);\n\n return new RegisterDAO(\"You have successfully registered\");\n }\n```\n\nThe error that I am getting in the console:\n\n```\ngraphql.GraphQL : Query failed to validate : '{\n register(username: \"user\", firstName: \"Bla\", lastName: \"Blabla\", password: \"password\", role: \"DEVELOPER\") {\n message\n }\n}'\n```\n\nThank you for your help.\n\n### UPDATE\n\nI changed my schema file like this, based on the answer I got:\n\n```\nquery UserQuery{\n login(username: String, password: String){\n token\n }\n}\n\nmutation UserMutation{\n register(input: RegisterUserInput) {\n message\n }\n}\n\ninput RegisterUserInput {\n username: String!\n firstName: String!\n lastName: String!\n password: String!\n role: String!\n}\n\nschema {\n query: UserQuery\n mutation: UserMutation\n}\n```\n\nBut now I am getting this error:\n\nThe operation type 'UserQuery' is not present when resolving type 'query'\nThe operation type 'UserMutation' is not present when resolving type 'mutation'\n\nSo what is now the problem? How can I make this work?\n\n========================================\n\nCode:\n```text\ntype Token {\n token: String\n}\ntype Register {\n message: String\n}\ntype User {\n username: String!\n firstName: String!\n lastName: String!\n password: String!\n role: String!\n}\n\ntype Query {\n login(username: String, password: String): Token\n}\n\ntype Mutation {\n register(input: RegisterUserInput!): Register\n}\n\ninput RegisterUserInput {\n username: String!\n firstName: String!\n lastName: String!\n password: String!\n role: String!\n}\n\nschema {\n query: Query\n mutation: Mutation\n}\n```\n\n```text\n@Autowired\n private UserService userService;\n\n /**\n * Login the user and return generated token\n * @param query\n * @return String token\n */\n @PostMapping(\"/login\")\n public ResponseEntity<Object> login(@RequestBody String query){\n ExecutionResult executionResult = userService.getGraphQL().execute(query);\n\n // Check if there are errors\n if(!executionResult.getErrors().isEmpty()){\n return new ResponseEntity<>(executionResult.getErrors().get(0).getMessage(), HttpStatus.UNAUTHORIZED);\n }\n\n return new ResponseEntity<>(executionResult, HttpStatus.OK);\n }\n\n /**\n * Create new user and save him to database\n * @param mutation\n * @return String message\n */\n@PostMapping(\"/register\")\npublic ResponseEntity<Object> register(@RequestBody String mutation){\n ExecutionResult executionResult = userService.getGraphQL().execute(mutation);\n\n // Check if there are errors\n if(!executionResult.getErrors().isEmpty()){\n return new ResponseEntity<>(executionResult.getErrors().get(0).getMessage(), HttpStatus.UNAUTHORIZED);\n }\n\n return new ResponseEntity<>(executionResult, HttpStatus.OK);\n}\n```\n\n```text\n@Value(\"classpath:graphql-schema/schema.graphqls\")\n Resource resource;\n\n private GraphQL graphQL;\n\n @Autowired\n private LoginDataFetcher loginDataFetcher;\n @Autowired\n private RegisterDataFetcher registerDataFetcher;\n\n @PostConstruct\n public void loadSchema() throws IOException{\n // Get the schema\n File schemaFile = resource.getFile();\n\n // Parse schema\n TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(schemaFile);\n RuntimeWiring runtimeWiring = buildRuntimeWiring();\n GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);\n graphQL = GraphQL.newGraphQL(graphQLSchema).build();\n}\n\nprivate RuntimeWiring buildRuntimeWiring() {\n return RuntimeWiring.newRuntimeWiring()\n .type(\"Query\", typeWiring ->\n typeWiring\n .dataFetcher(\"login\", loginDataFetcher))\n .type(\"Mutation\", typeWiring ->\n typeWiring\n .dataFetcher(\"register\", registerDataFetcher))\n .build();\n}\n\npublic GraphQL getGraphQL() {\n return graphQL;\n}\n```\n\n```text\n@Autowired\n private AppUserRepository appUserRepository;\n\n private JwtGenerator jwtGenerator;\n\n public LoginDataFetcher(JwtGenerator jwtGenerator) {\n this.jwtGenerator = jwtGenerator;\n }\n\n @Override\n public TokenDAO get(DataFetchingEnvironment dataFetchingEnvironment) {\n String username = dataFetchingEnvironment.getArgument(\"username\");\n String password = dataFetchingEnvironment.getArgument(\"password\");\n\n AppUser appUser = appUserRepository.findByUsername(username);\n\n // If user is not foung\n if(appUser == null){\n throw new RuntimeException(\"Username does not exist\");\n }\n\n // If the user is fount check passwords\n if(!appUser.getPassword().equals(password)){\n throw new RuntimeException(\"Incorrect password\");\n }\n\n // Generate the token\n String token = jwtGenerator.generate(appUser);\n\n return new TokenDAO(token);\n }\n```\n\n```text\n@Autowired\n private AppUserRepository appUserRepository;\n\n @Override\n public RegisterDAO get(DataFetchingEnvironment dataFetchingEnvironment) {\n String username = dataFetchingEnvironment.getArgument(\"username\");\n String firstName = dataFetchingEnvironment.getArgument(\"firstName\");\n String lastName = dataFetchingEnvironment.getArgument(\"lastName\");\n String password = dataFetchingEnvironment.getArgument(\"password\");\n String role = dataFetchingEnvironment.getArgument(\"role\");\n\n AppUser appUser = appUserRepository.findByUsername(username);\n\n // Check if username exists\n if(appUser != null){\n throw new RuntimeException(\"Username already taken\");\n }\n\n AppUser newAppUser = new AppUser(username, password, role, firstName, lastName);\n\n // Save new user\n appUserRepository.save(newAppUser);\n\n return new RegisterDAO(\"You have successfully registered\");\n }\n```\n\n```text\ngraphql.GraphQL : Query failed to validate : '{\n register(username: \"user\", firstName: \"Bla\", lastName: \"Blabla\", password: \"password\", role: \"DEVELOPER\") {\n message\n }\n}'\n```\n\n```text\nquery UserQuery{\n login(username: String, password: String){\n token\n }\n}\n\nmutation UserMutation{\n register(input: RegisterUserInput) {\n message\n }\n}\n\ninput RegisterUserInput {\n username: String!\n firstName: String!\n lastName: String!\n password: String!\n role: String!\n}\n\nschema {\n query: UserQuery\n mutation: UserMutation\n}\n```\n\n```text\nquery someOperationName {\n login {\n # other fields\n }\n}\n```\n\n```text\nmutation someOperationName {\n register {\n # other fields\n }\n}\n```\n\n```text\n{\n someQuery {\n # other fields\n }\n}\n```\n\n```text\nregister\n```\n\n```text\nquery\n```\n\n```text\nregister\n```\n\n========================================\n\nComments:\n- I don't think you understood the answer, there was no need to change the schema. Can you show the query/mutation string you're firing? It should look like: `mutation register { register(input: {username: \"someName\", ...}) { ... } }`\n- Yes, you were right. It worked. Thank you.","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":504,"estimatedTokens":3013}}322{"id":"stack-66580508","source":"stackoverflow","questionId":66580508,"title":"Authorization in Nestjs using graphql","tags":["graphql","nestjs","nestjs-passport","nestjs-jwt"],"text":"Title: Authorization in Nestjs using graphql\nTags: graphql, nestjs, nestjs-passport, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nI have started to learn Nestjs, express and graphql.\nI encountered a problem while trying to authorize access of user authenticated using jwt token.\nI followed the tutorial for authentication on the Nestjs website.\nI am able to get the current user, but when I try implementing the basic role base access control, I am unable to access the current user in the canActivate Method.\nI think it is because the Roles Guard is executed before the Graphql Guard.\n\nI will post the codes here\n\ngql-auth.guard.ts\n\n```\nimport { ExecutionContext } from \"@nestjs/common\";\nimport { GqlExecutionContext } from \"@nestjs/graphql\";\nimport { AuthGuard } from \"@nestjs/passport\";\n\nexport class GqlAuthGuard extends AuthGuard(\"jwt\") {\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n console.log(\"gql simple context: \", context);\n console.log(\"gqlContext: \", ctx.getContext());\n return ctx.getContext().req;\n }\n}\n```\n\nroles.guard.ts\n\n```\nimport { CanActivate, ExecutionContext, Injectable } from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\nimport { GqlExecutionContext } from \"@nestjs/graphql\";\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n canActivate(context: ExecutionContext) {\n const roles = this.reflector.get(\"roles\", context.getHandler());\n const ctx = GqlExecutionContext.create(context);\n console.log(\"roles: \", roles);\n console.log(\"context: \", context.switchToHttp().getRequest());\n console.log(\"gqlContext: \", ctx.getContext().req);\n\n return true;\n }\n}\n```\n\njwt.strategy.ts\n\n```\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { ExtractJwt, Strategy } from \"passport-jwt\";\nimport { jwtConstants } from \"../constants\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor() {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n ignoreExpiration: false,\n secretOrKey: jwtConstants.secret,\n });\n }\n\n validate(payload: any) {\n console.log(\"payload: \", payload);\n\n return payload;\n }\n}\n```\n\nresolver\n\n```\n@UseGuards(GqlAuthGuard)\n@Roles(\"ADMIN\")\n@UseGuards(RolesGuard)\n@Query((returns) => [Specialty], { nullable: \"itemsAndList\", name: \"specialties\" })\nasync getSpecialties(@Args() params: FindManySpecialtyArgs, @Info() info: GraphQLResolveInfo) {\n const select = new PrismaSelect(info).value;\n params = { ...params, ...select };\n return this.prismaService.specialty.findMany(params);\n}\n```\n\nHas anyone successfully implemented this before ?\n\n========================================\n\nTop Answer:\n```\nexport const Authorize = (roles?: string | string[]) =>\n applyDecorators(\n SetMetadata('roles', [roles].flat()),\n UseGuards(GqlAuthGuard, RolesGuard),\n );\n```\n\n```\n@Authorize(\"ADMIN\")\n@Query((returns) => [Specialty], { nullable: \"itemsAndList\", name: \"specialties\" })\nasync getSpecialties(@Args() params: FindManySpecialtyArgs, @Info() info: GraphQLResolveInfo) {\n const select = new PrismaSelect(info).value;\n params = { ...params, ...select };\n return this.prismaService.specialty.findMany(params);\n}\n```\n\n========================================\n\nCode:\n```js\nimport { ExecutionContext } from \"@nestjs/common\";\nimport { GqlExecutionContext } from \"@nestjs/graphql\";\nimport { AuthGuard } from \"@nestjs/passport\";\n\nexport class GqlAuthGuard extends AuthGuard(\"jwt\") {\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n console.log(\"gql simple context: \", context);\n console.log(\"gqlContext: \", ctx.getContext());\n return ctx.getContext().req;\n }\n}\n```\n\n```js\nimport { CanActivate, ExecutionContext, Injectable } from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\nimport { GqlExecutionContext } from \"@nestjs/graphql\";\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n canActivate(context: ExecutionContext) {\n const roles = this.reflector.get<string[]>(\"roles\", context.getHandler());\n const ctx = GqlExecutionContext.create(context);\n console.log(\"roles: \", roles);\n console.log(\"context: \", context.switchToHttp().getRequest());\n console.log(\"gqlContext: \", ctx.getContext().req);\n\n return true;\n }\n}\n```\n\n```js\nimport { Injectable } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { ExtractJwt, Strategy } from \"passport-jwt\";\nimport { jwtConstants } from \"../constants\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor() {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n ignoreExpiration: false,\n secretOrKey: jwtConstants.secret,\n });\n }\n\n validate(payload: any) {\n console.log(\"payload: \", payload);\n\n return payload;\n }\n}\n```\n\n```js\n@UseGuards(GqlAuthGuard)\n@Roles(\"ADMIN\")\n@UseGuards(RolesGuard)\n@Query((returns) => [Specialty], { nullable: \"itemsAndList\", name: \"specialties\" })\nasync getSpecialties(@Args() params: FindManySpecialtyArgs, @Info() info: GraphQLResolveInfo) {\n const select = new PrismaSelect(info).value;\n params = { ...params, ...select };\n return this.prismaService.specialty.findMany(params);\n}\n```\n\n```text\n@UseGuards()\n```\n\n```text\n@UseGuards(GqlAuthGuard, RolesGuard)\n```\n\n```text\nexport const Authorize = (roles?: string | string[]) =>\n applyDecorators(\n SetMetadata('roles', [roles].flat()),\n UseGuards(GqlAuthGuard, RolesGuard),\n );\n```\n\n```text\n@Authorize(\"ADMIN\")\n@Query((returns) => [Specialty], { nullable: \"itemsAndList\", name: \"specialties\" })\nasync getSpecialties(@Args() params: FindManySpecialtyArgs, @Info() info: GraphQLResolveInfo) {\n const select = new PrismaSelect(info).value;\n params = { ...params, ...select };\n return this.prismaService.specialty.findMany(params);\n}\n```\n\n```text\n@Injectable()\nexport class RolesGuard_ implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n canActivate(context: ExecutionContext): boolean {\n const ctx = GqlExecutionContext.create(context);\n\n const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [\n context.getHandler(),\n context.getClass(),\n ]);\n\n if (!requiredRoles) {\n return true;\n }\n\n const { user } = ctx.getContext().req;\n return requiredRoles.some((role) => user.role?.includes(role));\n }\n}\n```\n\n========================================\n\nComments:\n- Hi, why using an empty ´@UseGuards()´ ?\n- I was mentioning the decorator by it's full name. Don't look too much into it","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":245,"estimatedTokens":1701}}323{"id":"stack-67830070","source":"stackoverflow","questionId":67830070,"title":"Graphql apollo server resolvers arguments types","tags":["node.js","typescript","graphql","typescript-typings","apollo-server"],"text":"Title: Graphql apollo server resolvers arguments types\nTags: node.js, typescript, graphql, typescript-typings, apollo-server\nSource: Stack Overflow\n\nQuestion:\nType script is showing error not mentioning argument type for each arguments:\n\n```\nMutation: {\n createUser: (parent, args, context, info) =>{\n\n }\n```\n\nI can solve by using any type, but what are the correct types?\n\n```\nMutation: {\n createUser: (parent: any, args: any, context: any, info: any) =>{\n\n }\n```\n\nhttps://i.sstatic.net/LgQ9J.png\n\n========================================\n\nCode:\n```text\nMutation: {\n createUser: (parent, args, context, info) =>{\n\n }\n```\n\n```text\nMutation: {\n createUser: (parent: any, args: any, context: any, info: any) =>{\n\n }\n```\n\n```text\nexport declare type IFieldResolver<TSource, TContext, TArgs = Record<string, any>> = (source: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo & {\n mergeInfo: MergeInfo;\n}) => any;\n```\n\n```text\nimport express from 'express';\nimport { ApolloServer, gql, MergeInfo } from 'apollo-server-express';\nimport { GraphQLResolveInfo } from 'graphql';\n\nconst app = express();\n\nconst typeDefs = gql`\n type User {\n email: String!\n }\n type Query {\n user: User\n }\n type Mutation {\n createUser(email: String!, password: String!): Boolean\n }\n`;\n\nexport declare type IFieldResolver<TSource, TContext, TArgs = Record<string, any>> = (source: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo & {\n mergeInfo: MergeInfo;\n}) => any;\n\ntype CreateUserArgs = {\n email: string;\n password: string;\n};\n\ninterface AppContext {\n userService: UserService;\n}\n\nconst resolvers = {\n Query: {},\n Mutation: {\n createUser: (\n parent: undefined,\n args: CreateUserArgs,\n context: AppContext,\n info: GraphQLResolveInfo & { mergeInfo: MergeInfo },\n ) => {\n console.log(parent);\n return context.userService.createUser(args.email, args.password);\n },\n },\n};\n\ninterface UserService {\n createUser(email: string, password: string): boolean;\n}\nclass UserServiceImpl {\n createUser(email: string, password: string) {\n return true;\n }\n}\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n context: {\n userService: new UserServiceImpl(),\n },\n});\nserver.applyMiddleware({ app, path: '/graphql' });\napp.listen(8080, () => console.log('Apollo server started at http://localhost:8080'));\n```\n\n```json\n\"typescript\": \"^3.9.6\",\n\"apollo-server\": \"^2.15.1\",\n\"graphql\": \"^14.6.0\",\n```\n\n```text\nmutation{\n createUser(email: \"teresa@gmail.com\", password: \"1234\")\n}\n```\n\n```json\n{\n \"data\": {\n \"createUser\": true\n }\n}\n```\n\n```text\nApollo server started at http://localhost:8080\nundefined\n```\n\n```text\ntsconfig.json\n```\n\n```text\nparent\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n```text\nargs\n```\n\n```text\nRecord<string, any>\n```\n\n```text\nArgs\n```\n\n```text\ncontext\n```\n\n```text\ninfo\n```\n\n```text\nGraphQLResolveInfo & { mergeInfo: MergeInfo }\n```\n\n========================================\n\nComments:\n- Shouldn't it be `createUser: { resolve: (parent, args, context, info) =>`? Specifying the types should be optional anyway.\n- Seems to me that your context type is incorrect... What about datasources etc ? Do you know if there is a built in Context type ?\n- @ErnestJones If you have a new question, please ask a new question. Create a minimal, reproducible code example to explain your question","metadata":{"transformedAt":"2026-08-18T18:32:36.047Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":193,"estimatedTokens":859}}324{"id":"stack-68212971","source":"stackoverflow","questionId":68212971,"title":"graphql - how to filter a nested list","tags":["graphql","hotchocolate"],"text":"Title: graphql - how to filter a nested list\nTags: graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI am currently trying to filter a nested list based on a given id, but don't understand the syntax required. Although I have altered the entities and properties, this is what I am attempting\n\n```\n{\n companies{\n company{\n id,\n name,\n offices(where:{officeId: {eq: 2}}){\n officeId,\n address,\n }\n }\n }\n}\n```\n\nIn the returned data, I would like ALL companies and their offices where the office id is equal to 2. Is this possible and how would I do this?\n\n========================================\n\nTop Answer:\n```\ncompanies(\n where:{\n company: {\n offices: {\n some: {IsActive: {eq: true}}\n }\n }\n }\n)\n```\n\nIf filter is boolean then query doesn't work if Offices has IsActive bool field\n\n========================================\n\nCode:\n```text\n{\n companies{\n company{\n id,\n name,\n offices(where:{officeId: {eq: 2}}){\n officeId,\n address,\n }\n }\n }\n}\n```\n\n```text\n{\n companies(where:{company: {offices: {some: {officeId: {eq: 2}}}}}){\n company {\n id \n name \n offices {\n officeId\n address\n }\n }\n }\n}\n```\n\n```text\ncompanies(\n where:{\n company: {\n offices: {\n some: {IsActive: {eq: true}}\n }\n }\n }\n)\n```\n\n========================================\n\nComments:\n- Thx, the keyword **some** made the magic. Other useful operators **every**, **none**. A few documentation keystonejs.com/docs/guides/filters#to-many\n- I haven't tried it but this doesn't seem equivalent. It would filter out companies where there was no such office ID in the group, but list all offices of those who DO have office ID #2 in their list. The query as described suggests ALL companies included, and their office lists will be either empty, or contain only ID #2.\n- @JoshSutterfield not sure if i `It would filter out companies where there was no such office ID in the group, but list all offices of those who DO have office ID #2 in their list.` That was the question of OP `The query as described suggests ALL companies included, and their office lists will be either empty, or contain only ID #2.` This i do not understand, why would it do this?\n- @PascalSenn I understand the GQL shown to imply \"all companies, but only list their Office #2\". This is the title of the question \"how to filter a nested list\": the question is how to filter the *nested list* (offices), not how filter out any of the companies themselves. In fact the question detail states: \"I would like ALL companies and their offices where the office id is equal to 2\". In other words the correct answer would not filter out a company that does not *have* an Office #2. It would include the company, but yield: company.offices == []","metadata":{"transformedAt":"2026-08-18T18:32:36.048Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":93,"estimatedTokens":695}}325{"id":"stack-46933246","source":"stackoverflow","questionId":46933246,"title":"Passing variable into regex In Gatsby graphql query","tags":["javascript","regex","graphql","gatsby"],"text":"Title: Passing variable into regex In Gatsby graphql query\nTags: javascript, regex, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI have the following query which is receiving the variable `$tag`. Currently I am filtering the results based on the value of its `frontmatter.keywords`. `keywords` is a comma separated string, so I need to use a regex to check for the inclusion of `$tag` within it, however I can't work out how to pass the variable into the regex. If I hardcode a value into the regex (as in the code below where I have hardcoded `/example/`, the filtering works. If I replace `example` with `$tag` I receive an Error:\n\n GraphQLError: Variable \"$tag\" is never used in operation \"TagQuery\".\n\n```\nexport const pageQuery = graphql`\n query TagQuery($tag: String) {\n allMarkdownRemark(\n limit: 100\n sort: { fields: [frontmatter___date], order: DESC }\n filter: { frontmatter: { keywords: { regex: \"/example/\" } } }\n ) {\n totalCount\n edges {\n node {\n fields {\n slug\n }\n excerpt\n frontmatter {\n title\n keywords\n date\n }\n }\n }\n }\n }\n`;\n```\n\nHow should I use `$tag` within the regex?\n\nI'd actually prefer to take a different approach and add the tags as an array in `gatsby-node.js`, but there doesn't appear to be any way of filtering based on the value of the array.\n\n========================================\n\nTop Answer:\nWherever you are passing $tag, just transform it to \n\n```\nconst $tag = \"\\/\".concat(tag).concat(\"\\/\")\n```\n\nBut your error is specifically pointing to the fact that your query is not using the variable at all. So you'd also need to do\n\n```\nfilter: { frontmatter: { keywords: { regex: $tag } } }\n```\n\n========================================\n\nCode:\n```text\nexport const pageQuery = graphql`\n query TagQuery($tag: String) {\n allMarkdownRemark(\n limit: 100\n sort: { fields: [frontmatter___date], order: DESC }\n filter: { frontmatter: { keywords: { regex: \"/example/\" } } }\n ) {\n totalCount\n edges {\n node {\n fields {\n slug\n }\n excerpt\n frontmatter {\n title\n keywords\n date\n }\n }\n }\n }\n }\n`;\n```\n\n```text\n$tag\n```\n\n```text\nfrontmatter.keywords\n```\n\n```text\nkeywords\n```\n\n```text\n$tag\n```\n\n```text\n/example/\n```\n\n```text\nexample\n```\n\n```text\n$tag\n```\n\n```text\n$tag\n```\n\n```text\ngatsby-node.js\n```\n\n```text\nfilter: { fields: { tags: { in: [$tag] } } }\n```\n\n```text\nconst $tag = \"\\/\".concat(tag).concat(\"\\/\")\n```\n\n```text\nfilter: { frontmatter: { keywords: { regex: $tag } } }\n```\n\n========================================\n\nComments:\n- can you tell me how you pass the variable $tag into query?\n- @OtaniShuzo The variables available in a query are the values you pass as keys to the `context` object when using `createPage()`. So if you use a context of `{alpha: 'abc', bravo: 2}`, you can access two variables (if you need to) in the query: `query ExampleQuery($alpha: String, $bravo: Int) {`\n- @Undistraction do you mind posting how the whole query looks like now?\n- @VasilisTsirimokos Here you go. Think this was it: github.com/Undistraction/gatsby-starter-skeleton/blob/master‌​/…","metadata":{"transformedAt":"2026-08-18T18:32:36.048Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":140,"estimatedTokens":793}}326{"id":"stack-62953062","source":"stackoverflow","questionId":62953062,"title":"Prisma throws an error \"TypeError: cannot read property findmany of undefined\"","tags":["javascript","node.js","graphql","prisma","prisma-graphql"],"text":"Title: Prisma throws an error \"TypeError: cannot read property findmany of undefined\"\nTags: javascript, node.js, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI wanted to make a chat app to practice working with graphql and node, for database I used prisma. I was doing everything like in this tutorial.\n\nhttps://www.howtographql.com/graphql-js/0-introduction/\n\nI just changed variable names.\n\nso I have this code\n\n```\nconst { PrismaClient } = require('@prisma/client')\nconst prisma = new PrismaClient()\n\nconst resolvers = {\n Query: {\n history: async (parent, args, context) => {\n return context.prisma.Messages.findMany()\n },\n },\n Mutation: {\n post: (parent, args, context) => {\n const newMessage = context.prisma.Messages.create({\n data: {\n username: args.username,\n message: args.message,\n },\n })\n return newMessage\n },\n },\n}\n\nconst server = new GraphQLServer({\n typeDefs: './src/schema.graphql',\n resolvers,\n context: {\n prisma,\n }\n})\nserver.start(() => console.log(`Server is running on http://localhost:4000`))\n```\n\nas my index.js\n\nthis is my schema.prisma\n\n```\nprovider = \"sqlite\"\n url = \"file:./dev.db\"\n}\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\nmodel Message {\n id Int @id @default(autoincrement())\n sendedAt DateTime @default(now())\n message String\n username String\n}\n```\n\nscript.js\n\n```\nconst { PrismaClient } = require(\"@prisma/client\")\n\nconst prisma = new PrismaClient()\n\nasync function main() {\n const newMessage = await prisma.Messages.create({\n data: {\n message: 'Fullstack tutorial for GraphQL',\n username: 'www.howtographql.com',\n },\n })\n const allMessages = await prisma.Messages.findMany()\n console.log(allMessages)\n}\n\nmain()\n .catch(e => {\n throw e\n })\n // 5\n .finally(async () => {\n await prisma.disconnect()\n })\n```\n\nand schema.graphql\n\n```\ntype Query {\n history: [Message!]!\n}\n\ntype Mutation {\n post(username: String!, message: String!): Message!\n}\n\ntype Message {\n id: ID!\n message: String!\n username: String!\n}\n```\n\nand that is what i got in my playground\n\n```\n\"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot read property 'findMany' of undefined\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"history\"\n ]\n }\n ]\n}\n```\n\nplease help\n\n========================================\n\nTop Answer:\nI managed to fix that. Actually, all I needed was to use the same name but lowercased as in schema.prisma\n\n========================================\n\nCode:\n```text\nconst { PrismaClient } = require('@prisma/client')\nconst prisma = new PrismaClient()\n\n\nconst resolvers = {\n Query: {\n history: async (parent, args, context) => {\n return context.prisma.Messages.findMany()\n },\n },\n Mutation: {\n post: (parent, args, context) => {\n const newMessage = context.prisma.Messages.create({\n data: {\n username: args.username,\n message: args.message,\n },\n })\n return newMessage\n },\n },\n}\n\nconst server = new GraphQLServer({\n typeDefs: './src/schema.graphql',\n resolvers,\n context: {\n prisma,\n }\n})\nserver.start(() => console.log(`Server is running on http://localhost:4000`))\n```\n\n```text\nprovider = \"sqlite\"\n url = \"file:./dev.db\"\n}\n\n\ngenerator client {\n provider = \"prisma-client-js\"\n}\n\n\nmodel Message {\n id Int @id @default(autoincrement())\n sendedAt DateTime @default(now())\n message String\n username String\n}\n```\n\n```text\nconst { PrismaClient } = require(\"@prisma/client\")\n\n\nconst prisma = new PrismaClient()\n\n\nasync function main() {\n const newMessage = await prisma.Messages.create({\n data: {\n message: 'Fullstack tutorial for GraphQL',\n username: 'www.howtographql.com',\n },\n })\n const allMessages = await prisma.Messages.findMany()\n console.log(allMessages)\n}\n\n\nmain()\n .catch(e => {\n throw e\n })\n // 5\n .finally(async () => {\n await prisma.disconnect()\n })\n```\n\n```text\ntype Query {\n history: [Message!]!\n}\n\ntype Mutation {\n post(username: String!, message: String!): Message!\n}\n\ntype Message {\n id: ID!\n message: String!\n username: String!\n}\n```\n\n```text\n\"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot read property 'findMany' of undefined\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"history\"\n ]\n }\n ]\n}\n```\n\n```text\nMessage\n```\n\n```text\nmessage\n```\n\n```text\nMessagePerUser\n```\n\n```text\nmessagePerUser\n```\n\n```text\nStudentData\n```\n\n```text\nstudentData\n```\n\n========================================\n\nComments:\n- Developing a Shopify App using remix / Prisma, I faced the same. Just had to restart the `shopify app dev` command to update Prisma with new migrations, even if I use `prisma generate`.\n- The same name for what β can you elaborate what exactly was the error?\n- As itβs currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- Hello, please don't post code only and add an explantation as to why you think that this is the optimal solution. People are supposed to learn from your answer, which might not occur if they just copy paste code without knowing why it should be used.","metadata":{"transformedAt":"2026-08-18T18:32:36.048Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":292,"estimatedTokens":1315}}327{"id":"stack-54947605","source":"stackoverflow","questionId":54947605,"title":"Graphql data modeling: extending types and interfaces","tags":["graphql"],"text":"Title: Graphql data modeling: extending types and interfaces\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nThis is a very basic question but how do you call an extended type or interface?\n\nAll the documentations points to using `extend type Person` to add fields based on Person.\n\nI would expect it to work like this\n\n```\nEmployee extend type Person {\n salary: Int!\n}\n```\n\nBut the documentation suggests it's like this:\n\n```\nextend type Person{\n salary: Int!\n}\n```\n\nSo, how do I query for an Employee salary? What if there are multiple extensions of Person, e.g. Employee and Renter? I think I might be hampered by traditional thinking but I would expect the extension to result in something named and queryable.\n\n========================================\n\nCode:\n```text\nEmployee extend type Person {\n salary: Int!\n}\n```\n\n```text\nextend type Person{\n salary: Int!\n}\n```\n\n```text\nextend type Person\n```\n\n```text\n#base.graphql\ntype Query {\n viewer: User\n}\n\n# user.graphql\nextend type Query {\n users: [User!]!\n}\n\n# post.graphql\nextend type Query {\n post: [Post!]!\n}\n```\n\n```text\ntype Query {\n viewer: User\n users: [User!]!\n post: [Post!]!\n}\n```\n\n```text\nextend type SomeType @customDirective\n```\n\n```text\nextend\n```\n\n```text\nextend\n```\n\n========================================\n\nComments:\n- Ok, yeah, so I was indeed hampered by traditional thinking. I was indeed assuming some kind of inheritance.\n- Ok, so how does one actually query for the local field added via `extend`? The code generates a `GraphQLError: Cannot query field \"salary\" on type \"Person\".`\n- @DanDascalescu this would make a good separate question, since it doesn't directly deal with the subject of the original question or my answer.\n- The OP (also) asked, \"So, how do I query for an Employee salary?\", which is what I'm trying to do in that example. The schema definition works, querying does not.\n- Like I explained in response to your Github comment, `buildSchema` doesn't support extensions. It simply ignores any type system extension definitions that happen to be present. You're querying it correctly, but you need to build your schema using a different means.","metadata":{"transformedAt":"2026-08-18T18:32:36.048Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":91,"estimatedTokens":537}}328{"id":"stack-44574964","source":"stackoverflow","questionId":44574964,"title":"GraphQL: How to implement pagination with graphQL-java?","tags":["java","pagination","graphql","graphql-java"],"text":"Title: GraphQL: How to implement pagination with graphQL-java?\nTags: java, pagination, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nCurrently, I see no existing support for pagination in the graphql-java library. It does have some basic relay support, where-in, we can create a `connection`, Facebook's recommended way of implementing pagination. \n\nThis is the method which helps achieve that. However, with no documentation I'm finding it hard to understand how this function works. Can someone break-down the steps they would take to add pagination support if they already have an existing model which allows basic queries like `Add`, `delete`, `fetch` etc. using the graphql-java library?\n\n========================================\n\nCode:\n```text\nconnection\n```\n\n```text\nAdd\n```\n\n```text\ndelete\n```\n\n```text\nfetch\n```\n\n```text\nRelay relay = new Relay();\nGraphQLOutputType book = ...; //build your normal Book object type\nGraphQLObjectType bookEdge = relay.edgeType(book.getName(), book, null, Collections.emptyList());\nGraphQLObjectType bookConnection = relay.connectionType(book.getName(), bookEdge, Collections.emptyList());\n```\n\n```text\nSELECT * FROM ORDER BY timestamp OFFSET $after LIMIT $first\n```\n\n```text\nSELECT * FROM ORDER BY timestamp WHERE timestamp > $after LIMIT $first\n```\n\n```text\npublic class BookService {\n @GraphQLQuery(name = \"books\")\n //make sure the argument names and types match the Relay spec\n public Page<Book> getBooks(@GraphQLArgument(name = \"first\") int first, @GraphQLArgument(name = \"after\") String after) {\n //if you decide to fetch from a SQL DB, you need the limit and offset instead of a cursor\n //so, you can treat \"first\" as count as \"after\" as offset\n int offset = Integer.valueOf(after);\n List<Book> books = getBooksFromDB(first, offset);\n Page<Book> bookPage = PageFactory.createOffsetBasedPage(books, totalBookCount, offset);\n return bookPage;\n }\n}\n```\n\n```text\nGraphQLSchema schema = new GraphQLSchemaGenerator()\n .withOperationsFromSingleton(new BookService())\n .generate();\nGraphQL graphQL = GraphQLRuntime.newGraphQL(schema).build();\n```\n\n```text\nExecutionResult result = graphQL.execute(\"{books(first:10, after:\\\"20\\\") {\" +\n \" pageInfo {\" +\n \" hasNextPage\" +\n \" },\" +\n \" edges {\" +\n \" cursor, node {\" +\n \" title\" +\n \"}}}}\");\n```\n\n```text\nBook\n```\n\n```text\nBookConnection\n```\n\n```text\nafter\n```\n\n```text\nfirst\n```\n\n```text\nbefore\n```\n\n```text\nlast\n```\n\n```text\nafter\n```\n\n```text\nbefore\n```\n\n```text\nPage\n```\n\n========================================\n\nComments:\n- Wonderful answer!\n- @user3728233 Glad to help :)\n- For most pagination scenarios, you'll still want to know the total count. How would you handle that by just adding the skip/limit variables?\n- @Donuts Relay page already has the total count (missing in SPQR at the moment, but will be added soon, also easily added manually). Otherwise, you can return an object type encapsulating the result list and the count.\n- @kaqqao I was referring to the option where Relay isn't used. So yeah i see 2 options: 1, your query returns a type that has both the array of results and a total. or 2, in your graphql schema your Query type could contain an additional mapping for a count query -- so you could have books and then booksCount (which returns an int). The drawback for option 1 is that for each type that can be paged, you have to have an additional type to handle the paging because graphql doesn't handle generics. like i can't have PagedResult in my backend map to a PagedResult type in graphql\n- @Donuts If you're doing it by hand, it is a bit of nuisance, so it might be easier to just stick to the connection spec as the helpers already exist to make generating the connection types easy. If using SPQR, you can certainly set it up to generate the specific GraphQL type from the Java generic on the fly (that's how `Page` works).","metadata":{"transformedAt":"2026-08-18T18:32:36.048Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":121,"estimatedTokens":1013}}329{"id":"stack-45509228","source":"stackoverflow","questionId":45509228,"title":"Why do GraphQL fragments need __typename in queries?","tags":["graphql","apollo","apollo-client"],"text":"Title: Why do GraphQL fragments need __typename in queries?\nTags: graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI can't find or I am looking in the wrong place for any documentation on how fragments are matched. When I use the vanilla Apollo client if I turn off the option of `addTypename` when I use fragments I get a warning `heuristic fragment matching going on!` and if I add it this goes away but my response contains many `__typename` fields which I don't need. Why do they help?\n\n========================================\n\nCode:\n```text\naddTypename\n```\n\n```text\nheuristic fragment matching going on!\n```\n\n```text\n__typename\n```\n\n```text\nconst cache = new InMemoryCache({\n dataIdFromObject: object => object.key || null\n});\n```\n\n========================================\n\nComments:\n- Maybe that won't fully satisfy your question, but `__typename` seems to be the only trace by which Apollo is able to match fragments in it's cache. I think that to tackle this you don't need to pass `addType: true` - keep it false and instead try adding `__typename` to your fragment.","metadata":{"transformedAt":"2026-08-18T18:32:36.048Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":32,"estimatedTokens":274}}330{"id":"stack-51469006","source":"stackoverflow","questionId":51469006,"title":"How to get Vue (vue cli 3) to properly handle GraphQL files?","tags":["webpack","vue.js","graphql","vue-cli"],"text":"Title: How to get Vue (vue cli 3) to properly handle GraphQL files?\nTags: webpack, vue.js, graphql, vue-cli\nSource: Stack Overflow\n\nQuestion:\nI have a new vue-cli 3 based project, which has `.graphql` files in the `src/` folder, e.g.:\n\n```\n#import \"./track-list-fragment.graphql\"\n\nquery ListTracks(\n $sortBy: String\n $order: String\n $limit: Int\n $nextToken: String\n) {\n listTracks(\n sortBy: $sortBy\n order: $order\n limit: $limit\n nextToken: $nextToken\n ) {\n items {\n ...TrackListDetails\n }\n nextToken\n }\n}\n```\n\nAnd when I run `yarn serve`, it's complaining about not having a loader for GraphQL:\n\n```\nModule parse failed: Unexpected character '#' (1:0)\nYou may need an appropriate loader to handle this file type.\n> #import \"./track-list-fragment.graphql\"\n|\n| query ListTracks(\n```\n\nBut I do have my `vue.config.js` set up properly (I think):\n\n```\nconst webpack = require('webpack');\nconst path = require('path');\n\nmodule.exports = {\n configureWebpack: {\n resolve: {\n alias: {\n $scss: path.resolve('src/assets/styles'),\n },\n },\n plugins: [\n new webpack.LoaderOptionsPlugin({\n test: /\\.graphql$/,\n loader: 'graphql-tag/loader',\n }),\n ],\n },\n};\n```\n\nHow do I fix this?\n\n========================================\n\nTop Answer:\nI'm pretty sure LoaderOptionsPlugin is not what you want. The webpack docs mention that this is used for migrating from webpack 1 to webpack 2. That's not what we're doing here.\n\nHere's what configuring loaders looks like in a \"normal\" webpack config:\n\n```\nmodule.exports = {\n module: {\n rules: [\n {\n test: /\\.css$/,\n use: [\n { loader: 'style-loader' },\n {\n loader: 'css-loader',\n options: {\n modules: true\n }\n }\n ]\n }\n ]\n }\n};\n```\n\nFollowing this approach and assuming I correctly understand the Vue 3 docs, here's how I'd configure a Vue 3 application using the original example's data:\n\n```\nmodule.exports = {\n configureWebpack: {\n module: {\n rules: [\n {\n test: /\\.css$/,\n use: [\n { loader: 'style-loader' },\n {\n loader: 'css-loader',\n options: {\n modules: true\n }\n }\n ]\n }\n ]\n }\n }\n}\n```\n\nNow, we need to configure the graphql loader instead of the css loader:\n\n```\nmodule.exports = {\n configureWebpack: {\n module: {\n rules: [\n {\n test: /\\.graphql$/,\n use: 'graphql-tag/loader'\n }\n ]\n }\n }\n}\n```\n\nThis is untested and I'm just going off of my understanding of webpack and the Vue docs. I don't have a project to test this with but would be more than happy to test if you post a link to your project.\n\n========================================\n\nCode:\n```text\n#import \"./track-list-fragment.graphql\"\n\nquery ListTracks(\n $sortBy: String\n $order: String\n $limit: Int\n $nextToken: String\n) {\n listTracks(\n sortBy: $sortBy\n order: $order\n limit: $limit\n nextToken: $nextToken\n ) {\n items {\n ...TrackListDetails\n }\n nextToken\n }\n}\n```\n\n```text\nModule parse failed: Unexpected character '#' (1:0)\nYou may need an appropriate loader to handle this file type.\n> #import \"./track-list-fragment.graphql\"\n|\n| query ListTracks(\n```\n\n```text\nconst webpack = require('webpack');\nconst path = require('path');\n\nmodule.exports = {\n configureWebpack: {\n resolve: {\n alias: {\n $scss: path.resolve('src/assets/styles'),\n },\n },\n plugins: [\n new webpack.LoaderOptionsPlugin({\n test: /\\.graphql$/,\n loader: 'graphql-tag/loader',\n }),\n ],\n },\n};\n```\n\n```text\n.graphql\n```\n\n```text\nsrc/\n```\n\n```text\nyarn serve\n```\n\n```text\nvue.config.js\n```\n\n```text\nconst path = require('path');\n\nmodule.exports = {\n pluginOptions: {\n i18n: {\n locale: 'en',\n fallbackLocale: 'en',\n localeDir: 'locales',\n enableInSFC: false,\n },\n },\n configureWebpack: {\n resolve: {\n alias: {\n $element: path.resolve(\n 'node_modules/element-ui/packages/theme-chalk/src/main.scss'\n ),\n },\n },\n },\n chainWebpack: config => {\n config.module\n .rule('graphql')\n .test(/\\.graphql$/)\n .use('graphql-tag/loader')\n .loader('graphql-tag/loader')\n .end();\n },\n};\n```\n\n```text\nmodule.exports = {\n module: {\n rules: [\n {\n test: /\\.css$/,\n use: [\n { loader: 'style-loader' },\n {\n loader: 'css-loader',\n options: {\n modules: true\n }\n }\n ]\n }\n ]\n }\n};\n```\n\n```text\nmodule.exports = {\n configureWebpack: {\n module: {\n rules: [\n {\n test: /\\.css$/,\n use: [\n { loader: 'style-loader' },\n {\n loader: 'css-loader',\n options: {\n modules: true\n }\n }\n ]\n }\n ]\n }\n }\n}\n```\n\n```text\nmodule.exports = {\n configureWebpack: {\n module: {\n rules: [\n {\n test: /\\.graphql$/,\n use: 'graphql-tag/loader'\n }\n ]\n }\n }\n}\n```\n\n```text\nnpm i vite-plugin-graphql-loader --save-dev\n```\n\n```text\nimport { defineConfig } from \"vite\";\nimport graphqlLoader from \"vite-plugin-graphql-loader\";\n\nexport default defineConfig({\n plugins: [graphqlLoader()],\n});\n```\n\n```text\nimport ExampleQuery from \"./example.graphql\";\n```\n\n```text\ndata() {\n return {\n ExampleQuery,\n }\n }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.048Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":323,"estimatedTokens":1303}}331{"id":"stack-58050329","source":"stackoverflow","questionId":58050329,"title":"How to use an array inside a GraphQL Query Variable","tags":["graphql","gatsby","graphql-js"],"text":"Title: How to use an array inside a GraphQL Query Variable\nTags: graphql, gatsby, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'd like to use an array inside a GraphQL query variable so that I can get the data of more than one product from a single query with Gatsby however at the moment I get errors.\n\nMy graphQL query looks like:\n\n```\nquery ($id: [String!]) {\n shopifyProduct(handle: {eq: $id}) {\n handle\n id\n title\n handle\n productType\n shopifyId\n }\n}\n```\n\nand my Query Variable looks like:\n\n```\n{\n \"id\": [\"liner-jacket\", \"pocket-t-shirt\"]\n}\n```\n\nThe desired response would be (something like):\n\n```\n{\n \"data\": {\n \"shopifyProduct\": {\n \"handle\": \"liner-jacket\",\n \"id\": \"Shopify__Product__hopbjidjoqjndadnawdawda123123=\",\n \"title\": \"Liner Jacket\",\n \"productType\": \"jacket\",\n \"shopifyId\": \"hopbjidjoqjndadnawdawda123123=\"\n },\n \"shopifyProduct\": {\n \"handle\": \"pocket-t-shirt\",\n \"id\": \"Shopify__Product__iajwdoiajdoadjwaowda4023123=\",\n \"title\": \"Pocket T-Shirt\",\n \"productType\": \"t-shirt\",\n \"shopifyId\": \"iajwdoiajdoadjwaowda4023123=\"\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery ($id: [String!]) {\n shopifyProduct(handle: {eq: $id}) {\n handle\n id\n title\n handle\n productType\n shopifyId\n }\n}\n```\n\n```text\n{\n \"id\": [\"liner-jacket\", \"pocket-t-shirt\"]\n}\n```\n\n```text\n{\n \"data\": {\n \"shopifyProduct\": {\n \"handle\": \"liner-jacket\",\n \"id\": \"Shopify__Product__hopbjidjoqjndadnawdawda123123=\",\n \"title\": \"Liner Jacket\",\n \"productType\": \"jacket\",\n \"shopifyId\": \"hopbjidjoqjndadnawdawda123123=\"\n },\n \"shopifyProduct\": {\n \"handle\": \"pocket-t-shirt\",\n \"id\": \"Shopify__Product__iajwdoiajdoadjwaowda4023123=\",\n \"title\": \"Pocket T-Shirt\",\n \"productType\": \"t-shirt\",\n \"shopifyId\": \"iajwdoiajdoadjwaowda4023123=\"\n }\n }\n}\n```\n\n```text\n[String]\n```\n\n```text\nString\n```\n\n```text\n[String]\n```\n\n```text\nString\n```\n\n```text\nString\n```\n\n```text\n[String]\n```\n\n```text\nString\n```\n\n```text\nString\n```\n\n```text\n[String]\n```\n\n```text\nhandle\n```\n\n```text\neq\n```\n\n```text\neq\n```\n\n```text\nString!\n```\n\n```text\nString\n```\n\n```text\neq\n```\n\n```text\nin\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.049Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":159,"estimatedTokens":534}}332{"id":"stack-37369414","source":"stackoverflow","questionId":37369414,"title":"Viewer in Relay.js","tags":["graphql","relayjs"],"text":"Title: Viewer in Relay.js\nTags: graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nWhy do you need and how to use `viewer` correctly in Relay.js?\n\nI've spent past week to try and understand Relay.js. Im now good with GraphQL and I understand it pretty well but Im having some issues with uniting GraphQL and Relay.js in same application.\n\nFirst step would probably be to understand `viewer`. I've seen many examples and tutorials using it but it's never explained and it's not very clear what is it exactly and what it is used for.\n\nRelay documentation mentions `viewer` few times but there's not even a single word explaining it.\n\nI wish I could something more to this question but Im afraid there's no explanations online. It's only used in codes and ripping it out of context wouldn't make any sense. Answering this question will require some knowledge about Realy.js/GraphQL anyway.\n\nMy best guess based of countless examples I've examined is that it's somehow related to user? If user is anonymous or logged in? To grant different access to data based on login status or user level?\n\n========================================\n\nCode:\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\nviewer\n```\n\n```text\nexport const schema = new GraphQLSchema({\n query: Root,\n mutation: Mutation,\n});\n```\n\n```text\nexport const schema = new GraphQLSchema({\n query: queryType,\n mutation: mutationType,\n});\n```\n\n```text\nconst Root = new GraphQLObjectType({\n name: 'Root',\n fields: {\n viewer: {\n type: GraphQLUser,\n resolve: () => getViewer(),\n },\n node: nodeField,\n },\n});\n```\n\n```text\nconst queryType = new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n game: {\n type: gameType,\n resolve: () => getGame(),\n },\n }),\n});\n```\n\n```text\nviewer\n```\n\n```text\nquery\n```\n\n```text\nRoot\n```\n\n```text\nqueryType\n```\n\n```text\nviewer\n```\n\n```text\ngame\n```\n\n```text\nviewer\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.049Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":99,"estimatedTokens":480}}333{"id":"stack-71628520","source":"stackoverflow","questionId":71628520,"title":"Inter-service communication between Apollo Federation subgraphs","tags":["node.js","graphql","google-kubernetes-engine","apollo","apollo-federation"],"text":"Title: Inter-service communication between Apollo Federation subgraphs\nTags: node.js, graphql, google-kubernetes-engine, apollo, apollo-federation\nSource: Stack Overflow\n\nQuestion:\nLet's say we have `S1`, `S2` subgraphs, and `G` gateway.\n\n`S1` subgraph service needs some data from the `S2` service. How should it be handled through the gateway and schema level? Should we use gateway in this kind of communication?\n\nShould we have a separated schema & Apollo server inside every subgraph that contains the internal queries and mutations? Should `S1` call directly `S2` \"internal apollo server\"?\n\nBy default, all user-facing requests need to be authorized by JWT, but internal communications should work without this.\n\nSubgraphs are not available on the public network, but they're running on the same internal network. Technically they can see each other. They're hosted on GKE.\n\n========================================\n\nCode:\n```text\nS1\n```\n\n```text\nS2\n```\n\n```text\nG\n```\n\n```text\nS1\n```\n\n```text\nS2\n```\n\n```text\nS1\n```\n\n```text\nS2\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.049Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":45,"estimatedTokens":260}}334{"id":"stack-54559928","source":"stackoverflow","questionId":54559928,"title":"How to call a GraphQL query/mutation from an Express server backend?","tags":["express","graphql","apollo","apollo-client"],"text":"Title: How to call a GraphQL query/mutation from an Express server backend?\nTags: express, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nMy frontend is `localhost:3000`, and my GraphQL server is `localhost:3333`.\n\nI've used react-apollo to query/mutate in JSX land, but haven't made a query/mutation from Express yet.\n\nI'd like to make the query/mutation here in my `server.js`.\n\n```\nserver.get('/auth/github/callback', (req, res) => {\n // send GraphQL mutation to add new user\n});\n```\n\nBelow seems like the right direction, but I'm getting `TypeError: ApolloClient is not a constructor`:\n\n```\nconst express = require('express');\nconst next = require('next');\nconst ApolloClient = require('apollo-boost');\nconst gql = require('graphql-tag');\n\n// setup\nconst client = new ApolloClient({\n uri: 'http://localhost:3333/graphql'\n});\nconst app = next({dev});\nconst handle = app.getRequestHandler();\n\napp\n .prepare()\n .then(() => {\n const server = express();\n\n server.get('/auth/github/callback', (req, res) => {\n // GraphQL mutation\n client.query({\n query: gql`\n mutation ADD_GITHUB_USER {\n signInUpGithub(\n email: \"email@address.com\"\n githubAccount: \"githubusername\"\n githubToken: \"89qwrui234nf0\"\n ) {\n id\n email\n githubToken\n githubAccount\n }\n }\n `,\n })\n .then(data => console.log(data))\n .catch(error => console.error(error));\n });\n\n server.listen(3333, err => {\n if (err) throw err;\n console.log(`Ready on http://localhost:3333`);\n });\n })\n .catch(ex => {\n console.error(ex.stack);\n process.exit(1);\n });\n```\n\nThis post mentions Apollo as the solution, but doesn't give an example.\n\nHow do I call a GraphQL mutation from Express server `:3000` to GraphQL `:3333`?\n\n========================================\n\nTop Answer:\nYou can use graphql-request, it is a simple GraphQL client.\n\n```\nconst { request } = require('graphql-request');\n\nrequest('http://localhost:3333/graphql', `mutation ADD_USER($email: String!, $password: String!) {\n createUser(email: $email, password: $password) {\n id\n email\n }\n}`, {email: 'john.doe@mail.com', password: 'Pa$$w0rd'})\n.then(data => console.info(data))\n.catch(error => console.error(error));\n```\n\nIt also support CORS.\n\n```\nconst { GraphQLClient } = require('graphql-request');\n\nconst endpoint = 'http://localhost:3333/graphql';\nconst client = new GraphQLClient(endpoint, {\n credentials: 'include',\n mode: 'cors'\n});\n\nclient.request(`mutation ADD_USER($email: String!, $password: String!) {\n createUser(email: $email, password: $password) {\n id\n email\n }\n}`, {email: 'john.doe@mail.com', password: 'Pa$$w0rd'})\n.then(data => console.info(data))\n.catch(error => console.error(error));\n```\n\nI use it to make E2E tests.\n\n========================================\n\nCode:\n```text\nserver.get('/auth/github/callback', (req, res) => {\n // send GraphQL mutation to add new user\n});\n```\n\n```text\nconst express = require('express');\nconst next = require('next');\nconst ApolloClient = require('apollo-boost');\nconst gql = require('graphql-tag');\n\n\n// setup\nconst client = new ApolloClient({\n uri: 'http://localhost:3333/graphql'\n});\nconst app = next({dev});\nconst handle = app.getRequestHandler();\n\napp\n .prepare()\n .then(() => {\n const server = express();\n\n server.get('/auth/github/callback', (req, res) => {\n // GraphQL mutation\n client.query({\n query: gql`\n mutation ADD_GITHUB_USER {\n signInUpGithub(\n email: \"email@address.com\"\n githubAccount: \"githubusername\"\n githubToken: \"89qwrui234nf0\"\n ) {\n id\n email\n githubToken\n githubAccount\n }\n }\n `,\n })\n .then(data => console.log(data))\n .catch(error => console.error(error));\n });\n\n server.listen(3333, err => {\n if (err) throw err;\n console.log(`Ready on http://localhost:3333`);\n });\n })\n .catch(ex => {\n console.error(ex.stack);\n process.exit(1);\n });\n```\n\n```text\nlocalhost:3000\n```\n\n```text\nlocalhost:3333\n```\n\n```text\nserver.js\n```\n\n```text\nTypeError: ApolloClient is not a constructor\n```\n\n```text\n:3000\n```\n\n```text\n:3333\n```\n\n```js\nconst { createApolloFetch } = require('apollo-fetch');\n\nconst fetch = createApolloFetch({\n uri: 'https://1jzxrj179.lp.gql.zone/graphql',\n});\n\n\n// Example # 01\nfetch({\n query: '{ posts { title } }',\n}).then(res => {\n console.log(res.data);\n});\n\n\n// Example # 02\n// You can also easily pass variables for dynamic arguments\nfetch({\n query: `\n query PostsForAuthor($id: Int!) {\n author(id: $id) {\n firstName\n posts {\n title\n votes\n }\n }\n }\n `,\n variables: { id: 1 },\n}).then(res => {\n console.log(res.data);\n});\n```\n\n```text\n// es5 or Node.js\nconst Boost = require('apollo-boost');\nconst ApolloClient = Boost.DefaultClient;\n```\n\n```text\nconst ApolloBoost = require('apollo-boost');\nconst ApolloClient = ApolloBoost.default;\n```\n\n```text\nrequire\n```\n\n```text\nimport\n```\n\n```text\nconst { request } = require('graphql-request');\n\nrequest('http://localhost:3333/graphql', `mutation ADD_USER($email: String!, $password: String!) {\n createUser(email: $email, password: $password) {\n id\n email\n }\n}`, {email: 'john.doe@mail.com', password: 'Pa$$w0rd'})\n.then(data => console.info(data))\n.catch(error => console.error(error));\n```\n\n```text\nconst { GraphQLClient } = require('graphql-request');\n\nconst endpoint = 'http://localhost:3333/graphql';\nconst client = new GraphQLClient(endpoint, {\n credentials: 'include',\n mode: 'cors'\n});\n\nclient.request(`mutation ADD_USER($email: String!, $password: String!) {\n createUser(email: $email, password: $password) {\n id\n email\n }\n}`, {email: 'john.doe@mail.com', password: 'Pa$$w0rd'})\n.then(data => console.info(data))\n.catch(error => console.error(error));\n```\n\n```text\nnpm install graphql graphql-tag isomorphic-fetch\n```\n\n```text\nconst gql = require('graphql-tag');\nconst query = gql`\n query($foo: String) {\n // Graphql query\n }\n}\n```\n\n```text\nconst { print } = require('graphql/language/printer');\nconst query = require('./myQuery');\nrequire('isomorphic-fetch');\n\n// other logic\n\nconst foo = \"bar\"\nconst token = \"abcdef\"\n\nawait fetch('https://example.com/graphql', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'authorization': `Bearer ${token}`,\n },\n body: JSON.stringify({ \n query: `${print(query)}`,\n variables: { foo },\n }),\n})\n```\n\n========================================\n\nComments:\n- hi Chance, could you explain a little bit more about your issue? I don't understand... you said you've used `react-apollo` (React side...) but then you don't know how to query from React? I don't understand.\n- Server-side rendering\n- hey, @JVLobo - I updated my question.\n- cool, more clear now :) I've posted an answer, hope it helps\n- I wouldn't use a fully-featured client to do server-side requests. You can use something really simple like graphql-request instead.\n- The 2nd did the trick, but now it's looking for a `fetch`: `Error: fetch is not found globally and no fetcher passed, to fix pass a fetch for your environment like https://www.npmjs.com/package/node-fetch. >>> For example: import fetch from 'node-fetch'; import { createHttpLink } from 'apollo-link-http';`\n- I'm diving into this now... apollographql.com/docs/link/links/http.html\n- How can I require `createHttpLink`?\n- I guess something like `const HttpLink = require(\"apollo-link-http\").HttpLink;` or `const { HttpLink } = require('apollo-link-http');` should do it\n- For anyone still out there, `apollo-fetch` is officially deprecated now and will no longer be receiving future updates π So I'd advise against following this answer. This leaves fetch, axios, or even graphql-request as possibly the best alternatives out there. Personally, I'm leaning more towards Prisma's `graphql-request`.","metadata":{"transformedAt":"2026-08-18T18:32:36.049Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":336,"estimatedTokens":1998}}335{"id":"stack-60632660","source":"stackoverflow","questionId":60632660,"title":"Can I access request headers in my graphql query, in nestjs?","tags":["graphql","ip-address","nestjs"],"text":"Title: Can I access request headers in my graphql query, in nestjs?\nTags: graphql, ip-address, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to access the ip-address of the user in the query of graphql. But I cannot reach any header information. How can I access the context I am creating in my factory, inside of my graphql requests?\n\n```\n// app.module.ts\n...\n\n@Module({\n imports: [\n ConfigModule,\n GraphQLModule.forRootAsync({\n imports: [ \n LanguageModule,\n SearchModule],\n inject: [ConfigService],\n useFactory: () => ({\n autoSchemaFile: 'schema.gql',\n debug: true,\n fieldResolverEnhancers: ['guards'],\n formatError: (error: GraphQLError): GraphQLFormattedError => {\n return error.originalError instanceof BaseException\n ? error.originalError.serialize()\n : error;\n },\n context: ({ req }): object => {\n console.log(\"req.ip: \", req.ip); // Here I have the ip\n return { req };\n },\n }),\n }), \n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```\n// search.resolver.ts\n...\n\n@Resolver(() => Search)\nexport class SearchResolver {\n constructor(private readonly service: service) {}\n\n @Query(() => Search)\n async search(@Args() args: SearchArgs): Promise {\n\n // I want the ip here, I want to send it as an argument into the query function below\n const response = await this.service.query(args.query, {\n language: args.language,\n });\n return response;\n }\n}\n```\n\n========================================\n\nTop Answer:\nThe default context seems to be:\n\n```\nimport { IncomingMessage } from \"node:http\";\n\ninterface Context {\n req: IncomingMessage;\n}\n```\n\nBut you can also set your own context as shown here:\n\n```\n@Module({\n imports: [\n GraphQLModule.forRoot({\n driver: ApolloDriver,\n context: (request) => ({\n foo: 'bar',\n request,\n }),\n }),\n ],\n providers: [CustomContextResolver],\n})\nexport class CustomContextModule {}\n```\n\nAnd use it like this:\n\n```\nimport { Resolver, Query, Context } from '@nestjs/graphql';\n\n@Resolver()\nexport class CustomContextResolver {\n @Query(() => String)\n fooFromContext(@Context() ctx: Record) {\n return ctx.foo;\n }\n}\n```\n\n========================================\n\nCode:\n```text\n// app.module.ts\n...\n\n@Module({\n imports: [\n ConfigModule,\n GraphQLModule.forRootAsync({\n imports: [ \n LanguageModule,\n SearchModule],\n inject: [ConfigService],\n useFactory: () => ({\n autoSchemaFile: 'schema.gql',\n debug: true,\n fieldResolverEnhancers: ['guards'],\n formatError: (error: GraphQLError): GraphQLFormattedError => {\n return error.originalError instanceof BaseException\n ? error.originalError.serialize()\n : error;\n },\n context: ({ req }): object => {\n console.log(\"req.ip: \", req.ip); // Here I have the ip\n return { req };\n },\n }),\n }), \n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n// search.resolver.ts\n...\n\n@Resolver(() => Search)\nexport class SearchResolver {\n constructor(private readonly service: service) {}\n\n @Query(() => Search)\n async search(@Args() args: SearchArgs): Promise<Search> {\n\n // I want the ip here, I want to send it as an argument into the query function below\n const response = await this.service.query(args.query, {\n language: args.language,\n });\n return response;\n }\n}\n```\n\n```text\ncontext\n```\n\n```text\nreq\n```\n\n```text\n(parent, args, context, info)\n```\n\n```js\nimport { IncomingMessage } from \"node:http\";\n\ninterface Context {\n req: IncomingMessage;\n}\n```\n\n```js\n@Module({\n imports: [\n GraphQLModule.forRoot<ApolloDriverConfig>({\n driver: ApolloDriver,\n context: (request) => ({\n foo: 'bar',\n request,\n }),\n }),\n ],\n providers: [CustomContextResolver],\n})\nexport class CustomContextModule {}\n```\n\n```js\nimport { Resolver, Query, Context } from '@nestjs/graphql';\n\n@Resolver()\nexport class CustomContextResolver {\n @Query(() => String)\n fooFromContext(@Context() ctx: Record<string, unknown>) {\n return ctx.foo;\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks! I could access it with the context argument exactly like you said. Like this: '''@Query(() => Search) async search(@Args() args: SearchArgs, @Context() context): Promise { console.log(context); ... }'''\n- This works for me on localhost but when app is deployed context is null","metadata":{"transformedAt":"2026-08-18T18:32:36.049Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":216,"estimatedTokens":1106}}336{"id":"stack-55902881","source":"stackoverflow","questionId":55902881,"title":"Update ApolloClient headers after it was initialised","tags":["reactjs","graphql","apollo","react-apollo"],"text":"Title: Update ApolloClient headers after it was initialised\nTags: reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nMy app is wrapped with `` component that essentially initialises the client.\n\n```\nconst client = new ApolloClient({\n link: new HttpLink({\n // ...\n }),\n cache: new InMemoryCache({\n // ..\n }),\n});\n```\n\nFurther down the road users can make certain action that requires me to set few new headers to apollo client that were not there before. I initially thought to use react context for this to pass set new headers and consume them inside `` but am not sure if this is the right way to go about it.\n\nAfter looking through the docs, it seems that apollo headers can be only set when it is initialised?\n\n========================================\n\nTop Answer:\nTo expand on Daniel Rearden's answer, if you want to add headers just for a specific query/mutation and not all of the subsequent queries:\n\nInitialise Apollo:\n\n```\nconst httpLink = createHttpLink({\n uri: '/graphql',\n});\n\nconst authLink = setContext((_, { headers }) => {\n // get the authentication token from local storage if it exists\n const token = localStorage.getItem('token');\n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n});\n```\n\nAnd then simply add the context to the desired query/mutation itself:\n\n```\nconst {loading, data, error} = useQuery(QUERY_DEF, { \n context: {\n headers: {\n \"HeaderKey\": \"HeaderValue\"\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\nconst client = new ApolloClient({\n link: new HttpLink({\n // ...\n }),\n cache: new InMemoryCache({\n // ..\n }),\n});\n```\n\n```text\n<Apollo />\n```\n\n```text\n<Apollo />\n```\n\n```text\nconst headerLink = setContext((request, previousContext) => ({\n headers: {\n // Make sure you include any existing headers!\n ...previousContext.headers,\n authorization: localStorage.getItem('authHeader')\n },\n}));\n\nconst client = new ApolloClient({\n link: headerLink.concat(httpLink),\n cache: new InMemoryCache()\n});\n```\n\n```text\nconst headerLink = setContext(async (request, previousContext) => {\n const authorization = await someAsyncCall()\n return {\n headers: {\n ...previousContext.headers,\n authorization,\n },\n }\n});\n```\n\n```text\napollo-link-context\n```\n\n```text\nsetContext\n```\n\n```text\nimport React from 'react';\nimport { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';\nimport { setContext } from '@apollo/client/link/context';\n\nfunction App() {\n\n const link = new HttpLink({ uri: process.env.REACT_APP_GRAPHQL_URI });\n\n const setAuthorizationLink = setContext((request, previousContext) => ({\n headers: {\n ...previousContext.headers,\n authorization: `Bearer ${ localStorage.getItem('auth_token') }`\n }\n }));\n\n const client = new ApolloClient({\n link: setAuthorizationLink.concat(link),\n cache: new InMemoryCache()\n });\n\n return (\n <ApolloProvider client={client}>\n ...\n </ApolloProvider>\n );\n}\n\nexport default App;\n```\n\n```text\nconst httpLink = createHttpLink({\n uri: '/graphql',\n});\n\nconst authLink = setContext((_, { headers }) => {\n // get the authentication token from local storage if it exists\n const token = localStorage.getItem('token');\n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n});\n```\n\n```text\nconst {loading, data, error} = useQuery(QUERY_DEF, { \n context: {\n headers: {\n \"HeaderKey\": \"HeaderValue\"\n }\n }\n});\n```\n\n========================================\n\nComments:\n- But how do you update it after the fact? For example, an initial GraphQL request to log in, doesn't have an Authorization header. Once you have logged in, how do you then update the ApolloClient instance? Do you replace it with a fresh new ApolloClient?\n- This `const authorization = await someAsyncCall()` is called each time the request is called, for each query or mutation\n- What about the example of a log in? First GraphQL request, there is no Authorization header. How do you set it after the response comes back? How do you update headers during your app, later, down the chain?","metadata":{"transformedAt":"2026-08-18T18:32:36.049Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":191,"estimatedTokens":1125}}337{"id":"stack-58920213","source":"stackoverflow","questionId":58920213,"title":"$lastName of type String used in position expecting type String","tags":["javascript","node.js","graphql","apollo-server"],"text":"Title: $lastName of type String used in position expecting type String\nTags: javascript, node.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nthis may code\n\n**Schema**\n\n```\nimport { gql } from 'apollo-server-express';\n\nexport default gql`\n extend type Mutation {\n signUp(\n lastName: String!\n ): String!\n }\n`;\n```\n\n**Resolvers**\n\n```\n{\n Query: {},\n Mutation: {\n signUp: async (\n _,\n { lastName}\n ) => {\n try {\n console.log(lastName)\n return 'ok'; \n } catch (error) {\n return 'error';\n }\n },\n },\n};\n```\n\n**Request**\n\n```\nmutation($lastName:String){\n signUp(lastName:$lastName)\n}\n```\n\n**Query Veriables**\n\n```\n{\"lastName\":\"Darjo\" }\n```\n\nI canβt understand, but I get Error\n\n \"Variable \\\"$lastName\\\" of type \\\"String\\\" used in position expecting type \\\"String!\\\".\",\n\nbut when I remove the sign **!** `lastName: String` everything is working.\n\nI just canβt understand. What is the reason ?.\n\n========================================\n\nCode:\n```text\nimport { gql } from 'apollo-server-express';\n\nexport default gql`\n extend type Mutation {\n signUp(\n lastName: String!\n ): String!\n }\n`;\n```\n\n```text\n{\n Query: {},\n Mutation: {\n signUp: async (\n _,\n { lastName}\n ) => {\n try {\n console.log(lastName)\n return 'ok'; \n } catch (error) {\n return 'error';\n }\n },\n },\n};\n```\n\n```text\nmutation($lastName:String){\n signUp(lastName:$lastName)\n}\n```\n\n```text\n{\"lastName\":\"Darjo\" }\n```\n\n```text\nlastName: String\n```\n\n```text\n# String! argument and String! variable\ntype Mutation {\n signUp(lastName: String!): String!\n}\n\nmutation($lastName:String!) {\n signUp(lastName:$lastName)\n}\n```\n\n```text\n# String argument and String! variable\ntype Mutation {\n signUp(lastName: String): String!\n}\n\nmutation($lastName: String!) {\n signUp(lastName: $lastName)\n}\n```\n\n```text\n# String argument and String variable\ntype Mutation {\n signUp(lastName: String): String!\n}\n\nmutation($lastName: String) {\n signUp(lastName: $lastName)\n}\n```\n\n```text\n# String! argument and String variable\ntype Mutation {\n signUp(lastName: String!): String!\n}\n\nmutation($lastName: String) {\n signUp(lastName: $lastName)\n}\n```\n\n```text\n# String! argument and String variable\ntype Mutation {\n signUp(lastName: String!): String!\n}\n\nmutation($lastName: String = \"Some default value\") {\n signUp(lastName: $lastName)\n}\n```\n\n```text\nlastName\n```\n\n```text\nString!\n```\n\n```text\n!\n```\n\n```text\n$lastName\n```\n\n```text\nInt\n```\n\n```text\nBoolean\n```\n\n========================================\n\nComments:\n- Thanks. In our case I know that all consumers are passing a non-null value, but I'm still not able to refactor our schema to make the String variable required. That seems a shame.","metadata":{"transformedAt":"2026-08-18T18:32:36.049Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":195,"estimatedTokens":677}}338{"id":"stack-61170042","source":"stackoverflow","questionId":61170042,"title":"GraphQL query result for object that does not exist","tags":["rest","graphql"],"text":"Title: GraphQL query result for object that does not exist\nTags: rest, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQL query that calls a REST service to get the return object. The query contains an Id parameter that is then passed to the service. However, the REST service can respond with http status 404 Not Found if an object with that Id does not exist. That seems like the right response.\n\nHow do you model a Not Found response in GraphQL?\nIs there a way to inform the GQL caller that something does not exist?\n\n*Update*\n\nSome options I am considering:\n\n- Return null\n\n- Change the GrqlhQL Query to return a list of objects and return empty list of nothing is found\n\n- Return some kind of error object with an error code\n\nbut it is unclear if there is a recommended practice in GQL API design.\n\n========================================\n\nCode:\n```text\n{\n hero(episode: $episode) {\n name\n heroFriends: friends {\n id\n name\n }\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Name for character with ID 1002 could not be fetched.\",\n \"locations\": [ { \"line\": 6, \"column\": 7 } ],\n \"path\": [ \"hero\", \"heroFriends\", 1, \"name\" ]\n }\n ],\n \"data\": {\n \"hero\": {\n \"name\": \"R2-D2\",\n \"heroFriends\": [\n {\n \"id\": \"1000\",\n \"name\": \"Luke Skywalker\"\n },\n {\n \"id\": \"1002\",\n \"name\": null\n },\n {\n \"id\": \"1003\",\n \"name\": \"Leia Organa\"\n }\n ]\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Thank you, it makes sense! I am wondering though how a client would distinguish between different type of errors and act accordingly. - There might be a network or database error on the REST service. - Or the client might be requesting data that does not exist. In each scenario a client (say mobile app) needs to react differently.\n- @Andrejs the responsibility of the backend is to provide enough information for the client to distinguish these cases. If \"message\" and \"path\" it is not enough, you could use \"extensions\" entry and provide a code, a timestamp, a list of developers liable for this issue, the phone of your manager's grandma and whatever else you want (spec.graphql.org/draft/#sel-IAPHRLZBABABKonO)\n- Aha, `extensions` seems like the way to be explicit about the error type. Thanks for that!\n- but \"not found\" is not an error rather than a success response with no data in it, therefore i dont think is a good idea to consider it as an error.\n- @MohamedAarab I'd say \"Not found\" *is* an error. You expect something to be there but it isn't. What we're trying to replicate here is 404 - Not found which falls under errors. It might help the client understand why something is missing rather than actually having the value null.\n- That example in the spec refers to a different scenario. It does not say the hero with the requested ID cannot be found, rather that one of its fields (`name`) could not be fetched.\n- Bad answer because 404 is not an error.","metadata":{"transformedAt":"2026-08-18T18:32:36.049Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":78,"estimatedTokens":758}}339{"id":"stack-39008724","source":"stackoverflow","questionId":39008724,"title":"How to split schema in GraphQL without having circular dependencies?","tags":["javascript","graphql"],"text":"Title: How to split schema in GraphQL without having circular dependencies?\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nMy question is similar to Javascript circular dependency in GraphQL code but my problem is not on the structure and database level, but in javascript (ES6).\n\nMy schema definition is getting to grow too large but I don't see where I could cut the file into pieces. It seems to be logical to cut based on the different object types, but that brings to circular dependencies similarly to this very much simplified, non-working example:\n\n```\n// -- file A.js\n\n import { bConnection, getBs } from 'B';\n\n export class A { /*...*/ };\n export var getA = (a) => { /*...*/ };\n export var getAs = (array_of_as) => { /*...*/ };\n\n export var aType = new GraphQLObjectType ({\n name: 'A',\n fields: () => ({\n bs: {\n type: bConnection,\n /*...*/\n },\n resolve: (a, args) => connectionFromPromisedArray (\n getBs (a.bs)\n ),\n /*...*/\n }),\n interfaces: () => [ require ('./nodeDefs').nodeInterface ],\n /*...*/\n })\n\n export var {\n connectionType: aConnection,\n edgeType: aEdge\n } = connectionDefinitions ({\n name: 'A',\n nodeType: aType\n });\n\n // -- file B.js\n\n import { aConnection, getAs } from 'A';\n\n export class B { /*...*/ };\n export var getB = (b) => { /*...*/ };\n export var getBs = (array_of_bs) => { /*...*/ };\n\n export var bType = new GraphQLObjectType ({\n name: 'B',\n fields: () => ({\n as: {\n type: aConnection,\n /*...*/\n },\n resolve: (b, args) => connectionFromPromisedArray (\n getAs (b.bs)\n ),\n /*...*/\n }),\n interfaces: () => [ require ('./nodeDefs').nodeInterface ],\n /*...*/\n })\n\n export var {\n connectionType: bConnection,\n edgeType: bEdge\n } = connectionDefinitions ({\n name: 'B',\n nodeType: bType\n });\n\n // -- file nodeDefs.js\n\n import {\n fromGlobalId,\n nodeDefinitions,\n } from 'graphql-relay';\n\n import { A, getA, aType } from 'A'\n import { B, getB, bType } from 'B'\n\n export var {nodeInterface, nodeField} = nodeDefinitions (\n (globalId) => {\n var {type, id} = fromGlobalId (globalId);\n if (type === 'A') {\n return getA (id);\n } else if (type === 'B') {\n return getB (id);\n }\n },\n (obj) => {\n if (obj instanceof A) {\n return aType;\n } else if (obj instanceof B) {\n return bType;\n }\n }\n )\n\n // -- file schema.js\n\n import {\n GraphQLObjectType,\n GraphQLSchema,\n } from 'graphql';\n\n import { nodeField } from './nodeDefs';\n\n var queryType = new GraphQLObjectType ({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n /*...*/\n }),\n });\n```\n\nIs there a common way or best practice for this?\n\n========================================\n\nTop Answer:\nSee https://github.com/francoisa/todo/tree/master/server/graphql/types\n\ntodoType.js has a reference to viewerType which is defined in viewerType.js\n\nviewerType.js imports from todoType\n\n========================================\n\nCode:\n```text\n// -- file A.js\n\n import { bConnection, getBs } from 'B';\n\n export class A { /*...*/ };\n export var getA = (a) => { /*...*/ };\n export var getAs = (array_of_as) => { /*...*/ };\n\n export var aType = new GraphQLObjectType ({\n name: 'A',\n fields: () => ({\n bs: {\n type: bConnection,\n /*...*/\n },\n resolve: (a, args) => connectionFromPromisedArray (\n getBs (a.bs)\n ),\n /*...*/\n }),\n interfaces: () => [ require ('./nodeDefs').nodeInterface ],\n /*...*/\n })\n\n export var {\n connectionType: aConnection,\n edgeType: aEdge\n } = connectionDefinitions ({\n name: 'A',\n nodeType: aType\n });\n\n // -- file B.js\n\n import { aConnection, getAs } from 'A';\n\n export class B { /*...*/ };\n export var getB = (b) => { /*...*/ };\n export var getBs = (array_of_bs) => { /*...*/ };\n\n export var bType = new GraphQLObjectType ({\n name: 'B',\n fields: () => ({\n as: {\n type: aConnection,\n /*...*/\n },\n resolve: (b, args) => connectionFromPromisedArray (\n getAs (b.bs)\n ),\n /*...*/\n }),\n interfaces: () => [ require ('./nodeDefs').nodeInterface ],\n /*...*/\n })\n\n export var {\n connectionType: bConnection,\n edgeType: bEdge\n } = connectionDefinitions ({\n name: 'B',\n nodeType: bType\n });\n\n // -- file nodeDefs.js\n\n import {\n fromGlobalId,\n nodeDefinitions,\n } from 'graphql-relay';\n\n import { A, getA, aType } from 'A'\n import { B, getB, bType } from 'B'\n\n export var {nodeInterface, nodeField} = nodeDefinitions (\n (globalId) => {\n var {type, id} = fromGlobalId (globalId);\n if (type === 'A') {\n return getA (id);\n } else if (type === 'B') {\n return getB (id);\n }\n },\n (obj) => {\n if (obj instanceof A) {\n return aType;\n } else if (obj instanceof B) {\n return bType;\n }\n }\n )\n\n // -- file schema.js\n\n import {\n GraphQLObjectType,\n GraphQLSchema,\n } from 'graphql';\n\n import { nodeField } from './nodeDefs';\n\n var queryType = new GraphQLObjectType ({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n /*...*/\n }),\n });\n```\n\n```text\ngrunt.initConfig({\n concat: {\n js: {\n src: ['lib/before.js', 'lib/*', 'lib/after.js'],\n dest: 'schema.js',\n }\n }\n});\n```\n\n```text\nimport {\n GraphQLObjectType,\n GraphQLInt,\n GraphQLString,\n GraphQLSchema,\n GraphQLList,\n GraphQLNonNull\n} from 'graphql';\nimport db from '../models/index.js';\nimport Auth from '../classes/auth';\n```\n\n```text\nconst Schema = new GraphQLSchema({\n query: Query,\n mutation: Mutation\n})\nexport default Schema;\n```\n\n```text\nconst Funcionario = new GraphQLObjectType({\nname: 'Funcionario',\ndescription: 'This represent a Funcionario',\nfields: () => {\n return {\n id: {\n type: GraphQLInt,\n resolve(funcionario, args) {\n return funcionario.id;\n }\n },\n CPF: {\n type: GraphQLString,\n resolve(funcionario, args) {\n return funcionario.CPF;\n }\n },\n nome: {\n type: GraphQLString,\n resolve(funcionario, args) {\n return funcionario.nome;\n }\n },\n sobrenome: {\n type: GraphQLString,\n resolve(funcionario, args) {\n return funcionario.sobrenome;\n }\n },\n sessions: {\n type: new GraphQLList(Session),\n resolve(funcionario, args) {\n return funcionario.getSessions();\n }\n }\n }\n}\n})\n```\n\n========================================\n\nComments:\n- Have you found any other solutions?\n- Thank you, I accept your solution, as it definitely answers my problem. I'm still trying to find a way no to use grunt as it seems to be overkill to use it just because of this question. But if there will be no other way, I'll implement this one.\n- If you want to give a shot to Apollo's graphql-tools, it will really simplify your code and make it more readable. If you use it, I've written a tool called schemaglue.js that solves your exact problem. I've written about scaling and organizing your GraphQL code here: hackernoon.com/… Hope this helps.","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":324,"estimatedTokens":1827}}340{"id":"stack-57261326","source":"stackoverflow","questionId":57261326,"title":"Does Postman GraphQL Beta support subscription","tags":["graphql","postman","subscription"],"text":"Title: Does Postman GraphQL Beta support subscription\nTags: graphql, postman, subscription\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use Postman v7.3.4 to develop and test GraphQL APIs. However, when using a GraphQL subscription, the response never shows the data, instead it shows something like the following:\n\n```\n{\n \"data\": null,\n \"extensions\": {\n \"tracing\": {\n \"version\": 1,\n \"startTime\": \"2019-07-29T20:40:20.1062162Z\",\n \"endTime\": \"2019-07-29T20:40:22.7282162Z\",\n \"duration\": 2621830500,\n \"parsing\": {\n \"startOffset\": 8100,\n \"duration\": 160500\n },\n \"validation\": {\n \"startOffset\": 8100,\n \"duration\": 160500\n },\n \"execution\": {\n \"resolvers\": []\n }\n }\n }\n}\n```\n\nWhen using something like GraphiQL, the response shows the subscription value when it changes.\n\nI've looked at the Postman documentation but have not been able to determine if subscriptions are actually supported.\n\nSo my question is, does Postman v7.3.4 support subscriptions? Are there plans to support in the future?\n\n========================================\n\nTop Answer:\nGraphQL subscriptions work via WebSocket and WebSocket endpoints are currently not supported by Postman.\n\nHere is a feature request to support WebSocket in Postman: https://github.com/postmanlabs/postman-app-support/issues/4009\n\n========================================\n\nCode:\n```text\n{\n \"data\": null,\n \"extensions\": {\n \"tracing\": {\n \"version\": 1,\n \"startTime\": \"2019-07-29T20:40:20.1062162Z\",\n \"endTime\": \"2019-07-29T20:40:22.7282162Z\",\n \"duration\": 2621830500,\n \"parsing\": {\n \"startOffset\": 8100,\n \"duration\": 160500\n },\n \"validation\": {\n \"startOffset\": 8100,\n \"duration\": 160500\n },\n \"execution\": {\n \"resolvers\": []\n }\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":72,"estimatedTokens":472}}341{"id":"stack-73452881","source":"stackoverflow","questionId":73452881,"title":"Multiple Query Type in Graphql Hotchocolate","tags":["c#","graphql",".net-6.0","hotchocolate"],"text":"Title: Multiple Query Type in Graphql Hotchocolate\nTags: c#, graphql, .net-6.0, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI am using hot chocolate graphql. I have a scenario where I have two separate query type classes.\n\n- PostQuery -> contains post related queries\n\n- UserQuery -> contains user related queries\n\n**My Folder Structure**\n\nhttps://i.sstatic.net/rb2gE.png\n\nHere it is how I am configuring it\n\n```\n.AddAuthorization()\n //for inmemory subscription\n .AddInMemorySubscriptions()\n .AddQueryType()\n .AddQueryType()\n .AddMutationType()\n .AddSubscriptionType()\n .AddGlobalObjectIdentification()\n // Registers the filter convention of MongoDB\n .AddMongoDbFiltering()\n // Registers the sorting convention of MongoDB\n .AddMongoDbSorting()\n // Registers the projection convention of MongoDB\n .AddMongoDbProjections()\n // Registers the paging providers of MongoDB\n .AddMongoDbPagingProviders();\n```\n\nHowever, i am getting the following error\n\n```\nSystem.ArgumentException: The root type `Query` has already been registered\n```\n\nIs there anyway it can be configured or else I have to places everything in a single class?\n\n========================================\n\nTop Answer:\nFirst thanks to @sjokkogutten for his answer. I strongly disagree with his approach. As your application size gets larger your types will become more tedious to manage.\n\nThe better approach would be to define your queries in partial classes.\n\npostQuery.cs\n\n```\npublic partial class Query\n{\n public List GetAllPosts()\n {\n return List{...};\n }\n}\n```\n\nUserQuery.cs\n\n```\npublic partial class Query\n{\n public List GetAllUsers()\n {\n return List{...};\n }\n}\n```\n\n========================================\n\nCode:\n```text\n.AddAuthorization()\n //for inmemory subscription\n .AddInMemorySubscriptions()\n .AddQueryType<PostQuery>()\n .AddQueryType<UserQuery>()\n .AddMutationType<Mutation>()\n .AddSubscriptionType<Subscription>()\n .AddGlobalObjectIdentification()\n // Registers the filter convention of MongoDB\n .AddMongoDbFiltering()\n // Registers the sorting convention of MongoDB\n .AddMongoDbSorting()\n // Registers the projection convention of MongoDB\n .AddMongoDbProjections()\n // Registers the paging providers of MongoDB\n .AddMongoDbPagingProviders();\n```\n\n```text\nSystem.ArgumentException: The root type `Query` has already been registered\n```\n\n```text\nbuilder.Services\n.AddQueryType(q => q.Name(\"Query\"))\n.AddType<PostQuery>()\n.AddType<UserQuery>()\n```\n\n```text\n[ExtendObjectType(\"Query\")]\npublic class PostQuery \n{\n public List<Post> GetAllPosts()\n {\n return List<Post>{...};\n }\n}\n\n[ExtendObjectType(\"Query\")]\npublic class UserQuery\n{\n public List<User> GetAllUsers()\n {\n return List<User>{...};\n }\n}\n```\n\n```text\npublic partial class Query\n{\n public List<Post> GetAllPosts()\n {\n return List<Post>{...};\n }\n}\n```\n\n```text\npublic partial class Query\n{\n public List<User> GetAllUsers()\n {\n return List<User>{...};\n }\n}\n```\n\n```text\npublic class TemplatesQuery\n{\n public async Task<IQueryable<Template>> GetTemplates(\n [Service] ILogger<TemplatesQuery> logger,\n [Service] ITemplatesService templatesService)\n {\n ...\n }\n}\n```\n\n```text\n[ExtendObjectType(typeof(TemplatesQuery))]\npublic class SignaturesQuery\n{\n public async Task<IQueryable<Signature>> GetSignatures(\n [Service] ILogger<SignaturesQuery> logger,\n [Service] ISignaturesService signaturesService)\n {\n ...\n }\n}\n```\n\n```text\nbuilder.Services.AddGraphQLServer()\n .AddQueryType<TemplatesQuery>()\n .AddTypeExtension<SignaturesQuery>();\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":178,"estimatedTokens":911}}342{"id":"stack-44808291","source":"stackoverflow","questionId":44808291,"title":"React Apollo: Dynamically update GraphQL query from Component state","tags":["javascript","reactjs","graphql","react-apollo"],"text":"Title: React Apollo: Dynamically update GraphQL query from Component state\nTags: javascript, reactjs, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have a component that shows results from a GraphQL query using the `react-apollo` decorator syntax. The query accepts a parameter, which I want to set dynamically based on component state.\n\nConsider the following simplified example:\n\n```\nimport * as React from βreactβ;\nimport { graphql } from βreact-apolloβ;\nimport gql from βgraphql-tagβ;\n\nconst myQuery = gql`\n query($active: boolean!) {\n items(active: $active) {\n\n }\n }\n`;\n\n@graphql(myQuery)\nclass MyQueryResultComponent extends React.Component {\n public render() {\n return \n \n {this.props.data.items}\n ;\n }\n}\n```\n\nWhen the checkbox is clicked I want to resubmit the query, dynamically setting the `active` attribute in `myQuery`, based on the state of the checkbox. I've omitted the handler and bindings of the checkbox for brevity, but how can I cause the query to be re-submitted upon a state change?\n\n========================================\n\nCode:\n```text\nimport * as React from βreactβ;\nimport { graphql } from βreact-apolloβ;\nimport gql from βgraphql-tagβ;\n\nconst myQuery = gql`\n query($active: boolean!) {\n items(active: $active) {\n\n }\n }\n`;\n\n@graphql(myQuery)\nclass MyQueryResultComponent extends React.Component {\n public render() {\n return <div>\n <input type=βcheckboxβ /* other attributes and bindings */ />\n {this.props.data.items}\n <div>;\n }\n}\n```\n\n```text\nreact-apollo\n```\n\n```text\nactive\n```\n\n```text\nmyQuery\n```\n\n```text\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport gql from 'graphql-tag';\nimport { graphql } from 'react-apollo';\n\nconst Data = ({ data }) =>\n <div>\n <h2>Data</h2>\n <pre style={{ textAlign: 'left' }}>\n {JSON.stringify(data, undefined, 2)}\n </pre>\n </div>;\n\nData.propTypes = {\n active: PropTypes.bool.isRequired,\n};\n\nconst query = gql`\n query SearchAuthor($id: Int!) {\n author(id: $id) {\n id\n firstName\n lastName\n }\n }\n`;\n\nexport default graphql(query, {\n options(ownProps) {\n return {\n variables: {\n // This is the place where you can \n // access your component's props and provide\n // variables for your query\n id: ownProps.active ? 1 : 2,\n },\n };\n },\n})(Data);\n```\n\n```text\nimport React, { Component } from 'react';\nimport Data from './Data';\n\nclass App extends Component {\n constructor(props) {\n super(props);\n\n this.state = {\n active: false,\n };\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n handleChange() {\n this.setState(prevState => ({\n active: !prevState.active,\n }));\n }\n\n render() {\n const { active } = this.state;\n\n return (\n <div>\n <h1>App</h1>\n <div>\n <label>\n <input\n type=\"checkbox\"\n checked={active}\n onChange={this.handleChange}\n />\n If selected, fetch author <strong>id: 1</strong>\n </label>\n </div>\n <Data active={active} />\n </div>\n );\n }\n}\n\nexport default App;\n```\n\n```text\nprop\n```\n\n```text\nreact-apollo\n```\n\n```text\nData.js\n```\n\n```text\nApp.js\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":177,"estimatedTokens":819}}343{"id":"stack-51262873","source":"stackoverflow","questionId":51262873,"title":"How to implement auto refresh token in graphql for jwt based authentication?","tags":["node.js","jwt","graphql","apollo-client","apollo-server"],"text":"Title: How to implement auto refresh token in graphql for jwt based authentication?\nTags: node.js, jwt, graphql, apollo-client, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am trying to figure out this scenario for my JWT based authentication in Apollo based graphql server **(2.0)** .\n\nBasically after login a user gets accessToken and refreshToken from server.\n\nAccessToken gets expired after certain period of time and server sends an error message indicating that token expired (**TokenExpiredError**) and then client need to communicate with server for new accessToken via passing refreshToken.\n\nFlow is as following -\n\n- **TokenExpiredError** occurs\n\n- Get that error on client side\n\n- Queue all requests with old accessToken(so that server is not flooded with too many refreshToken calls and many accessTokens are generated by server)\n\n- Call refreshToken api on graphql server to get new accessToken\n\n- update accessToken for all authorised calls with new accessToken\n\n- Logout user incase refreshToken itself is expired\n\n- Prevent any kind of race condition b/w calls\n\nI have already implemented refreshToken mutation on client side but can't figure out about when error occurs stop all requests -> request new token -> make all pending request again and if refresh token is expired logout user.\n\n========================================\n\nCode:\n```text\n// @flow\nimport { ApolloLink, Observable } from 'apollo-link';\nimport type { ApolloClient } from 'apollo-client';\nimport type { Operation, NextLink } from 'apollo-link';\n\nimport { refreshToken2, getToken } from './token-service';\nimport { GraphQLError } from 'graphql';\n\nexport class AuthLink extends ApolloLink {\n tokenRefreshingPromise: Promise<boolean> | null;\n\ninjectClient = (client: ApolloClient): void => {\n this.client = client;\n};\n\nrefreshToken = (): Promise<boolean> => {\n //if (!this.tokenRefreshingPromise) this.tokenRefreshingPromise = refreshToken(this.client);\n if (!this.tokenRefreshingPromise) this.tokenRefreshingPromise = refreshToken2();\n return this.tokenRefreshingPromise;\n};\n\nsetTokenHeader = (operation: Operation): void => {\n const token = getToken();\n if (token) operation.setContext({ headers: { authorization: `Bearer ${token}` } });\n};\n\nrequest(operation: Operation, forward: NextLink) {\n // set token in header\n this.setTokenHeader(operation);\n // try refreshing token once if it has expired\n return new Observable(observer => {\n let subscription, innerSubscription, inner2Subscription;\n try {\n subscription = forward(operation).subscribe({\n next: result => {\n if (result.errors) {\n console.log(\"---->\", JSON.stringify(result.errors))\n for (let err of result.errors) {\n switch (err.extensions.code) {\n case 'E140':\n console.log('E140', result)\n observer.error(result.errors)\n break;\n case 'G130':\n this.refreshToken().then(response => {\n if (response.data && !response.errors) {\n this.setTokenHeader(operation);\n innerSubscription = forward(operation).subscribe(observer);\n } else {\n console.log(\"After refresh token\", JSON.stringify(response));\n observer.next(response)\n }\n }).catch(console.log);\n break;\n }\n }\n } \n observer.next(result)\n\n },\n complete: observer.complete.bind(observer),\n error: netowrkError => {\n observer.error(netowrkError);\n }\n },\n });\n } catch (e) {\n observer.error(e);\n }\n return () => {\n if (subscription) subscription.unsubscribe();\n if (innerSubscription) innerSubscription.unsubscribe();\n if (inner2Subscription) inner2Subscription.unsubscribe();\n };\n });\n}\n}\n```\n\n========================================\n\nComments:\n- what about ask for token before requests? ... :)\n- @dbvt10 that would be quite inefficient way to do\n- @WitVault mean checking expire date, ask for new token before expiration, replace token and make new requests with fresh token... these processes can run on background, so you dont need stop/delay requests...\n- @dbvt10 your idea was actually good, refresh the token few minutes before actually expiring the token and update the token in local-storage so that new requests use latest updated token","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":119,"estimatedTokens":1256}}344{"id":"stack-59192308","source":"stackoverflow","questionId":59192308,"title":"Github GraphQL v4 API nested pagination (Multiple pagination cursors can not be followed in a single query)","tags":["github","graphql","github-api"],"text":"Title: Github GraphQL v4 API nested pagination (Multiple pagination cursors can not be followed in a single query)\nTags: github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nLet's paint a hypothetical picture for discussion.\n\nLet's say a large company has 200 organizations each with 250 repositories and each of those repositories has 300 contributors.\n\nLet's say I would like to build up a GraphQL query that answers the question:\n\nGive me all contributors (and their privileges) of all repositories of all organizations in my account.\n\nObviously, pagination is needed.\n\nBut the way it is currently implemented, a pagination cursor is provided for each list of contributors, each list of repositories, and each list of organizations.\n\nAs a result, it is not possible to complete the query by following a single pagination cursor.\n\nIt is not clear to me that the query can be completed at all due to the ambiguity of specifying a pagination cursor for one list of contributors for one org/repo combo versus the next org/repo combo.\n\nThanks\n\n========================================\n\nCode:\n```text\nquery {\n organizations(first: 10) {\n repositories(first: 20) {\n contributors(first: 30) {\n name,\n privileges\n }\n }\n }\n}\n```\n\n```text\n200 * 250 * 300 = 15000000\n```\n\n```text\nfirst\n```\n\n```text\n100\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":50,"estimatedTokens":335}}345{"id":"stack-58673815","source":"stackoverflow","questionId":58673815,"title":"How to switch polling on and off in Apollo?","tags":["graphql","apollo","react-apollo","apollo-client","react-apollo-hooks"],"text":"Title: How to switch polling on and off in Apollo?\nTags: graphql, apollo, react-apollo, apollo-client, react-apollo-hooks\nSource: Stack Overflow\n\nQuestion:\nI use the `useQuery` Hook like this:\n\n```\nfunction Foo() {\n const { data, error, loading } = useQuery(MY_QUERY, { pollInterval: 1000 });\n\n return (\n <>\n \n \n {data}\n \n );\n}\n```\n\nNow, both `Bar` and `Baz` use the same query. `Baz` is a sidebar and I'd like to disable the polling while it is active.\n\nI have a global reducer for handling the state of `Baz` and I modified it like this:\n\n```\nif (isSidebarOpen === false) {\n ...\n apolloClient.stop();\n} else {\n // TODO\n}\n```\n\nThis stops the polling, but I don't know how to reactivate it when the sidebar gets closed (that is, in the `else` block above).\n\nAm I doing this correctly? Is there a different way to toggle the polling of a GraphQL query with Apollo?\n\n========================================\n\nTop Answer:\nThis is an code example :\n\n```\nconst { loading, error, data, startPolling, stopPolling } = useQuery(GET_DELIVERIES_QUERY)\n\n useEffect(() => {\n startPolling(5000)\n return () => {\n stopPolling()\n }\n }, [startPolling, stopPolling])\n```\n\n========================================\n\nCode:\n```js\nfunction Foo() {\n const { data, error, loading } = useQuery(MY_QUERY, { pollInterval: 1000 });\n\n return (\n <>\n <Bar/>\n <Baz/>\n {data}\n </>\n );\n}\n```\n\n```text\nif (isSidebarOpen === false) {\n ...\n apolloClient.stop();\n} else {\n // TODO\n}\n```\n\n```text\nuseQuery\n```\n\n```text\nBar\n```\n\n```text\nBaz\n```\n\n```text\nBaz\n```\n\n```text\nBaz\n```\n\n```text\nelse\n```\n\n```text\nstartPolling\n```\n\n```text\nstopPolling\n```\n\n```text\nconst { loading, error, data, startPolling, stopPolling } = useQuery(GET_DELIVERIES_QUERY)\n\n useEffect(() => {\n startPolling(5000)\n return () => {\n stopPolling()\n }\n }, [startPolling, stopPolling])\n```\n\n========================================\n\nComments:\n- If polling does not work, check if you have set `ssr` to `true` on your Apollo client. Polling is not supported if server side rendering is enabled.\n- Thank you! Apollo really should add in their documentation that if you add pollInterval to your useQuery, it will never stop! Your code worked perfectly for only polling when that component is visible.\n- they have. apollographql.com/docs/react/data/queries/#polling. `Note that if you set pollInterval to 0, the query does not poll.`. the example doesn't illustrate `startPolling` and `stopPolling` though\n- How do we pass variables to the query?","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":130,"estimatedTokens":627}}346{"id":"stack-72116940","source":"stackoverflow","questionId":72116940,"title":"Apollo GraphQL: GraphQLWsLink (Subscriptions) Troubles. Cannot get WebSocket implementation to work w/ Next.js","tags":["websocket","graphql","next.js","apollo-client"],"text":"Title: Apollo GraphQL: GraphQLWsLink (Subscriptions) Troubles. Cannot get WebSocket implementation to work w/ Next.js\nTags: websocket, graphql, next.js, apollo-client\nSource: Stack Overflow\n\nQuestion:\nSo I have a GraphQL server that I wrote in Go, following this tutorial pretty closely. I have my front-end written as a Next.js application, and I am currently trying to create a client to connect to my server and even following the subscription docs to the T, I cannot seem to get it to work. How is it that the examples provided do not include a `webSocketImpl`?\n\nIf I don't provide a `webSocketImpl`, I get this:\n\n```\nError: WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`\n```\n\nSo, naturally, I `import { WebSocket } from \"ws\";` , and have:\n\n```\nconst wsLink = new GraphQLWsLink(\n createClient({\n webSocketImpl: WebSocket,\n url: \"ws://localhost:8080/subscriptions\",\n })\n);\n```\n\nWhere I then get:\n\n```\nerror - ./node_modules/node-gyp-build/index.js:1:0\nModule not found: Can't resolve 'fs'\n```\n\nHere is the full code, basically all I need is to create a ApolloClient and export it for use in my React code.\n\n```\nimport { ApolloClient, HttpLink, InMemoryCache, split } from \"@apollo/client\";\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { createClient } from \"graphql-ws\";\nimport { getMainDefinition } from \"@apollo/client/utilities\";\nimport { WebSocket } from \"ws\";\n\nconst wsLink = new GraphQLWsLink(\n createClient({\n webSocketImpl: WebSocket,\n url: \"ws://localhost:8080/subscriptions\",\n })\n);\n\nconst httpLink = new HttpLink({\n uri: `http://localhost:8080/query`,\n});\n\nconst link = split(\n ({ query }) => {\n const def = getMainDefinition(query);\n return (\n def.kind === \"OperationDefinition\" && def.operation === \"subscription\"\n );\n },\n wsLink,\n httpLink\n);\n\nexport const Client = new ApolloClient({\n link,\n cache: new InMemoryCache(),\n});\n```\n\nAm I totally missing something here? Is there not a default WebSocket implementation in my installation? Obviously the `\"ws\"` implementation isn't cutting it, probably because `fs` is not available in-browser?\n\n========================================\n\nTop Answer:\nI found a way how it`s work with GraphQL-yoga\nIt's client :\n\n\r\n\r\n\n```\n// import { createServer } from \"@graphql-yoga/node\";\nimport { makeExecutableSchema } from \"@graphql-tools/schema\";\nimport typeDefs from \"@/server/graphql/typeDef/schema.graphql\";\nimport resolvers from \"@/server/graphql/resolvers\";\nimport dbInit from \"@/lib/dbInit\";\nimport JWT from \"jsonwebtoken\";\nimport Cors from \"micro-cors\";\n\n// const pubsub = new PubSub();\nconst schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n});\n\nimport {\n createServer,\n createPubSub,\n GraphQLYogaError,\n} from \"@graphql-yoga/node\";\nimport { useResponseCache } from \"@envelop/response-cache\";\nimport { WebSocketServer } from \"ws\"; // yarn add ws\n// import ws from 'ws'; yarn add ws@7\n// const WebSocketServer = ws.Server;\nimport { useServer } from \"graphql-ws/lib/use/ws\";\n\nconst pubSub = createPubSub();\n\nconst server = createServer({\n cors: {\n credentials: \"same-origin\",\n origin: [\"http://localhost:3000\"], // your frontend url.\n },\n\n plugins: [\n useResponseCache({\n includeExtensionMetadata: true,\n }),\n ],\n context: async (ctx) => {\n let wsServer = null;\n wsServer = ctx.res.socket.server.ws ||= new WebSocketServer({\n port: 4000,\n path: \"/api/graphql\",\n });\n wsServer &&= useServer({ schema }, wsServer);\n\n const db = await dbInit();\n let { token, customerId, customerExpire } = ctx.req.cookies;\n // 1. Find optional visitor id\n let id = null;\n if (token) {\n try {\n let obj = JWT.verify(token, \"MY_SECRET\");\n id = obj.id;\n } catch (err) {\n console.error(\"error on apollo server\", err); // expired token, invalid token\n // TODO try apollo-link-error on the client\n throw new AuthenticationError(\n \"Authentication token is invalid, please log in\"\n );\n }\n }\n\n return {\n ...ctx,\n userId: id,\n customerId,\n pubSub,\n };\n },\n schema,\n\n});\n\nexport default server;\n```\n\n\r\n\r\n\r\n\nAnd client\n\n\r\n\r\n\n```\nimport { useMemo } from \"react\";\nimport {\n ApolloClient,\n InMemoryCache,\n split,\n HttpLink,\n createHttpLink,\n} from \"@apollo/client\";\nimport merge from \"deepmerge\";\nimport { getMainDefinition } from \"apollo-utilities\";\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { createClient } from \"graphql-ws\";\n\n// const link = process.env.SERVER_LINK;\nlet apolloClient;\n//create websocket link\nconst wsLink =\n typeof window !== \"undefined\"\n ? new GraphQLWsLink(\n createClient({\n url: \"ws://localhost:4000/api/graphql\",\n\n on: {\n connected: () => console.log(\"connected client\"),\n closed: () => console.log(\"closed\"),\n },\n })\n )\n : null;\n\n//create http link\nconst httplink = new HttpLink({\n uri: \"http://localhost:3000/api/graphql\",\n credentials: \"same-origin\",\n});\n\n//Split the link based on graphql operation\nconst link =\n typeof window !== \"undefined\"\n ? split(\n //only create the split in the browser\n // split based on operation type\n ({ query }) => {\n const { kind, operation } = getMainDefinition(query);\n return kind === \"OperationDefinition\" && operation === \"subscription\";\n },\n wsLink,\n httplink\n )\n : httplink;\n\n//create apollo client\nfunction createApolloClient() {\n return new ApolloClient({\n ssrMode: typeof window === \"undefined\",\n link: link,\n cache: new InMemoryCache(),\n });\n}\n\nexport function initializeApollo(initialState = null) {\n const _apolloClient = apolloClient ?? createApolloClient();\n\n if (initialState) {\n // Get existing cache, loaded during client side data fetching\n const existingCache = _apolloClient.extract();\n\n // Merge the existing cache into data passed from getStaticProps/getServerSideProps\n const data = merge(initialState, existingCache);\n\n // Restore the cache with the merged data\n _apolloClient.cache.restore(data);\n }\n\n if (typeof window === \"undefined\") return _apolloClient;\n\n if (!apolloClient) apolloClient = _apolloClient;\n\n return _apolloClient;\n}\n\nexport function useApollo(initialState) {\n const store = useMemo(() => initializeApollo(initialState), [initialState]);\n return store;\n}\n```\n\n========================================\n\nCode:\n```text\nError: WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`\n```\n\n```text\nconst wsLink = new GraphQLWsLink(\n createClient({\n webSocketImpl: WebSocket,\n url: \"ws://localhost:8080/subscriptions\",\n })\n);\n```\n\n```text\nerror - ./node_modules/node-gyp-build/index.js:1:0\nModule not found: Can't resolve 'fs'\n```\n\n```text\nimport { ApolloClient, HttpLink, InMemoryCache, split } from \"@apollo/client\";\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { createClient } from \"graphql-ws\";\nimport { getMainDefinition } from \"@apollo/client/utilities\";\nimport { WebSocket } from \"ws\";\n\nconst wsLink = new GraphQLWsLink(\n createClient({\n webSocketImpl: WebSocket,\n url: \"ws://localhost:8080/subscriptions\",\n })\n);\n\nconst httpLink = new HttpLink({\n uri: `http://localhost:8080/query`,\n});\n\nconst link = split(\n ({ query }) => {\n const def = getMainDefinition(query);\n return (\n def.kind === \"OperationDefinition\" && def.operation === \"subscription\"\n );\n },\n wsLink,\n httpLink\n);\n\nexport const Client = new ApolloClient({\n link,\n cache: new InMemoryCache(),\n});\n```\n\n```text\nwebSocketImpl\n```\n\n```text\nwebSocketImpl\n```\n\n```text\nimport { WebSocket } from \"ws\";\n```\n\n```text\n\"ws\"\n```\n\n```text\nfs\n```\n\n```js\nimport { ApolloClient, HttpLink, InMemoryCache, split } from \"@apollo/client\";\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { createClient } from \"graphql-ws\";\nimport { getMainDefinition } from \"@apollo/client/utilities\";\n\nconst wsLink =\n typeof window !== \"undefined\"\n ? new GraphQLWsLink(\n createClient({\n url: \"ws://localhost:8080/subscriptions\",\n })\n )\n : null;\n\nconst httpLink = new HttpLink({\n uri: `http://localhost:8080/query`,\n});\n\nconst link =\n typeof window !== \"undefined\" && wsLink != null\n ? split(\n ({ query }) => {\n const def = getMainDefinition(query);\n return (\n def.kind === \"OperationDefinition\" &&\n def.operation === \"subscription\"\n );\n },\n wsLink,\n httpLink\n )\n : httpLink;\n\nexport const client = new ApolloClient({\n link,\n cache: new InMemoryCache(),\n});\n```\n\n```js\n// import { createServer } from \"@graphql-yoga/node\";\nimport { makeExecutableSchema } from \"@graphql-tools/schema\";\nimport typeDefs from \"@/server/graphql/typeDef/schema.graphql\";\nimport resolvers from \"@/server/graphql/resolvers\";\nimport dbInit from \"@/lib/dbInit\";\nimport JWT from \"jsonwebtoken\";\nimport Cors from \"micro-cors\";\n\n// const pubsub = new PubSub();\nconst schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n});\n\nimport {\n createServer,\n createPubSub,\n GraphQLYogaError,\n} from \"@graphql-yoga/node\";\nimport { useResponseCache } from \"@envelop/response-cache\";\nimport { WebSocketServer } from \"ws\"; // yarn add ws\n// import ws from 'ws'; yarn add ws@7\n// const WebSocketServer = ws.Server;\nimport { useServer } from \"graphql-ws/lib/use/ws\";\n\nconst pubSub = createPubSub();\n\nconst server = createServer({\n cors: {\n credentials: \"same-origin\",\n origin: [\"http://localhost:3000\"], // your frontend url.\n },\n\n plugins: [\n useResponseCache({\n includeExtensionMetadata: true,\n }),\n ],\n context: async (ctx) => {\n let wsServer = null;\n wsServer = ctx.res.socket.server.ws ||= new WebSocketServer({\n port: 4000,\n path: \"/api/graphql\",\n });\n wsServer &&= useServer({ schema }, wsServer);\n\n const db = await dbInit();\n let { token, customerId, customerExpire } = ctx.req.cookies;\n // 1. Find optional visitor id\n let id = null;\n if (token) {\n try {\n let obj = JWT.verify(token, \"MY_SECRET\");\n id = obj.id;\n } catch (err) {\n console.error(\"error on apollo server\", err); // expired token, invalid token\n // TODO try apollo-link-error on the client\n throw new AuthenticationError(\n \"Authentication token is invalid, please log in\"\n );\n }\n }\n\n return {\n ...ctx,\n userId: id,\n customerId,\n pubSub,\n };\n },\n schema,\n\n});\n\nexport default server;\n```\n\n```js\nimport { useMemo } from \"react\";\nimport {\n ApolloClient,\n InMemoryCache,\n split,\n HttpLink,\n createHttpLink,\n} from \"@apollo/client\";\nimport merge from \"deepmerge\";\nimport { getMainDefinition } from \"apollo-utilities\";\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { createClient } from \"graphql-ws\";\n\n// const link = process.env.SERVER_LINK;\nlet apolloClient;\n//create websocket link\nconst wsLink =\n typeof window !== \"undefined\"\n ? new GraphQLWsLink(\n createClient({\n url: \"ws://localhost:4000/api/graphql\",\n\n on: {\n connected: () => console.log(\"connected client\"),\n closed: () => console.log(\"closed\"),\n },\n })\n )\n : null;\n\n\n//create http link\nconst httplink = new HttpLink({\n uri: \"http://localhost:3000/api/graphql\",\n credentials: \"same-origin\",\n});\n\n//Split the link based on graphql operation\nconst link =\n typeof window !== \"undefined\"\n ? split(\n //only create the split in the browser\n // split based on operation type\n ({ query }) => {\n const { kind, operation } = getMainDefinition(query);\n return kind === \"OperationDefinition\" && operation === \"subscription\";\n },\n wsLink,\n httplink\n )\n : httplink;\n\n//create apollo client\nfunction createApolloClient() {\n return new ApolloClient({\n ssrMode: typeof window === \"undefined\",\n link: link,\n cache: new InMemoryCache(),\n });\n}\n\nexport function initializeApollo(initialState = null) {\n const _apolloClient = apolloClient ?? createApolloClient();\n\n if (initialState) {\n // Get existing cache, loaded during client side data fetching\n const existingCache = _apolloClient.extract();\n\n // Merge the existing cache into data passed from getStaticProps/getServerSideProps\n const data = merge(initialState, existingCache);\n\n // Restore the cache with the merged data\n _apolloClient.cache.restore(data);\n }\n\n if (typeof window === \"undefined\") return _apolloClient;\n\n if (!apolloClient) apolloClient = _apolloClient;\n\n return _apolloClient;\n}\n\nexport function useApollo(initialState) {\n const store = useMemo(() => initializeApollo(initialState), [initialState]);\n return store;\n}\n```\n\n========================================\n\nComments:\n- would you mind sharing your apollo-server code please?\n- Good stuff mate. Was battling with this for a while.","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":542,"estimatedTokens":3253}}347{"id":"stack-58055145","source":"stackoverflow","questionId":58055145,"title":"How to fix TypeError: Cannot read property 'hash' of undefined during hashing password for GraphQL mutation with bcryptjs?","tags":["node.js","mongodb","mongoose","graphql"],"text":"Title: How to fix TypeError: Cannot read property 'hash' of undefined during hashing password for GraphQL mutation with bcryptjs?\nTags: node.js, mongodb, mongoose, graphql\nSource: Stack Overflow\n\nQuestion:\nI am relatively new to Node/GraphQL/MongoDB/Moogose.\nI am trying to create a mutation to encrypt the user's password using bcryptjs instead of plain text. However, I am having this error:\n**TypeError: Cannot read property 'hash' of undefined**\n\nI came from Python background and I am having some difficulty understanding how async programming\nHere's my code block of my schema.js\n\n```\nconst RootMutation = new GraphQLObjectType({\n name: 'RootMutationType',\n fields: {\n createUser: {\n type: UserType,\n args: {\n email: { type: new GraphQLNonNull(GraphQLString) },\n password: { type: new GraphQLNonNull(GraphQLString) },\n },\n resolve(parents, args) {\n User.findOne({ email: args.email })\n .then(user => {\n if(user) {\n throw new Error('This email has already been used!');\n }\n return bcrypt.hash(args.password, 12); // Error at this line\n })\n .then(hashedPassword => {\n let user = new User({\n email: args.email,\n password: hashedPassword,\n });\n return user.save();\n })\n .catch(err => {\n throw err;\n });\n }\n }\n```\n\nI have tried, but i've gotten the error Cannot read property 'genSalt' of undefined:\n\n```\ncreateUser: {\n type: UserType,\n args: {\n email: { type: new GraphQLNonNull(GraphQLString) },\n password: { type: new GraphQLNonNull(GraphQLString) },\n },\n resolve(parents, args) {\n User.findOne({ email: args.email })\n .then(user => {\n if(user) {\n throw new Error('This email has already been used!');\n }\n bcrypt.genSalt(10, function(err, salt) {\n bcrypt.hash(args.password, salt, function(err, hash) {\n let user = new User({\n email: args.email,\n password: hash,\n });\n return user.save();\n });\n });\n });\n```\n\n**Update:**\nI am now able to create a user in my MongoDB after change to the below:\nTurns out it is because I am using:\n\n`const {bcrypt} = require('bcryptjs');`\n\ninstead of \n\n`const bcrypt = require('bcryptjs'); // this is working`\n\nCan someone explain what is the difference? I am using ES6.\n\nAlso my graphql **mutation** doesn't seem to return me the correct query. \nMutation cmd\n\n```\nmutation {\n createUser(email: \"test3@test.com\", password: \"testpassword\") {\n email\n password\n }\n}\n```\n\nResult:\n\n```\n{\n \"data\": {\n \"createUser\": null\n }\n}\n```\n\n========================================\n\nTop Answer:\nTry\n\n```\nimport * as bcrypt from 'bcrypt';\n```\n\nUpdate:\nThe TypeError: Cannot read property 'hash' of undefined error occurs when you are trying to access a property of an undefined variable. In this case, it seems that you were trying to access the hash property of an undefined variable when using bcryptjs.\n\nThe reason why switching to import * as bcrypt from 'bcrypt' worked is because it imports the entire bcrypt module as an object, which includes the hash function. This means that when you call bcrypt.hash(), the hash function is being called from the imported module.\n\n========================================\n\nCode:\n```text\nconst RootMutation = new GraphQLObjectType({\n name: 'RootMutationType',\n fields: {\n createUser: {\n type: UserType,\n args: {\n email: { type: new GraphQLNonNull(GraphQLString) },\n password: { type: new GraphQLNonNull(GraphQLString) },\n },\n resolve(parents, args) {\n User.findOne({ email: args.email })\n .then(user => {\n if(user) {\n throw new Error('This email has already been used!');\n }\n return bcrypt.hash(args.password, 12); // Error at this line\n })\n .then(hashedPassword => {\n let user = new User({\n email: args.email,\n password: hashedPassword,\n });\n return user.save();\n })\n .catch(err => {\n throw err;\n });\n }\n }\n```\n\n```text\ncreateUser: {\n type: UserType,\n args: {\n email: { type: new GraphQLNonNull(GraphQLString) },\n password: { type: new GraphQLNonNull(GraphQLString) },\n },\n resolve(parents, args) {\n User.findOne({ email: args.email })\n .then(user => {\n if(user) {\n throw new Error('This email has already been used!');\n }\n bcrypt.genSalt(10, function(err, salt) {\n bcrypt.hash(args.password, salt, function(err, hash) {\n let user = new User({\n email: args.email,\n password: hash,\n });\n return user.save();\n });\n });\n });\n```\n\n```text\nmutation {\n createUser(email: \"test3@test.com\", password: \"testpassword\") {\n email\n password\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"createUser\": null\n }\n}\n```\n\n```text\nconst {bcrypt} = require('bcryptjs');\n```\n\n```text\nconst bcrypt = require('bcryptjs'); // this is working\n```\n\n```text\nconst bcrypt = require(\"bcrypt\");\n```\n\n```text\nconst {bcrypt} = require('bcryptjs');\n```\n\n```text\nCannot read property 'hash' of undefined\n```\n\n```text\nconst {bcrypt} = require('bcryptjs');\n```\n\n```text\nconst { isEmail } = require(\"validator\");\n```\n\n```text\nimport bcrypt from 'bcrypt';\n```\n\n```text\nimport * as bcrypt from 'bcrypt';\n```\n\n========================================\n\nComments:\n- Actually, it should be `import * as bcrypt from 'bcrypt';`.\n- This is the only solution that worked for me. Why does this work?","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":237,"estimatedTokens":1463}}348{"id":"stack-55601091","source":"stackoverflow","questionId":55601091,"title":"Apollo Server - GraphQL Error: There can be only one type named \"Query\"","tags":["javascript","node.js","express","graphql","apollo-server"],"text":"Title: Apollo Server - GraphQL Error: There can be only one type named \"Query\"\nTags: javascript, node.js, express, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am new to GraphQL. I am following several guides on Internet in order to \"create\" a small app that uses Apollo Server + Express + GraphQL + MongoDB.\n\n- I have tried to replicate this YT guide (he creates *root.js* file on *typeDefs* folder).\n\n- This one for testing purposes.\n\n- And this one to make sure my folder structure is correct.\n\nI am getting from GraphQL when compiling:\n\nError: There can be only one type named \"User\".\n\nError: There can be only one type named \"Query\".\n\nI have structured my code like this:\n\n- config\n\n- models\nresolvers\n\n- index.js\n\n- user.js\n\ntypeDefs\n\n- index.js\n\n- root.js\n\n- user.js\n\n- index.js\n\nUntil now, my code looks like this:\n\n**typeDefs/user.js**:\n\n```\nimport { gql } from 'apollo-server-express';\n\nconst user = gql`\n type User {\n id: ID!\n name: String\n email: String\n password: String\n }\n\n type Query {\n getUsers: [User]\n }\n\n type Mutation {\n addUser(name: String!, email: String!, password: String!): User\n }\n`;\n\nexport default user;\n```\n\n**typeDefs/root.js**:\n\n```\nimport { gql } from 'apollo-server-express';\n\nexport default gql`\n extend type Query {\n _: String\n }\n\n type User {\n _: String\n }\n`;\n```\n\n**typeDefs/index.js**:\n\n```\nimport root from './root';\nimport user from './user';\n\nexport default [\n root,\n user\n];\n```\n\nAnd then in my **index.js**:\n\n```\nimport express from 'express';\nimport { ApolloServer, gql } from 'apollo-server-express';\n\nimport typeDefs from './typeDefs';\nimport resolvers from './resolvers';\n\nconst server = new ApolloServer({ typeDefs, resolvers });\nconst app = express();\nserver.applyMiddleware({ app });\n\napp.disable('x-powered-by');\n\napp.listen({ port: 4000 }, () => {\n console.log(`Server running at http://localhost:4000${server.graphqlPath}`)\n});\n```\n\nWhat am I doing wrong?\n\n========================================\n\nCode:\n```text\nimport { gql } from 'apollo-server-express';\n\nconst user = gql`\n type User {\n id: ID!\n name: String\n email: String\n password: String\n }\n\n type Query {\n getUsers: [User]\n }\n\n type Mutation {\n addUser(name: String!, email: String!, password: String!): User\n }\n`;\n\nexport default user;\n```\n\n```text\nimport { gql } from 'apollo-server-express';\n\nexport default gql`\n extend type Query {\n _: String\n }\n\n type User {\n _: String\n }\n`;\n```\n\n```text\nimport root from './root';\nimport user from './user';\n\nexport default [\n root,\n user\n];\n```\n\n```text\nimport express from 'express';\nimport { ApolloServer, gql } from 'apollo-server-express';\n\nimport typeDefs from './typeDefs';\nimport resolvers from './resolvers';\n\nconst server = new ApolloServer({ typeDefs, resolvers });\nconst app = express();\nserver.applyMiddleware({ app });\n\napp.disable('x-powered-by');\n\napp.listen({ port: 4000 }, () => {\n console.log(`Server running at http://localhost:4000${server.graphqlPath}`)\n});\n```\n\n```text\nconst user = require('./user');\nconst root= require('./root');\nconst typeDefs = gql`\n type Query{\n _empty: String\n }\n type Mutation {\n _empty: String\n }\n ${user}\n ${root}\n`;\n\nmodule.exports = typeDefs;\n```\n\n```text\ntype Query{\n _empty: String\n }\n```\n\n```text\nextend type Query {\n getUsers: [User]\n }\n```\n\n```text\nextend\n```\n\n```text\nroot\n```\n\n```text\nuser\n```\n\n```text\nQuery\n```\n\n```text\nextend\n```\n\n========================================\n\nComments:\n- You add two User definition, one in `typeDefs/root.js:`and the other within `typeDefs/user.js:`. Just remove the root one, should be enough.\n- @Striped, okay... I get only one error. Yes, as expected. But what if multiple queries are defined on mutiple files which are being combined in **typeDefs/index.js** as seen?\n- Your `typeDefs` are fine as long you've got the `extend` keyword on both types inside `root.js`. I ran the code locally and it runs fine. Are you still seeing an error about `Query` being defined more than once? If so, what version of `apollo-server-express` are you running?\n- @DanielRearden I have added `extend type Query` & `extend type User` on **typeDefs/user.js** and now seems to work. Make your answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.050Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":241,"estimatedTokens":1075}}349{"id":"stack-45100167","source":"stackoverflow","questionId":45100167,"title":"How can I access this.$route from within vue-apollo?","tags":["javascript","vue.js","graphql","vue-apollo"],"text":"Title: How can I access this.$route from within vue-apollo?\nTags: javascript, vue.js, graphql, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm constructing a GraphQL query using `vue-apollo` and `graphql-tag`.\n\nIf I hardcode the ID I want, it works, but I'd like to pass the current route ID to Vue Apollo as a variable.\n\n**Does work** (hardcoded ID):\n\n```\napollo: {\n Property: {\n query: PropertyQuery,\n loadingKey: 'loading',\n variables: {\n id: 'my-long-id-example'\n }\n }\n }\n```\n\nHowever, I'm unable to do this:\n\n**Doesn't work** (trying to access this.$route for the ID):\n\n```\napollo: {\n Property: {\n query: PropertyQuery,\n loadingKey: 'loading',\n variables: {\n id: this.$route.params.id\n }\n }\n }\n```\n\nI get the error:\n\n Uncaught TypeError: Cannot read property 'params' of undefined\n\nIs there any way to do this? \n\n**EDIT**: Full script block to make it easier to see what's going on:\n\n```\n\nimport gql from 'graphql-tag'\n\nconst PropertyQuery = gql`\n query Property($id: ID!) {\n Property(id: $id) {\n id\n slug\n title\n description\n price\n area\n available\n image\n createdAt\n user {\n id\n firstName\n lastName\n }\n }\n }\n`\n\nexport default {\n name: 'Property',\n data () {\n return {\n title: 'Property',\n property: {}\n }\n },\n apollo: {\n Property: {\n query: PropertyQuery,\n loadingKey: 'loading',\n variables: {\n id: this.$route.params.id // Error here!\n }\n }\n }\n}\n\n```\n\n========================================\n\nTop Answer:\nYou can't have access to \"this\" object like that:\n\n```\nvariables: {\n id: this.$route.params.id // Error here! \n}\n```\n\n**But you can like this:**\n\n```\nvariables () { \n return {\n id: this.$route.params.id // Works here! \n }\n}\n```\n\n========================================\n\nCode:\n```text\napollo: {\n Property: {\n query: PropertyQuery,\n loadingKey: 'loading',\n variables: {\n id: 'my-long-id-example'\n }\n }\n }\n```\n\n```text\napollo: {\n Property: {\n query: PropertyQuery,\n loadingKey: 'loading',\n variables: {\n id: this.$route.params.id\n }\n }\n }\n```\n\n```text\n<script>\nimport gql from 'graphql-tag'\n\nconst PropertyQuery = gql`\n query Property($id: ID!) {\n Property(id: $id) {\n id\n slug\n title\n description\n price\n area\n available\n image\n createdAt\n user {\n id\n firstName\n lastName\n }\n }\n }\n`\n\nexport default {\n name: 'Property',\n data () {\n return {\n title: 'Property',\n property: {}\n }\n },\n apollo: {\n Property: {\n query: PropertyQuery,\n loadingKey: 'loading',\n variables: {\n id: this.$route.params.id // Error here!\n }\n }\n }\n}\n</script>\n```\n\n```text\nvue-apollo\n```\n\n```text\ngraphql-tag\n```\n\n```text\nexport default {\n name: 'Property',\n data () {\n return {\n title: 'Property',\n property: {},\n routeParam: this.$route.params.id\n }\n },\n apollo: {\n Property: {\n query: PropertyQuery,\n loadingKey: 'loading',\n // Reactive parameters\n variables() {\n return{\n id: this.routeParam\n }\n }\n }\n }\n}\n```\n\n```text\nthis.propertyName\n```\n\n```text\napollo: {\n Property: gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`\n}\n```\n\n```text\napollo: {\n Property () {\n return gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`\n }\n}\n```\n\n```text\nthis\n```\n\n```text\nthis.$route\n```\n\n```text\nvariables: {\n id: this.$route.params.id // Error here! \n}\n```\n\n```text\nvariables () { \n return {\n id: this.$route.params.id // Works here! \n }\n}\n```\n\n========================================\n\nComments:\n- @VamsiKrishna Thanks for the reply. It's an object that sits on the default export. I have updated my question to show this in context.\n- Yep this worked! Thank you. So variables becomes a function that returns an object instead of directly being an object itself. Thanks!\n- @MichaelGiovanniPumo happy to help and to be frank i read the docs and learned something new, so thanks to you too :)","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":266,"estimatedTokens":999}}350{"id":"stack-37356362","source":"stackoverflow","questionId":37356362,"title":"How to check permissions and other conditions in GraphQL query?","tags":["node.js","mongoose","graphql"],"text":"Title: How to check permissions and other conditions in GraphQL query?\nTags: node.js, mongoose, graphql\nSource: Stack Overflow\n\nQuestion:\nHow could I check if user has permission to *see* or *query* something? I have no idea how to do this. \n\n- In `args`? How would that even work?\nIn `resolve()`? See if user has permission and somehow\neliminate/change some of the args?\n\n**Example:**\n\nIf user is \"visitor\", he can only see public posts, \"admin\" can see everything.\n\n```\nconst userRole = 'admin'; // Let's say this could be \"admin\" or \"visitor\"\n\nconst Query = new GraphQLObjectType({\n name: 'Query',\n fields: () => {\n return {\n posts: {\n type: new GraphQLList(Post),\n args: {\n id: {\n type: GraphQLString\n },\n title: {\n type: GraphQLString\n },\n content: {\n type: GraphQLString\n },\n status: {\n type: GraphQLInt // 0 means \"private\", 1 means \"public\"\n },\n },\n\n // MongoDB / Mongoose magic happens here\n resolve(root, args) {\n return PostModel.find(args).exec()\n }\n }\n }\n }\n})\n```\n\n**Update** - Mongoose model looks something like this:\n\n```\nimport mongoose from 'mongoose'\n\nconst postSchema = new mongoose.Schema({\n title: {\n type: String\n },\n content: {\n type: String\n },\n author: {\n type: mongoose.Schema.Types.ObjectId, // From user model/collection\n ref: 'User'\n },\n date: {\n type: Date,\n default: Date.now\n },\n status: {\n type: Number,\n default: 0 // 0 -> \"private\", 1 -> \"public\"\n },\n})\n\nexport default mongoose.model('Post', postSchema)\n```\n\n========================================\n\nTop Answer:\nOne approach that has helped us solve authorization at our company is to think about resolvers as a composition of middleware. The above example is great but it will become unruly at scale especially as your authorization mechanisms get more advanced.\n\nAn example of a resolver as a composition of middleware might look something like this:\n\n```\ntype ResolverMiddlewareFn = \n (fn: GraphQLFieldResolver) => GraphQLFieldResolver;\n```\n\nA `ResolverMiddlewareFn` is a function that takes a GraphQLFieldResolver and and returns a GraphQLFieldResolver.\n\nTo compose our resolver middleware functions we will use (you guessed it) the compose function! Here is an example of compose implemented in javascript, but you can also find compose functions in ramda and other functional libraries. Compose lets us combine simple functions to make more complicated functions.\n\nGoing back to the GraphQL permissions problem lets look at a simple example.\nSay that we want to log the resolver, authorize the user, and then run the meat and potatoes. Compose lets us combine these three pieces such that we can easily test and re-use them across our application.\n\n```\nconst traceResolve =\n (fn: GraphQLFieldResolver) =>\n async (obj: any, args: any, context: any, info: any) => {\n const start = new Date().getTime();\n const result = await fn(obj, args, context, info);\n const end = new Date().getTime();\n console.log(`Resolver took ${end - start} ms`);\n return result;\n };\n\nconst isAdminAuthorized =\n (fn: GraphQLFieldResolver) =>\n async (obj: any, args: any, context: any, info: any) => {\n if (!context.user.isAdmin) {\n throw new Error('User lacks admin authorization.');\n }\n return await fn(obj, args, context, info);\n }\n\nconst getPost = (obj: any, args: any, context: any, info: any) => {\n return PostModel.find(args).exec();\n}\n\nconst getUser = (obj: any, args: any, context: any, info: any) => {\n return UserModel.find(args).exec();\n}\n\n// You can then define field resolve functions like this:\npostResolver: compose(traceResolve, isAdminAuthorized)(getPost)\n\n// And then others like this:\nuserResolver: compose(traceResolve, isAdminAuthorized)(getUser)\n```\n\n========================================\n\nCode:\n```text\nconst userRole = 'admin'; // Let's say this could be \"admin\" or \"visitor\"\n\nconst Query = new GraphQLObjectType({\n name: 'Query',\n fields: () => {\n return {\n posts: {\n type: new GraphQLList(Post),\n args: {\n id: {\n type: GraphQLString\n },\n title: {\n type: GraphQLString\n },\n content: {\n type: GraphQLString\n },\n status: {\n type: GraphQLInt // 0 means \"private\", 1 means \"public\"\n },\n },\n\n // MongoDB / Mongoose magic happens here\n resolve(root, args) {\n return PostModel.find(args).exec()\n }\n }\n }\n }\n})\n```\n\n```text\nimport mongoose from 'mongoose'\n\nconst postSchema = new mongoose.Schema({\n title: {\n type: String\n },\n content: {\n type: String\n },\n author: {\n type: mongoose.Schema.Types.ObjectId, // From user model/collection\n ref: 'User'\n },\n date: {\n type: Date,\n default: Date.now\n },\n status: {\n type: Number,\n default: 0 // 0 -> \"private\", 1 -> \"public\"\n },\n})\n\nexport default mongoose.model('Post', postSchema)\n```\n\n```text\nargs\n```\n\n```text\nresolve()\n```\n\n```text\napp.use('/graphql', (req, res) => {\n graphqlHTTP({ schema: Schema, context: { user: req.user } })(req, res);\n}\n```\n\n```text\nresolve(parent, args, context){\n if(!context.user.isAdmin){\n args.isPublic = true;\n }\n return PostModel.find(args).exec();\n}\n```\n\n```text\ntype ResolverMiddlewareFn = \n (fn: GraphQLFieldResolver) => GraphQLFieldResolver;\n```\n\n```text\nconst traceResolve =\n (fn: GraphQLFieldResolver) =>\n async (obj: any, args: any, context: any, info: any) => {\n const start = new Date().getTime();\n const result = await fn(obj, args, context, info);\n const end = new Date().getTime();\n console.log(`Resolver took ${end - start} ms`);\n return result;\n };\n\nconst isAdminAuthorized =\n (fn: GraphQLFieldResolver) =>\n async (obj: any, args: any, context: any, info: any) => {\n if (!context.user.isAdmin) {\n throw new Error('User lacks admin authorization.');\n }\n return await fn(obj, args, context, info);\n }\n\nconst getPost = (obj: any, args: any, context: any, info: any) => {\n return PostModel.find(args).exec();\n}\n\nconst getUser = (obj: any, args: any, context: any, info: any) => {\n return UserModel.find(args).exec();\n}\n\n// You can then define field resolve functions like this:\npostResolver: compose(traceResolve, isAdminAuthorized)(getPost)\n\n// And then others like this:\nuserResolver: compose(traceResolve, isAdminAuthorized)(getUser)\n```\n\n```text\nResolverMiddlewareFn\n```\n\n========================================\n\nComments:\n- If you're using Mongoose it's easiest to do the checks in the resolve functions. I'm not super-familiar with Mongoose, but I wrote a GraphQL server tutorial that uses Mongoose and SQLite a while ago. It uses apolloServer in place of express-graphql. It looks a bit different, but for resolve functions and data fetching everything is pretty much the same. You can find it here.\n- Yeah, you can either return null or throw an error and GraphQL will stop going down that branch of the query. If you need to check permissions based on stuff in the database (e.g. roles or something), then you can chain promises. First fetch the item and the permissions related to the item, then when that's returned check if user has permission. If user doesn't have permission, throw error or return null. If user has permission, return the item (or something like that).","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":268,"estimatedTokens":1874}}351{"id":"stack-65842596","source":"stackoverflow","questionId":65842596,"title":"Apollo Client - using cached results from object list in response to query for single object","tags":["javascript","caching","graphql","apollo","apollo-client"],"text":"Title: Apollo Client - using cached results from object list in response to query for single object\nTags: javascript, caching, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nIs it possible to configure the Apollo Client to fetch a single cached Item from a query that returns a list of Items, in order to prefetch data when querying for a single Item?\n\nSchema:\n\n```\ntype Item {\n id: ID!\n name: String!\n}\n\ntype Query {\n items: [Item!]!\n itemById(id: ID!): Item!\n}\n```\n\nQuery1:\n\n```\nquery HomepageList {\n items {\n id\n name\n }\n}\n```\n\nQuery2:\n\n```\nquery ItemDetail($id: ID!) {\n itemById(id: $id) {\n id\n name\n }\n}\n```\n\nGiven that the individual Item's data will already be in the cache, it should be possible to use the already cached data whilst still executing a fetch incase any data has changed.\n\nHowever, the query does not utilise the cached data (by default at least), and it seems that we need to somehow tell Apollo that we know the Item is already in the cache.\n\nAny help greatly appreciated.\n\n========================================\n\nCode:\n```text\ntype Item {\n id: ID!\n name: String!\n}\n\ntype Query {\n items: [Item!]!\n itemById(id: ID!): Item!\n}\n```\n\n```text\nquery HomepageList {\n items {\n id\n name\n }\n}\n```\n\n```text\nquery ItemDetail($id: ID!) {\n itemById(id: $id) {\n id\n name\n }\n}\n```\n\n```text\ncacheRedirects: {\n Query: {\n getBook(_, args, { getCacheKey }) {\n return getCacheKey({\n __typename: 'Book',\n id: args.id,\n });\n }\n },\n },\n```\n\n```text\ntypePolicies: {\n Query: {\n fields: {\n getBook(_, { args, toReference }) {\n return toReference({\n __typename: 'Book',\n id: args.id,\n });\n }\n }\n }\n }\n```\n\n```text\ngetBooks\n```\n\n```text\ngetBooks\n```\n\n```text\nBook\n```\n\n```text\nBook:123\n```\n\n```text\nBook\n```\n\n```text\n123\n```\n\n```text\nid\n```\n\n```text\ngetBook\n```\n\n```text\nargs.id\n```\n\n========================================\n\nComments:\n- Excellent answer @Bram, this worked and helped me understand what was going on.","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":150,"estimatedTokens":519}}352{"id":"stack-53373101","source":"stackoverflow","questionId":53373101,"title":"Prisma Datamodel: Primary key as a combination of two relational models","tags":["mysql","graphql","prisma"],"text":"Title: Prisma Datamodel: Primary key as a combination of two relational models\nTags: mysql, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI have a problem in Prisma data modeling where I have **to constrain that a user can submit only one review for a product**. I have **following design for the non-constrained situation**.\n\n Should `Customer` and `Product` be combined into a primary key in `ProductReview` model, or should this constraint be imposed at the application server level, and not at the database level?\n\nDatamodel for now (non-constrained version):\n\n```\ntype Product {\n id: ID! @unique\n title: String!\n reviews: [ProductReview!]! @relation(name: \"ProductReviews\", onDelete: CASCADE)\n}\n\ntype Customer {\n id: ID! @unique\n email: String @unique\n}\n\ntype ProductReview {\n id: ID! @unique\n forProduct: Product! @relation(name: \"ProductReviews\", onDelete: SET_NULL)\n byCustomer: Customer!\n review: String!\n ratinng: Float!\n}\n```\n\n========================================\n\nTop Answer:\nPrisma v2 introduced composite primary keys:\n\nhttps://newreleases.io/project/github/prisma/prisma/release/2.0.0-preview023\n\nAn example from that link:\n\n```\nmodel User {\n firstName String\n lastName String\n email String\n\n @@id([firstName, lastName])\n}\n```\n\nSo in the given question example, it is now possible to add to `ProductReview`:\n\n```\n@@id([id, forProduct])\n```\n\n========================================\n\nCode:\n```text\ntype Product {\n id: ID! @unique\n title: String!\n reviews: [ProductReview!]! @relation(name: \"ProductReviews\", onDelete: CASCADE)\n}\n\ntype Customer {\n id: ID! @unique\n email: String @unique\n}\n\ntype ProductReview {\n id: ID! @unique\n forProduct: Product! @relation(name: \"ProductReviews\", onDelete: SET_NULL)\n byCustomer: Customer!\n review: String!\n ratinng: Float!\n}\n```\n\n```text\nCustomer\n```\n\n```text\nProduct\n```\n\n```text\nProductReview\n```\n\n```text\nasync function vote(parent, args, context, info) {\n // 1\n const userId = getUserId(context)\n\n // 2\n const linkExists = await context.db.exists.Vote({\n user: { id: userId },\n link: { id: args.linkId },\n })\n if (linkExists) {\n throw new Error(`Already voted for link: ${args.linkId}`)\n }\n\n // 3\n return context.db.mutation.createVote(\n {\n data: {\n user: { connect: { id: userId } },\n link: { connect: { id: args.linkId } },\n },\n },\n info,\n )\n}\n```\n\n```text\nUser\n```\n\n```text\nLink\n```\n\n```text\nVote\n```\n\n```text\nVote\n```\n\n```text\nALTER TABLE ProductReview ADD UNIQUE KEY uk_cust_prod (customer_id, product_id);\n```\n\n```text\n(cusotmer_id, product_id)\n```\n\n```text\nProductReview\n```\n\n```text\ntype Product {\nid: ID! @unique\n title: String!\n reviews: [ProductReview!]! @relation(name: \"ProductReviews\", onDelete: CASCADE)\n}\n\ntype Customer {\n id: ID! @unique\n email: String @unique\n}\n\ntype ProductReview {\n id: ID! @unique\n forProduct: Product! @relation(name: \"ProductReviews\", onDelete: SET_NULL)\n byCustomer: Customer!\n review: String!\n ratinng: Float!\n UniqueCustomerReview:String! # adding a extra field\n}\n```\n\n```text\nmutation{\ncreateProductReview(\ndata:{\nforProduct: {\"connect\":{\"id\":\"<Replacec_with_product_id>\"}}\nbyCustomer: {\"connect\":{\"email\":\"<Replacec_with_customer_email>\"}}\nreview: \"my product review...\"\nratinng: 5.0\nUniqueCustomerReview:\"loggedInUser@email.com_<Poductid>\" # replace the string with user email and product id. this will create a unique product review for the user alone.\n }\n )\n{\nUniqueCustomerReview\n# ... any requied fields\n}\n }\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nmodel User {\n firstName String\n lastName String\n email String\n\n @@id([firstName, lastName])\n}\n```\n\n```text\n@@id([id, forProduct])\n```\n\n```text\nProductReview\n```\n\n========================================\n\nComments:\n- Thanks @tim, since Prisma doesn't support this, application level check seems the only way. Would you suggest a \"right way\" to handle this there?\n- Hi @nburk, so the idea is to handle this at the application server level for now. Got it! Have raised a feature request with the same body too. Thanks!\n- You should add `@unique` to the `UniqueCustomerReview: String!`","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":220,"estimatedTokens":1040}}353{"id":"stack-43106173","source":"stackoverflow","questionId":43106173,"title":"Is adding an Enum value a breaking change for GraphQL?","tags":["graphql"],"text":"Title: Is adding an Enum value a breaking change for GraphQL?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nAccording to the GraphQL Best Practices, a GraphQL service should the \"common practice of always avoiding breaking changes and serving a versionless API.\"\n\nIs adding a value to an Enum considered a breaking change that should be avoided if following the Best Practices?\n\nTo illustrate this, let's say that the schema has this enum:\n\n```\nenum Episode {\n NEWHOPE\n EMPIRE\n JEDI\n}\n```\n\nIs it bad practice to evolve the enum to be this sometime in the future:\n\n```\nenum Episode {\n NEWHOPE\n EMPIRE\n JEDI\n FORCEAWAKENS\n ROGUEONE\n}\n```\n\n========================================\n\nTop Answer:\nSpecifically, *breaking changes* are changes to schema structure that would cause already-written queries to fail. I couldn't find an exhaustive list online, but here are few example breaking changes:\n\n- Removing a field from an Object type (queries which used that field would become invalid)\n\n- Adding a required argument to a field (queries which used the field *without* that argument would become invalid)\n\n- Changing the return type of a field when the new type is not a supertype of the old type (eg, changing from `Int` to `String`, clients which used that field may have type errors from the new response).\n\nIt's possible that a new enum value could break a client (if it didn't have code to handle the new case, it may have a runtime error), but I think that's a client *design* issue, but not a breaking change to the schema!\n\n========================================\n\nCode:\n```text\nenum Episode {\n NEWHOPE\n EMPIRE\n JEDI\n}\n```\n\n```text\nenum Episode {\n NEWHOPE\n EMPIRE\n JEDI\n FORCEAWAKENS\n ROGUEONE\n}\n```\n\n```text\nfindBreakingChanges\n```\n\n```text\nfindDangerousChanges\n```\n\n```text\nfindDangerousChanges\n```\n\n```text\nInt\n```\n\n```text\nString\n```\n\n========================================\n\nComments:\n- This particular example is not very good, because the schema is clearly poorly designed: there should be an episode entity and references to instances should be returned as IDs (or URIs). I posted a related question, taking as a given that adding a new eum value is a change that breaks clients.\n- @John I disagree. Regardless of how you would have designed your schema, this particular example fulfills its only purpose, which is to clearly illustrate the question that is being asked. The data that is being represented is not the point. Also worth noting is that this particular example is the example enum that the GraphQL docs use: graphql.org/learn/schema/#enumeration-types\n- playing devil's advocate: one of the benefits of enums is that they \"Validate that any arguments of this type are one of the allowed values\". How can a client know what is allowed if it becomes an arbitrary list that can grow? I know the Apollo iOS Client will treat any response with unknown Enum values as an error. I can't think of much else you can do in that situation. Would you expect the client to handle the response differently than that?\n- The first point (argument values are one of the enum values) holds true if you add to an enum: A, B, and C are still valid inputs if you add D to the enum. As for the second point, the alternative is to design the client with a fallback case for when a new enum value appears. I'm not sure which is better!\n- Also, changing a non-null field to nullable\n- FWIW, I believe that Apollo iOS client is now designed with a fallback case as suggested in the comment above.\n- Thanks for putting the effort into this! I know this is an old question, but it finally feels like it has a satisfying answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":95,"estimatedTokens":910}}354{"id":"stack-54367692","source":"stackoverflow","questionId":54367692,"title":"Do GraphQL enum types resolve their values automatically?","tags":["graphql"],"text":"Title: Do GraphQL enum types resolve their values automatically?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nShould I expect enum types to resolve automatically or do the types only exist to limit options?\n\nGiven a GraphQL Schema of the following:\n\n```\ntype Job {\n description: String!\n status: Status!\n}\n\nenum Status {\n PENDING_REVIEW\n PENDING_APPROVAL\n APPROVED\n}\n```\n\nand a query that looks like:\n\n```\nquery job {\n description\n status\n}\n```\n\nIf my database returned the following:\n\n```\n{ \"description\": \"Some irrelevant job description\", \"status\": 1 }\n```\n\nI would expect GraphQL to return:\n\n```\n{ \"description\": \"Some irrelevant job description\", \"status\": \"PENDING_APPROVAL\" }\n```\n\nHave I set something up incorrectly, or is this expected behaviour that will require me to write a resolver for `status`\n\n```\nconst getQuestionStatus = ({ status }) => ['PENDING_REVIEW', 'PENDING_APPROVAL', 'APPROVED'][status];\n```\n\n========================================\n\nTop Answer:\nYes, you need to write a resolver from the enum values to whatever you need, e.g. numbers, per the apollo-server docs for Internal values. Here's how to do this in TypeScript:\n\n```\nexport enum Status {\n DRAFT,\n PENDING,\n APPROVED\n}\n\nconst typeDefs = gql`\n enum Status {\n DRAFT\n PENDING\n APPROVED\n }\n\n type Query {\n echo(status: Status!): Int!\n }\n`;\n\nconst resolvers = {\n Status: {\n DRAFT: Status.DRAFT,\n PENDING: Status.PENDING,\n APPROVED: Status.APPROVED\n },\n\n Query: {\n echo(_, { status }): String {\n console.log(status);\n return status;\n }\n }\n};\n```\n\nHere's a Code Sandbox showing automatic enum parsing and return.\n\nNote though that for default enum values that are query parameters, the behavior is dubious - the resolver may receive the enum value as a string, or `undefined`.\n\n========================================\n\nCode:\n```js\ntype Job {\n description: String!\n status: Status!\n}\n\nenum Status {\n PENDING_REVIEW\n PENDING_APPROVAL\n APPROVED\n}\n```\n\n```js\nquery job {\n description\n status\n}\n```\n\n```js\n{ \"description\": \"Some irrelevant job description\", \"status\": 1 }\n```\n\n```js\n{ \"description\": \"Some irrelevant job description\", \"status\": \"PENDING_APPROVAL\" }\n```\n\n```js\nconst getQuestionStatus = ({ status }) => ['PENDING_REVIEW', 'PENDING_APPROVAL', 'APPROVED'][status];\n```\n\n```text\nstatus\n```\n\n```text\nenum ExampleEnum {\n FOO\n BAR\n}\n```\n\n```text\nconst resolvers = {\n Query: {\n example: () => 11, // field with ExampleEnum type\n },\n ExampleEnum: {\n FOO: 11,\n BAR: 23,\n },\n}\n```\n\n```text\nExampleEnum: {\n FOO: 'FOO',\n BAR: 'BAR',\n}\n```\n\n```text\nconst ExampleEnumType = new GraphQLEnumType({\n name: 'ExampleEnum',\n values: {\n FOO: {\n value: 11,\n },\n BAR: {\n value: 23,\n },\n },\n})\n```\n\n```text\nFOO\n```\n\n```text\n\"FOO\"\n```\n\n```text\ngraphql-tools\n```\n\n```text\napollo-server\n```\n\n```text\ngraphql-tools\n```\n\n```text\nFOO\n```\n\n```text\n11\n```\n\n```text\n\"FOO\"\n```\n\n```text\n\"BAR\"\n```\n\n```text\nApollo Server\n```\n\n```text\n1\n```\n\n```text\nApollo Server\n```\n\n```text\nPENDING_APPROVAL\n```\n\n```text\nAPPROVED\n```\n\n```js\nexport enum Status {\n DRAFT,\n PENDING,\n APPROVED\n}\n\nconst typeDefs = gql`\n enum Status {\n DRAFT\n PENDING\n APPROVED\n }\n\n type Query {\n echo(status: Status!): Int!\n }\n`;\n\nconst resolvers = {\n Status: {\n DRAFT: Status.DRAFT,\n PENDING: Status.PENDING,\n APPROVED: Status.APPROVED\n },\n\n Query: {\n echo(_, { status }): String {\n console.log(status);\n return status;\n }\n }\n};\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- What about default enum values? My tests showed that the resolver receives either the enum as a string, or `undefined`.","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":271,"estimatedTokens":913}}355{"id":"stack-53878566","source":"stackoverflow","questionId":53878566,"title":"how to make a case-insensitive graphql query?","tags":["graphql"],"text":"Title: how to make a case-insensitive graphql query?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nUsing GraphQL to fetch and parse a config file, sometimes the file name be `podfile`, sometimes be `Podfile`, so I am wondering how to make a case-insensitive query? \n\nnow I only can query repository->object: podfile and Podfile, but if the file name be `podFILE`, again not works.\n\n```\nquery($org_name: String!, $resp_name: String!)\n {\n repository(owner: $org_name name: $resp_name){\n object: object(expression: \"%s:proj.ios_mac/podfile\"){\n ... on Blob{\n text\n }\n }\n ios_object_1: object(expression: \"%s:proj.ios_mac/Podfile\"){\n ... on Blob{\n text\n }\n }\n }\n }\n```\n\nREF:https://github.community/t5/How-to-use-Git-and-GitHub/graphql-api-resource-query-is-case-sensitive/m-p/6003\n\n========================================\n\nTop Answer:\n```\n_similar: \"%key%\" performs Case sensitive query\n_ilike: \"%key%\" performs case insensitive query\n```\n\nFor Eg : Below query will return all devices with name contains iphone. It fails to return objects if name contains \"iPhone\" i.e. the query is case sensitive.\n\n```\nquery MyQuery {\n devices: devices(where: {name: { _similar: \"%iphone%\"}}) {\n name\n }\n}\n```\n\nBelow query will return all objects with name containing \"iphone\", \"IPhone\". i.e. case insensitive\n\n```\nquery MyQuery {\n devices: devices(where: {name: { _ilike: \"%iphone%\"}}) {\n name\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery($org_name: String!, $resp_name: String!)\n {\n repository(owner: $org_name name: $resp_name){\n object: object(expression: \"%s:proj.ios_mac/podfile\"){\n ... on Blob{\n text\n }\n }\n ios_object_1: object(expression: \"%s:proj.ios_mac/Podfile\"){\n ... on Blob{\n text\n }\n }\n }\n }\n```\n\n```text\npodfile\n```\n\n```text\nPodfile\n```\n\n```text\npodFILE\n```\n\n```text\nquery MyQuery {\n heroes(where: {name: {_ilike: \"%baTmaN%\"}}) {name, movie }\n}\n```\n\n```text\n_ilike\n```\n\n```text\n_similar: \"%key%\" performs Case sensitive query\n_ilike: \"%key%\" performs case insensitive query\n```\n\n```text\nquery MyQuery {\n devices: devices(where: {name: { _similar: \"%iphone%\"}}) {\n name\n }\n}\n```\n\n```text\nquery MyQuery {\n devices: devices(where: {name: { _ilike: \"%iphone%\"}}) {\n name\n }\n}\n```\n\n```text\nquery MyQuery {\n posts (\n filters: { name : { eqi: \"my post\"}}\n ) { ... }\n}\n```\n\n```text\nquery MyQuery {\n posts (\n filters: { name : { containsi: \"my \"}}\n ) { ... }\n}\n```\n\n```text\nconst users = await prisma.user.findMany({\n where: {\n email: {\n endsWith: 'prisma.io',\n mode: 'insensitive'\n },\n },\n})\n```\n\n```text\nmode\n```\n\n```text\ninsensitive\n```\n\n========================================\n\nComments:\n- The spec url doesn't work anymore, here is the update for 2019: graphql.github.io/graphql-spec/June2018/#sec-Names\n- please add bit of elaboration, it will help understand it clearly.\n- @MobileEvangelist have elaborated\n- _ilike this answer ;-)","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":163,"estimatedTokens":889}}356{"id":"stack-52034752","source":"stackoverflow","questionId":52034752,"title":"What is the point of GraphQL's ID Scalar?","tags":["graphql"],"text":"Title: What is the point of GraphQL's ID Scalar?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nhttps://graphql.org/learn/schema/#scalar-types\n\nI have read the description\n\n **`ID`**: The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialized in the same way as a String; however, defining it as an **`ID`** signifies that it is not intended to be humanβreadable.\n\nBut in practice, what actually changes if I use `ID` instead of `String` ?\n\n========================================\n\nCode:\n```text\nID\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n```text\nString\n```\n\n```text\nID\n```\n\n```text\nString\n```\n\n```text\nID\n```\n\n```text\nString\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":47,"estimatedTokens":177}}357{"id":"stack-56416447","source":"stackoverflow","questionId":56416447,"title":"Apollo Server Slow Performance when resolving large data","tags":["graphql","apollo-server"],"text":"Title: Apollo Server Slow Performance when resolving large data\nTags: graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nWhen resolving large data I notice a very slow performance, from the moment of returning the result from my resolver to the client.\n\nI assume `apollo-server` iterates over my result and checks the types... either way, the operation takes too long. \n\nIn my product I have to return large amount of data all at once, since its being used, all at once, to draw a chart in the UI. There is no pagination option for me where I can slice the data.\n\nI suspect the slowness coming from `apollo-server` and not my resolver object creation.\n\nNote, that I log the time the resolver takes to create the object, its fast, and not the bottle neck.\n\nLater operations performed by `apollo-server`, which I dont know how to measure, takes a-lot of time.\n\nNow, I have a version, where I return a custom scalar type JSON, the response, is much much faster. But I really prefer to return my `Series` type.\n\nI measure the difference between the two types (`Series` and `JSON`) by looking at the network panel.\n\nwhen AMOUNT is set to 500, and the type is `Series`, it takes ~1.5s (that is seconds)\n\nwhen AMOUNT is set to 500, and the type is `JSON`, it takes ~150ms (fast!)\n\nwhen AMOUNT is set to 1000, and the type is `Series`, its very slow...\n\nwhen AMOUNT is set to 10000, and the type is `Series`, I'm getting JavaScript heap out of memory (which is unfortunately what we experience in our product)\n\nI've also compared `apollo-server` performance to `express-graphql`, the later works faster, yet still not as fast as returning a custom scalar JSON.\n\nwhen AMOUNT is set to 500, `apollo-server`, network takes 1.5s\n\nwhen AMOUNT is set to 500, `express-graphql`, network takes 800ms\n\nwhen AMOUNT is set to 1000, `apollo-server`, network takes 5.4s\n\nwhen AMOUNT is set to 1000, `express-graphql`, network takes 3.4s\n\nThe Stack:\n\n```\n\"dependencies\": {\n \"apollo-server\": \"^2.6.1\",\n \"graphql\": \"^14.3.1\",\n \"graphql-type-json\": \"^0.3.0\",\n \"lodash\": \"^4.17.11\"\n}\n```\n\nThe Code:\n\n```\nconst _ = require(\"lodash\");\nconst { performance } = require(\"perf_hooks\");\nconst { ApolloServer, gql } = require(\"apollo-server\");\nconst GraphQLJSON = require('graphql-type-json');\n\n// The GraphQL schema\nconst typeDefs = gql`\n scalar JSON\n\n type Unit {\n name: String!\n value: String!\n }\n\n type Group {\n name: String!\n values: [Unit!]!\n }\n\n type Series {\n data: [Group!]!\n keys: [Unit!]!\n hack: String\n }\n\n type Query {\n complex: Series\n }\n`;\n\nconst AMOUNT = 500;\n\n// A map of functions which return data for the schema.\nconst resolvers = {\n Query: {\n complex: () => {\n let before = performance.now();\n\n const result = {\n data: _.times(AMOUNT, () => ({\n name: \"a\",\n values: _.times(AMOUNT, () => (\n {\n name: \"a\",\n value: \"a\"\n }\n )),\n })),\n keys: _.times(AMOUNT, () => ({\n name: \"a\",\n value: \"a\"\n }))\n };\n\n let after = performance.now() - before;\n\n console.log(\"resolver took: \", after);\n\n return result\n }\n }\n};\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers: _.assign({ JSON: GraphQLJSON }, resolvers),\n});\n\nserver.listen().then(({ url }) => {\n console.log(`π Server ready at ${url}`);\n});\n```\n\nThe gql Query for the Playground (for type Series):\n\n```\nquery {\n complex {\n data {\n name\n values {\n name\n value\n }\n }\n keys {\n name\n value\n }\n }\n}\n```\n\nThe gql Query for the Playground (for custom scalar type JSON):\n\n```\nquery {\n complex\n}\n```\n\nHere is a working example:\n\nhttps://codesandbox.io/s/apollo-server-performance-issue-i7fk7\n\nAny leads/ideas would be highly appreciated!\n\n========================================\n\nTop Answer:\n**Comment summary**\n\nThis data structure/types:\n\n- are not individual entities;\n\n- just a series of [groupped] data;\n\n- don't need normalization;\n\n- won't be normalized properly in apollo cache (no `id` fields);\n\nThis way **this dataset is not the graphQL was designed for.** Of course graphQL still can be used for fetching this data but type parsing/matching should be disabled. \n\nUsing custom scalar types (`graphql-type-json`) can be a solution. If you need some hybrid solution - you can type `Group.values` as json (instead entire `Series`). Groups still should have an `id` field if you want to use normalized cache [access].\n\n### Alternative\n\nYou can use `apollo-link-rest` for fetching 'pure' json data (file) leaving type parsing/matching to be client side only.\n\n### More advanced alternative\n\nIf you want to use one graphql endpoint ...\nwrite own link - use directives - 'ask for json, get typed' - mix of two above. Sth like in rest link with de-/serializers.\n\nIn both alternatives - **why do you really need it?** Just for drawing? Not worth the effort. No pagination but hopefully streaming (live updates?) ... no cursors ... load more (subscriptions/polling) by ... last time update? Doable but 'not feel right'.\n\n========================================\n\nCode:\n```text\n\"dependencies\": {\n \"apollo-server\": \"^2.6.1\",\n \"graphql\": \"^14.3.1\",\n \"graphql-type-json\": \"^0.3.0\",\n \"lodash\": \"^4.17.11\"\n}\n```\n\n```text\nconst _ = require(\"lodash\");\nconst { performance } = require(\"perf_hooks\");\nconst { ApolloServer, gql } = require(\"apollo-server\");\nconst GraphQLJSON = require('graphql-type-json');\n\n// The GraphQL schema\nconst typeDefs = gql`\n scalar JSON\n\n type Unit {\n name: String!\n value: String!\n }\n\n type Group {\n name: String!\n values: [Unit!]!\n }\n\n type Series {\n data: [Group!]!\n keys: [Unit!]!\n hack: String\n }\n\n type Query {\n complex: Series\n }\n`;\n\nconst AMOUNT = 500;\n\n// A map of functions which return data for the schema.\nconst resolvers = {\n Query: {\n complex: () => {\n let before = performance.now();\n\n const result = {\n data: _.times(AMOUNT, () => ({\n name: \"a\",\n values: _.times(AMOUNT, () => (\n {\n name: \"a\",\n value: \"a\"\n }\n )),\n })),\n keys: _.times(AMOUNT, () => ({\n name: \"a\",\n value: \"a\"\n }))\n };\n\n let after = performance.now() - before;\n\n console.log(\"resolver took: \", after);\n\n return result\n }\n }\n};\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers: _.assign({ JSON: GraphQLJSON }, resolvers),\n});\n\nserver.listen().then(({ url }) => {\n console.log(`π Server ready at ${url}`);\n});\n```\n\n```text\nquery {\n complex {\n data {\n name\n values {\n name\n value\n }\n }\n keys {\n name\n value\n }\n }\n}\n```\n\n```text\nquery {\n complex\n}\n```\n\n```text\napollo-server\n```\n\n```text\napollo-server\n```\n\n```text\napollo-server\n```\n\n```text\nSeries\n```\n\n```text\nSeries\n```\n\n```text\nJSON\n```\n\n```text\nSeries\n```\n\n```text\nJSON\n```\n\n```text\nSeries\n```\n\n```text\nSeries\n```\n\n```text\napollo-server\n```\n\n```text\nexpress-graphql\n```\n\n```text\napollo-server\n```\n\n```text\nexpress-graphql\n```\n\n```text\napollo-server\n```\n\n```text\nexpress-graphql\n```\n\n```text\nid\n```\n\n```text\ngraphql-type-json\n```\n\n```text\nGroup.values\n```\n\n```text\nSeries\n```\n\n```text\nid\n```\n\n```text\napollo-link-rest\n```\n\n========================================\n\nComments:\n- not graphql related - you're testing only node js performance (object creation) - this way you can even dig cryptocurrency in resolver and blame graphql\n- @xadm I dont think it is graphql related either, I did not say that. I think it is related to the following operation of `apollo-server` (regardless of it being a gql lib, if that helps) after I create the object in my resolver. My object creation is fast, what happens next is slow, up to out of memory heap... I think my stringify example proves it. My question is how to overcome this limit?\n- you didn't provide overal process results vs logged object creation time ... question is: do you really need all this nested data **at once** ... client cache will normalize it taking a lot of time, too\n- @xadm I dont know how to measure the overall process result, since it happens inside apollo-server internal code, I believe. I did measure my resolver object creation time which I am logging, as I wrote, you can see it in the example. The other thing I was able to measure is the network time, and the different results when I stringify the object and not. Regarding if I need it all at once, well right now yes, it is part of UI graph I draw on the client, or a table with many columns. There is no pagination option that may allow me to fetch parts unfortunately.\n- probably you don't need small granular data - you can use custom scalar types to return entire series as one object - if really need detailed granulation you can do it later, client side only\n- I would be interested in streaming or deferring, eventually, but those are not yet supported.\n- you can use subscriptions, polling\n- @xadm custom scalar JSON is a better solution then my stringify hack, also as fast. Still does not feel right, as I loose much of the gql concept along the way.\n- @sergelerner I have no answer but we are running into similar issues. Would like to ask, what do you consider \"large data\"? How many documents are you querying? I mean not returning but what is the db size... Approximately... Thanks.\n- what do you mean by \"this dataset is not the graphQL was designed for\"? would be happy to understand more. thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":401,"estimatedTokens":2323}}358{"id":"stack-40124494","source":"stackoverflow","questionId":40124494,"title":"Custom Error Object with Apollo Server","tags":["javascript","ecmascript-6","graphql","apollo-server"],"text":"Title: Custom Error Object with Apollo Server\nTags: javascript, ecmascript-6, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use a custom error with apollo-server and it seems that my custom error has a property (`code`) that isn't available from within `formatError`.\n\n```\nimport ExtendableError from 'es6-error'\n\nexport default class MyError extends ExtendableError {\n constructor(args) {\n let code = Object.keys(args)[0]\n let message = Object.values(args)[0]\n super(message)\n this.code = code\n }\n}\n```\n\nI have a simple error handler works something like this:\n\n```\nlet INVALIDREQUEST = 'invalid request'\nlet e = new MyError({INVALIDREQUEST})\nconsole.log(e.code) // => \"INVALIDREQUEST\"\n```\n\nI'm having trouble because when I log `error.code` from within `formatError` it's not available.\n\n```\nformatError: function (error) {\n console.log(error.code) // => undefined\n return error\n}\n```\n\nHow can I propagate custom properties (like `code`) of `error` from within `formatError`?\n\n========================================\n\nTop Answer:\nWith Apollo, you can easily multiplex the errors array in the graphql response for both graphql errors AND custom errors that are machine readable using this package:\n\nhttps://github.com/thebigredgeek/apollo-errors\n\n========================================\n\nCode:\n```text\nimport ExtendableError from 'es6-error'\n\nexport default class MyError extends ExtendableError {\n constructor(args) {\n let code = Object.keys(args)[0]\n let message = Object.values(args)[0]\n super(message)\n this.code = code\n }\n}\n```\n\n```text\nlet INVALIDREQUEST = 'invalid request'\nlet e = new MyError({INVALIDREQUEST})\nconsole.log(e.code) // => \"INVALIDREQUEST\"\n```\n\n```text\nformatError: function (error) {\n console.log(error.code) // => undefined\n return error\n}\n```\n\n```text\ncode\n```\n\n```text\nformatError\n```\n\n```text\nerror.code\n```\n\n```text\nformatError\n```\n\n```text\ncode\n```\n\n```text\nerror\n```\n\n```text\nformatError\n```\n\n```text\nformatError: function (error) {\n console.log(error.originalError.code)\n return error\n}\n```\n\n```text\nformatError\n```\n\n```text\npath\n```\n\n```text\npositions\n```\n\n```text\nsource\n```\n\n```text\noriginalError\n```\n\n```text\nerror\n```\n\n```text\nformatError\n```\n\n```text\nthrow new ApolloError('User already exist',\n 'DUPLICATE',\n { 'session': session })\n```\n\n========================================\n\nComments:\n- why node log is different from graphiql? in graphiql i can see the states when i add in formaterror: error.state = error.originalError; but in node console i see just: GraphQLError ( .. at locatedError ..) path, positions, and source. can I see in the console on node, my state property?\n- Throwing ANY `ApolloeError` or a subclass thereof will always strip the message and insert `Unexpected error value: { extensions: { code: }}` instead of *actually just passing up the error or presenting the error as thrown.* The message is *always* omitted, which defeats the whole process of using ApolloError type if `formatError` always destroys what you actually want to throw.","metadata":{"transformedAt":"2026-08-18T18:32:36.051Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":149,"estimatedTokens":775}}359{"id":"stack-48340191","source":"stackoverflow","questionId":48340191,"title":"Which syntax for filtering queries in Graphiql?","tags":["filter","graphql","graphiql"],"text":"Title: Which syntax for filtering queries in Graphiql?\nTags: filter, graphql, graphiql\nSource: Stack Overflow\n\nQuestion:\nNew to graphql and started playing with graphiql.\nI have a Product data type\n\n```\ntype Product {\n _id: String\n name: String\n price: Float\n }\n```\n\nI have mongodb populated with some products\n\n```\n{ \"_id\" : ObjectId(\"5a61b31e009c0bef5d724a47\"), \"name\" : \"GROUND COFFEE\", \"price\" : 3.06 }\n{ \"_id\" : ObjectId(\"5a61b31e009c0bef5d724a48\"), \"name\" : \"PORK SAUSAGES 500g\", \"price\" : 4.39 }\n{ \"_id\" : ObjectId(\"5a61b31e009c0bef5d724a49\"), \"name\" : \"MILK UHT 1LT\", \"price\" : 1.29 }\n{ \"_id\" : ObjectId(\"5a61b31e009c0bef5d724a4a\"), \"name\" : \"HEINEKEN PREMIUM LIGHT 33CL\", \"price\" : 1.61 }\n```\n\nIn graphiql I can execute a query like this\n\n```\nquery {\n products{\n name,\n price\n }\n}\n\nQuery result is\n\n{\n \"data\": {\n \"products\": [\n { \"name\" : \"GROUND COFFEE\", \"price\" : 3.06 },\n { \"name\" : \"PORK SAUSAGES 500g\", \"price\" : 4.39 },\n { \"name\" : \"MILK UHT 1LT\", \"price\" : 1.29 },\n { \"name\" : \"HEINEKEN PREMIUM LIGHT 33CL\", \"price\" : 1.61 }\n ]\n }\n}\n```\n\nWow, that's fine.\nSo next step is: now I want only products with price greater than 2.0\nAnd I face two problems I do not know how to solve\n\n1) Which is the correct syntax to implement filtering?\n\n2) How comparison operators have to be specified? And how this specification maps to mongodb comparison operators?\n\nI tried with\n\n```\nquery {\n products(filter:{price: {gt:2.0} }){\n name,\n price\n }\n}\n```\n\nbut I get an error for \"filter\":\n\nUnknown argument \"filter\" on field \"products\" of type \"Query\".\nI find no way to do this ...\n\n**UPDATE**\n@diego\n\n```\nconst typeDefs = [`\n type Query {\n product(_id: String): Product\n products: [Product]\n }\n\n type Product {\n _id: String\n name: String\n price: Float\n }\n\n type Mutation {\n createProduct(name: String, price: Float): Product\n }\n\n schema {\n query: Query\n mutation: Mutation\n }\n`];\n\nconst resolvers = {\n Query: {\n product: async (root, {_id}) => {\n return prepare(await Products.findOne(ObjectId(_id)))\n },\n products: async () => {\n return (await Products.find({}).toArray()).map(prepare)\n },\n },\n Mutation: {\n createProduct: async (root, args, context, info) => {\n const res = await Products.insert(args)\n return prepare(await Products.findOne({_id: res.insertedIds[1]}))\n },\n },\n}\n```\n\n========================================\n\nCode:\n```text\ntype Product {\n _id: String\n name: String\n price: Float\n }\n```\n\n```text\n{ \"_id\" : ObjectId(\"5a61b31e009c0bef5d724a47\"), \"name\" : \"GROUND COFFEE\", \"price\" : 3.06 }\n{ \"_id\" : ObjectId(\"5a61b31e009c0bef5d724a48\"), \"name\" : \"PORK SAUSAGES 500g\", \"price\" : 4.39 }\n{ \"_id\" : ObjectId(\"5a61b31e009c0bef5d724a49\"), \"name\" : \"MILK UHT 1LT\", \"price\" : 1.29 }\n{ \"_id\" : ObjectId(\"5a61b31e009c0bef5d724a4a\"), \"name\" : \"HEINEKEN PREMIUM LIGHT 33CL\", \"price\" : 1.61 }\n```\n\n```text\nquery {\n products{\n name,\n price\n }\n}\n\nQuery result is\n\n{\n \"data\": {\n \"products\": [\n { \"name\" : \"GROUND COFFEE\", \"price\" : 3.06 },\n { \"name\" : \"PORK SAUSAGES 500g\", \"price\" : 4.39 },\n { \"name\" : \"MILK UHT 1LT\", \"price\" : 1.29 },\n { \"name\" : \"HEINEKEN PREMIUM LIGHT 33CL\", \"price\" : 1.61 }\n ]\n }\n}\n```\n\n```text\nquery {\n products(filter:{price: {gt:2.0} }){\n name,\n price\n }\n}\n```\n\n```text\nconst typeDefs = [`\n type Query {\n product(_id: String): Product\n products: [Product]\n }\n\n type Product {\n _id: String\n name: String\n price: Float\n }\n\n type Mutation {\n createProduct(name: String, price: Float): Product\n }\n\n schema {\n query: Query\n mutation: Mutation\n }\n`];\n\nconst resolvers = {\n Query: {\n product: async (root, {_id}) => {\n return prepare(await Products.findOne(ObjectId(_id)))\n },\n products: async () => {\n return (await Products.find({}).toArray()).map(prepare)\n },\n },\n Mutation: {\n createProduct: async (root, args, context, info) => {\n const res = await Products.insert(args)\n return prepare(await Products.findOne({_id: res.insertedIds[1]}))\n },\n },\n}\n```\n\n```text\nproducts(filter: String): [Product]\n```\n\n```text\nproducts: async (_, {filter}) => {\n const query = JSON.parse(filter)\n return (await Products.find(query).toArray()).map(prepare)\n}\n```\n\n```text\nquery {\n products(filter: \"{\\\"price\\\": {\\\"gt\\\":2.0} }\") {\n name,\n price\n }\n}\n```\n\n========================================\n\nComments:\n- AFAIK, you should have a query defined in GraphQL that accepts a filter and uses it to filter mongo results. Can you show the resolver for `products`?\n- Ok, now it works (change gt to $gt). Anyway both resolver and query language depend on the backend used. Is there any way to avoid this?","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":232,"estimatedTokens":1162}}360{"id":"stack-54329598","source":"stackoverflow","questionId":54329598,"title":"Apollo Client: Variable is not defined. Received status code 400","tags":["node.js","graphql","apollo-client"],"text":"Title: Apollo Client: Variable is not defined. Received status code 400\nTags: node.js, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use dynamic variable in a GraphQL query using Apollo Client. I have followed the documentation, but Apollo keeps giving me errors, saying that my variables are not defined, and ultimately responding with status code 400.\n\nHere is what the documentation for Apollo said:\n\n mutate: (options?: MutationOptions) => Promise\n A function to trigger a mutation from your UI. You can optionally pass variables, optimisticResponse, refetchQueries, and update in as options, which will override any props passed to the Mutation component. The function returns a promise that fulfills with your mutation result.\n\nAnd here is the code I tried to write:\n\n```\nconst fetch = require('node-fetch');\nconst ApolloClient = require('apollo-boost').default;\nconst gql = require('graphql-tag');\n\nconst client = new ApolloClient({\n uri: \"http://api.domain.com/graphql\",\n fetch\n});\n\nrun();\n\nasync function run() {\n try {\n const resp = await client.mutate({\n mutation: gql`mutation {\n trackPr(id: $id, pr: $pr, title: $title, body: $body, state: $state, merged: $merged) {\n id\n }\n }`,\n variables: {\n id: 1,\n pr: 1,\n title: \"test title\",\n body: \"test body\",\n state: \"test state\",\n merged: false\n },\n });\n\n console.log(resp.data);\n } catch(ex) {\n console.log(ex);\n }\n}\n```\n\nI'll then get a error message for each variable saying it has not been defined:\n\n [GraphQL error]: Message: Variable \"$id\" is not defined., Location: [object Object],[object Object], Path: undefined\n\nAfter each of these error messages, I then get a final message with status code 400:\n\n [Network error]: ServerError: Response not successful: Received status code 400\n\nThe mutation itself runs fine without the variables and all the values set directly in the mutation, but I don't know why it thinks the variables are not defined.\n\n========================================\n\nCode:\n```text\nconst fetch = require('node-fetch');\nconst ApolloClient = require('apollo-boost').default;\nconst gql = require('graphql-tag');\n\nconst client = new ApolloClient({\n uri: \"http://api.domain.com/graphql\",\n fetch\n});\n\nrun();\n\nasync function run() {\n try {\n const resp = await client.mutate({\n mutation: gql`mutation {\n trackPr(id: $id, pr: $pr, title: $title, body: $body, state: $state, merged: $merged) {\n id\n }\n }`,\n variables: {\n id: 1,\n pr: 1,\n title: \"test title\",\n body: \"test body\",\n state: \"test state\",\n merged: false\n },\n });\n\n\n console.log(resp.data);\n } catch(ex) {\n console.log(ex);\n }\n}\n```\n\n```text\nmutation SomeOptionalMutationName ($id: ID!) {\n trackPr(id: $id) {\n id\n }\n}\n```\n\n========================================\n\nComments:\n- graphql.org/learn/queries/#variables\n- HI! Having same issue, just checked that declaration, over and over again, but I'm not able to notice where the bug is. I use apollo client from react js that calls my graphql mutations, when sending request, packets contain correct payload with correct variables, my mutation object contains the corresponding args but the response is always this {\"errors\":[{\"message\": \"isEnable is not defined\",\"locations\": [{\"line\": 2,\"column\": 3}],\"path\": [\"addItem\"]}],\"data\": {\"addItem\": null}}","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":115,"estimatedTokens":873}}361{"id":"stack-48693825","source":"stackoverflow","questionId":48693825,"title":"Making a graphQL mutation from my python code, getting error","tags":["python","python-requests","graphql","parse-error","express-graphql"],"text":"Title: Making a graphQL mutation from my python code, getting error\nTags: python, python-requests, graphql, parse-error, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to make a mutation to my Shopify store from python.\nI am new to graphQL, I have been able to make the mutation using graphiQL but I am not certain how to do it directly from my code.\n\nThis is my make query file, it has worked successfully for a simple query\n\n```\n`import requests \n def make_query(self, query, url, headers):\n \"\"\"\n Return query response\n \"\"\"\n request = requests.post(url, json={'query': query}, headers=headers)\n if request.status_code == 200:\n return request.json()\n else:\n raise Exception(\"Query failed to run by returning code of {}. {}\".format(request.status_code, query))`\n```\n\nNow an example of the mutation that worked in graphiQL is this:\n\n`\"mutation {customerCreate(input: {email: 'wamblamkazam@send22u.info', password: 'password'}) {userErrors { field message}customer{id}}}\"`\n\nBut when I pass it into my make_query function it gives this error\n\n```\n{'errors': [{'message': 'Parse error on \"\\'\" (error) at [1, 41]', 'locations': [{'line': 1, 'column': 41}]}]}\n```\n\nHow do I fix this?\nAlso one of the mutations I am making uses variables, and I haven't been able to find an example of how to do this directly from my code\n\n========================================\n\nTop Answer:\nI tracked the mutation request through my browser and copied exactly the json that was being sent, removing the line breaks. In the code I added { \"query\": json } and it worked\n\nExample I used sending 2 parameters and receiving a token:\n\n```\nmutation = \"\"\"mutation { \n login( username: \"myusername\", password: \"mypassword\", ) \n { \n token \n }\n }\"\"\"\n \nres = requests.post(url, json={\"query\": mutation} )\n```\n\n========================================\n\nCode:\n```text\n`import requests \n def make_query(self, query, url, headers):\n \"\"\"\n Return query response\n \"\"\"\n request = requests.post(url, json={'query': query}, headers=headers)\n if request.status_code == 200:\n return request.json()\n else:\n raise Exception(\"Query failed to run by returning code of {}. {}\".format(request.status_code, query))`\n```\n\n```text\n{'errors': [{'message': 'Parse error on \"\\'\" (error) at [1, 41]', 'locations': [{'line': 1, 'column': 41}]}]}\n```\n\n```text\n\"mutation {customerCreate(input: {email: 'wamblamkazam@send22u.info', password: 'password'}) {userErrors { field message}customer{id}}}\"\n```\n\n```text\ndef make_query(self, query, variables, url, headers):\n \"\"\"\n Make query response\n \"\"\"\n request = request.post(url, json={'query': query, 'variables': variables}, headers=headers)\n if request.status_code == 200:\n return request.json()\n else:\n raise Exception(\"Query failed to run by returning code of {}. {}\".format(request.status_code, query))\n```\n\n```text\nquery = \"\"\"\n mutation CreateCustomer($input:CustomerInput){\n customerCreate(customerData: $input){\n customer{\n name\n }\n }\n }\n\"\"\"\nvariables = {'input': customer}\n```\n\n```text\nclient = GraphQLClient('http://127.0.0.1:5000/graphql')\n\nquery = \"\"\"\nmutation CreateCustomer($input:CustomerInput){\n customerCreate(customerData: $input){\n customer{\n name\n }\n }\n}\n\"\"\"\n\nvariables = {'input': customer}\n\nclient.execute(query, variables)\n```\n\n```text\nmutation = \"\"\"mutation { \n login( username: \"myusername\", password: \"mypassword\", ) \n { \n token \n }\n }\"\"\"\n \nres = requests.post(url, json={\"query\": mutation} )\n```\n\n========================================\n\nComments:\n- Try double quotes (\") instead of single quotes for your strings, email and password.\n- Same issue. Queries work but not mutations and i've tried naming the mutation and still same syntax error. Wondering if the requests lib is doing something funny with the string passed as the val.\n- what library is it?\n- @Ricky This answer features `graphqlclient` you can find it here: pypi.org/project/graphqlclient","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":139,"estimatedTokens":1020}}362{"id":"stack-57777853","source":"stackoverflow","questionId":57777853,"title":"Why WebStorm show errors in gql query inside apollo object in Vue component or .grapgql files","tags":["javascript","vue.js","graphql","webstorm","vue-apollo"],"text":"Title: Why WebStorm show errors in gql query inside apollo object in Vue component or .grapgql files\nTags: javascript, vue.js, graphql, webstorm, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI have a problem with WebStorm syntax highlighting. I created valid GraphQL query which works on localhost app but WebStorm says that \n\n unknown field \"familyMembers\" on object type \"Query\"\n\nand highlights the whole query in red.\n\nI am really confused but maybe I should change something inside `apollo.config.js` - if yes please tell me what.\n\nHelloWorld.vue\n\n```\n\nimport gql from 'graphql-tag';\nexport default {\n apollo: {\n familyMembers: gql `\n query familyMembers {\n familyMembers {\n id\n firstName\n lastName\n }\n }`\n },\n name: 'HelloWorld',\n props: {\n msg: String\n }\n}\n\n```\n\napollo.config.js\n\n```\nmodule.exports = {\n client: {\n service: {\n name: 'vav',\n // URL to the GraphQL API\n url: 'http://localhost:4000',\n },\n // Files processed by the extension\n includes: [\n 'src/**/*.vue',\n 'src/**/*.js',\n ],\n },\n};\n```\n\nSome screenshots:\n\nhttps://i.sstatic.net/zupB7.png\n\nhttps://i.sstatic.net/IzdWr.png\n\n========================================\n\nCode:\n```text\n<script>\nimport gql from 'graphql-tag';\nexport default {\n apollo: {\n familyMembers: gql `\n query familyMembers {\n familyMembers {\n id\n firstName\n lastName\n }\n }`\n },\n name: 'HelloWorld',\n props: {\n msg: String\n }\n}\n</script>\n```\n\n```text\nmodule.exports = {\n client: {\n service: {\n name: 'vav',\n // URL to the GraphQL API\n url: 'http://localhost:4000',\n },\n // Files processed by the extension\n includes: [\n 'src/**/*.vue',\n 'src/**/*.js',\n ],\n },\n};\n```\n\n```text\napollo.config.js\n```\n\n```text\n{\n \"name\": \"Untitled GraphQL Schema\",\n \"schemaPath\": \"schema.graphql\",\n \"extensions\": {\n \"endpoints\": {\n \"Default GraphQL Endpoint\": {\n \"url\": \"http://localhost:4000\",\n \"headers\": {\n \"user-agent\": \"JS GraphQL\"\n },\n \"introspect\": false\n }\n }\n }\n}\n```\n\n```text\napollo.config.js\n```\n\n========================================\n\nComments:\n- Where did you put this `schema.graphql` file and what is the contents of it?\n- @martins16321 you have to create this file in the root of your project. I have also added integration docs to vue-appolo documentation. You can take a look on that: apollo.vuejs.org/guide/installation.html#webstorm\n- is there an example of what the `schema.graphql` file needs to look like? What content do I put inside of it?\n- Check GraphQL docs: graphql.org/learn/schema","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":137,"estimatedTokens":662}}363{"id":"stack-62271614","source":"stackoverflow","questionId":62271614,"title":"What does TypeError, __init__() missing 1 required positional argument: 'get_response' mean in python?","tags":["python","django","graphql"],"text":"Title: What does TypeError, __init__() missing 1 required positional argument: 'get_response' mean in python?\nTags: python, django, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm following the graphql python tutorial at https://www.howtographql.com/graphql-python/4-authentication/. It worked fine for the first 3 sections, but in the Authentication section I've run into this problem.\n\nI am learning python, don't know Django or graphql, so it's a lot to digest all at once, but it was going ok until now. Also not sure what relevant bits to include here.\n\nI followed all the instructions. When I go to my local project site at `localhost:8000/graphql/`, I get \n\n`TypeError at /graphql/`\n\n`__init__() missing 1 required positional argument: 'get_response'`\n\nHere is the relevant snippet of my settings.py:\n\n```\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n]\n\nGRAPHENE = {\n 'SCHEMA': 'hackernews.schema.schema',\n 'MIDDLEWARE': ['graphql_jwt.middleware.JSONWebTokenMiddleware', ],\n}\n\nAUTHENTICATION_BACKENDS = [\n 'graphql_jwt.backends.JSONWebTokenBackend',\n 'django.contrib.auth.backends.ModelBackend',\n]\n```\n\nI also did import graphql_jwt in my main schema.py \n\nHere is some kind of stack trace\n\n```\nEnvironment:\n\nRequest Method: GET\nRequest URL: http://localhost:8000/graphql/\n\nDjango Version: 2.1.4\nPython Version: 3.7.4\nInstalled Applications:\n['django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'graphene_django',\n 'links']\nInstalled Middleware:\n['django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware']\n\nTraceback:\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\core\\handlers\\exception.py\" in inner\n 34. response = get_response(request)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\core\\handlers\\base.py\" in _get_response\n 126. response = self.process_exception_by_middleware(e, request)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\core\\handlers\\base.py\" in _get_response\n 124. response = wrapped_callback(request, *callback_args, **callback_kwargs)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\views\\decorators\\csrf.py\" in wrapped_view\n 54. return view_func(*args, **kwargs)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\views\\generic\\base.py\" in view\n 62. self = cls(**initkwargs)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\graphene_django\\views.py\" in __init__\n 88. self.middleware = list(instantiate_middleware(middleware))\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\graphene_django\\views.py\" in instantiate_middleware\n 48. yield middleware()\n\nException Type: TypeError at /graphql/\nException Value: __init__() missing 1 required positional argument: 'get_response'\n```\n\n========================================\n\nTop Answer:\nupgrade django-graphql-jwt to 0.3.4 (or higher) from the tutorial's 0.1.5\n\n========================================\n\nCode:\n```text\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n]\n\nGRAPHENE = {\n 'SCHEMA': 'hackernews.schema.schema',\n 'MIDDLEWARE': ['graphql_jwt.middleware.JSONWebTokenMiddleware', ],\n}\n\nAUTHENTICATION_BACKENDS = [\n 'graphql_jwt.backends.JSONWebTokenBackend',\n 'django.contrib.auth.backends.ModelBackend',\n]\n```\n\n```text\nEnvironment:\n\n\nRequest Method: GET\nRequest URL: http://localhost:8000/graphql/\n\nDjango Version: 2.1.4\nPython Version: 3.7.4\nInstalled Applications:\n['django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'graphene_django',\n 'links']\nInstalled Middleware:\n['django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware']\n\n\n\nTraceback:\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\core\\handlers\\exception.py\" in inner\n 34. response = get_response(request)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\core\\handlers\\base.py\" in _get_response\n 126. response = self.process_exception_by_middleware(e, request)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\core\\handlers\\base.py\" in _get_response\n 124. response = wrapped_callback(request, *callback_args, **callback_kwargs)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\views\\decorators\\csrf.py\" in wrapped_view\n 54. return view_func(*args, **kwargs)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\django\\views\\generic\\base.py\" in view\n 62. self = cls(**initkwargs)\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\graphene_django\\views.py\" in __init__\n 88. self.middleware = list(instantiate_middleware(middleware))\n\nFile \"C:\\Users\\e79909\\projects\\python\\graphql-python\\venv\\lib\\site-packages\\graphene_django\\views.py\" in instantiate_middleware\n 48. yield middleware()\n\nException Type: TypeError at /graphql/\nException Value: __init__() missing 1 required positional argument: 'get_response'\n```\n\n```text\nlocalhost:8000/graphql/\n```\n\n```text\nTypeError at /graphql/\n```\n\n```text\n__init__() missing 1 required positional argument: 'get_response'\n```\n\n```py\nGRAPHENE = {\n 'SCHEMA': 'hackernews.schema.schema',\n 'MIDDLEWARES': ['graphql_jwt.middleware.JSONWebTokenMiddleware'],\n}\n```\n\n```py\nMIDDLEWARE = [\n'django.middleware.security.SecurityMiddleware',\n'django.contrib.sessions.middleware.SessionMiddleware',\n'django.middleware.common.CommonMiddleware',\n'django.middleware.csrf.CsrfViewMiddleware',\n'django.contrib.auth.middleware.AuthenticationMiddleware',\n'graphql_jwt.middleware.JSONWebTokenMiddleware', ### <---Add this line\n'django.contrib.messages.middleware.MessageMiddleware',\n'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n```\n\n```text\nS\n```\n\n```text\n'MIDDLEWARES'\n```\n\n```text\n'MIDDLEWARE'\n```\n\n```text\n'graphql_jwt.middleware.JSONWebTokenMiddleware'\n```\n\n```text\nMIDDLEWARE\n```\n\n========================================\n\nComments:\n- I have the same issue. Insomnia is not even part of my issue. Once the settings are updated according to the tutorial, I can not open the GraphiQL interface anymore.\n- I upvoted because this answer ultimately solved my issue, but I had to make some changes. Here is what worked for me: Under GRAPHENE = {} in settings use \"MIDDLEWARE\" (without the S). When I added both graphql_jwt middlwares to GRAPHENE and MIDDLEWARE I got an error saying to add the graphql_jwt middleware to GRAPHENE['MIDDLEWARE'] and to remove it from Django middleware classes.\n- As itβs currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- This is the solution that actually worked for me. Thanks.","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":245,"estimatedTokens":2180}}364{"id":"stack-49175623","source":"stackoverflow","questionId":49175623,"title":"Marking fields as deprecated with graphql shorthand","tags":["graphql"],"text":"Title: Marking fields as deprecated with graphql shorthand\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI'm using GraphQL shorthand to specify the types in a schema, eg\n\n```\ntype Car {\n id: ID!\n make: String\n model: String\n description: String\n}\n```\n\nUsing this shorthand, is there a way to mark a field as deprecated? Say I wanted to mark description as deprecated. Here's my wild guess on how to do this.\n\n```\ntype Car {\n id: ID!\n make: String\n model: String\n @deprecated\n description: String\n}\n```\n\nBut no dice. Is field deprecation achievable in GraphQL shorthand?\n\nThanks!\n\n========================================\n\nTop Answer:\nYou can deprecate like this\n\n```\ndirective @deprecated(\n reason: String = \"No longer supported\"\n) on FIELD_DEFINITION | ENUM_VALUE\n\ntype ExampleType {\n newField: String\n oldField: String @deprecated(reason: \"Use `newField`.\")\n}\n```\n\nfor more info plz refer to apollo server documentation\n\n========================================\n\nCode:\n```text\ntype Car {\n id: ID!\n make: String\n model: String\n description: String\n}\n```\n\n```text\ntype Car {\n id: ID!\n make: String\n model: String\n @deprecated\n description: String\n}\n```\n\n```text\ntype Car {\n id: ID!\n make: String\n model: String\n description: String @deprecated(reason: \"Field is deprecated!\")\n}\n```\n\n```text\ndirective @deprecated(\n reason: String = \"No longer supported\"\n) on FIELD_DEFINITION | ENUM_VALUE\n\ntype ExampleType {\n newField: String\n oldField: String @deprecated(reason: \"Use `newField`.\")\n}\n```\n\n========================================\n\nComments:\n- That's awesome! Do I need some special version of the tooling to take advantage of that? I'm using `makeExecutableSchema` from `graphql-tools` to build my schema. `var executableSchema = makeExecutableSchema({ typeDefs: schema, resolvers: resolvers });`\n- doesn't look like the introspection tool or the graphql intellij plugin is able to pick it up. unsure if anything has changed\n- It's documented in the GraphQL spec here: spec.graphql.org/June2018/#sec--deprecated","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":98,"estimatedTokens":508}}365{"id":"stack-62483120","source":"stackoverflow","questionId":62483120,"title":"How do I generate the schema.graphql file when using Apollo Server?","tags":["graphql","apollo","apollo-server"],"text":"Title: How do I generate the schema.graphql file when using Apollo Server?\nTags: graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nWhen using Apollo Server to write a GraphQL server, how can I run a command on the server to generate the `schema.graphql` file for the client to consume? Note: I'm not using the Apollo Client, I'm using Relay.\n\nI know I can run the GraphQL playground and download it from there, but I want a command line that I can automate.\n\nI'm searching for something similar to `rake graphql:schema:dump` when using GraphQL Ruby which you can run on the server to generate the `schema.graphql`.\n\n========================================\n\nTop Answer:\nThe `apollo` package has been deprecated.\n\n### TLDR;\n\nYou can try to use `@graphql-codegen/schema-ast` and generate a schema to a separate file with the config:\n\n```\ngenerates:\n src/@generated/graphql.ts:\n # TS definitions, if any\n src/@generated/schema.graphql:\n plugins:\n - 'schema-ast'\n```\n\n### Longer answer in case you struggle with a similar problem:\n\nOur setup consists of `@apollo/client` and `@graphql-codegen/cli`. The latter one works with apollo studio schema (the `codegen.yml` supports it).\n\nThe problem we were trying to resolve was integrating an `eslint` plugin, that doesn't support Apollo schema.\n\nWe ended up downloading and generating the schema locally using the `codegen` plugin, and then referencing it in `eslint`. Also we `gitignor`ed it\n\n========================================\n\nCode:\n```text\nschema.graphql\n```\n\n```text\nrake graphql:schema:dump\n```\n\n```text\nschema.graphql\n```\n\n```text\nnpm install -g apollo\n```\n\n```text\napollo client:download-schema --endpoint=URL_OF_YOUR_ENDPOINT schema.graphql\n```\n\n```text\nconst { getIntrospectionQuery, buildClientSchema, printSchema } = require('graphql')\nconst { ApolloServer } = require('apollo-server')\n\nconst apollo = new ApolloServer({ ... })\nconst { data } = await apollo.executeOperation({ query: getIntrospectionQuery() })\nconst schema = buildClientSchema(data)\nconsole.log(printSchema(schema))\n```\n\n```text\nApolloServer\n```\n\n```text\nGraphQLSchema\n```\n\n```text\nprintSchema\n```\n\n```text\ngenerates:\n src/@generated/graphql.ts:\n # TS definitions, if any\n src/@generated/schema.graphql:\n plugins:\n - 'schema-ast'\n```\n\n```text\napollo\n```\n\n```text\n@graphql-codegen/schema-ast\n```\n\n```text\n@apollo/client\n```\n\n```text\n@graphql-codegen/cli\n```\n\n```text\ncodegen.yml\n```\n\n```text\neslint\n```\n\n```text\ncodegen\n```\n\n```text\neslint\n```\n\n```text\ngitignor\n```\n\n========================================\n\nComments:\n- I'm not using Apollo client... if the server is running, isn't that barely a curl/wget?\n- I'm not sure how what client you're using factors into this. You asked for a CLI command to run to get a server's schema in SDL and this is one way of doing that. You can't just use curl for that because that would only return the introspection result. You need a way to turn that into a GraphQLSchema object and then print it. There's other ways of doing that, but you specifically asked for a CLI command.\n- I was after a CLI command on the server that would generate the `schema.graphql` from the defined types, without needing to download anything. I updated my question to specify this. I'm sorry.\n- See edit. If you want to run that from the command line, you'll need to turn it into an npm script.\n- Does this work for federated schemas?\n- Suggested package has been deprecated\n- How to specify auhentication headers?","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":137,"estimatedTokens":872}}366{"id":"stack-59055068","source":"stackoverflow","questionId":59055068,"title":"Make a POST call to GraphQL API programmatically using Java","tags":["java","graphql","graphql-java"],"text":"Title: Make a POST call to GraphQL API programmatically using Java\nTags: java, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI have to send a query with some headers and graphQL variables as a POST call to a GraphQL API in java. I also have to send some headers and authentication parameters in the query. Right now, I am doing a manual call in POSTMAN, but I want to do this programmatically. Can you guys help me where to start off. My query and variables are as follows\n\n```\nquery sampleQuery($param: SampleQueryParams!, $pagingParam: PagingParams) {\n sampleLookup(params: $param, pagingParams: $pagingParam) {\n ID\n name1\n name2 \n }\n}\n```\n\nAnd my GraphQL variables are as follows : \n\n```\n{\"param\": {\"id\": 58763897}, \"pagingParam\": {\"pageNumber\": 0, \"pageSize\": 10 } }\n```\n\nI have no clue where to start at. Could you guys please help\n\n========================================\n\nTop Answer:\nI would recommend using `graphql-java-codegen` plugin for these purposes.\n\nIt provides a possibility to generate classes based on the schema which you can supply to any HTTP client.\n\nFor example, GraphQL server has following schema and we want to perform `productById` query:\n\n```\ntype Query {\n productById(id: ID!): Product\n}\n\ntype Product {\n id: ID!\n title: String!\n price: BigDecimal!\n}\n```\n\n`graphql-java-codegen` will generate all classes required for you to perform a query:\n\n```\n// preparing request\nProductByIdQueryRequest request = new ProductByIdQueryRequest();\nrequest.setId(productId);\n// preparing response projection (which fields to expect in the response)\nProductResponseProjection responseProjection = new ProductResponseProjection()\n .id()\n .title()\n .price();\n\n// preparing a composite graphql request\nGraphQLRequest graphQLRequest = new GraphQLRequest(request, responseProjection);\n\n// performing a request with the constructed object\nProductByIdQueryResponse responseBody = restTemplate.exchange(URI.create(\"https://product-service:8080/graphql\"),\n HttpMethod.POST,\n new HttpEntity<>(graphQLRequest.toHttpJsonBody()),\n ProductByIdQueryResponse.class).getBody();\n// Fetching a serialized object from response\nProduct product = responseBody.productById();\n```\n\nMore examples can be found on GitHub: https://github.com/kobylynskyi/graphql-java-codegen#supported-plugins\n\n========================================\n\nCode:\n```text\nquery sampleQuery($param: SampleQueryParams!, $pagingParam: PagingParams) {\n sampleLookup(params: $param, pagingParams: $pagingParam) {\n ID\n name1\n name2 \n }\n}\n```\n\n```text\n{\"param\": {\"id\": 58763897}, \"pagingParam\": {\"pageNumber\": 0, \"pageSize\": 10 } }\n```\n\n```text\npublic Map<String, Object> graphqlGET(@RequestParam(\"query\") String query,\n @RequestParam(value = \"operationName\", required = false) String operationName,\n @RequestParam(\"variables\") String variablesJson) throws IOException {...\n```\n\n```text\nprivate Map<String, Object> executeGraphqlQuery(String operationName,\n String query, Map<String, Object> variables) {\n ExecutionInput executionInput = ExecutionInput.newExecutionInput()\n .query(query)\n .variables(variables)\n .operationName(operationName)\n .build();\n\n return graphql.execute(executionInput).toSpecification();\n}\n```\n\n```text\nval client = HttpClients.createDefault()\n val httpPost = HttpPost(url)\n val postParameters = ArrayList<NameValuePair>()\n postParameters.add(BasicNameValuePair(\"query\", \"query as string\"))\n postParameters.add(BasicNameValuePair(\"variables\", \"variables json string\"))\n httpPost.entity = UrlEncodedFormEntity(postParameters, Charset.defaultCharset())\n val response = client.execute(httpPost)\n val ret = EntityUtils.toString(response.getEntity())\n```\n\n```text\ntype Query {\n productById(id: ID!): Product\n}\n\ntype Product {\n id: ID!\n title: String!\n price: BigDecimal!\n}\n```\n\n```java\n// preparing request\nProductByIdQueryRequest request = new ProductByIdQueryRequest();\nrequest.setId(productId);\n// preparing response projection (which fields to expect in the response)\nProductResponseProjection responseProjection = new ProductResponseProjection()\n .id()\n .title()\n .price();\n\n// preparing a composite graphql request\nGraphQLRequest graphQLRequest = new GraphQLRequest(request, responseProjection);\n\n// performing a request with the constructed object\nProductByIdQueryResponse responseBody = restTemplate.exchange(URI.create(\"https://product-service:8080/graphql\"),\n HttpMethod.POST,\n new HttpEntity<>(graphQLRequest.toHttpJsonBody()),\n ProductByIdQueryResponse.class).getBody();\n// Fetching a serialized object from response\nProduct product = responseBody.productById();\n```\n\n```text\ngraphql-java-codegen\n```\n\n```text\nproductById\n```\n\n```text\ngraphql-java-codegen\n```\n\n========================================\n\nComments:\n- I don't know much about the GraphQL Java Ecosystem but the first step could be to look at a HTTP client library. This should be possible with any HTTP client that can create POST requests.\n- This helped. Thanks a lot for the detailed answer!!\n- Though the selected answer works, I would prefer this approach because it is more cleaner and structured and all the required classes are automatically generated if you have the schema file. I used this to integrate with one of the payment gateways and it worked very well.\n- Does this not mean your coupled to the schema - any underlying change to the servers schema and itβs a direct change in all clients?","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":172,"estimatedTokens":1411}}367{"id":"stack-58058535","source":"stackoverflow","questionId":58058535,"title":"Get commit changed files & patch using github API v4 graphQL","tags":["graphql","github-api"],"text":"Title: Get commit changed files & patch using github API v4 graphQL\nTags: graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nIn the Rest v3, I could easily query a commit and get the changed files and patch for each file: https://developer.github.com/v3/repos/commits/#get-a-single-commit\n\nI don't seem to be able to retrieve this info using the new v4 graphQL, does anyone have a clue how?\n\n========================================\n\nComments:\n- The 2 reference links are broken","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":13,"estimatedTokens":121}}368{"id":"stack-69915200","source":"stackoverflow","questionId":69915200,"title":"How to configure `*.graphql` imports for TypeScript?","tags":["typescript","graphql"],"text":"Title: How to configure `*.graphql` imports for TypeScript?\nTags: typescript, graphql\nSource: Stack Overflow\n\nQuestion:\nI want to publish a package that contains a type declaration for `*.graphql` \"modules\", and have projects consume the package so that they can write `import` statements for queries written in other files. Is this possible?\n\nHere's what I have so far.\n\nI have the following type, in a file named `graphql.d.ts`.\n\n```\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql';\n const Schema: DocumentNode;\n\n export default defaultDocument;\n}\n```\n\nAnd my `package.json` looks like this.\n\n```\n{\n \"name\": \"@my-private-scope/type-graphql-imports\",\n \"version\": \"1.0.0\",\n \"types\": \"graphql.d.ts\",\n \"files\": [\n \"graphql.d.ts\"\n ],\n \"peerDependencies\": {\n \"graphql\": \">=14.0.0\"\n }\n}\n```\n\nBut after publishing this package and importing it into a different project, I have the following errors.\n\n`error TS2307: Cannot find module './query.graphql' or its corresponding type declarations.`\n\nIs there a way to configure the project so that these types are visible to the compiler?\n\n========================================\n\nCode:\n```js\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql';\n const Schema: DocumentNode;\n\n export default defaultDocument;\n}\n```\n\n```json\n{\n \"name\": \"@my-private-scope/type-graphql-imports\",\n \"version\": \"1.0.0\",\n \"types\": \"graphql.d.ts\",\n \"files\": [\n \"graphql.d.ts\"\n ],\n \"peerDependencies\": {\n \"graphql\": \">=14.0.0\"\n }\n}\n```\n\n```text\n*.graphql\n```\n\n```text\nimport\n```\n\n```text\ngraphql.d.ts\n```\n\n```text\npackage.json\n```\n\n```text\nerror TS2307: Cannot find module './query.graphql' or its corresponding type declarations.\n```\n\n```text\ngenerates: src/api/user-service/queries.d.ts\n documents: src/api/user-service/queries.graphql\n plugins:\n - typescript-graphql-files-modules\n config:\n # resulting module definition path glob: \"*\\/api/user-service/queries.graphql\"\n modulePathPrefix: \"/api/user-service/\"\n```\n\n```text\ndeclare module '*/my-query.graphql' {\n import { DocumentNode } from 'graphql';\n const MyQuery: DocumentNode;\n\n export { MyQuery };\n\n export default defaultDocument;\n}\nAccordingly, you can import the generated types and use it in your code:\n\nimport myQuery from './my-query.graphql';\n\n// OR\n\nimport { myQuery } from './my-query.graphql';\n```\n\n```typescript\nloaders: [\n {\n test: /\\.(graphql|gql)$/,\n exclude: /node_modules/,\n loader: 'graphql-tag/loader'\n }\n]\n```\n\n```typescript\nquery GetAllRoles($value: String) {\n Role(filter: { role: $value }) {\n role\n }\n}\n```\n\n```typescript\nimport GetAllRoles from './queries.graphql'\n .....\n this.apollo.query({\n query: GetAllRoles,\n variables: {\n value: GetAllRoles, \n }\n})\n .subscribe(....)\n```\n\n```text\n// in your webpack.d.ts\ndeclare module \"*.gql\" {\n const content: any;\n export default content;\n}\n\ndeclare module \"*.graphql\" {\n const content: any;\n export default content;\n}\n```\n\n```text\n// in your tsconfig.json\n{\n \"compilerOptions\": {\n ...\n \"allowJs\": true,\n \"checkJs\": false,\n ...\n }\n}\n```\n\n```text\ngraphql queries\n```\n\n```text\nfix\n```\n\n```text\ncompiler errors\n```\n\n```text\nGraphQl\n```\n\n```text\nmy-query.graphql\n```\n\n```text\nwebpack loader\n```\n\n```text\nTypescript compiler errors\n```\n\n```text\ntypescript definitions\n```\n\n```text\ngraphql\n```\n\n```text\nmissing\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- Could you please include your consumer project's tsconfig file/s as well any triple slash directives used in the consumer project? The first thing that came to mind is that you might not be including the library types (or including correctly) in your tsconfig but the issue might be quite deeper. A minimal reproducible example would be nice, since many factors can cause this behavior.\n- I was always amazed how people are opening bounties on questions and then just not showing up for the -ups. This happens surprisingly often!","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":220,"estimatedTokens":990}}369{"id":"stack-56118471","source":"stackoverflow","questionId":56118471,"title":"String interpolation in graphQL query","tags":["javascript","typescript","graphql","gatsby"],"text":"Title: String interpolation in graphQL query\nTags: javascript, typescript, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI am new to Gatsby and its graphQL query system to retrieve assets. I have a working component `Image` that fetches an image and displays it. I want to have the name of the image customizable but I can't figure out how to dit. \n\nHere is the working component:\n\n```\nconst Image = () => (\n }\n />\n);\n```\n\nAnd here is what I tried to have a customizable image:\n\n```\nconst Image = ({ imgName }: { imgName: string }) => (\n }\n />\n);\n```\n\nBut it raises the following error for the query:\n\n`Expected 1 arguments, but got 2.ts(2554)`\n\nHow can I have a customizable image name?\n\n========================================\n\nTop Answer:\nCheck the docs for static query\n\n StaticQuery can do most of the things that page query can, including fragments. The main differences are:\n\n \n \n page queries can accept variables (via pageContext) but can only be\n added to page components\n StaticQuery does not accept variables (hence the name βstaticβ), but\n can be used in any component, including pages\n \n\nSo you might want to query for the image's `GatsbyImageSharpFluid` in your page query and pass it as the fluid prop directly to gatsby image.\n\n========================================\n\nCode:\n```text\nconst Image = () => (\n <StaticQuery\n query={graphql`\n query {\n // fetching the image gatsby-astronaut.png\n placeholderImage: file(relativePath: { eq: \"gatsby-astronaut.png\" }) {\n childImageSharp {\n fluid(maxWidth: 300) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n `}\n render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}\n />\n);\n```\n\n```text\nconst Image = ({ imgName }: { imgName: string }) => (\n <StaticQuery\n query={graphql`\n query {\n // fetching the image imgName\n placeholderImage: file(relativePath: { eq: \"${imgName}.png\" }) {\n childImageSharp {\n fluid(maxWidth: 300) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n `}\n render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}\n />\n);\n```\n\n```text\nImage\n```\n\n```text\nExpected 1 arguments, but got 2.ts(2554)\n```\n\n```text\nconst Image = props => {\n const data = useStaticQuery(graphql`\n query {\n firstImg: file(relativePath: { eq: \"firstImg.png\" }) {\n childImageSharp {\n fluid(maxWidth: 300) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n\n secondImg: file(\n relativePath: { eq: \"secondImg.png\" }\n ) {\n childImageSharp {\n fluid(maxWidth: 300) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n `)\n\n switch (props.name) {\n case \"firstImg\":\n return <Img fluid={data.firstImg.childImageSharp.fluid} />\n case \"secondImg\":\n return <Img fluid={data.secondImg.childImageSharp.fluid} />\n default:\n return <Img />\n }\n}\n```\n\n```text\n<Image name=\"firstImg\" />\n```\n\n```text\nconst Images = { firstImg: 'firstImg', secondImg: 'secondImg' }\n```\n\n```text\n<Image name={Images.firstImage} />\n```\n\n```text\n...\nswitch (props.name) {\ncase Images.firstImage:\n...\n```\n\n```text\nGatsbyImageSharpFluid\n```\n\n```text\nexport const pageQuery = graphql`\n coverImage: file(relativePath: { eq: \"coverImage.png\" }) {\n childImageSharp {\n fluid(maxWidth: 600) {\n ...GatsbyImageSharpFluid_tracedSVG\n }\n }\n }\n}`\n```\n\n```text\nimport React from 'react';\nimport gatsbyAstronaut from './gatsby-astronaut.png';\n```\n\n```html\n<img src={gatsbyAstronaut} alt=\"Gatsby Astronaut\" />\n```\n\n========================================\n\nComments:\n- I didn't manage to make it work but your answer is relevant. Thanks!\n- Very convenient","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":183,"estimatedTokens":955}}370{"id":"stack-44185188","source":"stackoverflow","questionId":44185188,"title":"Graphene Django \"Must provide query string\"","tags":["django","graphql","graphene-python"],"text":"Title: Graphene Django \"Must provide query string\"\nTags: django, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI have setup a Graphene server using Django. When I run my queries through GraphiQL (the web client), everything works fine. However, when I run from anywhere else, I get the error: \"Must provide query string.\"\n\nI did some troubleshooting. GraphiQL sends POST data to the GraphQL server with `Content-Type: application/json`. Here is the body of the request that I copied from Chrome network tab for GraphiQL:\n\n```\n{\"query\":\"query PartnersQuery {\\n partners{\\n name\\n url\\n logo\\n }\\n}\",\"variables\":\"null\",\"operationName\":\"PartnersQuery\"}\n```\n\nWhen I copy it to Postman with `Content-Type: application/json`, I get the following response:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Must provide query string.\"\n }\n ]\n}\n```\n\nWhat can be the cause of this problem? I have not done anything crazy with the schema. Just followed the tutorials from graphene's docs. What else can cause an issue like this?\n\n========================================\n\nTop Answer:\nThis error is raised when `parse_body` is unable to parse the incoming data. I'd start there by looking at the data passed into this method and ensuring it's of the correct type.\n\nFor example, the `multipart/form-data` section naively returns `request.POST`, which may need to be overwritten to handle, for example, the request that `apollo-upload-client` sends for file upload handling.\nIn our case we created a view to both require a login and to support the `apollo-upload-client` use case and it works fine.\n\n========================================\n\nCode:\n```text\n{\"query\":\"query PartnersQuery {\\n partners{\\n name\\n url\\n logo\\n }\\n}\",\"variables\":\"null\",\"operationName\":\"PartnersQuery\"}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Must provide query string.\"\n }\n ]\n}\n```\n\n```text\nContent-Type: application/json\n```\n\n```text\nContent-Type: application/json\n```\n\n```text\nfrom django.views.decorators.csrf import csrf_exempt\nfrom graphene_django.views import GraphQLView\n\nurl(r'^explore', GraphQLView.as_view(graphiql=True)),\nurl(r'^graphql', csrf_exempt(GraphQLView.as_view())),\n```\n\n```text\nparse_body\n```\n\n```text\nmultipart/form-data\n```\n\n```text\nrequest.POST\n```\n\n```text\napollo-upload-client\n```\n\n```text\napollo-upload-client\n```\n\n```text\n{\"query\":\"{myModels {id}}\",\"variables\":\"null\",\"operationName\":null}\n```\n\n```text\nurl(r'^graphql/', GraphQLView.as_view())\n```\n\n```text\nurl(r'^graphql', GraphQLView.as_view())\n```\n\n```text\n{\"query\":\"{user(id:902){id,username,DOB}}\"}\n```\n\n```text\n{ \"query\": \"mutation {createMutations(reviewer:36, comments:\\\"hello\\\",loan: 1659, approved: true ){id}}\" }\n\n #commnent: String Type\n #data_id:Int Type\n #approved:Boolean Type\n```\n\n```text\ngraphQl\n```\n\n```text\nPOSTMAN\n```\n\n```text\nrow\n```\n\n```text\njson\n```\n\n```text\nurl(r'^graphql', csrf_exempt(GraphQLView.as_view(graphiql=settings.DEBUG))),\n```\n\n```text\ncurl 'http://localhost:8000/graphql?' -H 'Origin: http://localhost:8000' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US,en;q=0.9,pl;q=0.8,de;q=0.7' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Cookie: _ga=GA1.1.1578283610.1528109563; _gid=GA1.1.920024733.1541592686; csrftoken=EGBeegFoyMVl8j1fQbuEBG587nOFP2INwv7Q0Ee6HeHHmsLOPUwRonzun9Y6pOjV; sessionid=4u9vngcnmjh927a9avpssvc4oq9qyqoe' -H 'Connection: keep-alive' -H 'X-CSRFToken: EGBeegFoyMVl8j1fQbuEBG587nOFP2INwv7Q0Ee6HeHHmsLOPUwRonzun9Y6pOjV' --data-binary '{\"query\":\"{\\n allStatistics(projectId: 413581, first:25) {\\n pageInfo {\\n startCursor\\n endCursor\\n hasPreviousPage\\n hasNextPage\\n }\\n edges {\\n cursor\\n node {\\n id\\n clickouts\\n commissionCanc\\n commissionConf\\n commissionLeads\\n commissionOpen\\n eventDate\\n extractTstamp\\n hash\\n leads\\n pageviews\\n projectId\\n transactionsCanc\\n transactionsConf\\n transactionsOpen\\n }\\n }\\n }\\n}\\n\",\"variables\":null,\"operationName\":null}' --compressed\n```\n\n========================================\n\nComments:\n- Hi @adam-donahue can you show your implementation of your custom `parse_body` function and how to overwrite this method. So pretty much you pointed me to the problem I was investigating all day long. For authentication I am attaching a custom `TokenAuthentication` class using the `authentication_classes` decorator from `rest_framework`. Not sure where to start to manipulate `parse_body`. Can you point me into the right direction?\n- github.com/graphql-python/graphene-django/issues/404 ok I found a solution posted here:)\n- Try ^graphql/$ so that it catches everything in the URL","metadata":{"transformedAt":"2026-08-18T18:32:36.052Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":142,"estimatedTokens":1224}}371{"id":"stack-46034801","source":"stackoverflow","questionId":46034801,"title":"Custom Scalar in Graphql-java","tags":["java","graphql","graphql-java"],"text":"Title: Custom Scalar in Graphql-java\nTags: java, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nWe are planning use Graphql as backend server in our application. We choose Graphql-Java to develop our POC. We came across a stituation to create our own scalartype to handle java.util.Map object type.\n\nwe havent found any documentation regarding creating a custom scalar type.\nIn example code as below\n\n```\nRuntimeWiring buildRuntimeWiring() {\n return RuntimeWiring.newRuntimeWiring()\n .scalar(CustomScalar)\n```\n\nhow to was the implementation done for CustomScalar object.\nneed help.\n\n========================================\n\nTop Answer:\nIn code first approach (SPQR v0.9.6) adding **@GraphQLScalar** is enough.\nOr, as alternative, add scalar definition to GraphQLSchemaGenerator:\n\n```\nnew GraphQLSchemaGenerator()\n.withScalarMappingStrategy(new MyScalarStrategy())\n```\n\nAnd define MyScalarStrategy:\n\n```\nclass MyScalarStrategy extends DefaultScalarStrategy {\n\n@Override\npublic boolean supports(AnnotatedType type) {\n return super.supports(type) || GenericTypeReflector.isSuperType(MyScalarStrategy.class, type.getType());\n}\n}\n```\n\n========================================\n\nCode:\n```text\nRuntimeWiring buildRuntimeWiring() {\n return RuntimeWiring.newRuntimeWiring()\n .scalar(CustomScalar)\n```\n\n```text\nRuntimeWiring.newRuntimeWiring().scalar(ExtendedScalars.Object)\n```\n\n```text\nMap\n```\n\n```text\nnew GraphQLSchemaGenerator()\n.withScalarMappingStrategy(new MyScalarStrategy())\n```\n\n```text\nclass MyScalarStrategy extends DefaultScalarStrategy {\n\n@Override\npublic boolean supports(AnnotatedType type) {\n return super.supports(type) || GenericTypeReflector.isSuperType(MyScalarStrategy.class, type.getType());\n}\n}\n```\n\n```text\n<dependency>\n <groupId>com.graphql-java</groupId>\n <artifactId>graphql-java-extended-scalars</artifactId>\n <version>21.0</version>\n</dependency>\n```\n\n```text\n@Configuration\n\npublic class ScalarRegister {\n\n @Bean\n public RuntimeWiring.Builder addLongScalar(RuntimeWiring.Builder builder) {\n return builder.scalar(ExtendedScalars.GraphQLLong);\n }\n\n}\n```\n\n========================================\n\nComments:\n- how do I utilize above scaler into my code? I've a Spring-boot application and it'll help if you could provide an example.\n- @Simple-Solution How do you use any built-in scalar, like String or Integer? There's no difference.\n- Not sure I understand what you mean. But those; String and Integer are built in and it all happens automatically. So above scalar is for object and I would need to create one for Map, right? Do you've an example. Also what is the significant of the `name` argument? Is that the name of the type we defined in the schema?\n- @Simple-Solution Happens automatically? Does that mean you're using GraphQL-SPQR? If so, annotate the type at the place of use with `@GraphQLScalar` (e.g. annotated a method argument) or use a different `ScalarMappingStrategy` (e.g. `gen.withScalarMappingStrategy(new MapScalarStrategy())`). Without SPQR, there's no automatic mapping. You set a type of each field, e.g. `newFieldDefinition().type(Scalars.GraphQLString)`, so you can use `newFieldDefinition().type(Scalars.graphQLObjectScalar(\"typeN‌​ame\"))` instead. You'll get a `Map` just like for any object input, but with a dynamic structure.\n- @Simple-Solution If using schema-first with graphql-java directly, you can use a custom scalar via `RuntimeWiring.newRuntimeWiring().scalar(Scalars.graphQLObjec‌​tScalar(\"typeNββame\"‌​))`. Mind you, in the 2nd and the 3rd example `Scalars` is `io.leangen.graphql.util.Scalars` not `graphql.Scalars`. Or just copy the SPQR code into your own class.\n- Never knew `GraphQL-SPQR` existed, I'm using Code-first approach, where I've a `schema.graphqls` file which holds my type/api definition. Do you know how does that fit into my approach? Here is another question i asked yesterday: stackoverflow.com/questions/47677140/…\n- @Simple-Solution If you have a schema in a file, that's a schema-first approach. And I've given you the exact literal code you need to add. I can't help you further. You seem to need some more reading of the docs first.\n- Where do you guys declare this class. I the example of graphql-java.readthedocs.io/en/latest/scalars.html where `public static class EmailScalar` is declared but the compiler fails because it is not allowed to just declare a static class anywhere. I cannot find the explaination where to declare this class actually\n- @xetra11 It's an instance of `GraphQLScalarType`, not a class. And who says it needs to be static?","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":107,"estimatedTokens":1156}}372{"id":"stack-48851800","source":"stackoverflow","questionId":48851800,"title":"GraphQL Dataloader not knowing keys in advance","tags":["javascript","node.js","caching","graphql","batching"],"text":"Title: GraphQL Dataloader not knowing keys in advance\nTags: javascript, node.js, caching, graphql, batching\nSource: Stack Overflow\n\nQuestion:\nDataloader is able to batch and cache requests, but it can only be used by either calling load(key) or loadMany(keys). \n\nThe problem I am having is that sometimes I do not know they keys of the items I want to load in advance.\n\nI am using an sql database and this works fine when the current object has a foreign key from a belongsTo relation with another model. \n\nFor example a user that belongs to a group and so has a groupId. To resolve the group you would just call groupLoader.load(groupId).\n\nOn the other hand, if I wanted to resolve the users within a group, of which there could be many I would want a query such as \n\n```\nSELECT * from users where user.groupId = theParticularGroupId\n```\n\nbut a query such as this doesn't use the keys of the users and so I am not sure how make use of dataloader.\n\nI could do another request to get the keys like\n\n```\nSELECT id from users where user.groupId = theParticularGroupId\n```\n\nand then call loadMany with those keys... But I could have just requested the data directly instead.\n\nI noticed that dataloader has a prime(key, value) function which can be used to prime the cache, however that can only be done once the data is already fetched. At which point many queries would already have been sent, and duplicate data could have been fetched.\n\nAnother example would be the following query\n\n```\nquery {\n groups(limit: 10) {\n id\n ...\n users {\n id\n name\n ...\n }\n }\n}\n```\n\nI cannot know the keys if I am searching for say the first or last 10 groups. Then once I have these 10 groups. I cannot know the keys of their users, and if each resolver would resolve the users using a query such as \n\n```\nSELECT * from users where user.groupId = theParticularGroupId\n```\n\nthat query will be executed 10 times. Once the data is loaded I could now prime the cache, but the 10 requests have already been made.\n\nIs there any way around this issue? Perhaps a different pattern or database structure or maybe dataloader isn't even the right solution.\n\n========================================\n\nCode:\n```text\nSELECT * from users where user.groupId = theParticularGroupId\n```\n\n```text\nSELECT id from users where user.groupId = theParticularGroupId\n```\n\n```text\nquery {\n groups(limit: 10) {\n id\n ...\n users {\n id\n name\n ...\n }\n }\n}\n```\n\n```text\nSELECT * from users where user.groupId = theParticularGroupId\n```\n\n```text\nimport DataLoader from 'dataloader';\n\nconst userIdsForGroupLoader = new DataLoader(groupIds => batchGetUsersIdsForGroups(groupIds));\n```\n\n```text\nSELECT id from users where user.groupId in (...groupIds)\n```\n\n```text\nbatchGetUsersForGroups\n```\n\n```text\nIN\n```\n\n```text\ngroupId\n```\n\n```text\ngroupIds\n```\n\n========================================\n\nComments:\n- Does this mean you would have to create a lot of different dataloaders for each way you want to load your data even if the same entities are being loaded? Like in a comment in your article you suggested using a loader such as `loader.load({ id, first, last, after, before, filters})` to batch the request for connections. But then you'd also have to use the returned data to prime other dataloaders which may request the same type of data through a different signature which may or may not be used depending on what fields client queries. It seems like this could quickly become difficult to manage?\n- I guess if you don't prime other dataloaders you just miss out on some caching but still get the batching effect which is the main benefit. That may greatly reduce the complexity.\n- So in this example, a usersForGroupLoader could return Users, which means you have sufficient data to prime a plain old usersByIdLoader. Ultimately the best strategy depends on a combination of the underlying data fetching patterns, and the most common query patterns. In the site I did this for (depop.com), the number of core entities is relatively low (users, products, likes, bookmarks, comments, conversations, messages, and a few others), and I basically had a loader per lookup-type, which tended to mean one loader for an entity-by-id, and another for each major join.\n- I'll admit it did get a little hard to manage, the module responsible for creating all the loaders and coordinating caching between them was easily the most complicated part of the codebase. But it was my first attempt, so i'm sure with a little more experience it could be done more elegantly.","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":119,"estimatedTokens":1134}}373{"id":"stack-54676109","source":"stackoverflow","questionId":54676109,"title":"Should I have multiple GraphQL instances or just a single one?","tags":["architecture","graphql"],"text":"Title: Should I have multiple GraphQL instances or just a single one?\nTags: architecture, graphql\nSource: Stack Overflow\n\nQuestion:\nMy company runs a microservice architecture that has 50+ services that are powered by a single GraphQL endpoint, which orchestrate the calls among our services, powering our Android & iOS applications for our end-users.\n\nWe're in process of creating a new product that's going to not be used by those end-users, but for companies that offer goods for our end-users through our apps. TL;DR: things like showing performance data regarding their sales through our platform.\n\nSince the data requirements for this new product and our apps are hardly different, we're under discussion of creating a new GraphQL endpoint just for this product, because we're afraid of turning the original GraphQL layer on a monolith that would behave as a single point of failure in case of a disaster, for instance.\n\nLooking into GraphQL's website, Facebook posts, Apollo's Principled Graphql, etc etc, it's quite easy to see the \"single endpoint\" phrase somewhere. I'd like to know until when this is still valid.\n\nAnyone recommendation/opinion, or even testimonials on who have been on this discussion as well is appreciated. In case your company had this discussion before, what was the final decision made, what was taken into consideration?\n\n========================================\n\nTop Answer:\nI'd suggest maybe thinking about the problem differently.\n\nYou have a couple of problems you're dealing with, if I am understanding this correctly:\n\n- You are about to expose internal APIs - or something close to your internal APIs - to external parties for the first time\n\n- You're concerned about the impact of one on the other (e.g. DDoS on the external bringing your internal processes to a halt)\n\n- You're unsure how to best architect GraphQL to similar functionality across related but potentially different APIs\n\nIs that a good summary?\n\nI'd suggest you should look at an API gateway to protect your external API, regardless of what you choose with your API implementations. You need the authentication and authorisation anyway.\n\nThe API gateway also gives you some control over how to route your API calls. If you chose to have identical APIs for internal and external, you could have a pool of these API implementations for redundancy, and only allow the API gateway to load balance between a subset of these. That would mean that even if they were flat out, you should have some reserved capacity to deal with internal requests. (If the load is actually on your back end data sources then that's another issue entirely!)\n\nIf you're looking at way to build separate GraphQL APIs that operate completely independently but reuse functionality, you could look at something like Apollo to do this, but I'm not a GraphQL expert.\n\nAs I mentioned above, though, your concern about a single point of failure probably needs to consider your back end(s). Regardless of how you segregate your gateways, proxies, GraphQL endpoints and so on, if they're all hitting the same database then a disaster is probably going to bring down your internal and external APIs at the same time.\n\nHope that gives you food for thought.","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":39,"estimatedTokens":807}}374{"id":"stack-51442150","source":"stackoverflow","questionId":51442150,"title":"How to handle httpOnly cookie authentication in next.js with apollo client","tags":["javascript","reactjs","graphql","apollo","next.js"],"text":"Title: How to handle httpOnly cookie authentication in next.js with apollo client\nTags: javascript, reactjs, graphql, apollo, next.js\nSource: Stack Overflow\n\nQuestion:\nIn my usual experience all single page apps I worked on used JWT as authentication mechanism. I came across api that uses httpOnly cookies for this.\n\nSince we can't access such cookie via javascript to know if it is present or not, how does one handle this in react app?\n\nMy initial idea was to track this by setting some `sessionStorage` upon successful sign in and removing it if I receive an error related to authentication.\n\nBut this doesn't work well with next.js server side rendering I believe? We have it set up with apollo client which allows setting custom headers and cache.\n\nIs there a common way to handle this authentication process with set up above?\n\n========================================\n\nCode:\n```text\nsessionStorage\n```\n\n```text\nhttpOnly\n```\n\n========================================\n\nComments:\n- @EricBurel β That's a matter of opinion, and dependant on context.\n- I am trying to gather info on this precise subject, which is not often covered in articles about auth, do you have examples of contexts where one can be preferred upon the other? In Next one specific problem with `localStorage` is that you can't get the auth token during SSR, since you have no control over the request content.\n- There isn't space in the comments of an SO question for a decent discussion on the topic.","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":32,"estimatedTokens":369}}375{"id":"stack-64119385","source":"stackoverflow","questionId":64119385,"title":"difference between @apollo/client , apollo-client and apollo boost","tags":["graphql","react-apollo","apollo-client","apollo-boost"],"text":"Title: difference between @apollo/client , apollo-client and apollo boost\nTags: graphql, react-apollo, apollo-client, apollo-boost\nSource: Stack Overflow\n\nQuestion:\nI am implementing using `@apollo/client`, but i do not see any complete example of `@apollo/client` with `react`.\nIf i search i get example with `apollo-client` and `apollo boost`.\n\n**What is the difference between all 3.**\nI understand `@apollo/client` is the new version of all. **Where can i get complete example of `@apollo/client` with `react` application?**\n\n```\nimport { ApolloClient, InMemoryCache, ApolloLink, createHttpLink, defaultDataIdFromObject } from '@apollo/client';\nimport { ApolloClient, InMemoryCache, ApolloLink } from 'apollo-boost';\n```\n\n========================================\n\nTop Answer:\nJust to add to the already posted answer for anyone wondering if they should still be using Boost.\n\nFrom the docs:\n\nThe Apollo Boost project is now retired, because Apollo Client 3.0\nprovides a similarly straightforward setup. We recommend removing all\napollo-boost dependencies and modifying your ApolloClient constructor\nas needed.\n\n========================================\n\nCode:\n```text\nimport { ApolloClient, InMemoryCache, ApolloLink, createHttpLink, defaultDataIdFromObject } from '@apollo/client';\nimport { ApolloClient, InMemoryCache, ApolloLink } from 'apollo-boost';\n```\n\n```text\n@apollo/client\n```\n\n```text\n@apollo/client\n```\n\n```text\nreact\n```\n\n```text\napollo-client\n```\n\n```text\napollo boost\n```\n\n```text\n@apollo/client\n```\n\n```text\n@apollo/client\n```\n\n```text\nreact\n```\n\n```text\napollo-client\n```\n\n```text\napollo-cache-inmemory\n```\n\n```text\napollo-link-http\n```\n\n```text\napollo-link-error\n```\n\n```text\ngraphql-tag\n```\n\n========================================\n\nComments:\n- i am getting this error. React Hook \"useQuery\" is called in function \"getData\" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks. I am using same package.json file from the example link. I ran the exmaple link you gave, it works fine. I created the app using yarn create-reactapp. is that something causing this issue?","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":92,"estimatedTokens":535}}376{"id":"stack-44270248","source":"stackoverflow","questionId":44270248,"title":"graphql-java - How to use subscriptions with spring boot?","tags":["java","spring-boot","graphql","graphql-java"],"text":"Title: graphql-java - How to use subscriptions with spring boot?\nTags: java, spring-boot, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nIn a project I use **graphql-java** and ***spring boot*** with a postgreSQL Database. Now I would like to use the **subscription feature** published in version 3.0.0. Unfortunately, the information about the application of the subsciption function is not very mature. \n\nHow is the approach to achieve **real-time functionality** using `graphql-java` with subscriptions?\n\n========================================\n\nTop Answer:\nI got the same issue where I was spiking on the lib to integrate with spring boot. I found graphql-java, however, it seems it only support 'subscription' on schema level, it is not perform any transnational support for this feature. Meaning you might need to implement it your self. \n\nPlease refer to https://github.com/graphql-java/graphql-java/blob/master/docs/schema.rst#subscription-support\n\n========================================\n\nCode:\n```text\ngraphql-java\n```\n\n```text\n// Somehow create a publisher, probably using Spring's Reactor project. Or RxJava.\nPublisher<ResultObject> publisher = ...; \n//The listener reacts on application events and pushes new values through the publisher\nApplicationListener listener = createListener(publisher);\ncontext.addApplicationListener(listener);\nreturn publisher;\n```\n\n```text\n//This is really just a thread-safe wrapper around Map<String, Set<FluxSink<Task>>>\nprivate final ConcurrentMultiRegistry<String, FluxSink<Task>> subscribers = new ConcurrentMultiRegistry<>();\n\n@GraphQLSubscription\npublic Publisher<Task> taskStatusChanged(String taskId) {\n return Flux.create(subscriber -> subscribers.add(taskId, subscriber.onDispose(() -> subscribers.remove(taskId, subscriber))), FluxSink.OverflowStrategy.LATEST);\n}\n```\n\n```text\nsubscribers.get(taskId).forEach(subscriber -> subscriber.next(task));\n```\n\n```text\n@GraphQLMutation\npublic Task updateTask(@GraphQLNonNull String taskId, @GraphQLNonNull Status status) {\n Task task = repo.byId(taskId); //find the task\n task.setStatus(status); //update the task\n repo.save(task); //persist the task\n //Notify all the subscribers following this task\n subscribers.get(taskId).forEach(subscriber -> subscriber.next(task));\n return task;\n}\n```\n\n```text\nDataFetcher\n```\n\n```text\norg.reactivestreams.Publisher\n```\n\n```text\n@Tailable\n```\n\n```text\nFlux\n```\n\n```text\nPublisher\n```\n\n```text\nPublisher\n```\n\n```text\ncontext.addApplicationListener(listener)\n```\n\n```text\nPublisher\n```\n\n```text\nDataFetcher\n```\n\n```text\nPublisher\n```\n\n========================================\n\nComments:\n- Did you found a solution?\n- How & where would ConcurrentMultiRegistry live on a application that has multiple instances running? Is each instance expected to maintain its own subscribers & notify them?\n- @raga Scaling GraphQL subscriptions is notoriously difficult because it invariably involves maintaining connections and state. Since subscriptions are client-initiated, and create a persistent connection to a node, I think each node must maintain it's own subscriber registry with the client connected to it.\n- Got it, Thanks. If such node goes down I assume clients would need to have a way to know its down as well as re-subscribe to another running node, am i correct ?\n- @raga Yes. The client's connection would drop when the node goes down, and it's common for clients to immediately try re-subscribing. I'd expect a reverse-proxy on the server that transparently makes sure to direct the connection to a live node.","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":106,"estimatedTokens":895}}377{"id":"stack-56808079","source":"stackoverflow","questionId":56808079,"title":"How to access context variable within the template component in Gatsby?","tags":["reactjs","graphql","gatsby"],"text":"Title: How to access context variable within the template component in Gatsby?\nTags: reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nWithin a react component in a Gatsby app, I understand how to use a context variable within the graphql queries, e.g:\n\n```\nexport const tagPageQuery = graphql`\n query TagPage($tag: String) {\n site {\n siteMetadata {\n title\n }\n }\n allItem(filter: { tags: { in: [$tag] } }) {\n totalCount\n edges {\n node {\n\n id\n move\n videoUrl\n```\n\n`$tag` is a string that allows me to filter. I get that. But is there someway to access this value within the component itself? I can access the data that the graphql query gets, but can't get the variable outside of Graphql. I would love to have it be `{context.tag}` or something like that, to be able to use that value within my `h1`. I've gone through the Gatsby GraphQL reference and no dice. It feels like getting this value should be easy but I'm wondering if I need to use something like a `getContext` hook?\n\n========================================\n\nCode:\n```text\nexport const tagPageQuery = graphql`\n query TagPage($tag: String) {\n site {\n siteMetadata {\n title\n }\n }\n allItem(filter: { tags: { in: [$tag] } }) {\n totalCount\n edges {\n node {\n\n id\n move\n videoUrl\n```\n\n```text\n$tag\n```\n\n```text\n{context.tag}\n```\n\n```text\nh1\n```\n\n```text\ngetContext\n```\n\n```text\nconst TagPage = ({ data, classes , pageContext}) => {\n```\n\n```text\n$tag\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":71,"estimatedTokens":373}}378{"id":"stack-65457513","source":"stackoverflow","questionId":65457513,"title":"How do I reset the useMutation hook of Apollo Client","tags":["reactjs","graphql","apollo","react-apollo","apollo-client"],"text":"Title: How do I reset the useMutation hook of Apollo Client\nTags: reactjs, graphql, apollo, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am developing a React form that's tied to a GraphQL mutation using the `useMutation` of Apollo Client. On the server, I perform some validation and in case of errors, I reject the mutation. On the client-side, I use the `error` object to receive the validation errors. My hook looks like this:\n\n```\nconst [addDrone, { error }] = useMutation(ADD_DRONE)\n```\n\nSo I unpack the `error` object and present it to the user in a dialog to let him/her know what went wrong. After the user dismisses the dialog, I want to give the user a chance to fix the error so he/she can resubmit the form. This is where things get hairy. I want to clear the `error` object when the user dismisses the dialog, but since this variable comes from the `useMutation` hook there is no way for me to mutate or reset it. It looks like the `useMutation` was designed to be fired once, and not used again.\n\nSo my question is, is there a way to \"reset\" a `useMutation` hook back to it's original state?\n\n========================================\n\nCode:\n```text\nconst [addDrone, { error }] = useMutation(ADD_DRONE)\n```\n\n```text\nuseMutation\n```\n\n```text\nerror\n```\n\n```text\nerror\n```\n\n```text\nerror\n```\n\n```text\nuseMutation\n```\n\n```text\nuseMutation\n```\n\n```text\nuseMutation\n```\n\n```text\nconst [addDrone, { error, reset }] = useMutation(ADD_DRONE)\n```\n\n```text\nconst [error, setError] = React.useState(null)\n const [addDrone] = useMutation(ADD_DRONE, {\n onError: setError,\n })\n```\n\n```text\n@apollo/client\n```\n\n```text\nuseMutation\n```\n\n```text\nreset\n```\n\n```text\n@apollo/client\n```\n\n```text\nuseMutation\n```\n\n```text\nerror\n```\n\n```text\nonError\n```\n\n```text\nuseMutation\n```\n\n```text\nerror\n```\n\n```text\nerror\n```\n\n```text\nsetError\n```\n\n```text\ndata\n```\n\n```text\n[data, setData]\n```\n\n```text\nsetData\n```\n\n```text\nonCompleted\n```\n\n========================================\n\nComments:\n- Resetting the mutation result was implemented in `@apollo/client 3.5.x` github.com/apollographql/apollo-client/issues/…","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":125,"estimatedTokens":533}}379{"id":"stack-53415286","source":"stackoverflow","questionId":53415286,"title":"Subscription not connecting using ApolloServer","tags":["javascript","graphql","apollo-server","graphql-subscriptions"],"text":"Title: Subscription not connecting using ApolloServer\nTags: javascript, graphql, apollo-server, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nI am trying to get a subscription up and running with ApolloServer (v 2.2.2). I had a setup that all-of-a-sudden just stopped working. When I try to connect to the subscription in `graphiql`/`Playground`I get the error:\n\n```\n{\n \"error\": \"Could not connect to websocket endpoint ws://localhost:4000/graphql. Please check if the endpoint url is correct.\"\n}\n```\n\nAs I have rest-endpoints in my app I need to have express but I can't get the minimal example from below running:\n\n```\nimport http from 'http';\nimport { ApolloServer, PubSub } from 'apollo-server-express';\nimport express from 'express';\n\nconst pubsub = new PubSub();\n\n// The DB\nconst messages = [];\n\nconst typeDefs = `\ntype Query {\n messages: [String!]!\n}\ntype Mutation {\n addMessage(message: String!): [String!]!\n}\ntype Subscription {\n newMessage: String!\n}\n\nschema {\n query: Query\n mutation: Mutation\n subscription: Subscription\n}\n`;\n\nconst resolvers = {\n Query: {\n messages() {\n return messages;\n }\n },\n Mutation: {\n addMessage(root, { message }) {\n let entry = JSON.stringify({ id: messages.length, message: message });\n messages.push(entry);\n pubsub.publish('newMessage', { entry: entry });\n return messages;\n },\n },\n Subscription: {\n newMessage: {\n resolve: (message) => {\n return message.entry;\n },\n subscribe: () => pubsub.asyncIterator('newMessage'),\n },\n },\n};\n\nconst app = express();\n\nconst PORT = 4000;\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n subscriptions: {\n onConnect: () => console.log('Connected to websocket'),\n }\n});\n\nserver.applyMiddleware({ app })\n\nconst httpServer = http.createServer(app);\nserver.installSubscriptionHandlers(httpServer);\n\nhttpServer.listen(PORT, () => {\n console.log(`π Server ready at http://localhost:${PORT}${server.graphqlPath}`)\n console.log(`π Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)\n})\n```\n\nThe other endpoints work fine but it is unable to create the WebSocket. As far as I understand it I shouldn't have to use a different server or port (see https://www.ably.io/concepts/websockets). I've tinkered with `SubsciptionServer` but this should be handled by `installSubscriptionHandlers` (here's the code).\n\n========================================\n\nTop Answer:\nA lot of time has passed and now I faced with the same problem and I found a solution.\n\n```\nimport { createServer } from 'http';\nconst app = express();\nconst server = new ApolloServer({});\nserver.applyMiddleware({ app });\nconst httpServer = createServer(app);\nserver.installSubscriptionHandlers(httpServer);\nserver.listen()\n```\n\nWorks for me\n\n========================================\n\nCode:\n```text\n{\n \"error\": \"Could not connect to websocket endpoint ws://localhost:4000/graphql. Please check if the endpoint url is correct.\"\n}\n```\n\n```text\nimport http from 'http';\nimport { ApolloServer, PubSub } from 'apollo-server-express';\nimport express from 'express';\n\nconst pubsub = new PubSub();\n\n// The DB\nconst messages = [];\n\nconst typeDefs = `\ntype Query {\n messages: [String!]!\n}\ntype Mutation {\n addMessage(message: String!): [String!]!\n}\ntype Subscription {\n newMessage: String!\n}\n\nschema {\n query: Query\n mutation: Mutation\n subscription: Subscription\n}\n`;\n\nconst resolvers = {\n Query: {\n messages() {\n return messages;\n }\n },\n Mutation: {\n addMessage(root, { message }) {\n let entry = JSON.stringify({ id: messages.length, message: message });\n messages.push(entry);\n pubsub.publish('newMessage', { entry: entry });\n return messages;\n },\n },\n Subscription: {\n newMessage: {\n resolve: (message) => {\n return message.entry;\n },\n subscribe: () => pubsub.asyncIterator('newMessage'),\n },\n },\n};\n\nconst app = express();\n\nconst PORT = 4000;\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n subscriptions: {\n onConnect: () => console.log('Connected to websocket'),\n }\n});\n\nserver.applyMiddleware({ app })\n\nconst httpServer = http.createServer(app);\nserver.installSubscriptionHandlers(httpServer);\n\nhttpServer.listen(PORT, () => {\n console.log(`π Server ready at http://localhost:${PORT}${server.graphqlPath}`)\n console.log(`π Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)\n})\n```\n\n```text\ngraphiql\n```\n\n```text\nPlayground\n```\n\n```text\nSubsciptionServer\n```\n\n```text\ninstallSubscriptionHandlers\n```\n\n```text\nconst wsLink = new WebSocketLink({\n uri: SUBSCRIPTION_URI,\n options: {\n reconnect: true,\n timeout: 20000,\n lazy: true,\n },\n});\n\nwindow.addEventListener('beforeunload', () => {\n // @ts-ignore - the function is private in typescript\n wsLink.subscriptionClient.close();\n});\n```\n\n```text\nimport { createServer } from 'http';\nconst app = express();\nconst server = new ApolloServer({});\nserver.applyMiddleware({ app });\nconst httpServer = createServer(app);\nserver.installSubscriptionHandlers(httpServer);\nserver.listen()\n```\n\n========================================\n\nComments:\n- On the final line, instead of `server.listen()`, I had to do `httpServer.listen()`. Perhaps it's a typo from the answer author?","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":239,"estimatedTokens":1306}}380{"id":"stack-56083422","source":"stackoverflow","questionId":56083422,"title":"apollo \"Subscription field must return Async Iterable. Received: undefined\"","tags":["javascript","reactjs","typescript","graphql","apollo"],"text":"Title: apollo \"Subscription field must return Async Iterable. Received: undefined\"\nTags: javascript, reactjs, typescript, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI have a mutation that fires the channel event 'countIncr', but I don't see the active corresponding subscription fire with the event payload.\n\n**UPDATE: I've made several updates to this posting and now I'm changing the title to be more representative of where I am.**\n\nI'm getting a graphqlPlayground error\n\n```\n\"Subscription field must return Async Iterable. Received: undefined\"\n```\n\n***TGRstack reproduction i'm having trouble with:*** https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/\n\n*Working Reproduction without TGRstack:* https://github.com/Falieson/fullstack-apollo-subscription-example\n\nhttps://i.sstatic.net/tw3mI.png\nhttps://i.sstatic.net/E3w5R.png\nhttps://i.sstatic.net/QhgT6.png\nhttps://i.sstatic.net/oB8FZ.png\nhttps://i.sstatic.net/Gpy8D.png\nhttps://i.sstatic.net/CRoz5.png\nhttps://i.sstatic.net/h8g5T.png\nFrontend: \nhttps://github.com/TGRstack/tgr-apollo-subscription-example-microservice/blob/master/counter-ui/src/app/routes/Home/HomePage.tsx\n\n```\nconst COUNTER_SUBSCRIPTION = gql`\nsubscription onCountIncr {\n count\n}\n`\n\nconst Counter = () => (\n \n {({ data, loading }) => {\n console.log({loading, data})\n return loading\n ? \n\n### Loading ...\n\n : data.count\n ? \n\n### Counter: {data.count}\n\n : \n\n### Counter Subscription Not Available\n\n }}\n \n)\n```\n\nBE Resolvers: https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/blob/master/counter-service/src/gql/Resolvers.ts\n\nBE Schema: https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/blob/master/counter-service/src/gql/Schema.ts\n\nBE Controller: https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/blob/master/counter-service/src/gql/Counter.ts\n\n```\nconst count = {\n resolve: data => {\n console.log('CounterSub>', {data})\n return data\n },\n subscribe: () => pubsub.asyncIterator(['countIncr'])\n}\n\nconst CounterSubscriptions = {\n count\n}\n```\n\n```\nasync function countIncr(root: any, args: any, context: any) {\n const count = Counter.increment()\n await pubsub.publish('countIncr', count )\n console.log('countIncr', '>>>', { count })\n return count\n}\n```\n\nHere is the service log after you've run through the #getting started instructions in the Readme.md\n\n```\n[FE] GET /favicon.ico 200 2.465 ms - 1551 # WEBCLIENT LOADED\n[BE] CounterSub> { data: undefined } # SUBSCRIPTION REQUEST\n[BE] { data: [Object: null prototype] { count: null } } # SUBSCRIPTION RESULT\n[BE] POST / 200 21.254 ms - 24\n[BE] 2019-05-10 11:37:20 [info]: HELLO # APOLLO CLIENT CONNECTED AGAIN (why always 2?)\n[BE] countIncr >>> { count: 1 } # MUTATION REQUEST\n[BE] { data: [Object: null prototype] { countIncr: 1 } } # MUTATION RESPONSE\n[BE] POST / 200 13.159 ms - 25\n[BE] countIncr >>> { count: 2 } # MUTATION REQUEST\n[BE] { data: [Object: null prototype] { countIncr: 2 } } # MUTATION RESPONSE\n[BE] POST / 200 4.380 ms - 25\n```\n\n**UPDATE**\n\nIncase you've tried to clone the repo and after running nps it didn't work its because there was a step missing in `nps setup`. I've pushed an update to the stack with the `nps setup` improved.\n\n**UPDATE 2**\n\nupdated code and links in question per latest commit\n\n**UPDATE 3**\n\nSome people have suggested that `pubsub` should be a single import. I've updated the code but this creates a new error:\n\n```\nError: Apollo Server requires either an existing schema, modules or typeDefs\n```\n\n**UPDATE 4**\n\nnumerous minor changes trying to hunt down import/export bugs(?) now getting the error. I fixed this error by hardening imports (there was some issue w/ the index file not properly exporting).\n\n```\n\"message\": \"Subscription field must return Async Iterable. Received: undefined\"\n```\n\nWorking Reproduction without TGRstack: https://github.com/Falieson/fullstack-apollo-subscription-example\n\n**Update 5**\n\nI demodularized/decomposed a bunch of things to make it easier to trace whats going on but still getting the same error\n\n========================================\n\nCode:\n```text\n\"Subscription field must return Async Iterable. Received: undefined\"\n```\n\n```text\nconst COUNTER_SUBSCRIPTION = gql`\nsubscription onCountIncr {\n count\n}\n`\n\nconst Counter = () => (\n <Subscription\n subscription={COUNTER_SUBSCRIPTION}\n >\n {({ data, loading }) => {\n console.log({loading, data})\n return loading\n ? <h1>Loading ...</h1>\n : data.count\n ? <h2>Counter: {data.count}</h2>\n : <h1>Counter Subscription Not Available</h1>\n }}\n </Subscription>\n)\n```\n\n```text\nconst count = {\n resolve: data => {\n console.log('CounterSub>', {data})\n return data\n },\n subscribe: () => pubsub.asyncIterator(['countIncr'])\n}\n\nconst CounterSubscriptions = {\n count\n}\n```\n\n```text\nasync function countIncr(root: any, args: any, context: any) {\n const count = Counter.increment()\n await pubsub.publish('countIncr', count )\n console.log('countIncr', '>>>', { count })\n return count\n}\n```\n\n```text\n[FE] GET /favicon.ico 200 2.465 ms - 1551 # WEBCLIENT LOADED\n[BE] CounterSub> { data: undefined } # SUBSCRIPTION REQUEST\n[BE] { data: [Object: null prototype] { count: null } } # SUBSCRIPTION RESULT\n[BE] POST / 200 21.254 ms - 24\n[BE] 2019-05-10 11:37:20 [info]: HELLO # APOLLO CLIENT CONNECTED AGAIN (why always 2?)\n[BE] countIncr >>> { count: 1 } # MUTATION REQUEST\n[BE] { data: [Object: null prototype] { countIncr: 1 } } # MUTATION RESPONSE\n[BE] POST / 200 13.159 ms - 25\n[BE] countIncr >>> { count: 2 } # MUTATION REQUEST\n[BE] { data: [Object: null prototype] { countIncr: 2 } } # MUTATION RESPONSE\n[BE] POST / 200 4.380 ms - 25\n```\n\n```text\nError: Apollo Server requires either an existing schema, modules or typeDefs\n```\n\n```text\n\"message\": \"Subscription field must return Async Iterable. Received: undefined\"\n```\n\n```text\nnps setup\n```\n\n```text\nnps setup\n```\n\n```text\npubsub\n```\n\n```text\nApolloServer.installSubscriptionHandlers(ws)\n\n const listener = ws.listen({port: config.PORT}, () => {\n middleware.apolloSubscriptions(ws)\n // middleware.apolloSubscriptions(ws)\n```\n\n```text\nprivate _terminatingLink = split(\n ({ query }) => {\n const { kind, operation } = getMainDefinition(query)\n return (\n kind === 'OperationDefinition' && operation === 'subscription'\n )\n },\n this._wsLink,\n this._httpLink,\n )\n```\n\n========================================\n\nComments:\n- This answer here solved my issue.","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":246,"estimatedTokens":1657}}381{"id":"stack-57539334","source":"stackoverflow","questionId":57539334,"title":"How to use passport-local with graphql","tags":["graphql","passport.js","apollo-server","passport-local"],"text":"Title: How to use passport-local with graphql\nTags: graphql, passport.js, apollo-server, passport-local\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement GraphQL in my project and I would like to use `passport.authenticate('local')` in my login Mutation\n\nCode adaptation of what I want:\n\n```\nconst typeDefs = gql`\ntype Mutation {\n login(userInfo: UserInfo!): User\n }\n`\n\n const resolvers = {\n Mutation: {\n login: (parent, args) => { \n passport.authenticate('local')\n return req.user\n }\n}\n```\n\nQuestions:\n\n- Was `passport` designed mostly for REST/Express?\n\n- Can I manipulate `passport.authenticate` method (pass username and password to it)?\n\n- Is this even a common practice or I should stick to some JWT library?\n\n========================================\n\nTop Answer:\nIt took me a while to wrap my head around the combination of GraphQL and Passport. Especially when you want to use the local strategy together with a login mutation makes life complicated. That's why I created a small npm package called graphql-passport.\n\nThis is how the setup of the server looks like.\n\n```\nimport express from 'express';\nimport session from 'express-session';\nimport { ApolloServer } from 'apollo-server-express';\nimport passport from 'passport';\nimport { GraphQLLocalStrategy, buildContext } from 'graphql-passport';\n\npassport.use(\n new GraphQLLocalStrategy((email, password, done) => {\n // Adjust this callback to your needs\n const users = User.getUsers();\n const matchingUser = users.find(user => email === user.email && password === user.password);\n const error = matchingUser ? null : new Error('no matching user');\n done(error, matchingUser);\n }),\n);\n\nconst app = express();\napp.use(session(options)); // optional\napp.use(passport.initialize());\napp.use(passport.session()); // if session is used\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n context: ({ req, res }) => buildContext({ req, res, User }),\n});\n\nserver.applyMiddleware({ app, cors: false });\n\napp.listen({ port: PORT }, () => {\n console.log(`π Server ready at http://localhost:${PORT}${server.graphqlPath}`);\n});\n```\n\nNow you will have access to passport specific functions and user via the GraphQL context. This is how you can write your resolvers:\n\n```\nconst resolvers = {\n Query: {\n currentUser: (parent, args, context) => context.getUser(),\n },\n Mutation: {\n login: async (parent, { email, password }, context) => {\n // instead of email you can pass username as well\n const { user } = await context.authenticate('graphql-local', { email, password });\n\n // only required if express-session is used\n context.login(user);\n\n return { user }\n },\n },\n};\n```\n\nThe combination of GraphQL and Passport.js makes sense. Especially if you want to add more authentication providers like Facebook, Google and so on. You can find more detailed information in this blog post if needed.\n\n========================================\n\nCode:\n```text\nconst typeDefs = gql`\ntype Mutation {\n login(userInfo: UserInfo!): User\n }\n`\n\n const resolvers = {\n Mutation: {\n login: (parent, args) => { \n passport.authenticate('local')\n return req.user\n }\n}\n```\n\n```text\npassport.authenticate('local')\n```\n\n```text\npassport\n```\n\n```text\npassport.authenticate\n```\n\n```text\nauthenticate\n```\n\n```text\nreq\n```\n\n```text\nreq.login\n```\n\n```text\nuser\n```\n\n```text\nreq.logout\n```\n\n```text\napollo-server-express\n```\n\n```text\nreq.user\n```\n\n```js\nimport express from 'express';\nimport session from 'express-session';\nimport { ApolloServer } from 'apollo-server-express';\nimport passport from 'passport';\nimport { GraphQLLocalStrategy, buildContext } from 'graphql-passport';\n\npassport.use(\n new GraphQLLocalStrategy((email, password, done) => {\n // Adjust this callback to your needs\n const users = User.getUsers();\n const matchingUser = users.find(user => email === user.email && password === user.password);\n const error = matchingUser ? null : new Error('no matching user');\n done(error, matchingUser);\n }),\n);\n\nconst app = express();\napp.use(session(options)); // optional\napp.use(passport.initialize());\napp.use(passport.session()); // if session is used\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n context: ({ req, res }) => buildContext({ req, res, User }),\n});\n\nserver.applyMiddleware({ app, cors: false });\n\napp.listen({ port: PORT }, () => {\n console.log(`π Server ready at http://localhost:${PORT}${server.graphqlPath}`);\n});\n```\n\n```js\nconst resolvers = {\n Query: {\n currentUser: (parent, args, context) => context.getUser(),\n },\n Mutation: {\n login: async (parent, { email, password }, context) => {\n // instead of email you can pass username as well\n const { user } = await context.authenticate('graphql-local', { email, password });\n\n // only required if express-session is used\n context.login(user);\n\n return { user }\n },\n },\n};\n```\n\n```text\npassport\n```\n\n```text\npassport\n```\n\n```text\npassport\n```\n\n========================================\n\nComments:\n- Wow, thanks a lot! How common this passport-graphql combination in real life? I have a feeling that I probably should not use passport here.\n- When you use REST login - how will you pass the HttpOnly cookie (with the JWT token) into the GraphQL playground?\n- You can read the cookie on the frontend and pass it to the GraphQL query. More details here: csaba-apagyi.medium.com/… Example here: github.com/thisismydesign/nestjs-starter","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":229,"estimatedTokens":1364}}382{"id":"stack-42670733","source":"stackoverflow","questionId":42670733,"title":"Graphql with nested mutations?","tags":["graphql","graphql-js"],"text":"Title: Graphql with nested mutations?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am trying to figure out how to mutate a nested object with graphql mutations, if possible. For instance I have the following schema:\n\n```\ntype Event {\n id: String\n name: String\n description: String\n place: Place\n}\n\ntype Place {\n id: String\n name: String\n location: Location\n}\n\ntype Location {\n city: String\n country: String\n zip: String\n}\n\ntype Query {\n events: [Event]\n}\n\ntype Mutation {\n updateEvent(id: String, name: String, description: String): Event\n}\n\nschema {\n query: Query\n mutation: Mutation\n}\n```\n\nHow can I add the place information inside my `updateEvent` mutation?\n\n========================================\n\nTop Answer:\nGenerally speaking, you should avoid thinking of the arguments to your mutations as a direct mapping to object types in your schema. Whilst it's true that they will often be similar, you're better off approaching things under the assumption that they won't be.\n\nUsing your basic types as an example. Let's say I wanted to create a new event, but rather than knowing the location, I just have the longitude/latitude - it's actually the backend that calculates the real location object from this data, and I certainly don't know its ID (it doesn't have one yet!). I'd probably construct my mutation like this:\n\n```\ninput Point {\n longitude: Float!\n latitude: Float!\n}\n\ninput PlaceInput {\n name\n coordinates: Point!\n}\n\ntype mutation {\n createEvent(\n name: String!\n description: String\n placeId: ID\n newPlace: PlaceInput\n ): Event \n updateEvent(\n id: ID!\n name: String!\n description: String\n placeId: ID\n newPlace: PlaceInput\n ): Event\n)\n```\n\nA mutation is basically just a function call, and it's best to think of it in those terms. If you wrote a function to create an Event, you likely wouldn't provide it an event and expect it to return an event, you'd provide the *information necessary to create an Event*.\n\n========================================\n\nCode:\n```text\ntype Event {\n id: String\n name: String\n description: String\n place: Place\n}\n\ntype Place {\n id: String\n name: String\n location: Location\n}\n\ntype Location {\n city: String\n country: String\n zip: String\n}\n\ntype Query {\n events: [Event]\n}\n\ntype Mutation {\n updateEvent(id: String, name: String, description: String): Event\n}\n\nschema {\n query: Query\n mutation: Mutation\n}\n```\n\n```text\nupdateEvent\n```\n\n```js\ntype Location {\n city: String\n country: String\n zip: String\n }\n\n type Place {\n id: String\n name: String\n location: Location\n }\n\n type Event {\n id: String\n name: String\n description: String\n place: Place\n }\n\n input LocationInput {\n city: String\n country: String\n zip: String\n }\n\n input PlaceInput {\n id: ID!\n name: String!\n location: LocationInput!\n }\n\n type Query {\n events: [Event]\n }\n\n type Mutation {\n updateEvent(id: String, name: String, description: String, place: PlaceInput!): Event\n }\n\n schema {\n query: Query\n mutation: Mutation\n }\n```\n\n```text\ninput Point {\n longitude: Float!\n latitude: Float!\n}\n\ninput PlaceInput {\n name\n coordinates: Point!\n}\n\ntype mutation {\n createEvent(\n name: String!\n description: String\n placeId: ID\n newPlace: PlaceInput\n ): Event \n updateEvent(\n id: ID!\n name: String!\n description: String\n placeId: ID\n newPlace: PlaceInput\n ): Event\n)\n```\n\n========================================\n\nComments:\n- This might serve as inspiration: graph.cool/docs/reference/simple-api/…\n- Is there any way to avoid providing all the nested fields? For example if I don't provide the full location object, the fields which I don't provide are replaced with null or removed. Any idea about it?\n- You could remove the \"!\" from the input type then it is not required anymore. Doing so you could use just a part of the location object. I think in the resolver function it will be undefined. But i'm not sure about that.\n- This should not work. GraphQL.org says that `The fields on an input object type can themselves refer to input object types, but you can't mix input and output types in your schema.` You would need an extra `LocationInput` type.\n- I was about to ask the same question as the OP - what would the usage of `createEvent()` look like in this case, as PlaceInput is still a complex type?\n- Can you add a sample resolver function too that consumes the newPlace and how it access the manipulated the data, a sample insert\n- @andymccullough I realize it's been three years, but for completeness: `mutation { createEvent(name: \"Foo\", newPlace: {name: \"Somewhere\", coordinates: {longitude: 42, latitude: 42}})`","metadata":{"transformedAt":"2026-08-18T18:32:36.053Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":205,"estimatedTokens":1202}}383{"id":"stack-52744900","source":"stackoverflow","questionId":52744900,"title":"Apollo / GraphQl - Type must be Input type","tags":["meteor","graphql","apollo"],"text":"Title: Apollo / GraphQl - Type must be Input type\nTags: meteor, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nReaching to you all as I am in the learning process and integration of Apollo and graphQL into one of my projects. So far it goes ok but now I am trying to have some mutations and I am struggling with the Input type and Query type. I feel like it's way more complicated than it should be and therefore I am looking for advice on how I should manage my situation. Examples I found online are always with very basic Schemas but the reality is always more complex as my Schema is quite big and look as (I'll copy just a part):\n\n```\ntype Calculation {\n _id: String!\n userId: String!\n data: CalculationData\n lastUpdated: Int\n name: String\n}\n\ntype CalculationData {\n Loads: [Load]\n validated: Boolean\n x: Float\n y: Float\n z: Float\n Inputs: [Input]\n metric: Boolean\n\n}\n```\n\nThen Inputs and Loads are defined, and so on...\n\nFor this I want a mutation to save the \"Calculation\", so in the same file I have this:\n\n```\ntype Mutation {\n saveCalculation(data: CalculationData!, name: String!): Calculation\n}\n```\n\nMy resolver is as :\n\n```\nexport default resolvers = {\n Mutation: {\n saveCalculation(obj, args, context) {\n if(context.user && context.user._id){\n const calculationId = Calculations.insert({\n userId: context.user._id,\n data: args.data,\n name: args.name\n })\n return Calculations.findOne({ _id: calculationId})\n }\n throw new Error('Need an account to save a calculation')\n }\n }\n}\n```\n\nThen my mutation is the following :\n import gql from 'graphql-tag';\n\n```\nexport const SAVE_CALCULATION = gql`\n mutation saveCalculation($data: CalculationData!, $name: String!){\n saveCalculation(data: $data, name: $name){\n _id\n }\n }\n`\n```\n\nFinally I am using the Mutation component to try to save the data:\n\n```\n\n {(saveCalculation, {Β data }) => (\n saveCalculation({ variables : { data: this.state, name:'name calcul' }})}>SAVE\n }}\n\n```\n\nNow I get the following error :\n\n [GraphQL error]: Message: The type of Mutation.saveCalculation(data:)\n must be Input Type but got: CalculationData!., Location: undefined,\n Path: undefined\n\nFrom my research and some other SO posts, I get that I should define Input type in addition to the Query type but Input type can only avec Scalar types but my schema depends on other schemas (and that is not scalar). Can I create Input types depending on other Input types and so on when the last one has only scalar types? I am kinda lost cause it seems like a lot of redundancy. Would very much appreciate some guidance on the best practice. I am convinced **Apollo/graphql** could bring me quite good help over time on my project but I have to admit it is more complicated than I thought to implement it when the Schemas are a bit complex. Online examples generally stick to a String and a Boolean.\n\n========================================\n\nTop Answer:\nYes, you can:\n\nThe fields on an input object type can themselves refer to input object types, but you can't mix input and output types in your schema. Input object types also can't have arguments on their fields.\n\nInput types are meant to be defined in addition to normal types. Usually they'll have some differences, eg input won't have an id or createdAt field.\n\n========================================\n\nCode:\n```text\ntype Calculation {\n _id: String!\n userId: String!\n data: CalculationData\n lastUpdated: Int\n name: String\n}\n\ntype CalculationData {\n Loads: [Load]\n validated: Boolean\n x: Float\n y: Float\n z: Float\n Inputs: [Input]\n metric: Boolean\n\n}\n```\n\n```text\ntype Mutation {\n saveCalculation(data: CalculationData!, name: String!): Calculation\n}\n```\n\n```text\nexport default resolvers = {\n Mutation: {\n saveCalculation(obj, args, context) {\n if(context.user && context.user._id){\n const calculationId = Calculations.insert({\n userId: context.user._id,\n data: args.data,\n name: args.name\n })\n return Calculations.findOne({ _id: calculationId})\n }\n throw new Error('Need an account to save a calculation')\n }\n }\n}\n```\n\n```text\nexport const SAVE_CALCULATION = gql`\n mutation saveCalculation($data: CalculationData!, $name: String!){\n saveCalculation(data: $data, name: $name){\n _id\n }\n }\n`\n```\n\n```text\n<Mutation mutation={SAVE_CALCULATION}>\n {(saveCalculation, {Β data }) => (\n <div onClick={() => saveCalculation({ variables : { data: this.state, name:'name calcul' }})}>SAVE</div>\n }}\n</Mutation>\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\nLoad\n```\n\n```text\nLoadInput\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\nfriends\n```\n\n```text\nUser\n```\n\n```text\npassword\n```\n\n========================================\n\nComments:\n- Once again thanks for clear answer about graphQL/Apollo\n- I have no idea what this answer means by `have to create a Load type and a LoadInput input\"\n- @YanickRochon GraphQL has object types designated by the `type` keyword and input object types designed by the `input` keyword. The former is used for output, the latter for input.\n- @DanielRearden thank you for the clarification, I'm beginning to use GraphQL and there is much I need to learn.","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":211,"estimatedTokens":1350}}384{"id":"stack-39313219","source":"stackoverflow","questionId":39313219,"title":"Optimizing graphql database queries","tags":["graphql","graphql-js"],"text":"Title: Optimizing graphql database queries\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nLets say we have following graphql schema:\n\n```\ntype Author : Object { \n id: ID!\n name: String,\n books: [Book]\n}\n\ntype Book : Object { \n id: ID!\n title: String\n authorId: Int\n author: Author\n}\n```\n\nAnd then making a query like:\n\n```\n{\n books: {\n id \n title\n author { id name }\n }\n}\n```\n\nIf, for example, we have 10 books, then we will end up with 10 author queries, as the resolve function will be called for each fetched book:\n\n```\nselect id, name from author where id = 123\n```\n\nInstead of this we can execute all author queries as a single query:\n\n```\nselect id, name from author where id in (123, 456, 789, 1011)\n```\n\nIs there some working solutions, best practices, techniques or something that can help to achieve this?\n\n========================================\n\nTop Answer:\nDataLoader is a great database-agnostic solution. If you're using SQL, Join Monster is more tailored for relational DBs and will even translate the GraphQL queries to SQL directly with a single round-trip. Another alternative is graph-joiner.\n\n========================================\n\nCode:\n```text\ntype Author : Object { \n id: ID!\n name: String,\n books: [Book]\n}\n\ntype Book : Object { \n id: ID!\n title: String\n authorId: Int\n author: Author\n}\n```\n\n```text\n{\n books: {\n id \n title\n author { id name }\n }\n}\n```\n\n```text\nselect id, name from author where id = 123\n```\n\n```text\nselect id, name from author where id in (123, 456, 789, 1011)\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":88,"estimatedTokens":391}}385{"id":"stack-44435510","source":"stackoverflow","questionId":44435510,"title":"Apollo (GraphQL) fetch more than one element in a query","tags":["reactjs","graphql","apollo"],"text":"Title: Apollo (GraphQL) fetch more than one element in a query\nTags: reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nCan I fetch more than one element in a GraphQL query? I have many products list data and I want to fetch, for example, three products in my component. I have an array of needed product IDs, can I pass it to query? This is my query for one product:\n\n```\nquery ProductInCartQuery($id: ID!){\n Product(id: $id) { \n id\n name\n price\n }\n}\n```\n\nBut I don't think I can just put it in a function and execute it for example three times for three products.\n\n========================================\n\nTop Answer:\nFor adding the product ids to the query you could define a `input` type. See the cheat sheet.\n\nSo the query on the client could look like:\n\n\r\n\r\n\n```\nquery ProductsInCartQuery($productIds: ProductIds!) {\r\n Products(productIds: $productIds) {\r\n id\r\n name\r\n price\r\n }\r\n}\n```\n\n\r\n\r\n\r\n\nOn the server you define the schema with the `input` type as follows:\n\n\r\n\r\n\n```\ninput ProductIds {\r\n ids: [ID!]\r\n}\r\n\r\ntype Query {\r\n Products(productIds: ProductIds!) {\r\n id\r\n name\r\n price\r\n }\r\n}\r\n\r\nschema {\r\n query: Query\r\n}\n```\n\n========================================\n\nCode:\n```text\nquery ProductInCartQuery($id: ID!){\n Product(id: $id) { \n id\n name\n price\n }\n}\n```\n\n```text\nquery ProductInCartQuery($firstId: ID!, $secondId: ID!){\n firstProduct: Product(id: $firstId) { \n id\n ... ProductInfo\n }\n\n secondProduct: Product(id: $secondId) { \n id\n ... ProductInfo\n }\n\n fragment ProductInfo on Product {\n name\n price\n }\n}\n```\n\n```text\nquery filteredProducts($ids: [ID!]!) {\n allProducts(filter: {\n id_in: $ids\n }) {\n ... ProductInfo\n }\n}\n\nfragment ProductInfo on Product {\n name\n price\n}\n```\n\n```text\nid\n```\n\n```text\nProduct\n```\n\n```text\nallProducts\n```\n\n```text\nProduct\n```\n\n```text\nallProducts\n```\n\n```js\nquery ProductsInCartQuery($productIds: ProductIds!) {\n Products(productIds: $productIds) {\n id\n name\n price\n }\n}\n```\n\n```js\ninput ProductIds {\n ids: [ID!]\n}\n\ntype Query {\n Products(productIds: ProductIds!) {\n id\n name\n price\n }\n}\n\nschema {\n query: Query\n}\n```\n\n```text\ninput\n```\n\n```text\ninput\n```\n\n========================================\n\nComments:\n- Please edit your post to contain your schema code.\n- Sure you can...\n- How? I added my query in edit.\n- Thanks! Filter parameter was exactly this what I needed ;)","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":176,"estimatedTokens":599}}386{"id":"stack-63166812","source":"stackoverflow","questionId":63166812,"title":"Correct way to remove item from client side cache in apollo-client","tags":["reactjs","typescript","graphql","react-apollo","apollo-client"],"text":"Title: Correct way to remove item from client side cache in apollo-client\nTags: reactjs, typescript, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am using GraphQL with Apollo-Client in my React(Typescript) application with an in memory cache. The cache is updated on new items being added which works fine with no errors.\n\nWhen items are removed a string is returned from GraphQL Apollo-Server backend stating the successful delete operation which initiates the update function to be called which reads the cache and then modifies it by filtering out the id of the item. This is performed using the mutation hook from Apollo-Client.\n\n```\nconst [deleteBook] = useMutation(DELETE_BOOK_MUTATION, {\n variables: { id },\n onError(error) {\n console.log(error);\n },\n update(proxy) {\n const bookCache = proxy.readQuery({ query: GET_BOOKS_QUERY });\n if (bookCache) {\n proxy.writeQuery({\n query: GET_BOOKS_QUERY,\n data: { getBooks: bookCache.getBooks.filter((b) => b._id !== id) },\n });\n }\n },\n });\n```\n\nThe function works and the frontend is updated with the correct items in cache, however the following error is displayed in the console:\n\n```\nCache data may be lost when replacing the getBooks field of a Query object.\n\nTo address this problem (which is not a bug in Apollo Client), define a custom merge function for the Query.getBooks field, so InMemoryCache can safely merge these objects:\n\n existing: [{\"__ref\":\"Book:5f21280332de1d304485ae80\"},{\"__ref\":\"Book:5f212a1332de1d304485ae81\"},{\"__ref\":\"Book:5f212a6732de1d304485ae82\"},{\"__ref\":\"Book:5f212a9232de1d304485ae83\"},{\"__ref\":\"Book:5f21364832de1d304485ae84\"},{\"__ref\":\"Book:5f214e1932de1d304485ae85\"},{\"__ref\":\"Book:5f21595a32de1d304485ae88\"},{\"__ref\":\"Book:5f2166601f6a633ae482bae4\"}]\n incoming: [{\"__ref\":\"Book:5f212a1332de1d304485ae81\"},{\"__ref\":\"Book:5f212a6732de1d304485ae82\"},{\"__ref\":\"Book:5f212a9232de1d304485ae83\"},{\"__ref\":\"Book:5f21364832de1d304485ae84\"},{\"__ref\":\"Book:5f214e1932de1d304485ae85\"},{\"__ref\":\"Book:5f21595a32de1d304485ae88\"},{\"__ref\":\"Book:5f2166601f6a633ae482bae4\"}]\n\nFor more information about these options, please refer to the documentation:\n\n * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\n * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\n```\n\nIs there a better way to update the cache so this error won't be received?\n\n========================================\n\nTop Answer:\nI've also faced the same problem. I've come across a GitHub thread that offers two alternative solutions here.\n\nThe first is evicting what's in your cache before calling `cache.writeQuery`:\n\n```\ncache.evict({\n // Often cache.evict will take an options.id property, but that's not necessary\n // when evicting from the ROOT_QUERY object, as we're doing here.\n fieldName: \"notifications\",\n // No need to trigger a broadcast here, since writeQuery will take care of that.\n broadcast: false,\n });\n```\n\nIn short this flushes your cache so your new data will be the new source of truth. There is no concern about losing your old data.\n\nAn alternative suggestion for the apollo-client v3 is posted further below in the same thread:\n\n```\ncache.modify({\n fields: {\n notifications(list, { readField }) {\n return list.filter((n) => readField('id', n) !==id)\n },\n },\n})\n```\n\nThis way removes a lot of boilerplate so you don't need to use `readQuery`, `evict`, and `writeQuery`. The problem is that if you're running Typescript you'll run into some implementation issues. Under-the-hood the format used is `InMemoryCache` format instead of the usual GraphQL data. You'll be seeing `Reference` objects, types that aren't inferred, and other weird things.\n\n========================================\n\nCode:\n```text\nconst [deleteBook] = useMutation<{ deleteBook: string }, DeleteBookProps>(DELETE_BOOK_MUTATION, {\n variables: { id },\n onError(error) {\n console.log(error);\n },\n update(proxy) {\n const bookCache = proxy.readQuery<{ getBooks: IBook[] }>({ query: GET_BOOKS_QUERY });\n if (bookCache) {\n proxy.writeQuery<IGetBooks>({\n query: GET_BOOKS_QUERY,\n data: { getBooks: bookCache.getBooks.filter((b) => b._id !== id) },\n });\n }\n },\n });\n```\n\n```text\nCache data may be lost when replacing the getBooks field of a Query object.\n\nTo address this problem (which is not a bug in Apollo Client), define a custom merge function for the Query.getBooks field, so InMemoryCache can safely merge these objects:\n\n existing: [{\"__ref\":\"Book:5f21280332de1d304485ae80\"},{\"__ref\":\"Book:5f212a1332de1d304485ae81\"},{\"__ref\":\"Book:5f212a6732de1d304485ae82\"},{\"__ref\":\"Book:5f212a9232de1d304485ae83\"},{\"__ref\":\"Book:5f21364832de1d304485ae84\"},{\"__ref\":\"Book:5f214e1932de1d304485ae85\"},{\"__ref\":\"Book:5f21595a32de1d304485ae88\"},{\"__ref\":\"Book:5f2166601f6a633ae482bae4\"}]\n incoming: [{\"__ref\":\"Book:5f212a1332de1d304485ae81\"},{\"__ref\":\"Book:5f212a6732de1d304485ae82\"},{\"__ref\":\"Book:5f212a9232de1d304485ae83\"},{\"__ref\":\"Book:5f21364832de1d304485ae84\"},{\"__ref\":\"Book:5f214e1932de1d304485ae85\"},{\"__ref\":\"Book:5f21595a32de1d304485ae88\"},{\"__ref\":\"Book:5f2166601f6a633ae482bae4\"}]\n\nFor more information about these options, please refer to the documentation:\n\n * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\n * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\n```\n\n```text\nconst client = new ApolloClient({\n ....\n cache: new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n getBooks: {\n merge(existing, incoming) {\n return incoming;\n },\n },\n },\n },\n }\n }),\n});\n```\n\n```text\ncache.evict({\n // Often cache.evict will take an options.id property, but that's not necessary\n // when evicting from the ROOT_QUERY object, as we're doing here.\n fieldName: \"notifications\",\n // No need to trigger a broadcast here, since writeQuery will take care of that.\n broadcast: false,\n });\n```\n\n```text\ncache.modify({\n fields: {\n notifications(list, { readField }) {\n return list.filter((n) => readField('id', n) !==id)\n },\n },\n})\n```\n\n```text\ncache.writeQuery\n```\n\n```text\nreadQuery\n```\n\n```text\nevict\n```\n\n```text\nwriteQuery\n```\n\n```text\nInMemoryCache\n```\n\n```text\nReference\n```\n\n========================================\n\nComments:\n- Thanks, that solved the error message. Seems strange, I guess Apollo-Client just wants an explicit method to merge queries.\n- Couldn't get cache.evict to work, but cache.modify seems to be the best way anyway","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":181,"estimatedTokens":1657}}387{"id":"stack-49078788","source":"stackoverflow","questionId":49078788,"title":"Using GitHub API v4 GraphQL to find all open issues belonging to repositories owned by the user","tags":["graphql","github-api","github-graphql"],"text":"Title: Using GitHub API v4 GraphQL to find all open issues belonging to repositories owned by the user\nTags: graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nCan someone please point me in the right direction for listing all open issues that are in repos owned by the user? Thanks in advance.\n\n========================================\n\nTop Answer:\nYour answer is probably the most efficient way in terms of pagination, but another approach you could take is to iterate over all of the user's owned repositories, and for each of those repositories fetch their issues with something like:\n\n```\nquery($userLogin: String!) {\n user(login: $userLogin) {\n repositories(affiliations: [OWNER], last: 10) {\n edges {\n node {\n issues(states: [OPEN], last: 10) {\n edges {\n node {\n createdAt\n title\n url\n repository {\n name\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n search(first: 100, type: ISSUE, query: \"user:will-stone state:open\") {\n issueCount\n pageInfo {\n hasNextPage\n endCursor\n }\n edges {\n node {\n ... on Issue {\n createdAt\n title\n url,\n repository {\n name\n }\n }\n }\n }\n }\n}\n```\n\n```text\nquery($userLogin: String!) {\n user(login: $userLogin) {\n repositories(affiliations: [OWNER], last: 10) {\n edges {\n node {\n issues(states: [OPEN], last: 10) {\n edges {\n node {\n createdAt\n title\n url\n repository {\n name\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks. With this method, I end up with lots of empty repo entries (the ones that don't have any current issues).\n- @WillStone, that's correct. Unfortunately there isn't a way to filter out repositories with no issues. If this is something you would find valuable, you can submit a schema request here and we can take a look. The tradeoff of using the `search` field is that it has to hit search infrastructure and will be much slower to return results.\n- Can I sort the repos by last push? The newest pushed repos also have recent issues.","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":95,"estimatedTokens":574}}388{"id":"stack-55008651","source":"stackoverflow","questionId":55008651,"title":"Error: Network error: Error writing result to store for query:","tags":["javascript","angular","typescript","graphql","apollo"],"text":"Title: Error: Network error: Error writing result to store for query:\nTags: javascript, angular, typescript, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nGetting this error from **Apollo**:\n\n```\ncore.js:14576 ERROR Error: Network error: Error writing result to store for query:\n {\"kind\":\"Document\",\"definitions\":[{\"kind\":\"OperationDefinition\",\"operation\":\"query\",\"name\":{\"kind\":\"Name\",\"value\":\"AdditionalServices\"},\"variableDefinitions\":[{\"kind\":\"VariableDefinition\",\"variable\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"vendorID\"}},\"type\":{\"kind\":\"NonNullType\",\"type\":{\"kind\":\"NamedType\",\"name\":{\"kind\":\"Name\",\"value\":\"ID\"}}},\"directives\":[]}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"vendor\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"value\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"vendorID\"}}}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"alias\":{\"kind\":\"Name\",\"value\":\"services\"},\"name\":{\"kind\":\"Name\",\"value\":\"products\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"productTypes\"},\"value\":{\"kind\":\"EnumValue\",\"value\":\"service\"}}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"nodes\"},\"arguments\":[],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"isActive\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"cartSection\"},\"arguments\":[],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"description\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"imageUrl\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"shortDescription\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}}]}}],\"loc\":{\"start\":0,\"end\":372}}\nStore error: the application attempted to write an object with no provided id but the store already contains an id of Restaurant:200 for this object. The selectionSet that was trying to be written is:\n{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"vendor\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"value\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"vendorID\"}}}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"alias\":{\"kind\":\"Name\",\"value\":\"services\"},\"name\":{\"kind\":\"Name\",\"value\":\"products\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"productTypes\"},\"value\":{\"kind\":\"EnumValue\",\"value\":\"service\"}}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"nodes\"},\"arguments\":[],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"isActive\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"cartSection\"},\"arguments\":[],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"description\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"imageUrl\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"shortDescription\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}}\n at new ApolloError (ApolloError.js:25)\n at QueryManager.js:276\n at QueryManager.js:638\n at Array.forEach ()\n at QueryManager.js:637\n at Map.forEach ()\n at QueryManager.push../node_modules/apollo-client/core/QueryManager.js.QueryManager.broadcastQueries (QueryManager.js:632)\n at QueryManager.js:226\n at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)\n at Object.onInvoke (core.js:16135)\n```\n\nThis is the code that makes this happen:\n\n```\nthis.restaurantID$.pipe(\n takeUntil(this._ngOnDestroy)\n )\n .subscribe((restaurantID) => {\n this.additionalServicesQuery$.next(this._apollo\n .watchQuery({\n query: AdditionalServicesQuery,\n variables: { vendorID: restaurantID }\n }));\n });\n\n const loadAdditionalServicesData = this.additionalServicesQuery$\n .pipe(\n takeUntil(this._ngOnDestroy),\n filter((query) => !!query),\n switchMap((query) => query.valueChanges), // This is the switchMap that makes it happen\n takeUntil(this._ngOnDestroy),\n map((response) => response.data.vendor.services.nodes)\n );\n```\n\nThere is a **SwitchMap** that I commented if that is removed, the error does not happen. I can't understand what is going on.\n\n**query**:\n\n```\nexport const AdditionalServicesQuery = gql`\n query AdditionalServices(\n $vendorID: ID!\n ) {\n vendor(\n id: $vendorID\n ) {\n services: products (productTypes: service) {\n nodes {\n id\n isActive\n cartSection {\n id\n name\n }\n description\n imageUrl\n shortDescription\n name\n }\n }\n }\n }\n`;\n```\n\n**Update:**\n\nAdded ID to query, still, same issue\n\n```\nexport const AdditionalServicesQuery = gql`\n query AdditionalServices(\n $vendorID: ID!\n ) {\n vendor(\n id: $vendorID\n ) {\n services: products (productTypes: service) {\n id\n nodes {\n id\n isActive\n cartSection {\n id\n name\n }\n description\n imageUrl\n shortDescription\n name\n }\n }\n }\n }\n`;\n```\n\n========================================\n\nCode:\n```text\ncore.js:14576 ERROR Error: Network error: Error writing result to store for query:\n {\"kind\":\"Document\",\"definitions\":[{\"kind\":\"OperationDefinition\",\"operation\":\"query\",\"name\":{\"kind\":\"Name\",\"value\":\"AdditionalServices\"},\"variableDefinitions\":[{\"kind\":\"VariableDefinition\",\"variable\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"vendorID\"}},\"type\":{\"kind\":\"NonNullType\",\"type\":{\"kind\":\"NamedType\",\"name\":{\"kind\":\"Name\",\"value\":\"ID\"}}},\"directives\":[]}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"vendor\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"value\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"vendorID\"}}}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"alias\":{\"kind\":\"Name\",\"value\":\"services\"},\"name\":{\"kind\":\"Name\",\"value\":\"products\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"productTypes\"},\"value\":{\"kind\":\"EnumValue\",\"value\":\"service\"}}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"nodes\"},\"arguments\":[],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"isActive\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"cartSection\"},\"arguments\":[],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"description\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"imageUrl\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"shortDescription\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}}]}}],\"loc\":{\"start\":0,\"end\":372}}\nStore error: the application attempted to write an object with no provided id but the store already contains an id of Restaurant:200 for this object. The selectionSet that was trying to be written is:\n{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"vendor\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"value\":{\"kind\":\"Variable\",\"name\":{\"kind\":\"Name\",\"value\":\"vendorID\"}}}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"alias\":{\"kind\":\"Name\",\"value\":\"services\"},\"name\":{\"kind\":\"Name\",\"value\":\"products\"},\"arguments\":[{\"kind\":\"Argument\",\"name\":{\"kind\":\"Name\",\"value\":\"productTypes\"},\"value\":{\"kind\":\"EnumValue\",\"value\":\"service\"}}],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"nodes\"},\"arguments\":[],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"isActive\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"cartSection\"},\"arguments\":[],\"directives\":[],\"selectionSet\":{\"kind\":\"SelectionSet\",\"selections\":[{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"id\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"description\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"imageUrl\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"shortDescription\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"name\"},\"arguments\":[],\"directives\":[]},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}},{\"kind\":\"Field\",\"name\":{\"kind\":\"Name\",\"value\":\"__typename\"}}]}}\n at new ApolloError (ApolloError.js:25)\n at QueryManager.js:276\n at QueryManager.js:638\n at Array.forEach (<anonymous>)\n at QueryManager.js:637\n at Map.forEach (<anonymous>)\n at QueryManager.push../node_modules/apollo-client/core/QueryManager.js.QueryManager.broadcastQueries (QueryManager.js:632)\n at QueryManager.js:226\n at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)\n at Object.onInvoke (core.js:16135)\n```\n\n```text\nthis.restaurantID$.pipe(\n takeUntil(this._ngOnDestroy)\n )\n .subscribe((restaurantID) => {\n this.additionalServicesQuery$.next(this._apollo\n .watchQuery<AdditionalServices>({\n query: AdditionalServicesQuery,\n variables: { vendorID: restaurantID }\n }));\n });\n\n const loadAdditionalServicesData = this.additionalServicesQuery$\n .pipe(\n takeUntil(this._ngOnDestroy),\n filter((query) => !!query),\n switchMap((query) => query.valueChanges), // This is the switchMap that makes it happen\n takeUntil(this._ngOnDestroy),\n map((response) => response.data.vendor.services.nodes)\n );\n```\n\n```text\nexport const AdditionalServicesQuery = gql`\n query AdditionalServices(\n $vendorID: ID!\n ) {\n vendor(\n id: $vendorID\n ) {\n services: products (productTypes: service) {\n nodes {\n id\n isActive\n cartSection {\n id\n name\n }\n description\n imageUrl\n shortDescription\n name\n }\n }\n }\n }\n`;\n```\n\n```text\nexport const AdditionalServicesQuery = gql`\n query AdditionalServices(\n $vendorID: ID!\n ) {\n vendor(\n id: $vendorID\n ) {\n services: products (productTypes: service) {\n id\n nodes {\n id\n isActive\n cartSection {\n id\n name\n }\n description\n imageUrl\n shortDescription\n name\n }\n }\n }\n }\n`;\n```\n\n```text\nexport const AdditionalServicesQuery = gql`\n query AdditionalServices(\n $vendorID: ID!\n ) {\n vendor(\n id: $vendorID\n ) {\n id # <----------------------------------------- ADD ME\n services: products (productTypes: service) {\n nodes {\n id\n isActive\n cartSection {\n id\n name\n }\n description\n imageUrl\n shortDescription\n name\n }\n }\n }\n }\n`;\n```\n\n```text\nid\n```\n\n```text\n_id\n```\n\n```text\nvendor\n```\n\n```text\nRestaurant\n```\n\n```text\nRestaurant\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- Wow. Tnx! After server migrates this id in, I will check to see it works, and accept this answer if it does\n- It did not work... edited my question for the new query\n- Hmm.. The error indicates there's another query that's producing a cache key of `Restuarant:200`. Do you know what other query is running that would return a Restaurant object with that key? Are you using a custom `dataIdFromObject` function?\n- I do have other queries returning the same object with that id, but they have one specified... And not using dataIdFromObject. Should I?\n- Ok, you were right, it was the issue. Missing id on a restaurant req, thank you.","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":268,"estimatedTokens":3543}}389{"id":"stack-45397333","source":"stackoverflow","questionId":45397333,"title":"Get last x commits from Github repo using Github Api V4","tags":["github","graphql","github-api"],"text":"Title: Get last x commits from Github repo using Github Api V4\nTags: github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use the new Github GraphQL api (v4) and I don't seem to be able to figure out how to get the last x commits for **master**. I've used **repository** and **ref** but they still don't give me what I need.\n\nThe query below almost gives me what I need:\n\n```\nquery{\n repository(owner: \"typelevel\", name: \"cats\") {\n refs(refPrefix:\"refs/heads/\", last: 5) {\n edges{\n node {\n associatedPullRequests(states: MERGED, last: 5) {\n edges{\n node {\n title\n baseRef {\n name\n prefix\n }\n baseRefName\n commits(last: 10) {\n edges {\n node {\n commit {\n abbreviatedOid\n message\n \n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\nbut:\n\n- doesn't seems to exactly match what is in the repo\n\n- limited to PRs\n\n- seems too unwieldy\n\nI also tried using **defaultBranchRef** but that didn't work either:\n\n```\nquery{\n repository(owner: \"typelevel\", name: \"cats\") {\n defaultBranchRef {\n name\n prefix\n associatedPullRequests(states: [MERGED], last: 5) {\n edges {\n node {\n title\n }\n }\n }\n }\n }\n}\n```\n\nI've been testing the queries using the explorer app on the Github api page.\n\nAny ideas?\n\n========================================\n\nTop Answer:\nWould using `history` be better in this case?\n\nSee this thread\n\nA \"`ref`\" (short for reference) is anything that points to a git commit. This could be a local branch, a tag, a remote branch, etc. So `master`, for example, would be considered a ref.\n\nIn that vein, you can use the `ref` field on the `Repository` type to get a reference that targets a commit.\n\nFrom that commit, you can get all of the commit's parents. If you target `master`, you can get the main `history` of the git repository.\n\n```\nquery {\n node(id: \"MDEwOlJlcG9zaXRvcnk4NDM5MTQ3\") {\n ... on Repository {\n ref(qualifiedName: \"master\") {\n target {\n ... on Commit {\n id\n history(first: 30) {\n totalCount\n pageInfo {\n hasNextPage\n }\n\n edges {\n node {\n oid\n message\n author {\n name\n email\n date\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```graphql\nquery{\n repository(owner: \"typelevel\", name: \"cats\") {\n refs(refPrefix:\"refs/heads/\", last: 5) {\n edges{\n node {\n associatedPullRequests(states: MERGED, last: 5) {\n edges{\n node {\n title\n baseRef {\n name\n prefix\n }\n baseRefName\n commits(last: 10) {\n edges {\n node {\n commit {\n abbreviatedOid\n message\n \n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```graphql\nquery{\n repository(owner: \"typelevel\", name: \"cats\") {\n defaultBranchRef {\n name\n prefix\n associatedPullRequests(states: [MERGED], last: 5) {\n edges {\n node {\n title\n }\n }\n }\n }\n }\n}\n```\n\n```graphql\nquery {\n repository(owner: \"typelevel\", name: \"cats\") {\n ref(qualifiedName: \"master\") {\n target {\n ... on Commit {\n history(first: 10) {\n pageInfo {\n hasNextPage\n endCursor\n }\n edges {\n node {\n oid\n messageHeadline\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```graphql\nquery {\n node(id: \"MDEwOlJlcG9zaXRvcnk4NDM5MTQ3\") {\n ... on Repository {\n ref(qualifiedName: \"master\") {\n target {\n ... on Commit {\n id\n history(first: 30) {\n totalCount\n pageInfo {\n hasNextPage\n }\n\n edges {\n node {\n oid\n message\n author {\n name\n email\n date\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nhistory\n```\n\n```text\nref\n```\n\n```text\nmaster\n```\n\n```text\nref\n```\n\n```text\nRepository\n```\n\n```text\nmaster\n```\n\n```text\nhistory\n```\n\n```graphql\n{\n repository(owner: \"fregante\", name: \"webext-fun\") {\n defaultBranchRef {\n target {\n ... on Commit {\n history(first: 10) {\n nodes {\n oid\n }\n }\n }\n }\n }\n }\n}\n```\n\n```graphql\n{\n repository(owner: \"fregante\", name: \"webext-fun\") {\n defaultBranchRef {\n target {\n oid\n }\n }\n }\n}\n```\n\n```text\nmaster\n```\n\n========================================\n\nComments:\n- Interesting syntax! I didn't know you could do that. I'm not sure how to get the node Id for master in this case?\n- @ssanj many object has an ID , docs.github.com/en/free-pro-team@latest/graphql/reference/…, any object that implement node interface will have the ID, to find the ID of your object, you have to find it first, other than ID, you could use some key to find them, for example , to find a repository, you can do a query with starting point repository(owner: \"typelevel\", name: \"cats\"){ id } in this way you get the ID\n- Good catch, probably easier than passing an id. +1\n- both of the links went 404 now.\n- @LukAron Such is the internet I guess. The Github Platform Community should be somewhere within: github.community I think. I tried searching for the previous post there but couldn't find anything close to it.","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":310,"estimatedTokens":1406}}390{"id":"stack-72361047","source":"stackoverflow","questionId":72361047,"title":"Error: No \"exports\" main defined in graphql-upload/package.json","tags":["javascript","graphql","nestjs","express-graphql"],"text":"Title: Error: No \"exports\" main defined in graphql-upload/package.json\nTags: javascript, graphql, nestjs, express-graphql\nSource: Stack Overflow\n\nQuestion:\nHave installed graphql-upload, do\n\n`import { graphqlUploadExpress } from 'graphql-upload';`\n\nAnd getting this error:\nError: No \"exports\" main defined in graphql-upload/package.json\n\nDependencies:\n\n```\n\"graphql-upload\": \"^14.0.0\",\n\"graphql\": \"15.8.0\",\n\"graphql-request\": \"^4.2.0\",\n\"graphql-tools\": \"^8.2.0\",\n\"@nestjs/axios\": \"^0.0.7\",\n\"@nestjs/common\": \"^8.4.1\",\n\"@nestjs/config\": \"^1.1.5\",\n\"@nestjs/core\": \"^8.4.1\",\n\"@nestjs/graphql\": \"^9.1.2\",\n\"@nestjs/platform-express\": \"^8.0.0\",\n```\n\nThe version of node: v16.10.0\n\n========================================\n\nTop Answer:\nJust ran into this problem.\nApparently, the the new version `i.e. ^16` ,has a major update\n\nnow you need to do\n\n`const Upload = require('graphql-upload/Upload.mjs');`\n\nor\n\n`import { default as Upload } from 'graphql-upload/Upload.mjs';`\n\nInstead of `.js`, all the imports needs to be from `.mjs`.\n\nHope this helps!\n\n========================================\n\nCode:\n```text\n\"graphql-upload\": \"^14.0.0\",\n\"graphql\": \"15.8.0\",\n\"graphql-request\": \"^4.2.0\",\n\"graphql-tools\": \"^8.2.0\",\n\"@nestjs/axios\": \"^0.0.7\",\n\"@nestjs/common\": \"^8.4.1\",\n\"@nestjs/config\": \"^1.1.5\",\n\"@nestjs/core\": \"^8.4.1\",\n\"@nestjs/graphql\": \"^9.1.2\",\n\"@nestjs/platform-express\": \"^8.0.0\",\n```\n\n```text\nimport { graphqlUploadExpress } from 'graphql-upload';\n```\n\n```text\nimport Upload = require('graphql-upload/Upload.js');\n```\n\n```text\n\"exports\": {\n \"./GraphQLUpload.js\": \"./GraphQLUpload.js\",\n \"./graphqlUploadExpress.js\": \"./graphqlUploadExpress.js\",\n \"./graphqlUploadKoa.js\": \"./graphqlUploadKoa.js\",\n \"./package.json\": \"./package.json\",\n \"./processRequest.js\": \"./processRequest.js\",\n \"./Upload.js\": \"./Upload.js\"\n },\n```\n\n```text\ngraphql-upload\n```\n\n```text\nindex.js\n```\n\n```text\npackage.json\n```\n\n```text\nexports\n```\n\n```text\nimport graphqlUploadKoa from \"graphql-upload/graphqlUploadKoa.js\";\n```\n\n```text\npackage.json\n```\n\n```text\ngraphql-upload\n```\n\n```text\n// @ts-ignore\nimport GraphQLUpload from 'graphql-upload/GraphQLUpload.js';\n// @ts-ignore\nimport Upload from 'graphql-upload/Upload.js';\n```\n\n```text\nconst graphqlUploadExpress = require('graphql-upload/graphqlUploadExpress.js');\n```\n\n```text\nconst GraphQLUpload = require('graphql-upload/GraphQLUpload.js');\n```\n\n```text\nimport { graphqlUploadExpress } from 'graphql-upload';\n```\n\n```text\ni.e. ^16\n```\n\n```text\nconst Upload = require('graphql-upload/Upload.mjs');\n```\n\n```text\nimport { default as Upload } from 'graphql-upload/Upload.mjs';\n```\n\n```text\n.js\n```\n\n```text\n.mjs\n```\n\n```text\nconst {\n graphqlUploadExpress, // A Koa implementation is also exported.\n} = require(\"graphql-upload\");\nconst { GraphQLUpload } = require(\"graphql-upload\");\n```\n\n```text\nconst {\n graphqlUploadExpress, // A Koa implementation is also exported.\n} = require(\"graphql-upload-minimal\");\nconst { GraphQLUpload } = require(\"graphql-upload-minimal\");\n```\n\n```text\n{\n \"dependencies\": {\n \"@nestjs/apollo\": \"^10.1.7\",\n \"@nestjs/axios\": \"1.0.0\",\n \"@nestjs/common\": \"^9.3.9\",\n \"@nestjs/config\": \"^2.0.0\",\n \"@nestjs/core\": \"^9.3.9\",\n \"@nestjs/graphql\": \"10.2.0\",\n \"@nestjs/platform-express\": \"^9.3.9\",\n \"graphql\": \"^16.6.0\",\n \"graphql-upload\": \"15.0.2\"\n },\n \"exports\": {\n \"./GraphQLUpload.js\": \"./GraphQLUpload.js\",\n \"./graphqlUploadExpress.js\": \"./graphqlUploadExpress.js\",\n \"./graphqlUploadKoa.js\": \"./graphqlUploadKoa.js\",\n \"./package.json\": \"./package.json\",\n \"./processRequest.js\": \"./processRequest.js\",\n \"./Upload.js\": \"./Upload.js\"\n }\n}\n```\n\n```text\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true,\n \"allowJs\": true,\n \"maxNodeModuleJsDepth\": 10\n }\n}\n```\n\n```text\n// @ts-ignore\n import Upload = require('graphql-upload/Upload.js');\n // @ts-ignore\n import GraphQLUpload = require('graphql-upload/GraphQLUpload.js');\n \n ...\n \n @Mutation(() => Boolean, {\n name: 'uploadImages',\n description: 'Insert array photos',\n })\n async uploadImages(\n @Args('files', { type: () => [GraphQLUpload] })\n files: [Upload],\n @Args('metadata')\n metadata: UploadImagesMetadataArgs,\n ): Promise<Boolean> {\n const functionPrefix = 'uploadImages';\n try {\n let uploadImagesArgs: Array<UploadImagesArgs> = [];\n for (const file of files) {\n // @ts-ignore\n const { filename, mimetype, encoding, createReadStream } = await file;\nconst stream = createReadStream();\n const chunks = [];\n for await (const chunk of stream) {\n chunks.push(chunk);\n }\n const buffer = Buffer.concat(chunks);\n uploadImagesArgs.push({ buffer, filename, mimetype });\n // your code with connect with services for save your images\n return true;\n }\n } catch(error){\n // your code \n return false;\n }\n }\n```\n\n========================================\n\nComments:\n- Then use app.use(graphqlUploadExpress()); and see an error: TypeError: (0 , graphqlUploadExpress_js_1.default) is not a function at Function.main (/blablabla/src/main.ts:28:33) at processTicksAndRejections (node:internal/process/task_queues:95:5) error Command failed with exit code 1.\n- For me by doing this `import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'`, type of `graphqlUploadExpress` returned a function. Make sure you write that `.js` extension in the import line also.","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":253,"estimatedTokens":1477}}391{"id":"stack-62054703","source":"stackoverflow","questionId":62054703,"title":"Avoiding circular dependencies the right way - NestJS","tags":["typescript","design-patterns","dependency-injection","graphql","nestjs"],"text":"Title: Avoiding circular dependencies the right way - NestJS\nTags: typescript, design-patterns, dependency-injection, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nSay I have a `StudentService` with a method that adds lessons to a student and a `LessonService` with a method that adds students to a lesson. In both my Lesson and Student Resolvers I want to be able to update this lesson student relationship. So in my `LessonResolver` I have something along the lines of:\n\n```\nasync assignStudentsToLesson(\n @Args('assignStudentsToLessonInput')\n assignStudentsToLesson: AssignStudentsToLessonInput,\n ) {\n const { lessonId, studentIds } = assignStudentsToLesson;\n await this.studentService.assignLessonToStudents(lessonId, studentIds); **** A.1 ****\n return this.lessonService.assignStudentsToLesson(lessonId, studentIds); **** A.2 ****\n }\n```\n\nand essentially the reverse in my `StudentResolver`\n\nThe difference between **A.1** and **A.2** above is that the `StudentService` has access to the `StudentRepository` and the `LessonService` has access to the `LessonRepository` - which I believe adheres to a solid separation of concerns.\n\nHowever, it seems to be an anti-pattern that the `StudentModule` must import the `LessonModule` and the `LessonModule` must import the `StudentModule`. This is fixable using the `forwardRef` method, but in the NestJS Documentation it mentions this pattern should be avoided if possible:\n\n While circular dependencies should be avoided where possible, you\n can't always do so. *(is this one of those cases?)*\n\nThis seems like it should be a common issue when using DI, but I'm struggling to get a definitive answer as to what options are available that can eliminate this situation, or if I've stumbled upon a situation where it's unavoidable.\n\nThe ultimate goal is for me to be able to write the two GraphQL queries below:\n\n```\nquery {\n students {\n firstName\n lessons {\n name\n }\n }\n}\n\nquery {\n lessons {\n name\n students {\n firstName\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nasync assignStudentsToLesson(\n @Args('assignStudentsToLessonInput')\n assignStudentsToLesson: AssignStudentsToLessonInput,\n ) {\n const { lessonId, studentIds } = assignStudentsToLesson;\n await this.studentService.assignLessonToStudents(lessonId, studentIds); **** A.1 ****\n return this.lessonService.assignStudentsToLesson(lessonId, studentIds); **** A.2 ****\n }\n```\n\n```text\nquery {\n students {\n firstName\n lessons {\n name\n }\n }\n}\n\nquery {\n lessons {\n name\n students {\n firstName\n }\n }\n}\n```\n\n```text\nStudentService\n```\n\n```text\nLessonService\n```\n\n```text\nLessonResolver\n```\n\n```text\nStudentResolver\n```\n\n```text\nStudentService\n```\n\n```text\nStudentRepository\n```\n\n```text\nLessonService\n```\n\n```text\nLessonRepository\n```\n\n```text\nStudentModule\n```\n\n```text\nLessonModule\n```\n\n```text\nLessonModule\n```\n\n```text\nStudentModule\n```\n\n```text\nforwardRef\n```\n\n```text\nasync assign({ lessonId, studentIds }: AssignStudentsToLessonInput) {\n await this.studentService.assignLessonToStudents(lessonId, studentIds);\n return this.lessonService.assignStudentsToLesson(lessonId, studentIds);\n}\n```\n\n```text\ntype AssignCallback = (assignStudentsToLesson: AssignStudentsToLessonInput) => Promise<void>;\n\nclass LessonResolver { // and similar for StudentResolver\n private assignCallbacks: AssignCallback[] = [];\n\n // ... dependencies, constructor etc.\n\n onAssign(callback: AssignCallback) {\n assignCallbacks.push(callback);\n }\n\n async assignStudentsToLesson(\n @Args('assignStudentsToLessonInput')\n assignStudentsToLesson: AssignStudentsToLessonInput,\n ) {\n const { lessonId, studentIds } = assignStudentsToLesson;\n await this.lessonService.assignStudentsToLesson(lessonId, studentIds); **** A.2 ****\n for (const cb of assignCallbacks) {\n await cb(assignStudentsToLesson);\n }\n }\n}\n\n// In another module\nthis.lessonResolver.onAssign(({ lessonId, studentIds }) => {\n this.studentService.assignLessonToStudents(lessonId, studentIds);\n});\nthis.studentResolver.onAssign(({ lessonId, studentIds }) => {\n this.lessonService.assignStudentsToLesson(lessonId, studentIds);\n});\n```\n\n```text\nStudentLessonResolver\n```\n\n```text\nResolverModule\n```\n\n```text\nStudentModule\n```\n\n```text\nLessonModule\n```\n\n```text\nResolverModule\n```\n\n```text\nStudentModule\n```\n\n```text\nLessonModule\n```\n\n```text\nSubject<AssignStudentsToLessonInput>\n```\n\n```text\nLessonRepository\n```\n\n```text\nLessonService\n```\n\n```text\nLessonModule\n```\n\n========================================\n\nComments:\n- interesting approach! I had thought of using a third resolver but wasn't sure if that was me over-engineering and failing to see a simpler solution. One idea I just thought of was to alternatively inject the `StudentRepository` and `LessonRepository` into both the `StudentService` and `LessonService`. This way each service has both repos and can update them accordingly. My only gripe about this method is it seems to introduce duplicate business logic. Curious what your thoughts are?\n- I just tried your first approach and it works great. I appreciate your feedback!\n- Thanks! I also updated the answer to consider your proposal.\n- What if I use async events everywhere instead of using forwardRef, resolver module, etc.? @mperktold\n- That's illustrated by the second code example, isn't it?","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":28,"totalLines":229,"estimatedTokens":1340}}392{"id":"stack-66024999","source":"stackoverflow","questionId":66024999,"title":"How can I extend the GraphQL introspection types with Hot Chocolate in .NET","tags":["c#",".net",".net-core","graphql","hotchocolate"],"text":"Title: How can I extend the GraphQL introspection types with Hot Chocolate in .NET\nTags: c#, .net, .net-core, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nIn my case I want to extend the `__EnumValue` introspection type to essentially carry additional information about the enum value. How can I add additional fields to the introspection.\n\n========================================\n\nCode:\n```text\n__EnumValue\n```\n\n```cs\n[ExtendObjectType(\"__EnumValue\")]\npublic class EnumTypeExtension\n{\n public string GetAdditionalInfo([Parent] IEnumValue enumValue) =>\n enumValue.ContextData[\"additionalInfo\"].ToString();\n}\n```\n\n```text\nextend type __EnumValue {\n additionalInfo: String!\n}\n```\n\n```cs\nservices\n .AddGraphQL()\n .AddQueryType<QueryType>()\n .AddTypeExtension<EnumTypeExtension>();\n```\n\n```text\nquery {\n __type(name: \"MyEnum\") {\n enumValues {\n additionalInfo\n }\n }\n}\n```\n\n```text\ntype EnumValueExtensions {\n additionalInfo: String!\n}\n\nextend type __EnumValue {\n extensions: EnumValueExtensions!\n}\n```\n\n```text\nExtendObjectTypeAttribute\n```\n\n```text\n__EnumValue\n```\n\n```text\nextensions\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":67,"estimatedTokens":283}}393{"id":"stack-48017187","source":"stackoverflow","questionId":48017187,"title":"Organization structure for fragment composition in large react-apollo apps","tags":["reactjs","graphql","apollo","apollo-client","react-apollo"],"text":"Title: Organization structure for fragment composition in large react-apollo apps\nTags: reactjs, graphql, apollo, apollo-client, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm using Apollo Client and React and I'm looking for a strategy to keep my component and component data requirements colocated in such a way that it can be accessible to parent/sibling/child components that might need it for queries and mutations. I want to be able to easily update the data requirements which in turn will update the fields that are queried by some parent component or returned by a mutation in a parent/sibling/child in order to accurately update my Apollo cache.\n\nI have tried creating a global high level `graphql` directory where all my `queries/mutations.graphql` files are located, importing all the related fragment files located throughout my app, and then importing those directly, but this can get tedious and doesn't the parent/child theme where parent queries include children fragments. Also in large projects you end up traversing long file paths when importing.\n\nI have also tried just creating fragment files colocated in the global `graphql` directory that correspond to component files but this doesn't give me the \"component/data requirement\" colocation I'm looking for.\n\nThis works:\n\n```\nclass CommentListItem extends Component {\n static fragments = {\n comment: gql`\n #...\n `,\n }\n}\nclass CommentList extends Component {\n static fragments = {\n comment: gql`\n #...\n ${CommentListItem.fragments.comment}\n `,\n }\n}\nclass CommentsPage extends Component {\n static fragments = {\n comment: gql`\n #...\n ${CommentList.fragments.comment}\n `,\n }\n}\ngraphql(gql`\n query Comments {\n comments {\n ...CommentsListItemComment\n }\n }\n ${CommentsPage.fragments.comment}\n`)\n```\n\nHowever, if I want a mutation in a descendent of `CommentsPage` I can't reference the fragment composition from `CommentsPage.fragments.comment`.\n\nIs there a preferred method or best practice for this type of thing?\n\n========================================\n\nCode:\n```text\nclass CommentListItem extends Component {\n static fragments = {\n comment: gql`\n #...\n `,\n }\n}\nclass CommentList extends Component {\n static fragments = {\n comment: gql`\n #...\n ${CommentListItem.fragments.comment}\n `,\n }\n}\nclass CommentsPage extends Component {\n static fragments = {\n comment: gql`\n #...\n ${CommentList.fragments.comment}\n `,\n }\n}\ngraphql(gql`\n query Comments {\n comments {\n ...CommentsListItemComment\n }\n }\n ${CommentsPage.fragments.comment}\n`)\n```\n\n```text\ngraphql\n```\n\n```text\nqueries/mutations.graphql\n```\n\n```text\ngraphql\n```\n\n```text\nCommentsPage\n```\n\n```text\nCommentsPage.fragments.comment\n```\n\n```text\n# A reusable likeComment mutation\nmutation likeComment($id: ID!) {\n likeComment(id: $id) {\n comment {\n id\n likeCount\n likes {\n id\n liker {\n id\n name\n }\n }\n }\n }\n}\n```\n\n```text\nlikeComment(id: ID!)\n```\n\n```text\nlikeCount\n```\n\n```text\nlikes\n```\n\n```text\nComment\n```\n\n```text\ncreateComment(comment: CreateCommentInput)\n```\n\n```text\ncomments\n```\n\n```text\nCommentListItem\n```\n\n```text\nlikeComment: (id: string) => Promise<any>\n```\n\n```text\nCommentsPage\n```\n\n```text\nmutations\n```\n\n```text\nlikeComment\n```\n\n```text\nid\n```\n\n```text\nCommentsPage\n```\n\n========================================\n\nComments:\n- great answer thank you, got me thinking in the right direction!","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":183,"estimatedTokens":865}}394{"id":"stack-58624224","source":"stackoverflow","questionId":58624224,"title":"Python GraphQL How to declare a self-referencing graphene object type","tags":["python","recursion","graphql"],"text":"Title: Python GraphQL How to declare a self-referencing graphene object type\nTags: python, recursion, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a django model which has a foreign key related to itself, I want to represent this model as a graphene `ObjectType`. \n\nI know it is trivial to do this using `DjangoObjectType` from the graphene_django library. \n\nI am looking for an elegant python solution without using graphene_django.\n\nAn example of a model I want to represent\n\n```\n# models.py\nclass Category(models.Model):\n name = models.CharField(unique=True, max_length=200)\n parent = models.ForeignKey(\n 'self', on_delete=models.SET_NULL, null=True, blank=True,\n related_name='child_category')\n```\n\nthe schema below obviously does not scale and the `ParentCategoryType` does not have the `parent` field so it is not strictly a parent of `CategoryType`.\n\n```\n# schema.py\nclass ParentCategoryType(graphene.ObjectType):\n id = graphene.types.uuid.UUID()\n name = graphene.String()\n\nclass CategoryType(graphene.ObjectType):\n id = graphene.types.uuid.UUID()\n name = graphene.String()\n parent = graphene.Field(ParentCategoryType)\n```\n\nthe code below gives a `CategoryType` undefined error.\n\n```\n#schema.py\nclass CategoryType(graphene.ObjectType):\n id = graphene.types.uuid.UUID()\n name = graphene.String()\n parent = graphene.Field(CategoryType)\n```\n\nAny help much appreciated.\n\n========================================\n\nCode:\n```py\n# models.py\nclass Category(models.Model):\n name = models.CharField(unique=True, max_length=200)\n parent = models.ForeignKey(\n 'self', on_delete=models.SET_NULL, null=True, blank=True,\n related_name='child_category')\n```\n\n```py\n# schema.py\nclass ParentCategoryType(graphene.ObjectType):\n id = graphene.types.uuid.UUID()\n name = graphene.String()\n\nclass CategoryType(graphene.ObjectType):\n id = graphene.types.uuid.UUID()\n name = graphene.String()\n parent = graphene.Field(ParentCategoryType)\n```\n\n```py\n#schema.py\nclass CategoryType(graphene.ObjectType):\n id = graphene.types.uuid.UUID()\n name = graphene.String()\n parent = graphene.Field(CategoryType)\n```\n\n```text\nObjectType\n```\n\n```text\nDjangoObjectType\n```\n\n```text\nParentCategoryType\n```\n\n```text\nparent\n```\n\n```text\nCategoryType\n```\n\n```text\nCategoryType\n```\n\n```text\nparent = graphene.Field(lambda: ParentCategoryType)\n```\n\n```text\nparent = graphene.Field(lambda: CategoryType)\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":111,"estimatedTokens":604}}395{"id":"stack-49252456","source":"stackoverflow","questionId":49252456,"title":"How can I get data from a json-file via GraphQL?","tags":["graphql","gatsby"],"text":"Title: How can I get data from a json-file via GraphQL?\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI have:\n\n```\n- src\n - data\n - data.json\n```\n\ndata.json:\n\n```\n\"gallery\": [\n {\"name\":...\n {\"name\":.. ...\n```\n\ngatsby-config.js contains:\n\n```\n`gatsby-transformer-json`,\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/data`,\n name: `data`,\n },\n},\n```\n\nHow can I get list of gallery.names from this json-file via GraphQL query?\nI'm trying to write:\n\n```\nexport const IndexQuery = graphql`\n query IndexQuery { \n mydata: file(name: { eq: \"data\" }, extension: { eq: \"json\" }) {\n allFile {\n gallery {\n name\n }\n }\n }\n }\n`\n```\n\nbut it doesn't work.\n\n========================================\n\nCode:\n```text\n- src\n - data\n - data.json\n```\n\n```text\n\"gallery\": [\n {\"name\":...\n {\"name\":.. ...\n```\n\n```text\n`gatsby-transformer-json`,\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/data`,\n name: `data`,\n },\n},\n```\n\n```text\nexport const IndexQuery = graphql`\n query IndexQuery { \n mydata: file(name: { eq: \"data\" }, extension: { eq: \"json\" }) {\n allFile {\n gallery {\n name\n }\n }\n }\n }\n`\n```\n\n```babel\nexport const IndexQuery = graphql`\n query IndexQuery {\n dataJson {\n gallery {\n name\n }\n }\n }\n`;\n```\n\n```babel\nthis.props.data.dataJson.gallery\n```\n\n```text\ngatsby-transformer-json\n```\n\n```text\ngatsby-source-filesystem\n```\n\n========================================\n\nComments:\n- const { mydata } = this.props.data.dataJson return ( {mydata.gallery.forEach(value => alert(value.name))} )\n- Do `console.log(this.props.data.dataJson)` and check what data you get returned. `mydata` does not exist in the query. Try `const { gallery } = this.props.data.dataJson` and loop over that instead.\n- We should write `dataJson`, because file name is data.json or directory name?\n- Yep, because of the directory name.","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":124,"estimatedTokens":487}}396{"id":"stack-61124950","source":"stackoverflow","questionId":61124950,"title":"Received incompatible instance in Graphql query","tags":["python","django","postgresql","graphql"],"text":"Title: Received incompatible instance in Graphql query\nTags: python, django, postgresql, graphql\nSource: Stack Overflow\n\nQuestion:\nWhen i hit insomnia with this request bellow then it shows this response. How can i solve this issue?\n\n**Request:**\n\n```\nquery{\n datewiseCoronaCasesList{\n updatedAt,\n affected,\n death,\n recovered\n }\n}\n```\n\n**Response:**\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Received incompatible instance \\\"{'updated_at': datetime.date(2020, 4, 8), 'affected': 137, 'death': 42, 'recovered': 104}\\\".\"\n }\n ],\n \"data\": {\n \"datewiseCoronaCasesList\": [\n null\n ]\n }\n}\n```\n\n**My expectation which i have already gotten in errors message but this way:**\n\n```\n{\n 'updated_at': datetime.date(2020, 4, 8),\n 'affected': 137,\n 'death': 42,\n 'recovered': 104\n}\n```\n\n**My GraphQL query:**\n\n```\nclass CoronaQuery(graphene.ObjectType):\n datewise_corona_cases_list = graphene.Field(CoronaCaseType)\n\n def resolve_datewise_corona_cases_list(self, info, **kwargs):\n return CoronaCase.objects.values('updated_at').annotate(\naffected=Sum('affected'),death=Sum('death'), recovered=Sum('recovered'))\n```\n\n**My model:**\n\n```\nclass CoronaCase(models.Model):\n affected = models.IntegerField(default=0)\n death = models.IntegerField(default=0)\n recovered = models.IntegerField(default=0)\n district = models.CharField(max_length=265, null=False, blank=False)\n created_at = models.DateTimeField(default=timezone.now)\n updated_at = models.DateTimeField(default=timezone.now)\n\n def __str__(self):\n return \"Affected from: {}\".format(self.district)\n```\n\n========================================\n\nCode:\n```text\nquery{\n datewiseCoronaCasesList{\n updatedAt,\n affected,\n death,\n recovered\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Received incompatible instance \\\"{'updated_at': datetime.date(2020, 4, 8), 'affected': 137, 'death': 42, 'recovered': 104}\\\".\"\n }\n ],\n \"data\": {\n \"datewiseCoronaCasesList\": [\n null\n ]\n }\n}\n```\n\n```text\n{\n 'updated_at': datetime.date(2020, 4, 8),\n 'affected': 137,\n 'death': 42,\n 'recovered': 104\n}\n```\n\n```text\nclass CoronaQuery(graphene.ObjectType):\n datewise_corona_cases_list = graphene.Field(CoronaCaseType)\n\n def resolve_datewise_corona_cases_list(self, info, **kwargs):\n return CoronaCase.objects.values('updated_at').annotate(\naffected=Sum('affected'),death=Sum('death'), recovered=Sum('recovered'))\n```\n\n```text\nclass CoronaCase(models.Model):\n affected = models.IntegerField(default=0)\n death = models.IntegerField(default=0)\n recovered = models.IntegerField(default=0)\n district = models.CharField(max_length=265, null=False, blank=False)\n created_at = models.DateTimeField(default=timezone.now)\n updated_at = models.DateTimeField(default=timezone.now)\n\n def __str__(self):\n return \"Affected from: {}\".format(self.district)\n```\n\n```py\nclass CoronaQuery(graphene.ObjectType):\n datewise_corona_cases_list = graphene.List(CoronaCaseType)\n```\n\n```text\nCoronaQuery\n```\n\n```text\ngraphene.Field\n```\n\n```text\ngraphene.List\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":150,"estimatedTokens":773}}397{"id":"stack-68390441","source":"stackoverflow","questionId":68390441,"title":"NestJS/GraphQL/Passport - getting unauthorised error from guard","tags":["graphql","nestjs","passport-local","nestjs-passport"],"text":"Title: NestJS/GraphQL/Passport - getting unauthorised error from guard\nTags: graphql, nestjs, passport-local, nestjs-passport\nSource: Stack Overflow\n\nQuestion:\nI'm trying to along with this tutorial and I'm struggling to convert the implementation to GraphQL.\n\n**local.strategy.ts**\n\n```\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authenticationService: AuthenticationService) {\n super();\n }\n\n async validate(email: string, password: string): Promise {\n const user = await this.authenticationService.getAuthenticatedUser(\n email,\n password,\n );\n\n if (!user) throw new UnauthorizedException();\n\n return user;\n }\n}\n```\n\n**local.guard.ts**\n\n```\n@Injectable()\nexport class LogInWithCredentialsGuard extends AuthGuard('local') {\n async canActivate(context: ExecutionContext): Promise {\n const ctx = GqlExecutionContext.create(context);\n const { req } = ctx.getContext();\n req.body = ctx.getArgs();\n\n await super.canActivate(new ExecutionContextHost([req]));\n await super.logIn(req);\n return true;\n }\n}\n```\n\n**authentication.type.ts**\n\n```\n@InputType()\nexport class AuthenticationInput {\n @Field()\n email: string;\n\n @Field()\n password: string;\n}\n```\n\n**authentication.resolver.ts**\n\n```\n@UseGuards(LogInWithCredentialsGuard)\n@Mutation(() => User, { nullable: true })\nlogIn(\n @Args('variables')\n _authenticationInput: AuthenticationInput,\n @Context() req: any,\n) {\n return req.user;\n}\n```\n\n**mutation**\n\n```\nmutation {\n logIn(variables: {\n email: \"email@email.com\",\n password: \"123123\"\n } ) {\n id\n email\n }\n}\n```\n\nEven the above credentials are correct, I'm receiving an unauthorized error.\n\n========================================\n\nTop Answer:\nI've been able to get a successful login with a guard like this:\n\n```\n@Injectable()\nexport class LocalGqlAuthGuard extends AuthGuard('local') {\n constructor() {\n super();\n }\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const req = ctx.getContext().req;\n req.body = ctx.getArgs();\n return req;\n }\n async canActivate(context: ExecutionContext) {\n await super.canActivate(context);\n const ctx = GqlExecutionContext.create(context);\n const req = ctx.getContext().req;\n await super.logIn(req);\n return true;\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n constructor(private readonly authenticationService: AuthenticationService) {\n super();\n }\n\n async validate(email: string, password: string): Promise<any> {\n const user = await this.authenticationService.getAuthenticatedUser(\n email,\n password,\n );\n\n if (!user) throw new UnauthorizedException();\n\n return user;\n }\n}\n```\n\n```text\n@Injectable()\nexport class LogInWithCredentialsGuard extends AuthGuard('local') {\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const ctx = GqlExecutionContext.create(context);\n const { req } = ctx.getContext();\n req.body = ctx.getArgs();\n\n await super.canActivate(new ExecutionContextHost([req]));\n await super.logIn(req);\n return true;\n }\n}\n```\n\n```text\n@InputType()\nexport class AuthenticationInput {\n @Field()\n email: string;\n\n @Field()\n password: string;\n}\n```\n\n```text\n@UseGuards(LogInWithCredentialsGuard)\n@Mutation(() => User, { nullable: true })\nlogIn(\n @Args('variables')\n _authenticationInput: AuthenticationInput,\n @Context() req: any,\n) {\n return req.user;\n}\n```\n\n```text\nmutation {\n logIn(variables: {\n email: \"email@email.com\",\n password: \"123123\"\n } ) {\n id\n email\n }\n}\n```\n\n```js\n@Injectable()\nexport class LogInWithCredentialsGuard extends AuthGuard('local') {\n // Override this method so it can be used in graphql\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const gqlReq = ctx.getContext().req;\n if (gqlReq) {\n const { variables } = ctx.getArgs();\n gqlReq.body = variables;\n return gqlReq;\n }\n return context.switchToHttp().getRequest();\n }\n}\n```\n\n```js\n@UseGuards(LogInWithCredentialsGuard)\n@Mutation(() => User, { nullable: true })\nlogIn(\n @Args('variables')\n _authenticationInput: AuthenticationInput,\n @Context() context: any, // <----------- it's not request\n) {\n return context.req.user;\n}\n```\n\n```text\nLogInWithCredentialsGuard\n```\n\n```text\ncanAcitavte\n```\n\n```text\nreq.body\n```\n\n```text\nreq.body\n```\n\n```text\ngetRequest\n```\n\n```js\n@Injectable()\nexport class LocalGqlAuthGuard extends AuthGuard('local') {\n constructor() {\n super();\n }\n getRequest(context: ExecutionContext) {\n const ctx = GqlExecutionContext.create(context);\n const req = ctx.getContext().req;\n req.body = ctx.getArgs();\n return req;\n }\n async canActivate(context: ExecutionContext) {\n await super.canActivate(context);\n const ctx = GqlExecutionContext.create(context);\n const req = ctx.getContext().req;\n await super.logIn(req);\n return true;\n }\n}\n```\n\n```text\nconstructor(private authenticationService: AuthenticationService) {\n //you should pass this {usernameField: 'email'} object to super π\n super({\n usernameField: 'email' \n });\n }\n```\n\n========================================\n\nComments:\n- related information: github.com/jaredhanson/passport-local, github.com/nestjs/passport/blob/…\n- Hi @Ellie. Iβm trying to learn NestJS and am having this issue. Did you manage to solve it?\n- Thanks, the guard works, but it won't set a session cookie without overriding the canActivate method.\n- @EllieG I am currently having the same problem, did you resolve it in the end? How can I get the correct request and also overwrite canActivate to set a session cookie?\n- Basicly you don't need a session and you don't need to override the canActivate method. Per definition, JWT is stateless. Maybe you missed to call something like an AuthService.login method, to return the JWT in the resolver? I know, it's a year ago, but when you still have issues, I will have a look in this thread.\n- I have tried to implement the AuthGuard like this but I still get an `unauthorized` when sending a login request. Is there any chance you have more detail on your solution?","metadata":{"transformedAt":"2026-08-18T18:32:36.054Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":278,"estimatedTokens":1554}}398{"id":"stack-59738496","source":"stackoverflow","questionId":59738496,"title":"GraphQL to query something other than ID","tags":["graphql","nuxt.js","apollo","strapi"],"text":"Title: GraphQL to query something other than ID\nTags: graphql, nuxt.js, apollo, strapi\nSource: Stack Overflow\n\nQuestion:\nI am using Strapi with Nuxt.js to implement my first Headless CMS. I am using Apollo and GraphQL.\n\nI am running into the current error and I've had no luck to figure this out for days.\n\nIf I write:\n\n```\nquery Page($id: ID!) {\n page(id: $id) {\n id\n slug\n title\n }\n}\n```\n\nAnd pass the following variable:\n\n```\n{\n \"id\" : \"1\"\n}\n```\n\nI received the correct expected result:\n\n```\n{\n \"data\": {\n \"page\": {\n \"id\": \"1\",\n \"slug\": \"/\",\n \"title\": \"Homepage\"\n }\n }\n}\n```\n\nHOWEVER, I would like to get the content not via ID, but via a field that I created in Strapi, called \"slug\".\nLooking around, it seems like I should be able to do something like:\n\n```\nquery Page($slug: String!) {\n page(slug: $slug) {\n id\n slug\n title\n }\n}\n```\n\nWith variable:\n\n```\n{\n \"slug\" : \"/\"\n}\n```\n\nbut I receive this error:\n\n```\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"slug\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 8\n }\n ],\n \"extensions\": {\n \"code\": \"GRAPHQL_VALIDATION_FAILED\",\n \"exception\": {\n \"stacktrace\": [\n```\n\n... the error continues....\n\n[UPDATE] After Italo replied, I changed it into:\n\n```\nquery Pages($slug: String!) {\n page(where: {slug: $slug}) {\n id\n slug\n title\n }\n}\n```\n\nBut I now get the following error:\n\n```\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"where\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n```\n\nI also noticed that I get a query if I change \"page\" into \"pages\", but it shows all of the pages...\n\nWhat am I missing?\nThanks!\n\n========================================\n\nTop Answer:\nThis seem to work for me using slug\n\ncreate new file schema.graphql.js in\napi/blog-post/config/schema.graphql.js\n\n```\nmodule.exports = {\n query: \"blogPostBySlug(slug: String!): BlogPost\",\n resolver: {\n Query: {\n blogPostBySlug: {\n description: \"Return blog post with a given slug\",\n resolver: \"application::blog-post.blog-post.findOne\",\n },\n },\n },\n};\n```\n\nchange routes.json in api/blog-post/config/routes.json, from \"path\": \"/blog-posts/:id\" to \"path\": \"/blog-posts/:slug:\n\n```\n{\n \"method\": \"GET\",\n \"path\": \"/blog-posts/:slug\",\n \"handler\": \"blog-post.findOne\",\n \"config\": {\n \"policies\": []\n }\n},\n```\n\nhttps://i.sstatic.net/pKHHS.png\n\n========================================\n\nCode:\n```text\nquery Page($id: ID!) {\n page(id: $id) {\n id\n slug\n title\n }\n}\n```\n\n```text\n{\n \"id\" : \"1\"\n}\n```\n\n```text\n{\n \"data\": {\n \"page\": {\n \"id\": \"1\",\n \"slug\": \"/\",\n \"title\": \"Homepage\"\n }\n }\n}\n```\n\n```text\nquery Page($slug: String!) {\n page(slug: $slug) {\n id\n slug\n title\n }\n}\n```\n\n```text\n{\n \"slug\" : \"/\"\n}\n```\n\n```text\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"slug\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 8\n }\n ],\n \"extensions\": {\n \"code\": \"GRAPHQL_VALIDATION_FAILED\",\n \"exception\": {\n \"stacktrace\": [\n```\n\n```text\nquery Pages($slug: String!) {\n page(where: {slug: $slug}) {\n id\n slug\n title\n }\n}\n```\n\n```text\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"where\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n```\n\n```text\nquery Pages($slug: String!) {\n pages(where: {slug: $slug}) {\n id\n slug\n title\n }\n}\n```\n\n```text\nmodule.exports = {\n query: \"blogPostBySlug(slug: String!): BlogPost\",\n resolver: {\n Query: {\n blogPostBySlug: {\n description: \"Return blog post with a given slug\",\n resolver: \"application::blog-post.blog-post.findOne\",\n },\n },\n },\n};\n```\n\n```text\n{\n \"method\": \"GET\",\n \"path\": \"/blog-posts/:slug\",\n \"handler\": \"blog-post.findOne\",\n \"config\": {\n \"policies\": []\n }\n},\n```\n\n========================================\n\nComments:\n- Hi Italo, thanks for your reply. Yes, I am using localhost:1337/graphql for testing, and making your changes, I now get the following error: \"message\": \"Unknown argument \\\"where\\\" on field \\\"page\\\" of type \\\"Query\\\".\",\n- Yeah, my mistake. Just try changing `page(where:)` to `pages(where:)` (to be clear, you're supposed to use the query that find all pages instead of the one that returns just one item)\n- Just go to the graphql interface and use the autocompletition (ctrl+space) to check if the where field is avaiable.@Saro\n- Yeah, it works this way. However, I have to reference to it as pages[0].id or I get nothing. I do get the correct one by slug. It kind of feel wrong to me to have to use the [0], so I wonder if there's a better way to do it.\n- It's ok using this way and getting the record using pages[0], nothing wrong with it at all. But if you want to have something better, the only way is creating a custom endpoint on graphql schema It's not so hard and it's a good way to start tweeking strapi.","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":276,"estimatedTokens":1230}}399{"id":"stack-52452982","source":"stackoverflow","questionId":52452982,"title":"Reusing input type as fragment in GraphQL","tags":["types","graphql"],"text":"Title: Reusing input type as fragment in GraphQL\nTags: types, graphql\nSource: Stack Overflow\n\nQuestion:\nA very common use case in GraphQL is creating an object with a mutation, and receiving the exact same fields back, plus and ID returned by the database. Here's a related question asking about this.\n\nMy question is, how can this pattern be simplified to avoid repeated fields? I've tried reusing the input type as a fragment,\n\n```\ninput ClientInput {\n short_name: String\n full_name: String\n address: String\n email: String\n location: String \n}\n\ntype Client {\n id: String\n ...ClientInput\n}\n```\n\n...but that failed with\n\n Syntax Error: Expected Name, found ...\n\nAll the documentation and blog posts I've seen on Fragments always creates them `on` an existing type. That means still repeating all but the ID field:\n\n```\ntype Client {\n _id: String\n short_name: String\n full_name: String\n address: String\n email: String\n location: String\n}\n\nfragment ClientFields on Client {\n short_name: String\n full_name: String\n address: String\n email: String\n location: String\n}\n\ninput ClientInput {\n ...ClientFields\n}\n```\n\nHow is that any better?\n\n========================================\n\nCode:\n```text\ninput ClientInput {\n short_name: String\n full_name: String\n address: String\n email: String\n location: String \n}\n\ntype Client {\n id: String\n ...ClientInput\n}\n```\n\n```text\ntype Client {\n _id: String\n short_name: String\n full_name: String\n address: String\n email: String\n location: String\n}\n\nfragment ClientFields on Client {\n short_name: String\n full_name: String\n address: String\n email: String\n location: String\n}\n\ninput ClientInput {\n ...ClientFields\n}\n```\n\n```text\non\n```\n\n```text\nconst sharedClientFields = `\n short_name: String\n full_name: String\n address: String\n email: String\n location: String \n`\nconst schema = `\n type Client {\n _id: String\n ${sharedClientFields}\n }\n\n type ClientInput {\n ${sharedClientFields}\n }\n`\n```\n\n```text\ntype\n```\n\n========================================\n\nComments:\n- Thanks for the answer! Since my question turned out to be a dupe, would you like to move this answer to the original question?","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":128,"estimatedTokens":541}}400{"id":"stack-60024063","source":"stackoverflow","questionId":60024063,"title":"Making Graphql input where input can take different types","tags":["graphql","graphql-java","graphql-schema"],"text":"Title: Making Graphql input where input can take different types\nTags: graphql, graphql-java, graphql-schema\nSource: Stack Overflow\n\nQuestion:\nI want to create mutation apis where input can be of different types, something like interface which we have in types. I know that we cannot have interface in input types, I want to know how we can support multiple input types in just one input. To explain the problem, I am using a dummy example:\n\n```\ninput CreateCatInput{\n id: String\n name: String\n}\n\ninput CreateDogInput{\n id: String\n name: String\n breed: String\n}\n\ninput CreateElephantInput{\n id: String\n name: String\n weight: String\n}\n```\n\nNow, if we want to write apis for it, I will have to write api for each type\n\n```\ncreateCat(input: CreateCatInput!)\ncreateDog(input: CreateDogInput!)\ncreateElephant(input: CreateElephantInput!)\n```\n\nThe problem I have with this approach is:\n\nI will have to write a lot of apis, assume if I support 20 types of\nanimal then I will have to write 20 create apis. But I don't like this many apis for the users, I want that the user should see very few apis.\n\n- Assume we support 20 types of animals, how will the user know what all animals are supported, they will have to see all the apis we support in the API explorer.\n\nThe solution I am looking for is that I have only one api :\n\n```\ncreateAnimal(input: CreateAnimalInput!)\n```\n\nSince interface support is not there currently, how companies are implementing input which can be of multiple types? How can I define the input such that I can only give only one input in the api ?\n\nI have read this suggestion, but it involves defining annotations, I am currently trying it. I want to see how other people are solving this issue.\n\nEdit: Looks like a lot of work is now done on this topic https://github.com/graphql/graphql-spec/pull/733 and the feature will be available soon.\n\n========================================\n\nCode:\n```text\ninput CreateCatInput{\n id: String\n name: String\n}\n\ninput CreateDogInput{\n id: String\n name: String\n breed: String\n}\n\ninput CreateElephantInput{\n id: String\n name: String\n weight: String\n}\n```\n\n```text\ncreateCat(input: CreateCatInput!)\ncreateDog(input: CreateDogInput!)\ncreateElephant(input: CreateElephantInput!)\n```\n\n```text\ncreateAnimal(input: CreateAnimalInput!)\n```\n\n```text\ninput CreateAnimalInput{\n id: String\n name: String\n animalType :AnimalType!\n dogParam : CreateDogInput\n elephantParam : CreateElephantInput\n}\n\nenum AnimalType{\n DOG\n ELEPHANT\n}\n\ninput CreateDogInput{\n breed: String\n}\n\ninput CreateElephantInput{\n weight: String\n}\n\ncreateAnimal(input: CreateAnimalInput!)\n```\n\n```text\nanimalType\n```\n\n```text\nDOG\n```\n\n```text\ndogParam\n```\n\n```text\nOneOf\n```\n\n========================================\n\nComments:\n- Hey @Ken Chan, Thanks for answering the question. Since union support is not there a developer can only use either the composition way you discussed or make separate entity for dog/cat.\n- @Key Chan. Thanks for this detailed answer. I also had this nested solution in mind, But you explained it very nicely. The only problem I see here is that the update api will also be nested, In one update api we will be updating the dog and cat both. Is there a other way too for update ?\n- The update schema will look exactly the name. So @Key Chan no need to add the update part.\n- Just to update the current status. The oringal RFC link, links back to this thread, but the actual link is here. However, this has been surplanted by the `oneof` input type, whichc can be viewed here.","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":133,"estimatedTokens":884}}401{"id":"stack-39579416","source":"stackoverflow","questionId":39579416,"title":"GraphQL fields as a function","tags":["javascript","graphql","closures","graphql-js","hoisting"],"text":"Title: GraphQL fields as a function\nTags: javascript, graphql, closures, graphql-js, hoisting\nSource: Stack Overflow\n\nQuestion:\nI am studying `GraphQL` and I get a bit confused from different implementations on the specific issue when writing the `fields` of a `GraphQLObjectType`.\n\nWhat is the difference between these two implementations?\n\n1.\n\n```\nvar schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'RootQueryType',\n fields: { // as object\n echo: {\n type: GraphQLString,\n args: {\n email: { type: EmailType }\n },\n resolve: (root, {email}) => {\n return email;\n }\n }\n }\n })\n});\n```\n\n- \n\n```\nvar ComplicatedArgs = new GraphQLObjectType({\n name: 'ComplicatedArgs',\n fields: () => ({ // as function\n complexArgField: {\n type: GraphQLString,\n args: {\n complexArg: { type: ComplexInput }\n },\n }\n }),\n});\n```\n\n========================================\n\nTop Answer:\nThis is a great example of CLOSURE. Imagine you have two types in a file and they are referencing each other.\n\n```\nconst BookType= new GraphQLObjectType({\n name: 'BookType',\n fields: { // as object\n author: {\n type: AuthorType,\n \n resolve: (parentValue, args) => {\n // query the author based on your db implementation.\n }\n } }\n })\n```\n\nBookType has a field author and referencing **AuthorType**. Now imagine you have AuthorType defined under \"BookType\" referencing **BookType**\n\n```\nconst AuthorType= new GraphQLObjectType({\n name: 'AuthorType',\n fields: { // as object\n books: {\n type: new GraphQLList(BookType), //one author might have multiple books\n \n resolve: (parentValue, args) => {\n // query the books based on your db implementation.\n }\n } }\n })\n```\n\nSo when Javascript engine needs to use `BookType` it will see that `fields.author.type` is AuthorType and AuthorType is not defined above. So it will give\n\n```\nreference error:AuthorType is not defined\n```\n\nto circumvent this, we turn fields to a function. this function is a CLOSURE function. this is a great example why closures are so helpful.\n\nWhen js engine reads the file first, it saves all the variables that are referenced inside of a function into memory heap as a closure storage of that function. All the variables that `BookType.fields` need are stored into the closure environment of the BookType.fields(). So now if javascript executes the Booktype.fields(), it checks if \"AuthorType\" is defined inside the function, it is not defined so it checks its closure storage, **AuthorType** was already stored there in the beginning, so it uses it.\n\n========================================\n\nCode:\n```text\nvar schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'RootQueryType',\n fields: { // as object\n echo: {\n type: GraphQLString,\n args: {\n email: { type: EmailType }\n },\n resolve: (root, {email}) => {\n return email;\n }\n }\n }\n })\n});\n```\n\n```text\nvar ComplicatedArgs = new GraphQLObjectType({\n name: 'ComplicatedArgs',\n fields: () => ({ // as function\n complexArgField: {\n type: GraphQLString,\n args: {\n complexArg: { type: ComplexInput }\n },\n }\n }),\n});\n```\n\n```text\nGraphQL\n```\n\n```text\nfields\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nconst BookType= new GraphQLObjectType({\n name: 'BookType',\n fields: { // as object\n author: {\n type: AuthorType,\n \n resolve: (parentValue, args) => {\n // query the author based on your db implementation.\n }\n } }\n })\n```\n\n```text\nconst AuthorType= new GraphQLObjectType({\n name: 'AuthorType',\n fields: { // as object\n books: {\n type: new GraphQLList(BookType), //one author might have multiple books\n \n resolve: (parentValue, args) => {\n // query the books based on your db implementation.\n }\n } }\n })\n```\n\n```text\nreference error:AuthorType is not defined\n```\n\n```text\nBookType\n```\n\n```text\nfields.author.type\n```\n\n```text\nBookType.fields\n```\n\n========================================\n\nComments:\n- What difference in particular do you refer to? The first snippet creates a whole schema with a query type and a resolvable `echo` field, the second snippet only creates an object type with a `complexArgField` field and no resolver.\n- So would you say it is a good practice to always use `fields` as a function?\n- Thats strongly opinioned, but in my opinion it is! It has no big harm on the performance\n- great answer explaining JavaScript's hoisting behavior with closures.","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":190,"estimatedTokens":1124}}402{"id":"stack-34820629","source":"stackoverflow","questionId":34820629,"title":"What is a good pattern for implementing access control in a GraphQL server?","tags":["node.js","authentication","access-control","graphql"],"text":"Title: What is a good pattern for implementing access control in a GraphQL server?\nTags: node.js, authentication, access-control, graphql\nSource: Stack Overflow\n\nQuestion:\n**Background:**\n\nI have a set of models, including a User and various other models, some of which contain references to a User. I am exposing these models for querying via a GraphQL API generated by Graffiti, backed by a Mongo database using the graffiti-mongoose adaptor. My current REST API (which I am migrating to GraphQL) uses JSON Web Tokens to authenticate users, and has some custom permission logic on the server side to handle access control.\n\n**Problem:**\n\nI'd like to restrict access to objects in GraphQL based upon the current logged-in user. Some models should be accessible for reads by unauthenticated calls. Most other models should be only accessible to the User who created them. What's the best way to manage access control to objects via the Graffiti-generated API?\n\n**In general, are there good patterns of access control for GraphQL? And in particular, are there any good examples or libraries for doing it with Graffiti?**\n\n**Notes:**\n\nI understand that pre- and post- hooks have been implemented for graffiti-mongoose, and that they can be used to do basic binary checks for authentication. I'd like to see how a more detailed access-control logic could be worked into a GraphQL API. In the future, we'll want to support things like Administrators who have access to model instances created by a certain group of Users (e.g. Users whose Affiliations include that of the Administrator).\n\n========================================\n\nTop Answer:\nI create a rule base access control to be used with GraphQL.\n\nhttps://github.com/joonhocho/graphql-rule\n\nIt is simple and unopionated that it can be used with or without GraphQL.\n\nYou can use it with a plain javascript objects.\n\nHope it helps GraphQLers!\n\n========================================\n\nCode:\n```text\nvar UserType = new GraphQLObjectType({\n name: 'User',\n fields: {\n name: { type: GraphQLString },\n birthday: {\n type: GraphQLString,\n resolve(user, context) {\n var auth = context.myLoggedInAuth;\n if (myCanAuthSeeBirthday(auth, user)) {\n return user.birthday;\n }\n }\n }\n }\n});\n```\n\n========================================\n\nComments:\n- You should look into XACML and ABAC which are fine grained attribute based access control models you can use to secure GraphQL and other apps\n- This might lead to unwieldy code depending on your project's scope. This is the official stance on de-coupling authorization from resolvers themselves graphql.org/learn/authorization\n- You may want to look at How to offer personal open-source libraries?\n- Thanks. Didn't know such rules even existed.","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":60,"estimatedTokens":697}}403{"id":"stack-59582142","source":"stackoverflow","questionId":59582142,"title":"Import (cannot import name 'ResolveInfo' from 'graphql') error when using newest graphene and graphene-django version","tags":["python","django","graphql"],"text":"Title: Import (cannot import name 'ResolveInfo' from 'graphql') error when using newest graphene and graphene-django version\nTags: python, django, graphql\nSource: Stack Overflow\n\nQuestion:\nI am having some issues with my django app since updating my dependencies.\nHere aer my installed apps:\n\n```\nINSTALLED_APPS = [\n 'graphene_django',\n 'rest_framework',\n 'corsheaders',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'dojo_manager.dojo',\n]\n```\n\nand my requirements.txt:\n\n```\naniso8601==8.0.0 \nasgiref==3.2.3 \nDjango==3.0.2 \ndjango-cors-headers==3.2.0 \ndjango-filter==2.2.0 \ndjango-graphql-jwt==0.3.0 \ndjangorestframework==3.11.0 \ndjangorestframework-jwt==1.11.0 \ngraphene==2.1.8 \ngraphene-django==2.8.0 \ngraphene-django-extras==0.4.8 \ngraphql-core==3.0.1 \ngraphql-relay==3.0.0 \npip-upgrade-outdated==1.5 \npipupgrade==1.5.2 \npromise==2.3 \nPyJWT==1.7.1 \npython-dateutil==2.8.1 \npytz==2019.3 \nRx==3.0.1 \nsingledispatch==3.4.0.3 \nsix==1.13.0 \nsqlparse==0.3.0\n```\n\nI am getting \n\n```\nImportError: cannot import name 'ResolveInfo' from 'graphql' (E:\\Ben\\GitHub-Repos\\dojo-manager\\env\\lib\\site-packages\\graphql\\__init__.py)\n```\n\nI am aware of https://github.com/graphql-python/graphene-django/issues/737 and https://github.com/graphql-python/graphene/issues/546 , none of which seem to solve it in my case.\n\nAny help greatly appreciated.\n\n========================================\n\nTop Answer:\nTry to replace the header\n\n```\nfrom graphql.type import GraphQLResolveInfo as ResolveInfo\n# from graphql.execution.base import ResolveInfo\n```\n\n========================================\n\nCode:\n```text\nINSTALLED_APPS = [\n 'graphene_django',\n 'rest_framework',\n 'corsheaders',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'dojo_manager.dojo',\n]\n```\n\n```text\naniso8601==8.0.0 \nasgiref==3.2.3 \nDjango==3.0.2 \ndjango-cors-headers==3.2.0 \ndjango-filter==2.2.0 \ndjango-graphql-jwt==0.3.0 \ndjangorestframework==3.11.0 \ndjangorestframework-jwt==1.11.0 \ngraphene==2.1.8 \ngraphene-django==2.8.0 \ngraphene-django-extras==0.4.8 \ngraphql-core==3.0.1 \ngraphql-relay==3.0.0 \npip-upgrade-outdated==1.5 \npipupgrade==1.5.2 \npromise==2.3 \nPyJWT==1.7.1 \npython-dateutil==2.8.1 \npytz==2019.3 \nRx==3.0.1 \nsingledispatch==3.4.0.3 \nsix==1.13.0 \nsqlparse==0.3.0\n```\n\n```text\nImportError: cannot import name 'ResolveInfo' from 'graphql' (E:\\Ben\\GitHub-Repos\\dojo-manager\\env\\lib\\site-packages\\graphql\\__init__.py)\n```\n\n```text\ngraphql-core==3.0.1\n```\n\n```text\ngraphql-core<3\n```\n\n```text\npip install -r requirements.txt\n```\n\n```text\nfrom graphql.type import GraphQLResolveInfo as ResolveInfo\n# from graphql.execution.base import ResolveInfo\n```\n\n========================================\n\nComments:\n- had similar issue when migrating from `graphene-django==2.15` to `graphene-django==3.0.0b7`. the issue was related to another outdated package relying on graphene-django. i fixed it by updating the other one\n- I had the same problem with `get_introspection_query`. Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":141,"estimatedTokens":813}}404{"id":"stack-49868843","source":"stackoverflow","questionId":49868843,"title":"GraphQL: how can I throw a warning after a successful mutation?","tags":["graphql","apollo"],"text":"Title: GraphQL: how can I throw a warning after a successful mutation?\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nLet's imagine I have a `createPost` mutation that inserts a new post. In a typical app, that mutation can either:\n\n- Succeed, returning a `Post`.\n\n- Fail, throwing an error (I use apollo-errors to handle this).\n\nWhat I'd like to implement is a middle scenario, where the mutation succeeds (returning a `Post`); but *also* somehow returns a warning to the user (e.g. `Your post is similar to post XYZ` or similar).\n\nWhat would be a good GraphQL pattern to implement this? Adding a `warning` field to the `Post` type seems a little weird, but then again I'm not sure how to return both a `Post` and a `Warning` in the same mutation? Any ideas?\n\n(Note that I'm using this scenario as an example, I'm interested in the general pattern of returning extra post-mutation data, not finding similar posts specifically)\n\n========================================\n\nCode:\n```text\ncreatePost\n```\n\n```text\nPost\n```\n\n```text\nPost\n```\n\n```text\nYour post is similar to post XYZ\n```\n\n```text\nwarning\n```\n\n```text\nPost\n```\n\n```text\nPost\n```\n\n```text\nWarning\n```\n\n```text\ntype CreatePostError = {\n // Whatever you want\n}\n\ntype CreatePostSuccess = {\n post: Post!\n warning: String\n}\n\nunion CreatePostPayload = CreatePostSuccess | CreatePostError\n\nmutation {\n // Other mutations\n createPost(/* args /*): CreatePostPayload\n}\n```\n\n```text\nPost\n```\n\n========================================\n\nComments:\n- That makes a lot of sense, and from asking around it does seem like the consensus best practice. Thanks!\n- @AndrewIngram wouldn't this work so long as the warning is requested by the client. I found this post looking for a way to possibly return some warning messages such as soon to be deprecated features, etc.\n- GraphQL Rules is similar in that it recommends a mutation payload","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":80,"estimatedTokens":475}}405{"id":"stack-60974566","source":"stackoverflow","questionId":60974566,"title":"How can I get the arguments and types of graphql mutations via introspection?","tags":["graphql"],"text":"Title: How can I get the arguments and types of graphql mutations via introspection?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nWith a GraphQL introspection query like the following I get all the field names on the mutation type of a GraphQL schema. In addition I'd like to get the arguments and their types. How can I query these in addition?\n\n```\nquery {\n __schema {\n mutationType {\n name\n fields {\n name\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nIf you would like to get the arguments of a specific mutation, you can use an introspection query to get its InputObject type.\n\nSay you have a create user mutation that looks something like this\n\n```\nmutation createUser($input: CreateUserInput!) {\n create_user(input: $input) {\n user {\n id\n name\n }\n }\n}\n```\n\nYou can then use an introspection query to get the `CreateUserInput`\n\n```\nquery createUserInput { \n __type(name: \"CreateUserInput\") {\n name\n inputFields {\n name\n description\n defaultValue\n }\n }\n}\n```\n\nand use the `inputFields` from that query to see the mutations arguments. gql introspection docs\n\n========================================\n\nCode:\n```text\nquery {\n __schema {\n mutationType {\n name\n fields {\n name\n }\n }\n }\n}\n```\n\n```text\nquery {\n __schema {\n mutationType {\n name\n fields {\n name\n args {\n name\n defaultValue\n type {\n ...TypeRef\n }\n }\n }\n }\n }\n}\n\nfragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nofType\n```\n\n```text\nmutation createUser($input: CreateUserInput!) {\n create_user(input: $input) {\n user {\n id\n name\n }\n }\n}\n```\n\n```text\nquery createUserInput { \n __type(name: \"CreateUserInput\") {\n name\n inputFields {\n name\n description\n defaultValue\n }\n }\n}\n```\n\n```text\nCreateUserInput\n```\n\n```text\ninputFields\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":159,"estimatedTokens":573}}406{"id":"stack-63035058","source":"stackoverflow","questionId":63035058,"title":"urql useQuery's pause option doesn't freezes the request temporarily","tags":["javascript","reactjs","graphql","react-hooks","urql"],"text":"Title: urql useQuery's pause option doesn't freezes the request temporarily\nTags: javascript, reactjs, graphql, react-hooks, urql\nSource: Stack Overflow\n\nQuestion:\nI'm trying with the following code to execute urql useQuery only at once. But for some reason it is getting called on every re-render.\n\nAs per the docs https://formidable.com/open-source/urql/docs/basics/queries/#pausing-usequery\nthis query should be paused initially on the render and it should only get executed when called from React.useEffect on mount.\n\n```\nconst [{ fetching, data, error }, reExecute] = useQuery({\n query: INITIAL_CONFIG_QUERY,\n pause: true\n});\n\nReact.useEffect(() => {\n reExecute();\n}, []);\n```\n\nWhat could be the best way to execute query only at once using urql?\n\n========================================\n\nTop Answer:\nThis could be a urlq bug, but it also could be that your component is being unmounted and remounted every time the parent component rerenders.\n\nTo test this, add:\n\n```\nReact.useEffect(() => {\n console.log(\"Component was mounted.\");\n}, []);\n```\n\nAnd see if the console.log statement gets printed more than once.\n\n========================================\n\nCode:\n```text\nconst [{ fetching, data, error }, reExecute] = useQuery({\n query: INITIAL_CONFIG_QUERY,\n pause: true\n});\n\nReact.useEffect(() => {\n reExecute();\n}, []);\n```\n\n```text\nconst MyComponent = () => {\n const client = useClient();\n useEffect(() => {\n client.query(\n INITIAL_CONFIG_QUERY\n ).toPromise().then(result => /* do something */)\n }, [])\n}\n```\n\n```text\nuseClient\n```\n\n```text\nclient.query().toPromise()\n```\n\n```text\nReact.useEffect(() => {\n console.log(\"Component was mounted.\");\n}, []);\n```\n\n========================================\n\nComments:\n- Thank you very much for answering. That'll solve the purpose. But I'm still not getting why my query gets executed if I've set paused option to `true`. does pause have a different use case than my understanding?\n- I'm making this `useQuery` hook in the App Root Component, where it needs the initial config, which also sets the global context value after this query result, which cause the rerender.\n- Another use case, I don't want to make a call on SSR (required xcsrf cookie and token to be present), so setting a pause option to `true`. but it is still making a call there.\n- @AnkitBalyan this seems to work correctly for me codesandbox.io/s/nervous-butterfly-xwwh8?file=/src/component‌​s/…\n- no, the component is rendering at a single time only. this useEffect hook gets called only once if I pass the empty dependency array.","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":85,"estimatedTokens":648}}407{"id":"stack-37237673","source":"stackoverflow","questionId":37237673,"title":"Do I need mongoose with graphql?","tags":["mongodb","graphql"],"text":"Title: Do I need mongoose with graphql?\nTags: mongodb, graphql\nSource: Stack Overflow\n\nQuestion:\nIf I want to connect a mongo database to graphql schema, do I need mongoose ORM or can I just do raw drivers calls?\n\n========================================\n\nCode:\n```text\nvar QueryType = new GraphQLObjectType({ \n name: 'Query',\n fields: () => ({\n todos: {\n type: new GraphQLList(TodoType),\n resolve: () => {\n return new Promise((resolve, reject) => {\n TODO.find((err, todos) => {\n if (err) reject(err)\n else resolve(todos)\n })\n })\n }\n }\n })\n})\n```\n\n```text\nresolve: () => {\n return new Promise((resolve, reject) => {\n db.collection('todos').find({}).toArray((err, todos) => {\n if (err) reject(err)\n else resolve(todos)\n })\n })\n}\n```\n\n```text\nresolve\n```\n\n========================================\n\nComments:\n- Mongoose retruns a promise if you don't pass a callback. You may simply return `TODO.find()` in the resolve function.","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":48,"estimatedTokens":256}}408{"id":"stack-42631523","source":"stackoverflow","questionId":42631523,"title":"Remove read-only fields before mutation in GraphQL","tags":["javascript","graphql","graphql-js","react-apollo","apollo-client"],"text":"Title: Remove read-only fields before mutation in GraphQL\nTags: javascript, graphql, graphql-js, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI've got a type called `Article` in my schema:\n\n```\ntype Article {\n id: ID!\n updated: DateTime\n headline: String\n subline: String\n}\n```\n\nFor updates to it, there's a corresponding input type that is used by a `updateArticle(id: ID!, article: ArticleInput!)` mutation:\n\n```\ninput ArticleInput {\n headline: String\n subline: String\n}\n```\n\nThe mutation itself looks like this:\n\n```\nmutation updateArticle($id: ID!, $article: ArticleInput!) {\n updateArticle(id: $id, article: $article) {\n id\n updated\n headline\n subline\n }\n}\n```\n\nThe article is always saved as a whole (not individual fields one by one) and so when I pass an article to that mutation that I've previously fetched, it throws errors like `Unknown field. In field \"updated\"`, `Unknown field. In field \"__typename\"` and `Unknown field. In field \"id\"`. These have the root cause, that those fields aren't defined on the input type.\n\nThis is correct behaviour according to the spec:\n\n(β¦) This unordered map should not contain any entries with names not\ndefined by a field of this input object type, otherwise an error\nshould be thrown.\n\nNow my question is what a good way to deal these kinds of scenarios is. Should I list all properties that are allowed on the input type in my app code?\n\nIf possible I'd like to avoid this and maybe have a utility function slice them off for me which knows about the input type. However, since the client doesn't know about the schema, this would have to happen on the server side. Thus, the unnecessary properties would be transferred there, which I suppose is the reason why they shouldn't be transferred in the first place.\n\nIs there a better way than maintaining a list of properties?\n\nI'm using `apollo-client`, `react-apollo` and `graphql-server-express`.\n\n========================================\n\nTop Answer:\nI've personally had same idea and took @amann 's approach earlier, but after some time the conceptual flaw of using query fragments on input types became evident. You would'n have an option to pick input type field that isn't present in (corresponding) object type - is there even any?\n\nCurrently I'm describing my input data by `typesafe-joi` schemas and using it's `stripUnknown` option to filter out my form data.\n\n**Invalid data never leaves form so valid data can be statically typed.**\n\nIn a sense, creating joi schema is same activity as defining \"input fragment\" so no code duplication takes place and your code can be type-safe.\n\n========================================\n\nCode:\n```text\ntype Article {\n id: ID!\n updated: DateTime\n headline: String\n subline: String\n}\n```\n\n```text\ninput ArticleInput {\n headline: String\n subline: String\n}\n```\n\n```text\nmutation updateArticle($id: ID!, $article: ArticleInput!) {\n updateArticle(id: $id, article: $article) {\n id\n updated\n headline\n subline\n }\n}\n```\n\n```text\nArticle\n```\n\n```text\nupdateArticle(id: ID!, article: ArticleInput!)\n```\n\n```text\nUnknown field. In field \"updated\"\n```\n\n```text\nUnknown field. In field \"__typename\"\n```\n\n```text\nUnknown field. In field \"id\"\n```\n\n```text\napollo-client\n```\n\n```text\nreact-apollo\n```\n\n```text\ngraphql-server-express\n```\n\n```text\nconst ArticleMutableFragment = gql`\nfragment ArticleMutable on Article {\n headline\n subline\n publishing {\n published\n time\n }\n}\n`\n\nconst ArticleFragment = gql`\nfragment Article on Article {\n ...ArticleMutable\n id\n created\n updated\n}\n${ArticleMutableFragment}\n`;\n\nconst query = gql`\nquery Article($id: ID!) {\n article(id: $id) {\n ...Article\n }\n}\n${ArticleFragment}\n`;\n\nconst articleUpdateMutation = gql`\nmutation updateArticle($id: ID!, $article: ArticleInput!) {\n updateArticle(id: $id, article: $article) {\n ...Article\n }\n}\n${ArticleFragment}\n`;\n\n...\n\nimport filterGraphQlFragment from 'graphql-filter-fragment';\n\n...\n\ngraphql(articleUpdateMutation, {\n props: ({mutate}) => ({\n onArticleUpdate: (id, article) =>\n // Filter for properties the input type knows about\n mutate({variables: {id, article: filterGraphQlFragment(ArticleMutableFragment, article)}})\n })\n})\n\n...\n```\n\n```text\nArticleMutable\n```\n\n```text\ntypesafe-joi\n```\n\n```text\nstripUnknown\n```\n\n```text\nimport { CodegenConfig } from '@graphql-codegen/cli';\n\nimport { commonConfig } from './configs/common.config';\n\nconst classesCodegen: CodegenConfig = {\n schema: 'apps/back/src/app/schema.gql',\n documents: ['apps/front/**/*.tsx'],\n ignoreNoDocuments: true,\n generates: {\n 'libs/data-layer/src/lib/gql/classes.ts': {\n plugins: ['typescript'],\n config: {\n declarationKind: {\n // directive: 'type',\n // scalar: 'type',\n input: 'class',\n // type: 'type',\n // interface: 'type',\n // arguments: 'type',\n },\n ...commonConfig,\n },\n },\n },\n};\n\nexport default classesCodegen;\n```\n\n```text\n/** Material Input */\nexport class MaterialInput {\n /** Material's id */\n _id?: InputMaybe<Scalars['Id']['input']>;\n /** Material's coding config */\n codingConfig: CodingConfigUnionInput;\n /** Material's content */\n content?: InputMaybe<Scalars['String']['input']>;\n /** Material's cost usages */\n costUsages: Array<CostUsageInput>;\n /** Material's label */\n label: Scalars['String']['input'];\n /** Material's status id */\n statusId: Scalars['Id']['input'];\n /** Material's title */\n title?: InputMaybe<Scalars['String']['input']>;\n};\n```\n\n```text\nimport type { C, O } from 'ts-toolbelt';\nimport { assign, keys, pick } from 'lodash';\n\nexport const pruneInput = <I extends object>(\n instance: O.Object,\n Class: C.Class<unknown[], I>,\n): I => {\n const input = new Class();\n assign(input, pick(instance, keys(input)));\n return input;\n};\n```\n\n```text\nimport type { O } from 'ts-toolbelt';\n\nimport { CostUsageInput, MaterialInput } from '@your-organization/data-layer';\n\nimport { pruneInput } from '../../../utils/prune-input.util';\n\nimport { codingConfigForm2ApiMapper } from '../../mappers/coding-config.form2api.mapper';\n\nimport type {\n MaterialForm_Material,\n MaterialInput as IMaterialInput,\n} from '..';\n\nexport function materialForm2ApiMapper(\n material: O.Readonly<MaterialForm_Material>,\n): O.Readonly<IMaterialInput> {\n const materialInput = pruneInput(material, MaterialInput);\n\n const costUsagesInput = materialInput.costUsages.map((costUsage) =>\n pruneInput(costUsage, CostUsageInput),\n );\n\n return {\n ...materialInput,\n costUsages: costUsagesInput,\n codingConfig: codingConfigForm2ApiMapper(material.codingConfig),\n };\n}\n```\n\n```text\ngraphql-codegen\n```\n\n```text\ngraphql-codegen\n```\n\n========================================\n\nComments:\n- Can you please show the actual mutation that you're calling? It sounds like something else is amiss here.\n- Thanks for the quick response @marktani! I've added the mutation code to the question.\n- Do you have the possibility to run a \"raw\" mutation against your server? That is, using GraphiQL or a HTTP client like curl or fetch. I want to understand if this is an error thrown by Apollo or thrown by your server.\n- I've just simulated the request with a curl. The error is definitely thrown by the server. Removing the fields that are unknown to the input type fixes the problem.\n- So looks like your payload for that mutation just doesn't offer `id`, `updated` or `updated`. That it doesn't offer `__typename` is troublesome, as that's part of the spec. If you can the endpoint that would be helpful, otherwise check the docs generated by GraphiQL.\n- Exactly, the root cause seems to be that the mutation doesn't know about those fields. My preferred solution would have been that they are ignored, but that would involve transferring them to the server, which I guess is the reason this isn't supported. Sadly I can't the endpoint with you, but I guess every GraphQL endpoint will respond in the same way when a mutation is called with an input type that includes extra fields.\n- Again, I don't think the input arguments are the problem, rather the items you include in the query.\n- Sorry, I think I overlooked that. I just tried again with a mutation that only queries fields on the input type after the mutation but that fails with the same error.\n- Yeah GraphQL currently doesn't include a lot of nice-to-have stuff for CRUD operations, like utilities for saving an entire object via an input object. It kind of assumes you are calling each mutation with exactly the data you mean to pass in. Which might be good because if someone added a new field to the input type, then you will end up sending more fields than you expected.\n- That's true. On the other hand, when new fields are added to `Article` that are queried and updatable with the view, I might forget to add them to the whitelist β so that's something to keep in mind. But good to know that I'm not missing anything obvious β thanks!\n- Actually, this might be solved in a good way with the filter capabilities of your graphql-anywhere package. That way I can write a query that filters the data before a mutation. That query can be placed right next to the query that fetches the data and so it might be easier to keep those in sync.\n- Or even better a shared fragment between the query and the filter query for the mutation. I'll give that another try.\n- Ooh, I like this a lot because it still lets you specify exactly the fields you are trying to send!","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":315,"estimatedTokens":2376}}409{"id":"stack-55113542","source":"stackoverflow","questionId":55113542,"title":"How to have GraphQL enum resolve Strings","tags":["javascript","graphql","graphql-js","apollo-client","apollo-server"],"text":"Title: How to have GraphQL enum resolve Strings\nTags: javascript, graphql, graphql-js, apollo-client, apollo-server\nSource: Stack Overflow\n\nQuestion:\nPreviously, I just typed my `input KeyInput` as `mode: String!`, and I'm looking to change the type from String! to a custom enum. \n\nI have the tried following schema:\n\n```\nenum Mode= {\n test\n live\n}\n\ninput KeyInput = {\n mode: Mode!\n}\n\ntype Key {\n name,\n mode\n}\n\ntype Query {\n Keys(input: KeyInput): [Key]\n}\n```\n\nAnd my query looks like this:\n\n```\nquery{\n Keys(input: {mode: \"test\"}){\n name\n }\n}\n```\n\nHowever, I get the following error:\n\n```\n\"message\": \"Expected type Mode!, found \\\"test\\\"; Did you mean the enum value test?\"\n```\n\nIs it possible to have enum values resolve String values? If I remove the quotes from the input, it will work. However, I need to be able to continue to resolve the Mode as Strings.\n\n========================================\n\nCode:\n```text\nenum Mode= {\n test\n live\n}\n\ninput KeyInput = {\n mode: Mode!\n}\n\ntype Key {\n name,\n mode\n}\n\ntype Query {\n Keys(input: KeyInput): [Key]\n}\n```\n\n```text\nquery{\n Keys(input: {mode: \"test\"}){\n name\n }\n}\n```\n\n```text\n\"message\": \"Expected type Mode!, found \\\"test\\\"; Did you mean the enum value test?\"\n```\n\n```text\ninput KeyInput\n```\n\n```text\nmode: String!\n```\n\n```text\nKeys(input: { mode: test }) {\n name\n}\n```\n\n```text\nKeys(input: { mode: $mode }) {\n name\n}\n\n// in your component...\nvariables: {\n mode: 'test'\n}\n```\n\n```text\ntest\n```\n\n```text\ndata\n```\n\n```text\nmode\n```\n\n========================================\n\nComments:\n- It's not clear what you mean by \"continue to resolve the Mode as Strings\". Can you please clarify why omitting the quotation marks in the query is a problem for you?\n- Sorry; If i were to query Keys like so without quotes: `Keys(input: mode: test})`, GraphQL will have no problems resolving `test`. However, I would like it to resolve `test` in quotes as `\"test\"`.\n- Perfect answer, thank you! And for the link to the spec as well; I hadn't thunk to look there, as I was too focused on `apollo-server` docs.\n- I was hoping to keep a consistent way to have my `graphiql` users be able to use `Strings` along `enums`. For example, if I were to have `name: String!` along side `Mode: enum`, the query would not seem consistent: `Keys(input: { name: \"Jim\", mode: test})`\n- Instead, I'd prefer it be able to be queried like this: `Keys(input: { name: \"Jim\", mode: \"test\"})`\n- Yes, from the perspective of existing consumers of your API, changing the field to an enum would be a breaking change.\n- Sadly this doesn't work for me","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":129,"estimatedTokens":649}}410{"id":"stack-52736868","source":"stackoverflow","questionId":52736868,"title":"Does it make sense to use GraphQL for microservices intercommunication?","tags":["graphql","microservices"],"text":"Title: Does it make sense to use GraphQL for microservices intercommunication?\nTags: graphql, microservices\nSource: Stack Overflow\n\nQuestion:\nI've read a lot on using GraphQL as API gateway for the front-end in front of the micro-services.\nBut I wonder if all the GraphQL advantages over Rest aren't relevant to communication between the micro-services as well.\nAny inputs, pros/cons and successful usage examples will be appreciated.\n\n========================================\n\nTop Answer:\nI don't have experience with using GraphQL in a microservices environment but I'm inclined to think that its not the greatest for microservices.\n\nTo add a little more color to @Lior Bar-On's answer, GraphQL is more of a query language and is more dynamic in nature. It is often used to aggregate data sets as a result of a single request which in turn will potentially require many requests being made to many services in a microservice environment. At the same time, it also adds complexity to have to translate the gathering of information from respective sources of the information (other microservices). Of course, how complex would depend on how micro your services are and what queries you may look to support.\n\nOn the other hand, I think a monolith that uses an MVC architecture may actually have an upper hand because it owns a larger body of a data that it can query.","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":17,"estimatedTokens":342}}411{"id":"stack-47331391","source":"stackoverflow","questionId":47331391,"title":"GraphQL - return calculated type dependent on argument","tags":["mysql","node.js","schema","graphql","reducers"],"text":"Title: GraphQL - return calculated type dependent on argument\nTags: mysql, node.js, schema, graphql, reducers\nSource: Stack Overflow\n\nQuestion:\n**Overview** (simplified):\n\nIn my NodeJS server I've implemented the following GraphQL schema:\n\n```\ntype Item {\n name: String,\n value: Float\n}\n\ntype Query {\n items(names: [String]!): [Item]\n}\n```\n\nThe client query then passes an array of names, as an argument:\n\n```\n{\n items(names: [\"total\",\"active\"] ) {\n name\n value\n }\n}\n```\n\nThe backend API queries a mysql DB, for the \"**total**\" and \"**active**\" fields (columns on my DB table) and reduces the response like so:\n\n```\n[{\"name\":\"total\" , value:100} , {\"name\":\"active\" , value:50}]\n```\n\nI would like my graphQL API to support \"ratio\" Item, I.E: I would like to send the following query: \n\n```\n{\n items(names: [\"ratio\"] ) {\n name\n value\n }\n}\n```\n\nor\n\n```\n{\n items(names: [\"total\",\"active\",\"ratio\"] ) {\n name\n value\n }\n}\n```\n\nAnd return **active / total** as the calculated result of that new field (`[{\"name\":\"ratio\" , value:0.5}]`). What would be a generic way to handle the \"**ratio**\" field differently? \n\nShould it be a new type in my schema or should I implement the logic in the reducer?\n\n========================================\n\nTop Answer:\nYou could set your resolver function up so it uses the second parameter - the arguments - to see if the name \"ratio\" is in your names array:\n\n```\nresolve: (root, { names }, context, fieldASTs) => {\n let arrayOfItems;\n // Contact DB, populate arrayOfItems with your total / active items\n\n // if 'ratio' is within your name array argument, calculate it:\n if (names.indexOf(\"ratio\") > -1){\n // Calculate ratio\n arrayOfItems.push({ name: \"ratio\", value: calculatedRatio });\n }\n\n return(arrayOfItems);\n}\n```\n\nI hope I understood your question correctly\n\n========================================\n\nCode:\n```text\ntype Item {\n name: String,\n value: Float\n}\n\n\ntype Query {\n items(names: [String]!): [Item]\n}\n```\n\n```text\n{\n items(names: [\"total\",\"active\"] ) {\n name\n value\n }\n}\n```\n\n```text\n[{\"name\":\"total\" , value:100} , {\"name\":\"active\" , value:50}]\n```\n\n```text\n{\n items(names: [\"ratio\"] ) {\n name\n value\n }\n}\n```\n\n```text\n{\n items(names: [\"total\",\"active\",\"ratio\"] ) {\n name\n value\n }\n}\n```\n\n```text\n[{\"name\":\"ratio\" , value:0.5}]\n```\n\n```text\nItem {\n total: Int,\n active: Int,\n ratio: Float\n}\n\ntype Query {\n items: [Item]\n}\n```\n\n```text\n{\n items {\n total \n active \n ratio\n }\n}\n```\n\n```text\nconst express = require('express');\nconst graphqlHTTP = require('express-graphql');\nconst { graphql } = require('graphql');\nconst { makeExecutableSchema } = require('graphql-tools');\nconst getFieldNames = require('graphql-list-fields');\n\nconst typeDefs = `\ntype Item {\n total: Int,\n active: Int,\n ratio: Float\n}\n\ntype Query {\n items: [Item]\n}\n`;\n\nconst resolvers = {\n Query: {\n items(obj, args, context, info) {\n const fields = getFieldNames(info) // get the array of field names specified by the client\n return context.db.getItems(fields)\n }\n },\n Item: {\n ratio: (obj) => obj.active / obj.total // resolver for finding ratio\n }\n};\n\nconst schema = makeExecutableSchema({ typeDefs, resolvers });\n\nconst db = {\n getItems: (fields) => // table.select(fields)\n [{total: 10, active: 5},{total: 5, active: 5},{total: 15, active: 5}] // dummy data\n}\ngraphql(\n schema, \n `query{\n items{\n total,\n active,\n ratio\n }\n }`, \n {}, // rootValue\n { db } // context\n).then(data => console.log(JSON.stringify(data)))\n```\n\n```text\n{\"name\":\"ratio\" , value:data.active/data.total}\n```\n\n```text\nratio\n```\n\n```text\nratio\n```\n\n```text\nresolve: (root, { names }, context, fieldASTs) => {\n let arrayOfItems;\n // Contact DB, populate arrayOfItems with your total / active items\n\n // if 'ratio' is within your name array argument, calculate it:\n if (names.indexOf(\"ratio\") > -1){\n // Calculate ratio\n arrayOfItems.push({ name: \"ratio\", value: calculatedRatio });\n }\n\n return(arrayOfItems);\n}\n```\n\n========================================\n\nComments:\n- Whoud you like to return \"ratio\" in addition to \"total\" and \"active\" or return just \"ratio\"?\n- It depends on the Query, but theoretically I would like to be able to get it all in a single query. `items(names: [\"total\",\"active\",\"ratio\"] )`\n- Why not calculate the ratio in backend API when you get your db results. Then just return it as third name/value pair in addition to total and active.\n- At the moment the backend receives the names and builds a DB query. if I want to calculate the results there, then I should check if one of the names is \"ratio\" remove it from the generic DB query, and when I have the results I can calculate the value ... Since I'm new to graphQL I was thinking there must be a more generic way to handle this scenario.\n- You can make a new type, e.g. `type Kpi {total: Int, active: Int, ratio: Float}` and make the same input type. Then you can pass that in your query but as calculating is concerned I think it must be done in your resolver functions and GraphQL has no way of doing it.\n- you could map your calculated items, I.E `(\"ratio\" == \"active\"/\"total\")` so when you ask for \"ratio\" the DB query will request active + total and then will run a post processor for the calculations.\n- So where would you place this logic, in the reducer?\n- That is a better perspective, I'll adopt the change ... thank you :)\n- I know this is a very old answer but hope you can see it :) what if the user would like to give a function, not just ratio. I mean defining variables and doing a calculation with them?","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":247,"estimatedTokens":1405}}412{"id":"stack-38043757","source":"stackoverflow","questionId":38043757,"title":"How to link schema in \"GraphQL for .NET\" and \"Relay\"?","tags":["c#","reactjs","asp.net-core","graphql","relay"],"text":"Title: How to link schema in \"GraphQL for .NET\" and \"Relay\"?\nTags: c#, reactjs, asp.net-core, graphql, relay\nSource: Stack Overflow\n\nQuestion:\nI want to build a web app with Javascript for the front end and C# for the back end and I want to determine the value of GraphQL.\n\n- For my C# back end I use a GraphQL implementation named GraphQL for .NET.\n\n- For my front end, I would like to use Relay as it plays well with ReactJS.\n\nNow for my back end, I implemented a sample schema like in one of the examples which looks like this:\n\n```\npublic class StarWarsSchema : Schema\n{\n public StarWarsSchema()\n {\n Query = new StarWarsQuery();\n }\n}\n```\n\nIn my front end, I now need to tell Relay somehow about this schema. At least this is what I understood when walking through the tutorials, because for some reason the GraphQL queries needs to be transpiled.\nThis is an example as how I would like to load all Droids:\n\n```\nclass Content extends React.Component {\n ...\n}\n\nexport default Relay.createContainer(Content, {\n fragments: {\n viewer: () => Relay.QL`\n fragment on User {\n query HeroNameQuery {\n droids {\n id\n name\n }\n }\n }\n `,\n }\n});\n```\n\nIn one of the examples for Relay, I have seen that the babel-relay-plugin is used for conversion. It gets a schema file (JSON). The Getting Started Guide of Relay shows, how to create such a schema with graphql-js and graphql-relay-js.\n\nNow my questions:\n\n- Do I really need to create schemas on the front and on the back end?\n\n- What is the point of teaching Relay my schema, as the back end already uses the schema to return the well formed data?\n\n- What is the benefit at all from using Relay in this scenario? What would I lose when I would just access the backend via a regular REST endpoint along with a GraphQL query as a parameter?\n\n========================================\n\nCode:\n```text\npublic class StarWarsSchema : Schema\n{\n public StarWarsSchema()\n {\n Query = new StarWarsQuery();\n }\n}\n```\n\n```text\nclass Content extends React.Component<ContentProps, { }> {\n ...\n}\n\nexport default Relay.createContainer(Content, {\n fragments: {\n viewer: () => Relay.QL`\n fragment on User {\n query HeroNameQuery {\n droids {\n id\n name\n }\n }\n }\n `,\n }\n});\n```\n\n========================================\n\nComments:\n- Try using hotchocolate library for your use case - chillicream.com/docs/hotchocolate/v13\n- Thanks for clarification.I meanwhile realized that the schema.json is needed in transpilation process when building the frontend code from GraphQL queries.","metadata":{"transformedAt":"2026-08-18T18:32:36.055Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":96,"estimatedTokens":667}}413{"id":"stack-47231290","source":"stackoverflow","questionId":47231290,"title":"Github GraphQL API: How can I gather specific user's repositories?","tags":["rest","github","graphql","github-api","github-graphql"],"text":"Title: Github GraphQL API: How can I gather specific user's repositories?\nTags: rest, github, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get repositories of user with login name \"somelogin\".\n\nIt returns all repositories but I'm trying to get repositories owned by him only. Because new API uses GraphQL I couldn't did it.\n\nCurrently I'm using:\n\n```\n{\n \"query\": \"query { user(login:\\\"furknyavuz\\\") {repositories(first: 50) { nodes { name url }}}}\"\n}\n```\n\n========================================\n\nTop Answer:\nIt's super easy to build graph QL using the Github GraphQL explorer. Please refer to the attached screenshot.\nhttps://docs.github.com/en/graphql/overview/explorer\n\n{\nuser(login: \"leerob\") {\nname\nemail\ncompany\nbio\nfollowers {\ntotalCount\n}\nfollowing {\ntotalCount\n}\nrepositories(first: 50, isFork: false) {\nnodes {\nname\nurl\nstargazerCount\nprimaryLanguage {\nid\nname\n}\n}\n}\n}\n}\n\nhttps://i.sstatic.net/0nBGs.png\n\n========================================\n\nCode:\n```json\n{\n \"query\": \"query { user(login:\\\"furknyavuz\\\") {repositories(first: 50) { nodes { name url }}}}\"\n}\n```\n\n```text\n{\n user(login: \"furknyavuz\") {\n repositories(first: 50, isFork: false) {\n nodes {\n name\n url\n }\n }\n }\n}\n```\n\n```text\ncurl -H \"Authorization: bearer token\" -d '\n {\n \"query\": \"query { user(login: \\\"furknyavuz\\\") { repositories(first: 50, isFork: false) { nodes { name url } } } }\"\n }\n' https://api.github.com/graphql\n```\n\n```text\nisFork: false\n```\n\n========================================\n\nComments:\n- Do you mean you want to exclude fork ? use `isFork: false`\n- Yes actually I want to exclude all repositories not owned by me. Can you give me the correct usage of it.","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":90,"estimatedTokens":432}}414{"id":"stack-66680731","source":"stackoverflow","questionId":66680731,"title":"How to send multiline string from graphQL from flutter?","tags":["javascript","flutter","dart","graphql"],"text":"Title: How to send multiline string from graphQL from flutter?\nTags: javascript, flutter, dart, graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying put multiline support in one of the comment section of app and it is not accepting it.\n\nthe input which i put is\n\n```\nHi\nHello\nHello\n```\n\nand it is showing this error\n\nhttps://i.sstatic.net/NWOWF.jpg\n\nAnd this is the code i am writing for the inputfield\n\n```\nListTile(\n leading: CircleAvatar(\n backgroundImage: AssetImage(UIData.pkImage),\n ),\n title: Container(\n constraints: BoxConstraints(\n maxHeight: double.infinity,\n minHeight: 20,\n ),\n child: TextField(\n keyboardType: TextInputType.multiline,\n minLines: 1,//Normal textInputField will be displayed\n maxLines: 10,// when user presses enter it will adapt to it\n decoration: InputDecoration(\n suffix: IconButton(\n color: Colors.grey,\n icon: Icon(Icons.send),\n onPressed: () {\n createComment();\n },\n ),\n hintText: 'Leave a Comment....',\n border: OutlineInputBorder(\n borderRadius: BorderRadius.circular(20.0),\n borderSide: BorderSide(color: Colors.teal))),\n controller: commentController,\n ),\n ),\n ),\n```\n\nThe problem is with updating the graphQL query and initializing it with String block\n\n```\nString createComments(String postId, var text) {\n return \"\"\"\nmutation{\n createComment(postId: \"$postId\", \n data:{\n text: \"\"$text\"\",\n }\n ){\n _id\n }\n}\n\"\"\"\n;\n }\n```\n\n========================================\n\nTop Answer:\nWe can use the additional putting of the spaces also\n\n========================================\n\nCode:\n```text\nHi\nHello\nHello\n```\n\n```text\nListTile(\n leading: CircleAvatar(\n backgroundImage: AssetImage(UIData.pkImage),\n ),\n title: Container(\n constraints: BoxConstraints(\n maxHeight: double.infinity,\n minHeight: 20,\n ),\n child: TextField(\n keyboardType: TextInputType.multiline,\n minLines: 1,//Normal textInputField will be displayed\n maxLines: 10,// when user presses enter it will adapt to it\n decoration: InputDecoration(\n suffix: IconButton(\n color: Colors.grey,\n icon: Icon(Icons.send),\n onPressed: () {\n createComment();\n },\n ),\n hintText: 'Leave a Comment....',\n border: OutlineInputBorder(\n borderRadius: BorderRadius.circular(20.0),\n borderSide: BorderSide(color: Colors.teal))),\n controller: commentController,\n ),\n ),\n ),\n```\n\n```text\nString createComments(String postId, var text) {\n return \"\"\"\nmutation{\n createComment(postId: \"$postId\", \n data:{\n text: \"\"$text\"\",\n }\n ){\n _id\n }\n}\n\"\"\"\n;\n }\n```\n\n```text\nString createComments(String postId, var text) {\n const createCommentMutation = \"\"\"\n mutation createComment(\\$postId: String, \\$comment:String) { \n createComment(postId: \\$postId, \n data:{\n text: \\$comment,\n }\n ){\n _id\n }\n }\n \"\"\";\n\n dynamic _resp = await _graphClient\n .mutate(MutationOptions(\n document: gql(createCommentMutation),\n variables: {\n 'postId': postId, //Add your variables here\n 'comment':text\n },\n ));\n\n}\n```\n\n```text\ngraphql\n```\n\n```text\n\\$postId\n```\n\n```text\n\\$comment\n```\n\n```text\nString\n```\n\n========================================\n\nComments:\n- Can you please edit your code to add the place where you provide that string?\n- sure i am adding it @MikiMints\n- And can you also provide a sample `comments` object?\n- it is of a type string\n- You can use AutoSize text widget and set maximum lines\n- the problem is that it is not taking custom next line in the input\n- it is showing that _resp is not used anywhere and second string cant be assigned to document\n- i think document should be document node\n- and it is saying that future can't be assinged to map\n- @YasharthDubey You might be using an older version of `flutter_graphql`. They have depricated `documentNode` in favor of `document`","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":190,"estimatedTokens":1087}}415{"id":"stack-37012595","source":"stackoverflow","questionId":37012595,"title":"RelayContainer: Expected prop `%s` to be supplied to `%s`, but ' + 'got `undefined`. Pass an explicit `null` if this is intentional","tags":["reactjs","graphql","relayjs"],"text":"Title: RelayContainer: Expected prop `%s` to be supplied to `%s`, but ' + 'got `undefined`. Pass an explicit `null` if this is intentional\nTags: reactjs, graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nI try to Implement some stuff with React, Relay and GraphQL, but I faced a Problem I dont understand and where i cant find a solution.\n\nFirst I created a RootQuery and had one Component and it worked well. Now I created a Sub Component with an own fragment an i get this Error: \n\n relay.js:1799 Warning: RelayContainer: Expected prop `room` to be supplied to `RoomList`, but got `undefined`. Pass an explicit `null` if this is intentional.\n\nIn the Networkrequest I see all the requested Data.\n\nHere is some code:\n\nRoot Query\n\n```\nconst RoomQuery = {\n room: (Component) => Relay.QL`\n query {\n room {\n ${Component.getFragment('room')},\n }\n }\n `\n};\n```\n\nRoute\n\n```\n\n```\n\nRelay Container\n\n```\nexport default Relay.createContainer(Rooms, {\nfragments: {\n room: () => Relay.QL`\n fragment on Room {\n title,\n description,\n publicKeys,\n takenKeys,\n image_filename,\n subRoomsCount,\n owner {\n fullName\n },\n ${RoomList.getFragment('room')},\n }\n`,\n}\n});\n```\n\nRelay Sub Container\n\n```\nexport default Relay.createContainer(RoomList, {\nfragments: {\n room: () => Relay.QL`\n fragment on Room {\n subRooms{\n title,\n description,\n publicKeys,\n takenKeys,\n image_filename,\n availableKeys,\n owner {\n fullName\n },\n subRoomsCount\n }\n }\n`,\n}\n});\n```\n\nIn my React Component I use this Sub React Component like this:\n\n```\n\n```\n\nI dont know if I understand something wrong but I thougt that Relay will load the Data and fill it in this.props, but there is only a relay Object.\n\nThanks for your help :)\n\nGreetings \n\nRonny Gerndt\n\n========================================\n\nCode:\n```text\nconst RoomQuery = {\n room: (Component) => Relay.QL`\n query {\n room {\n ${Component.getFragment('room')},\n }\n }\n `\n};\n```\n\n```text\n<Route name=\"rooms\" path=\"/rooms\" component={Rooms} onEnter={requireAuth} queries={RoomQuery}/>\n```\n\n```text\nexport default Relay.createContainer(Rooms, {\nfragments: {\n room: () => Relay.QL`\n fragment on Room {\n title,\n description,\n publicKeys,\n takenKeys,\n image_filename,\n subRoomsCount,\n owner {\n fullName\n },\n ${RoomList.getFragment('room')},\n }\n`,\n}\n});\n```\n\n```text\nexport default Relay.createContainer(RoomList, {\nfragments: {\n room: () => Relay.QL`\n fragment on Room {\n subRooms{\n title,\n description,\n publicKeys,\n takenKeys,\n image_filename,\n availableKeys,\n owner {\n fullName\n },\n subRoomsCount\n }\n }\n`,\n}\n});\n```\n\n```text\n<RoomList></RoomList>\n```\n\n```text\nroom\n```\n\n```text\nRoomList\n```\n\n```text\nundefined\n```\n\n```text\nnull\n```\n\n```text\n<RoomList></RoomList>\n```\n\n```text\n<RoomList room={this.props.room}></RoomList>\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":187,"estimatedTokens":746}}416{"id":"stack-53372696","source":"stackoverflow","questionId":53372696,"title":"DynamoDB schema updates with AWS Amplify","tags":["amazon-web-services","amazon-dynamodb","graphql","database-migration","aws-amplify"],"text":"Title: DynamoDB schema updates with AWS Amplify\nTags: amazon-web-services, amazon-dynamodb, graphql, database-migration, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nAccording to the AWS Amplify documentation:\n\n- \"objects annotated with @model are stored in Amazon DynamoDB\";\n\n- \"a single @model directive configures ... an Amazon DynamoDB table\"; and\n\n- one can \"push updated changes with `amplify push`\".\n\nIt seems clear that `amplify push` creates a DynamoDB table for each @model. \n\nMy questions relate to schema updates:\n\nI imagine that adding/removing a model or adding/removing a field in a model works by updating the schema document and then running `amplify push`. Is that right?\n\nHow does one rename a model or a field? How would `amplify push` know to rename vs. drop the old and add the new?\n\nHow does one implement a migration that requires some business logic, e.g., to update the contents of existing rows? Doing this without Amplify has already been addressed but it is unclear whether that would conflict with something that `amplify push` might try to do.\n\n========================================\n\nTop Answer:\nHave you tried compiling the schema with this:\n\n```\namplify api gql-compile\n```\n\n========================================\n\nCode:\n```text\namplify push\n```\n\n```text\namplify push\n```\n\n```text\namplify push\n```\n\n```text\namplify push\n```\n\n```text\namplify push\n```\n\n```text\namplify api gql-compile\n```\n\n```text\namplify codegen models\n```\n\n```text\namplify push\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":66,"estimatedTokens":372}}417{"id":"stack-37331238","source":"stackoverflow","questionId":37331238,"title":"How to pass request body into GraphQL Context?","tags":["node.js","graphql","graphql-js"],"text":"Title: How to pass request body into GraphQL Context?\nTags: node.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm currently attempting to get the request body into context, because part of the body contains a JWT that needs to be decoded. However when I try the following I get undefined for context:\n\n```\napp.use('/', graphqlHTTP((req) => ({\n schema: Schema,\n context: req.body,\n pretty: true,\n graphiql: false\n })));\n```\n\nI logged out req and I didn't see body in there. I'm using a library called react-reach, it adds the following to the body on the request:\n\n```\n{\n query: {...},\n queryParams: {...},\n options: {\n token: '...' // I know the body is being interpreted because my queries/mutations that are in the body are being interpreted and executed. Just can't seem to find it when passed to context.\n\n========================================\n\nCode:\n```js\napp.use('/', graphqlHTTP((req) => ({\n schema: Schema,\n context: req.body,\n pretty: true,\n graphiql: false\n })));\n```\n\n```js\n{\n query: {...},\n queryParams: {...},\n options: {\n token: '...' // <-- I'm passing the token into options\n }\n }\n```\n\n```text\nreq.body\n```\n\n```text\nundefined\n```\n\n```text\ngraphqlHTTP\n```\n\n```text\nreq.body\n```\n\n========================================\n\nComments:\n- I feel like it's much easier if you put the token in a header, then you can do it like this: docs.apollostack.com/apollo-server/tools.html#auth-tokens (Apollo Server is just a thin wrapper around Express-GraphQL)\n- Ill try that out, @stubailo\n- That worked @stubailo","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":69,"estimatedTokens":396}}418{"id":"stack-67657738","source":"stackoverflow","questionId":67657738,"title":"Error in function createFiberFromTypeAndProps in ./node_modules/react-dom/cjs/react-dom.development.js:25058","tags":["javascript","reactjs","graphql","gatsby"],"text":"Title: Error in function createFiberFromTypeAndProps in ./node_modules/react-dom/cjs/react-dom.development.js:25058\nTags: javascript, reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI am learning to create a gatsby blog website with a YouTube tutorial. I have followed the exact steps as shown in the tutorials. There were errors that were related to graphql query format. which were solved.\n\nI have searched for the error. But all the answers were related to react app. There was no answers related to gatsby. So I was unable to figure out the right way to solve it.\n\nThe page loads at local server port 8000. The error comes while clicking the `Read more` button to see the single post. The error seems to be of React.\n\nElement type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of `singlePost`.\n\nHere is the codesandbox link: https://codesandbox.io/s/gatsby-starter-hello-world-m685p\n\nsinglePost.js\n\n```\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\nimport { MDXRenderer } from \"gatsby-plugin-mdx\"\nimport { H1 } from \"../elements\"\nimport { Container, Post, FeatureImage, Seo } from \"../components\"\n\nconst singlePost = ({ data }) => {\n const featureImage = data.mdx.frontmatter.featureImage.childImageSharp.fixed\n\n const seoImage = data.mdx.frontmatter.featureImage.publicURL\n\n return (\n \n \n \n \n \n\n### {data.mdx.frontmatter.title}\n\n {data.mdx.body}\n \n \n )\n}\n\nexport default singlePost\n\nexport const pageQuery = graphql`\n query SinglePostQuery($id: String!) {\n mdx(id: { eq: $id }) {\n body\n frontmatter {\n date\n excerpt\n slug\n title\n featureImage {\n childImageSharp {\n fixed {\n ...GatsbyImageSharpFixed\n }\n }\n }\n }\n }\n }\n`\n```\n\n========================================\n\nCode:\n```text\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\nimport { MDXRenderer } from \"gatsby-plugin-mdx\"\nimport { H1 } from \"../elements\"\nimport { Container, Post, FeatureImage, Seo } from \"../components\"\n\nconst singlePost = ({ data }) => {\n const featureImage = data.mdx.frontmatter.featureImage.childImageSharp.fixed\n\n const seoImage = data.mdx.frontmatter.featureImage.publicURL\n\n return (\n <Container>\n <Seo\n title={data.mdx.frontmatter.title}\n image={seoImage}\n description={data.mdx.frontmatter.excerpt}\n />\n <FeatureImage fixed={featureImage} />\n <Post>\n <H1 margin=\"0 0 2rem 0\">{data.mdx.frontmatter.title}</H1>\n <MDXRenderer>{data.mdx.body}</MDXRenderer>\n </Post>\n </Container>\n )\n}\n\nexport default singlePost\n\nexport const pageQuery = graphql`\n query SinglePostQuery($id: String!) {\n mdx(id: { eq: $id }) {\n body\n frontmatter {\n date\n excerpt\n slug\n title\n featureImage {\n childImageSharp {\n fixed {\n ...GatsbyImageSharpFixed\n }\n }\n }\n }\n }\n }\n`\n```\n\n```text\nRead more\n```\n\n```text\nsinglePost\n```\n\n```text\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\nimport { MDXRenderer } from \"gatsby-plugin-mdx\"\nimport { H1 } from \"../elements\"\nimport { Container, Post, FeatureImage, Seo } from \"../components\"\n\nconst SinglePost = ({ data }) => {\n const featureImage = data.mdx.frontmatter.featureImage.childImageSharp.fixed\n\n const seoImage = data.mdx.frontmatter.featureImage.publicURL\n\n return (\n <Container>\n <Seo\n title={data.mdx.frontmatter.title}\n image={seoImage}\n description={data.mdx.frontmatter.excerpt}\n />\n <FeatureImage fixed={featureImage} />\n <Post>\n <H1 margin=\"0 0 2rem 0\">{data.mdx.frontmatter.title}</H1>\n <MDXRenderer>{data.mdx.body}</MDXRenderer>\n </Post>\n </Container>\n )\n}\n\nexport default singlePost\n\nexport const pageQuery = graphql`\n query SinglePostQuery($id: String!) {\n mdx(id: { eq: $id }) {\n body\n frontmatter {\n date\n excerpt\n slug\n title\n featureImage {\n childImageSharp {\n fixed {\n ...GatsbyImageSharpFixed\n }\n }\n }\n }\n }\n }\n`\n```\n\n```text\nimport DefaultComponent from '../path/to/default/component'\n```\n\n```text\nimport { NonDefaultComponent} from '../path/to/non-default/component'\n```\n\n```text\nSinglePost\n```\n\n```text\nsinglePost\n```\n\n```text\n<div>\n```\n\n```text\n<span>\n```\n\n========================================\n\nComments:\n- Thanks for the explanation. I did try to capitalize the component but did not work. But it did help me to reanalyze the components in this file. And the problem was I had misspelled the component name in the component file. Now, it is resolved.","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":211,"estimatedTokens":1209}}419{"id":"stack-47056844","source":"stackoverflow","questionId":47056844,"title":"Emit deprecation warnings with Apollo client","tags":["graphql","apollo","apollo-client"],"text":"Title: Emit deprecation warnings with Apollo client\nTags: graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\n### Background\n\nWe are working on a fairly large Apollo project. A very simplified version of our api looks like this:\n\n```\ntype Operation {\n foo: String\n activity: Activity\n}\n\ntype Activity {\n bar: String\n # Lots of fields here ...\n}\n```\n\nWe've realised splitting `Operation` and `Activity` does no benefit and adds complexity. We'd like to merge them. But there's a lot of queries that assume this structure in the code base. In order to make the transition gradual we add `@deprecated` directives:\n\n```\ntype Operation {\n foo: String\n bar: String\n activity: Activity @deprecated\n}\n\ntype Activity {\n bar: String @deprecated(reason: \"Use Operation.bar instead\")\n # Lots of fields here ...\n}\n```\n\n### Actual question\n\nIs there some way to highlight those deprecations going forward? Preferably by printing a warning in the browser console when (in the test environment) running a query that uses a deprecated field?\n\n========================================\n\nCode:\n```apollo\ntype Operation {\n foo: String\n activity: Activity\n}\n\ntype Activity {\n bar: String\n # Lots of fields here ...\n}\n```\n\n```apollo\ntype Operation {\n foo: String\n bar: String\n activity: Activity @deprecated\n}\n\ntype Activity {\n bar: String @deprecated(reason: \"Use Operation.bar instead\")\n # Lots of fields here ...\n}\n```\n\n```text\nOperation\n```\n\n```text\nActivity\n```\n\n```text\n@deprecated\n```\n\n```js\nimport { SchemaDirectiveVisitor } from \"graphql-tools\"\nimport { defaultFieldResolver } from \"graphql\"\nimport { ApolloServer } from \"apollo-server\"\n\n\nclass DeprecatedDirective extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field ) {\n field.isDeprecated = true\n field.deprecationReason = this.args.reason\n\n const { resolve = defaultFieldResolver, } = field\n field.resolve = async function (...args) {\n const [_,__,___,info,] = args\n const { operation, } = info\n const queryName = operation.name.value\n // eslint-disable-next-line no-console\n console.warn(\n `Deprecation Warning:\n Query [${queryName}] used field [${field.name}]\n Deprecation reason: [${field.deprecationReason}]`)\n return resolve.apply(this, args)\n }\n }\n\n public visitEnumValue(value) {\n value.isDeprecated = true\n value.deprecationReason = this.args.reason\n }\n}\n\nnew ApolloServer({\n typeDefs,\n resolvers,\n schemaDirectives: {\n deprecated: DeprecatedDirective,\n },\n}).listen().then(({ url, }) => {\n console.log(`π Server ready at ${url}`)\n})\n```\n\n========================================\n\nComments:\n- I'm thinking that it can be done in a apollo-client middleware?\n- I'm also interested in some kind of implementation or tool that does this :)\n- @Striped Added solution below.\n- Someone built a plugin","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":129,"estimatedTokens":720}}420{"id":"stack-47655399","source":"stackoverflow","questionId":47655399,"title":"React, Apollo 2, GraphQL, Authentication. How to re-render component after login","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: React, Apollo 2, GraphQL, Authentication. How to re-render component after login\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have this code: https://codesandbox.io/s/507w9qxrrl\n\nI don't understand:\n\n1) **How to re-render() `Menu`** component after:\n\n```\nthis.props.client.query({\n query: CURRENT_USER_QUERY,\n fetchPolicy: \"network-only\"\n});\n```\n\nIf I login() I expect my `Menu` component to re-render() itself. But nothing.\nOnly if I click on the Home link it re-render() itself. I suspect because I'm using this to render it:\n\n```\n\n```\n\nfor embrace it in react-router props. Is it wrong?\n\nPlus, if inspect `this.props` of Menu after `login()` I see `loading: true` forever. Why?\n\n2) **How to prevent `Menu` component to query if not authenticated** (eg: there isn't a token in localStorage); I'm using in `Menu` component this code:\n\n```\nexport default graphql(CURRENT_USER_QUERY)(Menu);\n```\n\n3) **Is this the right way to go?**\n\n========================================\n\nTop Answer:\n**EDITED**\n\n**1)** I just created new link https://codesandbox.io/s/0y3jl8znw\n\nYou want to fetch the user data in the `componentWillReceiveProps` method:\n\n```\ncomponentWillReceiveProps() {\n this.props.client.query({query: CURRENT_USER_QUERY})\n .then((response) => {\n this.setState({ currentUser: response.data.currentUser})\n })\n .catch((e) => {\n console.log('there was an error ', e)\n })\n }\n```\n\nThis will make the component re-render.\n\n**2)** Now when we moved the query call in the component's lifecycle method we have full control over it. If you want to call the query only if you have something in localstorage you just need to wrap the query in a simple condition:\n\n```\ncomponentWillReceiveProps() {\n if(localstora.getItem('auth_token')) {\n this.props.client.query({query: CURRENT_USER_QUERY})\n .then((response) => {\n this.setState({ currentUser: response.data.currentUser})\n })\n .catch((e) => {\n console.log('there was an error ', e)\n })\n }\n }\n```\n\n**3)** You want to store the global application state in redux store. Otherwise you will have to fetch the user info every time you need to work with it. I would recommend to define a `state` in you `App` component and store all the global values there.\n\n========================================\n\nCode:\n```text\nthis.props.client.query({\n query: CURRENT_USER_QUERY,\n fetchPolicy: \"network-only\"\n});\n```\n\n```text\n<Route component={Menu} />\n```\n\n```text\nexport default graphql(CURRENT_USER_QUERY)(Menu);\n```\n\n```text\nMenu\n```\n\n```text\nMenu\n```\n\n```text\nthis.props\n```\n\n```text\nlogin()\n```\n\n```text\nloading: true\n```\n\n```text\nMenu\n```\n\n```text\nMenu\n```\n\n```text\nexport default graphql(CURRENT_USER_QUERY, {\n skip: () => !localStorage.get(\"auth_token\"),\n})(Menu);\n```\n\n```text\nthis.forceUpdate()\n```\n\n```text\n<Login onLogin={() => this.forceUpdate() } />\n```\n\n```text\ncomponentWillReceiveProps() {\n this.props.client.query({query: CURRENT_USER_QUERY})\n .then((response) => {\n this.setState({ currentUser: response.data.currentUser})\n })\n .catch((e) => {\n console.log('there was an error ', e)\n })\n }\n```\n\n```text\ncomponentWillReceiveProps() {\n if(localstora.getItem('auth_token')) {\n this.props.client.query({query: CURRENT_USER_QUERY})\n .then((response) => {\n this.setState({ currentUser: response.data.currentUser})\n })\n .catch((e) => {\n console.log('there was an error ', e)\n })\n }\n }\n```\n\n```text\ncomponentWillReceiveProps\n```\n\n```text\nstate\n```\n\n```text\nApp\n```\n\n========================================\n\nComments:\n- `` I didn't seem to find this line of code.?\n- Is commented because I'm trying to use it without.\n- @Dane, if I remove that line and use just `` it doesn't re-render at all.\n- I reset the code as in question.\n- About **(2)**, you can easily skip queries as explained here: apollographql.com/docs/react/basics/queries.html#graphql-ski‌​p\n- You think there is no way to work without App state? I don't believe I can't use the power of Apollo!\n- Also I read online that many people are turning off Redux with Apollo 2. But I don't understand how! This problem is a basic one. Doesn't it?\n- Redux is basically a \"global\" app's state. It is perfectly fine to save user information in `App` component. Why would you call API every time you need to work with user information? :) It is perfectly fine to store information that is not sensitive in your components.\n- I would love to show you power of redux but I need to get back to work. :D\n- Thanks @Michal, but there is still a problem: if in my Menu I need `currentUser` information I think I should go with something like this: `export default graphql(CURRENT_USER_QUERY)(Menu);` and also if I use Redux like you said it on first render throw \"Unauthorized\" because of no token present.\n- You don't need to refetch the user data because you already fetched it when user logged in. However if you need to fetch additional user data you have two options 1) create nested component in your menu component that will be wrapped in the `graphql` HOC component and you will render that component only if user is logged in. 2) You can use `branch` from recompose but that is a little bit advanced: medium.com/@tkh44/…\n- The short answer to that is you don't want to fetch the query because you don't need to. :)\n- You can also use `apolloClient.query` insted of the `graphql HOC` and fetch the query only when you want to but as I said above you don't need to make the app more complicated for no reason. :)\n- Ok @Michal, but I need to refetch when I refresh the page with my token in localStorage, no? I was talking about this case. Anyway, how to use `apolloClient.query`? I need to use `withApollo()`, right?\n- Anyway I FOUND THE PROBLEM IN MY CODE! `this.props.client.query({` ---> `await this.props.client.query({` and IT WORKS! So I think this is the problem of no re-rendering(). Maybe the following code is blocking the fetch: `this.props.history.push(`/`);`.\n- Ha ha nice. You are right. I just edited the answer. The only thing I changed is the `Menu` component. When you click on login it will take a couple of milliseconds before the menu re-renders because it takes a while before you get response from the server after logging in. Ideally you should wait for server to respond and then redirect user to homepage.\n- I just updated the `_confirm` method. Now the app works properly. (it shows loader, it redirects user when the call to API is finished)\n- Thanks @Michal but we are not good: 1) I receive this in console: `Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op. Please check the code for the Login component.`. 2) I think we don't need Redux. We can just work with Apollo Cache. Because everything is already there. You talk about \"refetch\", but it doesn't. I fetch just one time my currentUser info. Then I store that info in my Apollo Cache and with re-render the components know them. I just need an how-to!\n- And then if you reload the page nothing happens! Also with token in localStorage.\n- You don't use the token anywhere after you set it. Maybe like this? :) codesandbox.io/s/0y3jl8znw\n- Maybe one of the problems is this one? stackoverflow.com/questions/47733633/…\n- And this error after login: `Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.` ???\n- I was calling the set state after react router unmounted the component. I fixed couple of other small things this should look a lot better now :) codesandbox.io/s/0y3jl8znw\n- It's a lot better, but maybe instaed of check the component state `currentUser` I can use the power of Apollo and try with something like: `client.query({query: CURRENT_USER_QUERY})` because if are in cache I see that data, if not it make a network request and I can also handle the error \"unauthorized\" if I don't want check also the localStorage token. I need this also for example if I need the currentUser info in other components. I don't like the component state for this. Maybe the App one (or maybe Redux), but what I wanna say to you is that I already have the Apollo Cache with data!!!!\n- You are making things too complicated for no reason. What exactly happens when you call graphql query? Cache first? Cache only? Network first? Just use the react state it is fine.\n- Sorry @Michal. Why to not use what Apollo just give us? It's cache is like a Redux one. Except for what I don't have in Backend. They are just developing this: github.com/apollographql/apollo-link-state infact. What I want now is to use just Apollo and React (no apollo-link-state) and my problem is that I need to reuse `currentUser` info across my entire App, I hate local component state. You r work is very good, just incomplete. But we have to make it AMAZING! Any idea?\n- I believe that I answered your question and provided more than enough source code. :) Maybe you can create another question where I can show you how to implement redux.\n- The `skip` option is amazing. In my example below I basically extracted the whole query so that I could control it in the component lifecycle methods.\n- Other than that I do not believe that forceUpdate is the solution that John is looking for. Redux is. Because you don't really want to use forceUpdate - although I used it in my example source code too because there was no other option.\n- I feel like Redux is a bit of an overkill here to save one property. We have a big Apollo app and we don't use Redux at all. Instead we use a bit of React state to save a few things (usually UI state) that are not in the server's state. Instead of Redux you could create a \"userIsLoggedIn\" state property on the App component. And then the question is if a forceUpdate is not more elegant since you won't have two sources of truth for the login. Redux does not really unify this since you want to keep login state through page reloads.\n- Yea I spent quite a lot of time on GitHub helping this guy and even in one of my older examples I stored the userIsLoggedIn flag in App component. The problem with that is that you would either want to use `context` or you would potentially have to pass the `userIsLoggedIn` flag to every component that needs to know if the user is logged in manually. You can prevent yourself from this headache by using redux.\n- Redux is basically is a fancy state manager. Not using it saves you a couple of `kbs` because you don't have one more dependency but using it makes your project a lot more extendable. Apollo takes care of server-side application state. Redux is here because of client-side application state. These are two different things.","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":211,"estimatedTokens":2714}}421{"id":"stack-62423228","source":"stackoverflow","questionId":62423228,"title":"Mapping GraphQL query to Select() linq to sql","tags":["c#",".net-core","linq-to-sql","graphql","azure-cosmosdb"],"text":"Title: Mapping GraphQL query to Select() linq to sql\nTags: c#, .net-core, linq-to-sql, graphql, azure-cosmosdb\nSource: Stack Overflow\n\nQuestion:\nI am building an Web API with .NET core using `GraphQL` and `DocumentDb`.\n\nIn theory, `GraphQL` is optimized the data is shipped across the network and thus avoid over-fetching data. But I recognize that the backend server and database is doing the extra unnecessary work (query the entire document) when querying the database.\n\nThe best strategy here is using `Select()` to specific properties we need to fetch. But I have no idea how to build the expression from client's query that so complex.\n\nAny help really appreciated.\n\nThanks\n\n========================================\n\nTop Answer:\nFor a SQL expression if we want to query for jedis and we want the columns name and side, we can use the script as below:\n\n```\nSELECT name, side\nFROM jedis;\n```\n\nLet's update the code with our query like so:\n\n```\nvar json = schema.Execute(_ =>\n{\n _.Query = \"{ jedis { name, side } }\";\n});\n\nConsole.WriteLine(json);\n```\n\nand the result is:\nhttps://i.sstatic.net/Egr2G.png\n\nFor more details, you could refer to this article and this one.\n\n========================================\n\nCode:\n```text\nGraphQL\n```\n\n```text\nDocumentDb\n```\n\n```text\nGraphQL\n```\n\n```text\nSelect()\n```\n\n```cs\nInstall-Package SmartGraphQLClient\n```\n\n```cs\nservices.AddSmartGraphQLClient();\n```\n\n```cs\nusing SmartGraphQLClient;\n\nGraphQLHttpClient client = ... // from DI\n\nvar users = await client.Query<UserModel>(\"users\")\n .Include(x => x.Roles)\n .ThenInclude(x => x.Users)\n .Where(x => x.UserName.StartsWith(\"A\") || x.Roles.Any(r => r.Code == RoleCode.ADMINISTRATOR))\n .Select(x => new \n {\n x.Id,\n Name = x.UserName,\n x.Roles,\n IsAdministrator = x.Roles.Any(r => r.Code == RoleCode.ADMINISTRATOR)\n })\n .Skip(5)\n .Take(10)\n .Argument(\"secretKey\", \"1234\")\n .ToListAsync();\n```\n\n```text\n{ \n users (\n where: {\n or: [ \n { userName: { startsWith: \"A\" } }\n { roles: { some: { code: { eq: ADMINISTRATOR } } } }\n ]\n }\n skip: 5\n take: 10\n secretKey: \"1234\"\n ) {\n id\n userName\n roles {\n code\n name\n description\n id\n users {\n userName\n age\n id\n }\n }\n }\n}\n```\n\n```text\nSELECT name, side\nFROM jedis;\n```\n\n```text\nvar json = schema.Execute(_ =>\n{\n _.Query = \"{ jedis { name, side } }\";\n});\n\nConsole.WriteLine(json);\n```\n\n========================================\n\nComments:\n- invisible queries are simple, they returns null or errors\n- Thank you for reply, but seem like it's not solve for the question I am asking\n- As the link you provided, Graphql-to-SQL engine uses open-source `NReco.Data`. This library can be used with existing ADO.NET providers like azure sql which is contains cosmosdb.\n- Thanks for your recommend, but I am using cosmos db, and seems like it haven't yet support :)\n- ref: nrecosite.com/graphql_to_sql_database.aspx#faq2\n- as far as I know, add adapter to connect to cosmo db it's not big deal. anyway, I's recommend to ping support if it's still actual","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":143,"estimatedTokens":808}}422{"id":"stack-58337364","source":"stackoverflow","questionId":58337364,"title":"How to get the name of a query from a `gql` object?","tags":["graphql","apollo","graphql-tag"],"text":"Title: How to get the name of a query from a `gql` object?\nTags: graphql, apollo, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nI use `gql` from graphql-tag.\nLet's say I have a `gql` object defined like this:\n\n```\nconst QUERY_ACCOUNT_INFO = gql`\n query AccountInfo {\n viewer {\n lastname\n firstname\n email\n phone\n id\n }\n }\n`\n```\n\nThere must be a way to get `AccountInfo` from it. How can I do it?\n\n========================================\n\nTop Answer:\nWhat's returned by `gql` is a DocumentNode object. A GraphQL document could include multiple definitions, but assuming it only has the one and it's an operation, you can just do:\n\n```\nconst operation = doc.definitions[0]\nconst operationName = operation && operation.name\n```\n\nIf we allow there may be fragments, we probably want to do:\n\n```\nconst operation = doc.definitions.find((def) => def.kind === 'OperationDefinition')\nconst operationName = operation && operation.name\n```\n\nKeep in mind it's technically possible for multiple operations to exist in the same document, but if you're running this client-side against your own code that fact may be irrelevant.\n\nThe core library also provides a utility function:\n\n```\nconst { getOperationAST } = require('graphql')\nconst operation = getOperationAST(doc)\nconst operationName = operation && operation.name\n```\n\n========================================\n\nCode:\n```text\nconst QUERY_ACCOUNT_INFO = gql`\n query AccountInfo {\n viewer {\n lastname\n firstname\n email\n phone\n id\n }\n }\n`\n```\n\n```text\ngql\n```\n\n```text\ngql\n```\n\n```text\nAccountInfo\n```\n\n```text\nimport { getOperationName } from \"@apollo/client/utilities\";\n\nexport const AdminListItemsDocument = gql`\n query AdminListItems(\n $first: Int\n $after: String\n $before: String\n $last: Int\n ) {\n items(\n first: $first\n after: $after\n before: $before\n last: $last\n ) {\n nodes {\n id\n name\n }\n totalCount\n pageInfo {\n hasPreviousPage\n hasNextPage\n startCursor\n endCursor\n }\n }\n }\n`;\n\ngetOperationName(AdminListBlockLanguagesDocument); // => \"AdminListItems\"\n```\n\n```text\ngetOperationName\n```\n\n```text\nconst operation = doc.definitions[0]\nconst operationName = operation && operation.name\n```\n\n```text\nconst operation = doc.definitions.find((def) => def.kind === 'OperationDefinition')\nconst operationName = operation && operation.name\n```\n\n```text\nconst { getOperationAST } = require('graphql')\nconst operation = getOperationAST(doc)\nconst operationName = operation && operation.name\n```\n\n```text\ngql\n```\n\n========================================\n\nComments:\n- If I use getOperationAST I get the typescript error: Expected 2 arguments but got 1.\n- If I use the operation = doc.definition[0] ... way then I get typescript error Property 'name' does not exist on type 'DefinitionNode'\n- Side question: how to do the same with a fragment? The question is different but googling led me here\n- If I have `x = gql' query MyFakeName ($var: var) { realName (var: $var) { someField } } '`, then I get `x.definitions[0].name.value = MyFakeName`. How do I get `realName` ?\n- @Juan Perez `x.definitions[0].selectionSet.selections[0].name.value` -> `realName`\n- How can I get `items` from above query?","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":147,"estimatedTokens":819}}423{"id":"stack-41852880","source":"stackoverflow","questionId":41852880,"title":"How to handle Errors with the Apollo stack","tags":["graphql","apollo","apollostack","apollo-server","apollo-client"],"text":"Title: How to handle Errors with the Apollo stack\nTags: graphql, apollo, apollostack, apollo-server, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm using the Apollo Stack with `graphql-server-express` and `apollo-client`.\n\nBecause my backend is not perfect errors can appear and therefore I have to respond to a request with an error for that path.\n\nTill now my main problem was authentication and therefore I responded with an error.\n\n```\nreturn new Error(`${data.status}: ${data.statusText} @ ${data.url}`)\n```\n\nIn the frontend I use apollo-client to query data.\n\n```\nreturn apollo\n .query({query: gql`\n query {\n ${query}\n }`,\n forceFetch: forceFetch\n })\n .then(result => { debugger; return result.data })\n .catch(error => { debugger; console.error(error); });\n```\n\nBut if one property of the query responds with an error, only the catch function will be invoked.\nEven the data of the remaining properties is transferred, I see this in the network tab of the Chrome Dev Tools. In is not error object in the catch function.\n\nMy attempt works fine with GraphiQL where I get the errors and data in the same object.\n\nSo how can I throw errors for a property without loosing the whole request?\n\n========================================\n\nCode:\n```text\nreturn new Error(`${data.status}: ${data.statusText} @ ${data.url}`)\n```\n\n```text\nreturn apollo\n .query({query: gql`\n query {\n ${query}\n }`,\n forceFetch: forceFetch\n })\n .then(result => { debugger; return result.data })\n .catch(error => { debugger; console.error(error); });\n```\n\n```text\ngraphql-server-express\n```\n\n```text\napollo-client\n```\n\n```text\nformatError: (error) => {\n return {\n name: error.name,\n mensaje: error.message\n }\n}\n```\n\n```text\nresult.error\n```\n\n```text\nthen\n```\n\n```text\ncatch\n```\n\n```text\nthen\n```\n\n```text\ncatch\n```\n\n```text\nError\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":95,"estimatedTokens":474}}424{"id":"stack-59617266","source":"stackoverflow","questionId":59617266,"title":"can i use graphql in react without using Apollo?","tags":["reactjs","graphql","apollo-client"],"text":"Title: can i use graphql in react without using Apollo?\nTags: reactjs, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am trying to use the GraphQl with React.\nIt is suggested to use the Apollo client for React to implement GraphQL in the application.\nBut I don't want to use it in the first place.\n\nCan I use GraphQL in React without using the Apollo client?\n\n========================================\n\nTop Answer:\nYes, because GraphQL is a spec rather than just one company's implementation (no matter how good many consider that implementation to be). At its core, GraphQL is just a query format and structured response. Even a network call is not strictly needed.\n\nYou could skip Apollo in the browser too, and just invoke a plain web request. You can easily make an AJAX call with XMLHttpRequest or Fetch API to perform the GraphQL query. The easiest way I can think of to work this out is to install GraphiQL or Playground somewhere, open up your browser's developer tools, and execute a query. The Network tab of most browser's developer tools will show you all of the request headers and URL parameters you would need.\n\nThe Apollo client just does a lot of that work for you and has a very healthy ecosystem to add caching, federation, etc., but there is nothing stopping you from skipping that library and making the HTTP calls yourself with no middlemen.\n\n========================================\n\nCode:\n```text\nfetch(<graphql_endpoint>, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ query: '{ posts { title } }' }),\n})\n.then(res => res.json())\n.then(res => console.log(res.data));\n```\n\n========================================\n\nComments:\n- What package we need for that kind of support as in example?Thanks.\n- `fetch` is inbuilt in JavaScript. You can directly use it.\n- GraphQL is transport-agnostic. It is not specific to HTTP. A GraphQL service could execute documents without a network call at all.","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":39,"estimatedTokens":494}}425{"id":"stack-69451691","source":"stackoverflow","questionId":69451691,"title":"There was no argument with the name `...` found on the field `...`","tags":["c#","asp.net-core","graphql","hotchocolate"],"text":"Title: There was no argument with the name `...` found on the field `...`\nTags: c#, asp.net-core, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI'm using HotChocolate 12.0.1. I have following type definition:\n\n```\npublic class MyType : ObjectType\n {\n protected override void Configure(IObjectTypeDescriptor descriptor)\n {\n descriptor.Field(p => p.Name)\n .ResolveWith(r => r.Get(default))\n .Type();\n descriptor.Field(p => p.Logo)\n .Type();\n }\n\n private class TestResolver\n {\n public string Get(My my)\n {\n return my.Logo;\n }\n }\n }\n```\n\nI expect injection of My object in TestResolver Get(My my) after it is populated with Logo value, as I've seen in example:\nhttps://github.com/ChilliCream/graphql-workshop/blob/master/docs/3-understanding-dataLoader.md\n\nBut for some reason, I've got from HotChocolate parameter lookup:\n\n```\nThere was no argument with the name `my` found on the field `name`.\n```\n\nMy query:\n\n```\nquery {\n my(someId: 123) {\n name\n logo\n }\n }\n```\n\nStartup:\n\n```\nservices.AddGraphQLServer()\n .AddQueryType()\n .AddType()\n```\n\nWhere could be the problem?\n\n========================================\n\nCode:\n```text\npublic class MyType : ObjectType<My>\n {\n protected override void Configure(IObjectTypeDescriptor<My> descriptor)\n {\n descriptor.Field(p => p.Name)\n .ResolveWith<TestResolver>(r => r.Get(default))\n .Type<IdType>();\n descriptor.Field(p => p.Logo)\n .Type<StringType>();\n }\n\n private class TestResolver\n {\n public string Get(My my)\n {\n return my.Logo;\n }\n }\n }\n```\n\n```text\nThere was no argument with the name `my` found on the field `name`.\n```\n\n```text\nquery {\n my(someId: 123) {\n name\n logo\n }\n }\n```\n\n```text\nservices.AddGraphQLServer()\n .AddQueryType<QueryType>()\n .AddType<MyType>()\n```\n\n```cs\nprivate class TestResolver\n{\n public string Get([Parent] My my)\n {\n return my.Logo;\n }\n}\n```\n\n========================================\n\nComments:\n- I'm also facing this issue in this tutorial :/ I tried debugging, and it seems like the resolver is not being used\n- This was exactly what I needed. There are a few YouTube tutorials out there that are written on V11, and this simple solution fixed the problem. Thank you!\n- Yeah, I don't know why this would be buried deep into the documentation, lol","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":119,"estimatedTokens":616}}426{"id":"stack-65704023","source":"stackoverflow","questionId":65704023,"title":"Django GraphQL JWT: tokenAuth mutation returns \"str object has no attribute decode\"","tags":["django","graphql","graphene-django","django-graphql-jwt"],"text":"Title: Django GraphQL JWT: tokenAuth mutation returns \"str object has no attribute decode\"\nTags: django, graphql, graphene-django, django-graphql-jwt\nSource: Stack Overflow\n\nQuestion:\nCurrently I'm running a basic example of django-graphqljwt from the documentation page. https://django-graphql-jwt.domake.io/en/latest/quickstart.html\n\n```\nimport graphene\nimport graphql_jwt\n\nclass Mutation(graphene.ObjectType):\n token_auth = graphql_jwt.ObtainJSONWebToken.Field()\n verify_token = graphql_jwt.Verify.Field()\n refresh_token = graphql_jwt.Refresh.Field()\n\nschema = graphene.Schema(mutation=Mutation)\n```\n\nHowever if I run the `tokenAuth` mutation it throws me the below error in the `GraphiQL` interface. **Note** that if I enter incorrect credentials it throws an \"`Please enter valid credentials`\" instead of the below.\n\n```\n{\n \"errors\": [\n {\n \"message\": \"'str' object has no attribute 'decode'\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"tokenAuth\"\n ]\n }\n ],\n \"data\": {\n \"tokenAuth\": null\n }\n}\n```\n\n========================================\n\nTop Answer:\nI'm using the `django-graphql-jwt==0.2.1` without this problem. Apparently, the problem is related to the new version of `django-graphql-jwt` which is `0.3.0` by now. Or, as you mentioned, you could bound the `PyJWT` to `1.7.0`.\n\nThe solution is using these bounded packages in your `requirements.txt` file as follows:\n\n```\ndjango-graphql-jwt==0.3.0\nPyJWT==1.7.0\n```\n\nOr\n\n```\ndjango-graphql-jwt==0.2.1\n```\n\n========================================\n\nCode:\n```text\nimport graphene\nimport graphql_jwt\n\n\nclass Mutation(graphene.ObjectType):\n token_auth = graphql_jwt.ObtainJSONWebToken.Field()\n verify_token = graphql_jwt.Verify.Field()\n refresh_token = graphql_jwt.Refresh.Field()\n\n\nschema = graphene.Schema(mutation=Mutation)\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"'str' object has no attribute 'decode'\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"tokenAuth\"\n ]\n }\n ],\n \"data\": {\n \"tokenAuth\": null\n }\n}\n```\n\n```text\ntokenAuth\n```\n\n```text\nGraphiQL\n```\n\n```text\nPlease enter valid credentials\n```\n\n```text\ndjango-graphql-jwt\n```\n\n```text\n1.7.0\n```\n\n```text\nPyJWT\n```\n\n```text\n2.0\n```\n\n```text\ndjango-graphql-jwt==0.3.0\nPyJWT==1.7.0\n```\n\n```text\ndjango-graphql-jwt==0.2.1\n```\n\n```text\ndjango-graphql-jwt==0.2.1\n```\n\n```text\ndjango-graphql-jwt\n```\n\n```text\n0.3.0\n```\n\n```text\nPyJWT\n```\n\n```text\n1.7.0\n```\n\n```text\nrequirements.txt\n```\n\n```text\npip show PyJWT\n```\n\n```text\npip install --upgrade PyJWT==1.7.0\n```\n\n```text\nPyJWT==2.3.0\n```\n\n```text\ndjango-graphql-jwt\n```\n\n```text\nPyJWT==2.3.0\n```\n\n```text\nPyJWT==1.7.0\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.056Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":184,"estimatedTokens":677}}427{"id":"stack-60458080","source":"stackoverflow","questionId":60458080,"title":"Graphql mutation error: \"Field 'createUser' is missing required arguments: input\"","tags":["ruby-on-rails","graphql","graphiql"],"text":"Title: Graphql mutation error: \"Field 'createUser' is missing required arguments: input\"\nTags: ruby-on-rails, graphql, graphiql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to along this article on how to create a mutation on a rails server using GraphQl https://www.howtographql.com/graphql-ruby/4-authentication\n\nHowever, I'm stuck at the CreateUser Mutation step, I get the error hash when trying it out in GraphiQL:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Field 'createUser' is missing required arguments: input\",\n \"locations\": [\n {\n \"line\": 45,\n \"column\": 3\n }\n ],\n \"path\": [\n \"mutation CreateUser\",\n \"createUser\"\n ],\n \"extensions\": {\n \"code\": \"missingRequiredArguments\",\n \"className\": \"Field\",\n \"name\": \"createUser\",\n \"arguments\": \"input\"\n }\n },\n {\n \"message\": \"Field 'createUser' doesn't accept argument 'username'\",\n \"locations\": [\n {\n \"line\": 46,\n \"column\": 5\n }\n ],\n \"path\": [\n \"mutation CreateUser\",\n \"createUser\",\n \"username\"\n ],\n \"extensions\": {\n \"code\": \"argumentNotAccepted\",\n \"name\": \"createUser\",\n \"typeName\": \"Field\",\n \"argumentName\": \"username\"\n }\n },\n {\n \"message\": \"Field 'createUser' doesn't accept argument 'authProvider'\",\n \"locations\": [\n {\n \"line\": 47,\n \"column\": 5\n }\n ],\n \"path\": [\n \"mutation CreateUser\",\n \"createUser\",\n \"authProvider\"\n ],\n \"extensions\": {\n \"code\": \"argumentNotAccepted\",\n \"name\": \"createUser\",\n \"typeName\": \"Field\",\n \"argumentName\": \"authProvider\"\n }\n },\n {\n \"message\": \"Variable $username is declared by CreateUser but not used\",\n \"locations\": [\n {\n \"line\": 44,\n \"column\": 1\n }\n ],\n \"path\": [\n \"mutation CreateUser\"\n ],\n \"extensions\": {\n \"code\": \"variableNotUsed\",\n \"variableName\": \"username\"\n }\n },\n {\n \"message\": \"Variable $email is declared by CreateUser but not used\",\n \"locations\": [\n {\n \"line\": 44,\n \"column\": 1\n }\n ],\n \"path\": [\n \"mutation CreateUser\"\n ],\n \"extensions\": {\n \"code\": \"variableNotUsed\",\n \"variableName\": \"email\"\n }\n },\n {\n \"message\": \"Variable $password is declared by CreateUser but not used\",\n \"locations\": [\n {\n \"line\": 44,\n \"column\": 1\n }\n ],\n \"path\": [\n \"mutation CreateUser\"\n ],\n \"extensions\": {\n \"code\": \"variableNotUsed\",\n \"variableName\": \"password\"\n }\n }\n ]\n}\n```\n\nI just followed the code in the article, my files:\n\n**create_user.rb**\n\n```\nmodule Mutations\n class CreateUser **user_type.rb**\n\n```\nmodule Types\n class UserType I have no clue where this 'input' thing is coming from.\n\n========================================\n\nTop Answer:\nIf you're not interested in commenting out fields... I ran across the same error. For whatever reason `input` is the name of the key you pass your arguments into as a hash/object.\n\nExample from using this tutorial:https://www.howtographql.com/graphql-ruby/3-mutations/\n\n```\nmutation {\n createLink(input: {\n url: \"foo\",\n description:\"bar\"\n }) {\n url\n description\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n \"errors\": [\n {\n \"message\": \"Field 'createUser' is missing required arguments: input\",\n \"locations\": [\n {\n \"line\": 45,\n \"column\": 3\n }\n ],\n \"path\": [\n \"mutation CreateUser\",\n \"createUser\"\n ],\n \"extensions\": {\n \"code\": \"missingRequiredArguments\",\n \"className\": \"Field\",\n \"name\": \"createUser\",\n \"arguments\": \"input\"\n }\n },\n {\n \"message\": \"Field 'createUser' doesn't accept argument 'username'\",\n \"locations\": [\n {\n \"line\": 46,\n \"column\": 5\n }\n ],\n \"path\": [\n \"mutation CreateUser\",\n \"createUser\",\n \"username\"\n ],\n \"extensions\": {\n \"code\": \"argumentNotAccepted\",\n \"name\": \"createUser\",\n \"typeName\": \"Field\",\n \"argumentName\": \"username\"\n }\n },\n {\n \"message\": \"Field 'createUser' doesn't accept argument 'authProvider'\",\n \"locations\": [\n {\n \"line\": 47,\n \"column\": 5\n }\n ],\n \"path\": [\n \"mutation CreateUser\",\n \"createUser\",\n \"authProvider\"\n ],\n \"extensions\": {\n \"code\": \"argumentNotAccepted\",\n \"name\": \"createUser\",\n \"typeName\": \"Field\",\n \"argumentName\": \"authProvider\"\n }\n },\n {\n \"message\": \"Variable $username is declared by CreateUser but not used\",\n \"locations\": [\n {\n \"line\": 44,\n \"column\": 1\n }\n ],\n \"path\": [\n \"mutation CreateUser\"\n ],\n \"extensions\": {\n \"code\": \"variableNotUsed\",\n \"variableName\": \"username\"\n }\n },\n {\n \"message\": \"Variable $email is declared by CreateUser but not used\",\n \"locations\": [\n {\n \"line\": 44,\n \"column\": 1\n }\n ],\n \"path\": [\n \"mutation CreateUser\"\n ],\n \"extensions\": {\n \"code\": \"variableNotUsed\",\n \"variableName\": \"email\"\n }\n },\n {\n \"message\": \"Variable $password is declared by CreateUser but not used\",\n \"locations\": [\n {\n \"line\": 44,\n \"column\": 1\n }\n ],\n \"path\": [\n \"mutation CreateUser\"\n ],\n \"extensions\": {\n \"code\": \"variableNotUsed\",\n \"variableName\": \"password\"\n }\n }\n ]\n}\n```\n\n```text\nmodule Mutations\n class CreateUser < BaseMutation\n # often we will need input types for specific mutation\n # in those cases we can define those input types in the mutation class itself\n class AuthProviderSignupData < Types::BaseInputObject\n argument :credentials, Types::AuthProviderCredentialsInput, required: false\n end\n\n argument :username, String, required: true\n argument :auth_provider, AuthProviderSignupData, required: false\n\n type Types::UserType\n\n def resolve(username: nil, auth_provider: nil)\n User.create!(\n username: username,\n email: auth_provider&.[](:credentials)&.[](:email),\n password: auth_provider&.[](:credentials)&.[](:password)\n )\n end\n end\nend\n```\n\n```text\nmodule Types\n class UserType < BaseObject\n field :id, ID, null: false\n field :email, String, null: false\n field :username, String, null: false\n field :photo, String, null: true\n field :phone, String, null: false\n field :island, IslandType, null: false, method: :island\n field :archipel, ArchipelType, null: false, method: :archipel\n\n field :created_at, String, null: false\n field :updated_at, String, null: false\n end\nend\n```\n\n```text\n# Opt in to the new runtime (default in future graphql-ruby versions)\n # use GraphQL::Execution::Interpreter\n # use GraphQL::Analysis::AST\n\n # Add built-in connections for pagination\n # use GraphQL::Pagination::Connections\n```\n\n```text\n# class BaseMutation < GraphQL::Schema::RelayClassicMutation\n # argument_class Types::BaseArgument\n # field_class Types::BaseField\n # input_object_class Types::BaseInputObject\n # object_class Types::BaseObject\n # end\n\n class BaseMutation < GraphQL::Schema::Mutation\n null false\n end\n```\n\n```text\nmutation {\n createLink(input: {\n url: \"foo\",\n description:\"bar\"\n }) {\n url\n description\n }\n}\n```\n\n```text\ninput\n```\n\n```text\nmutation {\n createLink(\n url: \"foo\"\n ) \n ...\n}\n```\n\n```text\nmutation {\n createLink(\n input: { url: \"foo\" }\n )\n ...\n}\n```\n\n```text\ninput: { ... }\n```\n\n```text\nurl: \"foo\"\n```\n\n```text\ninput: { url: \"foo\" }\n```\n\n```text\nmodule Mutations\n class CreateUser < BaseMutation\n argument :first_name, String, required: true\n argument :last_name, String, required: true\n argument :email, String, required: true\n \n field :user, Types::UserType, null: false\n field :errors, [String], null: true\n \n def resolve(first_name:, last_name:, email:)\n user = User.new(first_name: first_name, last_name: last_name, email: email)\n if user.save\n { user: user} # see this line of code carefully \n else\n { user: nil, errors: user.errors.full_messages }\n end\n end\n end\n end\n```\n\n========================================\n\nComments:\n- github.com/rmosolgo/graphql-ruby/blob/… ?\n- The important thing here which I missed was changing the inherited class from `GraphQL::Schema::RelayClassicMutation` to `GraphQL::Schema::Mutation`\n- Nice, thanks for sharing. Just adding: BaseMutation is generated by \"rails g graphql:install\". I struggled after reading this answer because I did not remember that this file exists in my project!\n- a little confused by your answer here. It seems like `input` is not mentioned anywhere on that tutorial you linked\n- Yup, thatβs why I left this answer in the first place. Itβs been a while since I posted my answer. If youβre finding different results maybe something updated.","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":411,"estimatedTokens":2174}}428{"id":"stack-50414899","source":"stackoverflow","questionId":50414899,"title":"Node.js Sequelize UUID primary key + Postgres","tags":["node.js","postgresql","orm","sequelize.js","graphql"],"text":"Title: Node.js Sequelize UUID primary key + Postgres\nTags: node.js, postgresql, orm, sequelize.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI try to create database model by using sequelize but I'm facing a problem with model's primary key.\n\n### Setting\n\nI'm using Postgres (v10) in docker container and sequalize (Node.js v10.1.0\n) for models and GraphQL (0.13.2) + GraphQL-Sequalize (8.1.0) for request processing.\n\n### Problem\n\nAfter creating models by sequelize-cli I've **manually tried to replace id column with uuid**. Here's my model migration that I'm using.\n\n```\n'use strict';\nconst DataTypes = require('sequelize').DataTypes;\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('Currencies', {\n uuid: {\n primaryKey: true,\n type: Sequelize.UUID,\n defaultValue: DataTypes.UUIDV4,\n allowNull: false\n },\n name: {\n type: Sequelize.STRING\n },\n ticker: {\n type: Sequelize.STRING\n },\n alt_tickers: {\n type: Sequelize.ARRAY(Sequelize.STRING)\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable('Currencies');\n }\n};\n```\n\nModel:\n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n const Currency = sequelize.define('Currency', {\n uuid: DataTypes.UUID,\n name: DataTypes.STRING,\n ticker: DataTypes.STRING,\n alt_tickers: DataTypes.ARRAY(DataTypes.STRING)\n }, {});\n Currency.associate = function(models) {\n // associations can be defined here\n };\n return Currency;\n};\n```\n\nDue to some problem sequalize executes next expression:\n\nExecuting (default): SELECT \"id\", \"uuid\", \"name\", \"ticker\", \"alt_tickers\", \"createdAt\", \"updatedAt\" FROM \"Currencies\" AS \"Currency\" ORDER BY \"Currency\".\"id\" ASC;\n\nThat leads to \"column 'id' doesn't exist\" error.\n\nAlternatively, I've tried to fix it by renaming *uuid* column to *id* at migration:\n\n```\n... \n id: {\n allowNull: false,\n primaryKey: true,\n type: Sequelize.UUID,\n defaultValue: Sequelize.UUIDV4()\n },\n ...\n```\n\nAnd at the model:\n\n```\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n const Currency = sequelize.define('Currency', {\n id: DataTypes.INTEGER,\n name: DataTypes.STRING,\n ticker: DataTypes.STRING,\n alt_tickers: DataTypes.ARRAY(DataTypes.STRING)\n }, {});\n Currency.associate = function(models) {\n // associations can be defined here\n };\n return Currency;\n};\n```\n\nbut the result was the following error at the start of the program:\n\nError: A column called 'id' was added to the attributes of 'Currencies' but not marked with 'primaryKey: true'\n\n### Questions\n\n- So, is there a way to force sequelize to use UUID as the tables primary key without defining id column?\n\n- Is there a way to create columns without id columns?\n\n- What possibly caused this errors and how should fix it?\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nThis is just about the only resource I've found online that explains what it takes to set up a UUID column that the *database* provides defaults for, without relying on the third-party `uuid` npm package: https://krmannix.com/2017/05/23/postgres-autogenerated-uuids-with-sequelize/\n\nShort version:\n\n- You'll need to install the \"uuid-ossp\" postgres extension, using a sqlz migration\n\n- When defining the table, use this `defaultValue`: `Sequelize.literal( 'uuid_generate_v4()' )`\n\n========================================\n\nCode:\n```text\n'use strict';\nconst DataTypes = require('sequelize').DataTypes;\n\nmodule.exports = {\n up: (queryInterface, Sequelize) => {\n return queryInterface.createTable('Currencies', {\n uuid: {\n primaryKey: true,\n type: Sequelize.UUID,\n defaultValue: DataTypes.UUIDV4,\n allowNull: false\n },\n name: {\n type: Sequelize.STRING\n },\n ticker: {\n type: Sequelize.STRING\n },\n alt_tickers: {\n type: Sequelize.ARRAY(Sequelize.STRING)\n },\n createdAt: {\n allowNull: false,\n type: Sequelize.DATE\n },\n updatedAt: {\n allowNull: false,\n type: Sequelize.DATE\n }\n });\n },\n down: (queryInterface, Sequelize) => {\n return queryInterface.dropTable('Currencies');\n }\n};\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n const Currency = sequelize.define('Currency', {\n uuid: DataTypes.UUID,\n name: DataTypes.STRING,\n ticker: DataTypes.STRING,\n alt_tickers: DataTypes.ARRAY(DataTypes.STRING)\n }, {});\n Currency.associate = function(models) {\n // associations can be defined here\n };\n return Currency;\n};\n```\n\n```text\n... \n id: {\n allowNull: false,\n primaryKey: true,\n type: Sequelize.UUID,\n defaultValue: Sequelize.UUIDV4()\n },\n ...\n```\n\n```text\n'use strict';\nmodule.exports = (sequelize, DataTypes) => {\n const Currency = sequelize.define('Currency', {\n id: DataTypes.INTEGER,\n name: DataTypes.STRING,\n ticker: DataTypes.STRING,\n alt_tickers: DataTypes.ARRAY(DataTypes.STRING)\n }, {});\n Currency.associate = function(models) {\n // associations can be defined here\n };\n return Currency;\n};\n```\n\n```text\nconst User = sequelize.define('user', {\n uuid: {\n type: Sequelize.UUID,\n defaultValue: Sequelize.UUIDV1,\n primaryKey: true\n },\n username: Sequelize.STRING,\n});\n\nsequelize.sync({ force: true })\n .then(() => User.create({\n username: 'test123'\n }).then((user) => {\n console.log(user);\n }));\n```\n\n```text\nmodel\n```\n\n```text\nid\n```\n\n```text\nuuid\n```\n\n```text\nid\n```\n\n```text\nuuid\n```\n\n```text\nuuid\n```\n\n```text\nuuid\n```\n\n```text\ndefaultValue\n```\n\n```text\nSequelize.literal( 'uuid_generate_v4()' )\n```\n\n========================================\n\nComments:\n- Actually, the model has been changed in the first place. I've also tried to rollback to Integer \"id\", but the primary key was not set in the database.\n- Sure. Take a look.\n- The model still shows `id` field? it should be `uuid`. You should also make it primary key `primaryKey: true`\n- I've provided two cases. First is the table with *uuid* as UUID data type and second with *id* as UUID data type, so two models are provided, one after another. If I understood you correct you want me to add a primary key to migration but that is already done.\n- Model and DB declaration of primary key should happen independently and recommended. So if you are solving `Error: A column called 'id' was added to the attributes of 'Currencies', you should make it primary key in the model as well as in the db as the query is generated by the Sequelize\n- Ok, now I get it. Thanks a lot.","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":281,"estimatedTokens":1667}}429{"id":"stack-63625892","source":"stackoverflow","questionId":63625892,"title":"Variable \"$userId\" of type \"ID\" used in position expecting type \"ID!\"","tags":["typescript","graphql","template-strings"],"text":"Title: Variable \"$userId\" of type \"ID\" used in position expecting type \"ID!\"\nTags: typescript, graphql, template-strings\nSource: Stack Overflow\n\nQuestion:\nI am trying to make a graphql request using the npm package `graphql-request`. I am discovering the use of template literals.\n\n```\nasync getCandidate(userId: number) {\n const query = gql`\n query($userId: ID){\n candidate(id: $userId){\n id _id source phone\n }\n }\n `\n const variables = {userId: \"/api/candidates/\" + userId}\n return await request(GRAPHQL_URL, query, variables)\n }\n```\n\nI am trying to use the `usedId` variable but I am having the error :\n\n```\nVariable \"$userId\" of type \"ID\" used in position expecting type \"ID!\".: {\"response\":{\"errors\":[{\"message\":\"Variable \\\"$userId\\\" of type \\\"ID\\\" used in position expecting type \\\"ID!\\\".\",\"extensions\":{\"category\":\"graphql\"},\"locations\":[{\"line\":2,\"column\":9},{\"line\":3,\"column\":19}]}],\"status\":200},\"request\":{\"query\":\"\\n\\t\\tquery($userId: ID){\\n\\t\\t candidate(id: $userId){\\n\\t\\t id _id source phone\\n\\t\\t }\\n\\t\\t}\\n\\t\\t\",\"variables\":{\"userId\":\"/api/candidates/1\"}\n```\n\n========================================\n\nCode:\n```text\nasync getCandidate(userId: number) {\n const query = gql`\n query($userId: ID){\n candidate(id: $userId){\n id _id source phone\n }\n }\n `\n const variables = {userId: \"/api/candidates/\" + userId}\n return await request(GRAPHQL_URL, query, variables)\n }\n```\n\n```text\nVariable \"$userId\" of type \"ID\" used in position expecting type \"ID!\".: {\"response\":{\"errors\":[{\"message\":\"Variable \\\"$userId\\\" of type \\\"ID\\\" used in position expecting type \\\"ID!\\\".\",\"extensions\":{\"category\":\"graphql\"},\"locations\":[{\"line\":2,\"column\":9},{\"line\":3,\"column\":19}]}],\"status\":200},\"request\":{\"query\":\"\\n\\t\\tquery($userId: ID){\\n\\t\\t candidate(id: $userId){\\n\\t\\t id _id source phone\\n\\t\\t }\\n\\t\\t}\\n\\t\\t\",\"variables\":{\"userId\":\"/api/candidates/1\"}\n```\n\n```text\ngraphql-request\n```\n\n```text\nusedId\n```\n\n```text\nquery($userId: ID){\n```\n\n```text\nquery($userId: ID!){\n```\n\n```text\nuserId\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":67,"estimatedTokens":529}}430{"id":"stack-54372077","source":"stackoverflow","questionId":54372077,"title":"How to read request headers from incoming message in a graphQL endpoint in spring boot application","tags":["java","spring-boot","graphql"],"text":"Title: How to read request headers from incoming message in a graphQL endpoint in spring boot application\nTags: java, spring-boot, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a spring boot application running with a graphql endpoint that validates and executes queries and mutations, however, I need to read one header in the incoming message in order to pass its value to another endpoint. Is there a way in graphql to read these values? some sort of getHeaders or something like that?\n\n========================================\n\nTop Answer:\nThe solution by @Ken Chan was not working for me. `GraphQLContext` had no method named `getHttpServletRequest`. \n\nSolved it by using `GraphQLServletContext` instead. You can change the code to:\n\n```\npublic Foo resolveFoo(Map input , DataFetchingEnvironment env){\n\n GraphQLServletContext context = env.getContext();\n String header = context.getHttpServletRequest().getHeader(\"content-type\");\n}\n```\n\n========================================\n\nCode:\n```java\npublic Foo resolveFoo(Map<String,String> input , DataFetchingEnvironment env){\n\n GraphQLContext context = env.getContext();\n HttpServletRequest request = context.getHttpServletRequest().get();\n request.getHeader(\"content-type\");\n }\n```\n\n```text\ngraphql-java-tools\n```\n\n```text\nGraphQLContext\n```\n\n```text\nDataFetchingEnvironment\n```\n\n```text\nGraphQLContext\n```\n\n```text\nHttpServletRequest\n```\n\n```text\npublic Foo resolveFoo(Map<String,String> input , DataFetchingEnvironment env){\n\n GraphQLServletContext context = env.getContext();\n String header = context.getHttpServletRequest().getHeader(\"content-type\");\n}\n```\n\n```text\nGraphQLContext\n```\n\n```text\ngetHttpServletRequest\n```\n\n```text\nGraphQLServletContext\n```\n\n```java\nDefaultGlobalContext<ServletWebRequest> context = handlerParameters.getDataFetchingEnvironment().getContext();\n context.getNativeRequest().getHeader(\"something\");\n```\n\n```text\ngraphql.kickstart.servlet.context.DefaultGraphQLServletContext.DefaultGraphQLServletContext context = dataFetchingEnvironment.getContext();\n jakarta.servlet.http.HttpServletRequest request = context.getHttpServletRequest();\n String tokenBearer = request.getHeader(\"Authorization\");\n```\n\n```text\npublic class HeaderFilter implements Filter {\n\n@Override\npublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {\n final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;\n \n String headerVal= httpServletRequest.getHeader(\"<header string>\");\n \n try {\n filterChain.doFilter(httpServletRequest, servletResponse);\n } catch (IOException | ServletException e) {\n //handle as you wish\n }\n}\n```\n\n```text\n@Slf4j\n@Controller\npublic class YourQueryController {\n@Autowired\nprivate HttpServletRequest request;\n....\n```\n\n```text\nrequest.getHeader(\"Authorization\")\n```\n\n```text\nServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();\n\nval authorization = attributes.getRequest().getHeader(\"Authorization\");\n```\n\n```text\nRequestContextHolder\n```\n\n```kotlin\n/**\n * Interceptor that extracts headers from the request and adds them to the GraphQL context.\n * This allows you to access them in your GraphQL resolvers via '@ContextValue'.\n */\n@Component\nclass GraphQlRequestHeaderInterceptor(\n private val log: KLogger = KotlinLogging.logger {}\n) : WebGraphQlInterceptor {\n\n override fun intercept(request: WebGraphQlRequest, chain: Chain): Mono<WebGraphQlResponse> {\n val headers = getHeadersFromRequest(request)\n log.trace { \"Found ${headers.size} headers that will be added to the GQL-context: $headers\" }\n addHeadersToGraphQLContext(request, headers)\n return chain.next(request)\n }\n\n private fun getHeadersFromRequest(request: WebGraphQlRequest): Map<String, Any> {\n return request.headers.mapValues { it.value.first() }\n }\n\n private fun addHeadersToGraphQLContext(\n request: WebGraphQlRequest, customHeaders: Map<String, Any>\n ) = request.configureExecutionInput { _, builder ->\n builder.graphQLContext(customHeaders).build()\n }\n}\n```\n\n```kotlin\n@Controller\nclass AddTaskController(private val useCase: AddTaskUseCase) {\n\n private val log = KotlinLogging.logger {}\n\n @MutationMapping\n fun addTask(\n @Argument payload: TaskInput,\n @ContextValue(X_USER_ID) userId: String\n ): TaskDto {\n log.debug { \"Received graphql-request to add task: $payload\" }\n val command = payload.toAddTaskCommand(userId)\n val task = useCase.addTask(command)\n return TaskDto.from(task)\n }\n}\n```\n\n```text\n@ContextValue\n```\n\n========================================\n\nComments:\n- Depends on how do you expose GraphQL over HTTP . Do you expose it using servlet , spring mvc or other libraries ?\n- i'm using the spring boot graphql starter and graphql-java-tools maven dependency, I just had to implement the GraphQLMutationResolver class\n- Thank you very much! Worked perfectly, this was just what I needed to do\n- env.getContext() returns null for me. I am using it in DataFetcher. Can you please help?\n- @ArjunNayak how did you solve this...\n- @user1912935 I used below code final GraphQLServletContext ctx = env.getContext(); final HttpServletRequest request = ctx.getHttpServletRequest();\n- But as you mentioned in your earlier comment your getting null for env.getContext(), and HttpServletRequest request = ctx.getHttpServletRequest(); throws null pointer isn't it.... how did you solve null..?\n- How can we do this in a webflux model where we don't have access to the servlet methods? I'm having trouble applying these solutions.\n- If you use this method with an Autowired request then how do you test the controller in a unit test as if you test like this?: GraphQlTester.Response response = tester.document(Files.read(searchQuery, UTF_8).execute(); It will fall over as there is no autowired request in the controller.\n- This is the correct answer in 2025.","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":190,"estimatedTokens":1517}}431{"id":"stack-53983315","source":"stackoverflow","questionId":53983315,"title":"Is there a way to get rid of [Object: null prototype] in GraphQL","tags":["javascript","node.js","mongoose","graphql","apollo-server"],"text":"Title: Is there a way to get rid of [Object: null prototype] in GraphQL\nTags: javascript, node.js, mongoose, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make one-to-many relationship database with `Mongoose` and `GraphQL`.\n\nWhenever I insert the data to GraphQL mutation argument, I will get `[Object: null prototype]` error.\n\nI notice the object will have `[Object: null prototype]` in front of it when I tried to `console.log` for debug purpose.\n\nI have tried many ways, tried to `map()` args or even to use `replace()` but no luck. All I have been getting is `\"args.ingredient.map/replace is not a function\"`\n\nI have test hard coded method by changing the args for example:\n\n```\nargs.category = '5c28c79af62fad2514ccc788'\nargs.ingredient = '5c28c8deb99a9d263462a086'\n```\n\nSurprisingly it works with this method. I assume the input cannot be an object but just an ID.\n\nRefer below for actual results.\n\nResolvers\n\n```\nQuery: {\n recipes: async (root, args, { req }, info) => {\n return Recipe.find({}).populate('ingredient category', 'name createdAt').exec().then(docs => docs.map(x => x))\n },\n},\nMutation: {\n addRecipe: async (root, args, { req }, info) => {\n // args.category = '5c28c79af62fad2514ccc788'\n // args.ingredient = '5c28c8deb99a9d263462a086'\n // console.log(args.map(x => x))\n return Recipe.create(args)\n }\n}\n```\n\nTypeDef\n\n```\nextend type Mutation {\n addRecipe(name: String!, direction: [String!]!, ingredient: [IngredientInput], category: [CategoryInput]): Recipe\n}\n\ntype Recipe {\n id: ID!\n name: String!\n direction: [String!]!\n ingredient: [Ingredient!]!\n category: [Category!]!\n}\n\ninput IngredientInput {\n id: ID!\n}\n\ninput CategoryInput {\n id: ID!\n}\n```\n\nModels\n\n```\nconst recipeSchema = new mongoose.Schema({\n name: String,\n direction: [String],\n ingredient: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Ingredient' }],\n category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' }\n}, {\n timestamps: true // createdAt, updateAt\n})\n\nconst Recipe = mongoose.model('Recipe', recipeSchema)\n```\n\nThis is the result I console log the args when inserting the data\n\n```\n{ \n name: 'Butter Milk Chicken TEST2',\n direction: [ 'Step1', 'Step2', 'Step3' ],\n ingredient:[[Object: null prototype] { id: '5c28c8d6b99a9d263462a085' }],\n category: [[Object: null prototype] { id: '5c28c79af62fad2514ccc788' }]\n}\n```\n\nI assume I need to get something like this\n\n```\n{ \n name: 'Butter Milk Chicken TEST2',\n direction: [ 'Step1', 'Step2', 'Step3' ],\n args.category = ['5c28c79af62fad2514ccc788']\n args.ingredient = ['5c28c8ccb99a9d263462a083', '5c28c8d3b99a9d263462a084', '5c28c8d6b99a9d263462a085']\n}\n```\n\n========================================\n\nTop Answer:\nYou can do something like below,and [Object: null prototype] would disappear\n\n```\nconst a = JSON.parse(JSON.stringify(args));\n```\n\n`args.category` is \n\n```\n[[Object: null prototype] { id: '5c28c79af62fad2514ccc788' }],\n```\n\nJSON.parse(JSON.stringify(args.category) would be `{ id: '5c28c79af62fad2514ccc788' }`\n\n========================================\n\nCode:\n```text\nargs.category = '5c28c79af62fad2514ccc788'\nargs.ingredient = '5c28c8deb99a9d263462a086'\n```\n\n```text\nQuery: {\n recipes: async (root, args, { req }, info) => {\n return Recipe.find({}).populate('ingredient category', 'name createdAt').exec().then(docs => docs.map(x => x))\n },\n},\nMutation: {\n addRecipe: async (root, args, { req }, info) => {\n // args.category = '5c28c79af62fad2514ccc788'\n // args.ingredient = '5c28c8deb99a9d263462a086'\n // console.log(args.map(x => x))\n return Recipe.create(args)\n }\n}\n```\n\n```text\nextend type Mutation {\n addRecipe(name: String!, direction: [String!]!, ingredient: [IngredientInput], category: [CategoryInput]): Recipe\n}\n\ntype Recipe {\n id: ID!\n name: String!\n direction: [String!]!\n ingredient: [Ingredient!]!\n category: [Category!]!\n}\n\ninput IngredientInput {\n id: ID!\n}\n\ninput CategoryInput {\n id: ID!\n}\n```\n\n```text\nconst recipeSchema = new mongoose.Schema({\n name: String,\n direction: [String],\n ingredient: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Ingredient' }],\n category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' }\n}, {\n timestamps: true // createdAt, updateAt\n})\n\nconst Recipe = mongoose.model('Recipe', recipeSchema)\n```\n\n```text\n{ \n name: 'Butter Milk Chicken TEST2',\n direction: [ 'Step1', 'Step2', 'Step3' ],\n ingredient:[[Object: null prototype] { id: '5c28c8d6b99a9d263462a085' }],\n category: [[Object: null prototype] { id: '5c28c79af62fad2514ccc788' }]\n}\n```\n\n```text\n{ \n name: 'Butter Milk Chicken TEST2',\n direction: [ 'Step1', 'Step2', 'Step3' ],\n args.category = ['5c28c79af62fad2514ccc788']\n args.ingredient = ['5c28c8ccb99a9d263462a083', '5c28c8d3b99a9d263462a084', '5c28c8d6b99a9d263462a085']\n}\n```\n\n```text\nMongoose\n```\n\n```text\nGraphQL\n```\n\n```text\n[Object: null prototype]\n```\n\n```text\n[Object: null prototype]\n```\n\n```text\nconsole.log\n```\n\n```text\nmap()\n```\n\n```text\nreplace()\n```\n\n```text\n\"args.ingredient.map/replace is not a function\"\n```\n\n```text\nservice: {\n price: 9999\n}\n```\n\n```text\n[ [Object: null prototype] { price: 9.99 } ]\n```\n\n```text\nconst a = JSON.parse(JSON.stringify(args));\n```\n\n```text\n[[Object: null prototype] { id: '5c28c79af62fad2514ccc788' }],\n```\n\n```text\nargs.category\n```\n\n```text\n{ id: '5c28c79af62fad2514ccc788' }\n```\n\n```text\nMutation: {\n addRecipe: async (root, { args }, { req }, info) => {\n return Recipe.create(args)\n }\n}\n```\n\n```html\naddRecipe: async (root, { ...args }, { req }, info) => {\n // args.category = '5c28c79af62fad2514ccc788'\n // args.ingredient = '5c28c8deb99a9d263462a086'\n // console.log(args.map(x => x))\n return Recipe.create(args)\n}\n```\n\n========================================\n\nComments:\n- Where would the arrays come from?\n- Where exactly do you \"*get [Object: null prototype] error*\", in the `Recipe.create` line? Can you post the full error message, please\n- I filed as an issue in the apollo project: github.com/apollographql/apollo-server/issues/3149\n- This has been very quickly fixed in firestore. github.com/googleapis/nodejs-firestore/pull/736\n- Please include some explanation for your answer.\n- @amanb the reason why this works it's because you first use `JSON.strigify(args)` transforming the value of args from [[Object: null prototype] { id: '5c28c79af62fad2514ccc788' }] to [{ id: '5c28c79af62fad2514ccc788' }] and then with the `JSON.parse` you transform it to a valid JS value. In my case I prefered to do `JSON.strigify(args[0])` to achieve the needed result of `{ name: 'test', type: 'A' }`\n- I get the null prototype when I run a create mutation and return the results as well, so not sure if it's a naming thing.","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":282,"estimatedTokens":1690}}432{"id":"stack-53192184","source":"stackoverflow","questionId":53192184,"title":"Error: Expected undefined to be a GraphQL schema","tags":["javascript","reactjs","node.js","graphql"],"text":"Title: Error: Expected undefined to be a GraphQL schema\nTags: javascript, reactjs, node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI am getting an error which says \" Error: Expected undefined to be a GraphQL schema.\" Please check what issue is this \nwhen I move to localhost:3000/graphiql it shows the above error.\nMaybe i am doing some mistake please anyone check and help me if possible.\n\nMy Server.js\n\n```\nconst express = require ('express');\nconst mongoose = require('mongoose');\nconst bodyParser = require('body-parser');\n\n//importing the Schema\nconst Story = require('./models/Story');\nconst User = require('./models/Story');\n\n//Bring in GraphQl-Express middleware\nconst { graphiqlExpress, graphqlExpress } = require('apollo-server-express');\nconst { makeExecutableSchema } = require('graphql-tools');\n\nconst { resolvers } = require('./resolvers');\nconst { typeDefs } = require('./schema');\n\n//create schema\nconst Schema = makeExecutableSchema({\n typeDefs,\n resolvers\n})\n\nrequire('dotenv').config({ path: 'variables.env' });\n// connecting mongoose to database\nmongoose\n.connect(process.env.MONGO_URI)\n.then(()=> console.log('DB Connected'))\n.catch(err => console.log(err));\n\n//initializing express\nconst app = express();\n\n//create GraphiQl application\napp.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql'}))\n\n//connect schemas with GraphQl\napp.use('/graphql',bodyParser.json(), graphqlExpress({\n Schema,\n context:{\n Story,\n User\n }\n}))\n\nconst PORT = process.env.PORT || 3000;\n\napp.listen(PORT, ()=> {\n console.log(`Server Running on PORT ${PORT}`);\n})\n```\n\nmy Schema.js\n\n```\nexports.typeDefs = `\n\ntype Story {\n name: String!\n category: String!\n description: String!\n instructions: String!\n createDate: String\n likes: Int\n username: String\n}\n\ntype User {\n username: String! @unique\n password: String!\n email: String!\n joinDate: String\n favorites: [Story]\n}\n\ntype Query {\n getAllStories: [Story]\n}\n\n`;\n```\n\nMy Resolvers.js\n\n```\nexports.resolvers= {\n\n Query:{\n getAllStories: ()=> {}\n }\n\n};\n```\n\nMy Story.js\n\n```\nconst mongoose = require('mongoose');\n\nconst Schema = mongoose.Schema;\n\nconst StorySchema = new Schema({\n name: {\n type: String,\n required:true,\n },\n category:{\n type:String,\n required:true\n },\n description:{\n type:String,\n required:true\n },\n instructions:{\n type:String,\n required:true\n },\n createdDate:{\n type:Date,\n default: Date.now\n },\n likes:{\n type:Number,\n default:0\n },\n username:{\n type:String\n }\n\n})\n\nmodule.exports = mongoose.model('Story', StorySchema );\n```\n\nMy User.js\n\n```\nconst mongoose = require('mongoose');\n\nconst Schema = mongoose.Schema;\n\nconst UserSchema = new Schema({\n username:{\n type:String,\n required:true,\n unique:true\n },\n password:{\n type:String,\n required:true\n },\n email:{\n type:String,\n required:true\n },\n joinDate:{\n type:Date,\n default:Date.now\n },\n favorites:{\n type:[Schema.Types.ObjectId],\n refs:'Story'\n }\n})\n\nmodule.exports = mongoose.model('User', UserSchema);\n```\n\n========================================\n\nTop Answer:\n### Feb, 2022 Update:\n\nI downgraded **graphql** to **15.x** then the problem was solved:\n\n```\nnpm install graphql@15.8.0\n```\n\nIf you don't mind **the specific version**:\n\n```\nnpm install graphql@15\n```\n\nIf you use **\"yarn\"**:\n\n```\nyarn add graphql@15.8.0\n```\n\nIf you don't mind **the specific version**:\n\n```\nyarn add graphql@15\n```\n\n========================================\n\nCode:\n```text\nconst express = require ('express');\nconst mongoose = require('mongoose');\nconst bodyParser = require('body-parser');\n\n\n//importing the Schema\nconst Story = require('./models/Story');\nconst User = require('./models/Story');\n\n\n//Bring in GraphQl-Express middleware\nconst { graphiqlExpress, graphqlExpress } = require('apollo-server-express');\nconst { makeExecutableSchema } = require('graphql-tools');\n\nconst { resolvers } = require('./resolvers');\nconst { typeDefs } = require('./schema');\n\n//create schema\nconst Schema = makeExecutableSchema({\n typeDefs,\n resolvers\n})\n\n\nrequire('dotenv').config({ path: 'variables.env' });\n// connecting mongoose to database\nmongoose\n.connect(process.env.MONGO_URI)\n.then(()=> console.log('DB Connected'))\n.catch(err => console.log(err));\n\n//initializing express\nconst app = express();\n\n//create GraphiQl application\napp.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql'}))\n\n//connect schemas with GraphQl\napp.use('/graphql',bodyParser.json(), graphqlExpress({\n Schema,\n context:{\n Story,\n User\n }\n}))\n\nconst PORT = process.env.PORT || 3000;\n\napp.listen(PORT, ()=> {\n console.log(`Server Running on PORT ${PORT}`);\n})\n```\n\n```text\nexports.typeDefs = `\n\n\ntype Story {\n name: String!\n category: String!\n description: String!\n instructions: String!\n createDate: String\n likes: Int\n username: String\n}\n\n\n\ntype User {\n username: String! @unique\n password: String!\n email: String!\n joinDate: String\n favorites: [Story]\n}\n\ntype Query {\n getAllStories: [Story]\n}\n\n\n`;\n```\n\n```text\nexports.resolvers= {\n\n Query:{\n getAllStories: ()=> {}\n }\n\n};\n```\n\n```text\nconst mongoose = require('mongoose');\n\nconst Schema = mongoose.Schema;\n\nconst StorySchema = new Schema({\n name: {\n type: String,\n required:true,\n },\n category:{\n type:String,\n required:true\n },\n description:{\n type:String,\n required:true\n },\n instructions:{\n type:String,\n required:true\n },\n createdDate:{\n type:Date,\n default: Date.now\n },\n likes:{\n type:Number,\n default:0\n },\n username:{\n type:String\n }\n\n})\n\nmodule.exports = mongoose.model('Story', StorySchema );\n```\n\n```text\nconst mongoose = require('mongoose');\n\nconst Schema = mongoose.Schema;\n\nconst UserSchema = new Schema({\n username:{\n type:String,\n required:true,\n unique:true\n },\n password:{\n type:String,\n required:true\n },\n email:{\n type:String,\n required:true\n },\n joinDate:{\n type:Date,\n default:Date.now\n },\n favorites:{\n type:[Schema.Types.ObjectId],\n refs:'Story'\n }\n})\n\nmodule.exports = mongoose.model('User', UserSchema);\n```\n\n```text\napp.use('/graphql',bodyParser.json(), graphqlExpress({\n Schema,\n context:{\n Story,\n User\n }\n}))\n```\n\n```text\napp.use('/graphql',bodyParser.json(), graphqlExpress({\n schema: Schema,\n context:{\n Story,\n User\n }\n}))\n```\n\n```text\napp.use('/graphql',bodyParser.json(), graphqlExpress({\n schema,\n context:{\n Story,\n User\n }\n}))\n```\n\n```text\n/graphql\n```\n\n```text\nnpm install graphql@15.8.0\n```\n\n```text\nnpm install graphql@15\n```\n\n```text\nyarn add graphql@15.8.0\n```\n\n```text\nyarn add graphql@15\n```\n\n```text\nconst response = await graphql({schema, source: query, rootValue});\n```\n\n```text\nconst response = await graphql(schema, query, rootValue);\n```\n\n```text\ngraphql\n```\n\n```text\nGraphQLArgs\n```\n\n```text\ngraphql-js\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":447,"estimatedTokens":1737}}433{"id":"stack-37995394","source":"stackoverflow","questionId":37995394,"title":"GraphQL object property should be a list of strings","tags":["javascript","node.js","graphql","graphql-js"],"text":"Title: GraphQL object property should be a list of strings\nTags: javascript, node.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nHow do I make a schema for an object property that is an array of strings in GraphQL? I want the response to look like this:\n\n```\n{\n name: \"colors\",\n keys: [\"red\", \"blue\"]\n}\n```\n\nHere is my Schema\n\n```\nvar keysType = new graphql.GraphQLObjectType({\n name: 'keys',\n fields: function() {\n key: { type: graphql.GraphQLString }\n }\n});\n\nvar ColorType = new graphql.GraphQLObjectType({\n name: 'colors',\n fields: function() {\n return {\n name: { type: graphql.GraphQLString },\n keys: { type: new graphql.GraphQLList(keysType)\n };\n }\n});\n```\n\nWhen I run this query I get an error and no data, the error is just `[{}]` \n\n*query { colors { name, keys } }*\n\nHowever when I run a query to return just the name I get a successful response. \n\n*query { colors { name } }*\n\nHow do I create a schema that returns an array of strings for when I query for keys?\n\n========================================\n\nCode:\n```text\n{\n name: \"colors\",\n keys: [\"red\", \"blue\"]\n}\n```\n\n```text\nvar keysType = new graphql.GraphQLObjectType({\n name: 'keys',\n fields: function() {\n key: { type: graphql.GraphQLString }\n }\n});\n\nvar ColorType = new graphql.GraphQLObjectType({\n name: 'colors',\n fields: function() {\n return {\n name: { type: graphql.GraphQLString },\n keys: { type: new graphql.GraphQLList(keysType)\n };\n }\n});\n```\n\n```text\n[{}]\n```\n\n```text\nvar ColorType = new graphql.GraphQLObjectType({\n name: 'colors',\n fields: function() {\n return {\n name: { type: graphql.GraphQLString },\n keys: { type: new graphql.GraphQLList(graphql.GraphQLString)\n };\n }\n});\n```\n\n```text\n{\n name: \"colors\",\n keys: [\"red\", \"blue\"]\n}\n```\n\n```text\ngraphql.GraphQLString\n```\n\n```text\ngraphql.GraphQLList()\n```\n\n========================================\n\nComments:\n- Awesome, thanks for taking the time to write your solution up. Saved me a bunch of time!\n- @davnicwil Exactly!","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":110,"estimatedTokens":502}}434{"id":"stack-54688108","source":"stackoverflow","questionId":54688108,"title":"ApolloClient is not a constructor (apollo-client with nodejs)","tags":["node.js","graphql"],"text":"Title: ApolloClient is not a constructor (apollo-client with nodejs)\nTags: node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI don't have any UI framework. Just a simple Nodejs script where I need to query a GraphQL.\n\nCodes:\n\n```\nconst ApolloClient = require('apollo-client')\nconst client = new ApolloClient()\n```\n\nError message:\n\n```\nTypeError: ApolloClient is not a constructor\n```\n\nPackage.json:\n\n```\n{\n ...\n\n \"dependencies\": {\n \"apollo-client\": \"^2.4.13\",\n \"graphql\": \"^14.1.1\",\n \"graphql-tag\": \"^2.10.1\"\n },\n}\n```\n\nNode: `v8.9.4`\n\nI googled a while people have this issue mainly because `ApolloClient is no longer in react-apollo. You have to import it from 'apollo-client'`\n\nAnd I'm importing from `apollo-client` as `const ApolloClient = require('apollo-client')`\n\nAny ideas? Thanks!\n\n========================================\n\nTop Answer:\nFor people who like me using Node `require` and just want to get it working.\n\nPackages:\n\n`npm install graphql apollo-client apollo-cache-inmemory apollo-link-http node-fetch --save`\n\nCodes:\n\n```\nconst fetch = require('node-fetch')\nconst { createHttpLink } = require('apollo-link-http')\nconst { InMemoryCache } = require('apollo-cache-inmemory')\nconst { ApolloClient } = require('apollo-client')\nconst gql = require('graphql-tag')\n\nconst httpLink = createHttpLink({\n uri: 'https://api.github.com/graphql',\n fetch: fetch\n})\n\nconst client = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache()\n})\n\nconst query = gql`\n query {\n viewer {\n login\n }\n }\n`\n\nclient.query({\n query\n}).catch((error) => {\n console.log(error)\n done()\n})\n```\n\nThe response is error as you need to add `Authorization: bearer YOURTOKEN` to request header but that's another thing.\n\nThanks to this answer\n\n========================================\n\nCode:\n```text\nconst ApolloClient = require('apollo-client')\nconst client = new ApolloClient()\n```\n\n```text\nTypeError: ApolloClient is not a constructor\n```\n\n```text\n{\n ...\n\n \"dependencies\": {\n \"apollo-client\": \"^2.4.13\",\n \"graphql\": \"^14.1.1\",\n \"graphql-tag\": \"^2.10.1\"\n },\n}\n```\n\n```text\nv8.9.4\n```\n\n```text\nApolloClient is no longer in react-apollo. You have to import it from 'apollo-client'\n```\n\n```text\napollo-client\n```\n\n```text\nconst ApolloClient = require('apollo-client')\n```\n\n```text\nconst ApolloClient = require('apollo-client').default\n```\n\n```text\nconst { ApolloClient } = require('apollo-client')\n```\n\n```text\nrequire\n```\n\n```text\nconst fetch = require('node-fetch')\nconst { createHttpLink } = require('apollo-link-http')\nconst { InMemoryCache } = require('apollo-cache-inmemory')\nconst { ApolloClient } = require('apollo-client')\nconst gql = require('graphql-tag')\n\nconst httpLink = createHttpLink({\n uri: 'https://api.github.com/graphql',\n fetch: fetch\n})\n\nconst client = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache()\n})\n\nconst query = gql`\n query {\n viewer {\n login\n }\n }\n`\n\nclient.query({\n query\n}).catch((error) => {\n console.log(error)\n done()\n})\n```\n\n```text\nrequire\n```\n\n```text\nnpm install graphql apollo-client apollo-cache-inmemory apollo-link-http node-fetch --save\n```\n\n```text\nAuthorization: bearer YOURTOKEN\n```\n\n```text\nimport { default as ApolloClient } from 'apollo-client';\n\nconst client = new ApolloClient();\n```\n\n```text\nimport apolloClient from 'apollo-client';\nconst { ApolloClient } = apolloClient;\n```\n\n```text\nimport nodeFetch from 'node-fetch';\nglobal.fetch = nodeFetch;\nimport apolloClient from 'apollo-client';\nconst { ApolloClient } = apolloClient;\nimport apolloInMemoryCache from 'apollo-cache-inmemory';\nconst { InMemoryCache } = apolloInMemoryCache;\nimport apolloHttpLink from 'apollo-link-http';\nconst { HttpLink } = apolloHttpLink;\n\n const cache = new InMemoryCache();\n const link = new HttpLink({\n uri\n });\n\n const client = new ApolloClient({\n cache,\n link\n });\n```\n\n```text\nnode --experimental-modules\n```\n\n```text\napollo-client\n```\n\n```text\n2.6.x\n```\n\n```text\n12.x\n```\n\n```text\n--experimental-modules\n```\n\n```text\npackage.json\n```\n\n```text\n\"module\"\n```\n\n```text\n\"type\"\n```\n\n```text\npackage.json\n```\n\n```text\n.mjs\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\npackage.json\n```\n\n```text\nesm\n```\n\n```text\nesm\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\n\"main\"\n```\n\n```text\npackage.json\n```\n\n```text\nimport fetch from 'node-fetch';\nimport apolloClient from 'apollo-client';\nimport apolloInMemoryCache from 'apollo-cache-inmemory';\nimport apolloHttpLink from 'apollo-link-http';\nimport gql from 'graphql-tag';\n\nconst { ApolloClient } = apolloClient;\nconst { InMemoryCache } = apolloInMemoryCache;\nconst { HttpLink } = apolloHttpLink;\n\nconst uri = 'https://countries.trevorblades.com/';\n\nconst link = new HttpLink({ uri, fetch });\nconst cache = new InMemoryCache();\nconst client = new ApolloClient({ link, cache });\n\nconst query = gql`\n query {\n countries {\n name\n }\n }\n`;\n\nclient\n .query({ query })\n .then((result) => console.log(result.data));\n```\n\n```text\nfetch\n```\n\n```text\nglobal.fetch\n```\n\n```js\nimport { ApolloProvider } from \"@apollo/client/index.js\";\nimport { ApolloClient } from \"@apollo/client/core/ApolloClient.js\";\nimport { InMemoryCache } from \"@apollo/client/cache/inmemory/inMemoryCache.js\";\nimport { HttpLink } from \"@apollo/client/link/http/HttpLink.js\";\nimport fetch from \"cross-fetch\";\n\nconst client = new ApolloClient({\n link: new HttpLink({ uri: \"http://localhost:4000/graphql\", fetch }),\n cache: new InMemoryCache(),\n});\n```\n\n```text\n@apollo/client\n```\n\n```text\nHttpLink\n```\n\n```text\nfetch\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":41,"totalLines":349,"estimatedTokens":1379}}435{"id":"stack-45511335","source":"stackoverflow","questionId":45511335,"title":"React-Apollo, don't run query on component load","tags":["javascript","reactjs","graphql","apollo"],"text":"Title: React-Apollo, don't run query on component load\nTags: javascript, reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm using the awesome https://github.com/apollographql/react-apollo library and I'm trying to see if there is a better convention to load data into components than how I'm doing it now.\n\nI've set up my components to with the apollo HOC to load data into my components, like so:\n\n```\nconst mainQuery = gql`\n query currentProfileData($userId:String, $communityId:String!){\n created: communities(id:$communityId) {\n opportunities{\n submittedDate\n approvalDate\n status\n opportunity{\n id\n }\n }\n }\n }\n`;\nconst mainQueryOptions = {\n options: {\n variables: { userId: '_', communityId: '_' },\n },\n};\n\nconst ComponentWithData = compose(\n graphql(mainQuery, mainQueryOptions),\n)(Component);\n```\n\nThis setup works great, but with some problems.\n\nI end up with queries that always run twice, as I need to pass props to apollo refetch for the query. I also have to pass in some dummy data (aka the \"_\") to prevent useless data fetching.\n\nI end up having to do some fancy checking in componentWillReceiveProps to prevent loading the query multiple times.\n\n- I can't use the skip option on the query as this prevents re-fetch function from being passed in.\n\nShort of my sidestepping the HOC all together and manually running the queries through apollo directly, how can I solve this?\n\n========================================\n\nTop Answer:\nJust a little up.\n\nWith the insight of @daniel, I was able to solve my 2 primary problems, run queries with props, and skipping the query conditionally until it's ready. I just wanted to post my final code result. As you can set functions for both of these options, it helps a ton.\n\n```\nconst mainQueryOptions = {\n skip: ({ community: { id: communityId } }) => !communityId,\n options: ({ community: { id: communityId }, user: { id: userId = '_' } }) => ({\n variables: { userId, communityId },\n }),\n};\n```\n\nYou can find more info here on the apollo api page: http://dev.apollodata.com/react/api-graphql.html#graphql\n\n========================================\n\nCode:\n```js\nconst mainQuery = gql`\n query currentProfileData($userId:String, $communityId:String!){\n created: communities(id:$communityId) {\n opportunities{\n submittedDate\n approvalDate\n status\n opportunity{\n id\n }\n }\n }\n }\n`;\nconst mainQueryOptions = {\n options: {\n variables: { userId: '_', communityId: '_' },\n },\n};\n\nconst ComponentWithData = compose(\n graphql(mainQuery, mainQueryOptions),\n)(Component);\n```\n\n```text\nconst mainQueryOptions = {\n options: ({ userId, communityId }) => ({\n variables: { userId, communityId },\n },\n});\n```\n\n```text\nrefetch\n```\n\n```text\noptions\n```\n\n```text\nconst mainQueryOptions = {\n skip: ({ community: { id: communityId } }) => !communityId,\n options: ({ community: { id: communityId }, user: { id: userId = '_' } }) => ({\n variables: { userId, communityId },\n }),\n};\n```\n\n========================================\n\nComments:\n- Such wow. I never knew you could do that. Don't know how I missed that! I dove a little deeper and found as well that you can conditionally skip, solving my other main issue. Many thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":121,"estimatedTokens":814}}436{"id":"stack-52780033","source":"stackoverflow","questionId":52780033,"title":"Uncaught TypeError: Cannot read property 'data' of undefined with Gatsby and graphQl","tags":["javascript","reactjs","graphql","graphql-js","gatsby"],"text":"Title: Uncaught TypeError: Cannot read property 'data' of undefined with Gatsby and graphQl\nTags: javascript, reactjs, graphql, graphql-js, gatsby\nSource: Stack Overflow\n\nQuestion:\nI'm testing Gatsby and GraphQl for the first time and I'm trying on a simple example....\n\nI have this error when I want to display the title via a GraphQl request in my layout? : **Uncaught TypeError: Cannot read property 'site' of undefined** \n\nhere is my layout: \n\n```\nimport React from 'react'\nimport { graphql } from 'gatsby'\n\nexport default ({ children, data }) =>\n \n \n\n### {data.site.siteMetadata.title}\n\n {children}\n \n Copyright blablb abolajoa.\n \n\nexport const query = graphql`\nquery LayoutQuery {\n site {\n siteMetadata {\n title\n }\n }\n}\n`\n```\n\nand my gatsby-config.js : \n\n```\nmodule.exports = {\n siteMetadata: {\n title: `Hardcoders`\n },\n plugins: [\n {\n resolve: 'gatsby-plugin-typography',\n options: {\n pathToConfigModule: 'src/utils/typography.js'\n }\n },\n ]\n}\n```\n\nand here is the configuration of the project: \n\n```\n\"dependencies\": {\n \"gatsby\": \"^2.0.0\",\n \"gatsby-plugin-typography\": \"^2.2.0\",\n \"react\": \"^16.5.1\",\n \"react-dom\": \"^16.5.1\",\n \"react-typography\": \"^0.16.13\",\n \"typography\": \"^0.16.17\",\n \"typography-theme-github\": \"^0.15.10\"\n }\n```\n\nany idea what's jamming?\n\n========================================\n\nCode:\n```text\nimport React from 'react'\nimport { graphql } from 'gatsby'\n\nexport default ({ children, data }) =>\n <div style={{margin: 'auto', maxWidth: 760}}>\n <h2>{data.site.siteMetadata.title}</h2>\n {children}\n <footer>\n Copyright blablb abolajoa.\n </footer>\n</div>\n\nexport const query = graphql`\nquery LayoutQuery {\n site {\n siteMetadata {\n title\n }\n }\n}\n`\n```\n\n```text\nmodule.exports = {\n siteMetadata: {\n title: `Hardcoders`\n },\n plugins: [\n {\n resolve: 'gatsby-plugin-typography',\n options: {\n pathToConfigModule: 'src/utils/typography.js'\n }\n },\n ]\n}\n```\n\n```text\n\"dependencies\": {\n \"gatsby\": \"^2.0.0\",\n \"gatsby-plugin-typography\": \"^2.2.0\",\n \"react\": \"^16.5.1\",\n \"react-dom\": \"^16.5.1\",\n \"react-typography\": \"^0.16.13\",\n \"typography\": \"^0.16.17\",\n \"typography-theme-github\": \"^0.15.10\"\n }\n```\n\n```text\nexport default ({ data }) => (\n <Layout data={data}>\n </Layout>\n);\n\nexport const query = graphql`\n query LayoutQuery {\n site {\n siteMetadata {\n title\n }\n }\n }\n}\n```\n\n```text\nsrc/pages\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":146,"estimatedTokens":604}}437{"id":"stack-49348326","source":"stackoverflow","questionId":49348326,"title":"Select * for Github GraphQL Search","tags":["github","field","graphql","github-api","github-graphql"],"text":"Title: Select * for Github GraphQL Search\nTags: github, field, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nOne of the advantage of Github Search v4 (GraphQL) over v3 is that it can selectively pick the fields that we want, instead of always getting them all. However, the problem I'm facing now is how to get certain fields. \n\nI tried the online help but it is more convolution to me than helpful. Till now, I'm still unable to find the fields for size, score and open issues for the returned repository(ies). \n\nThat's why I'm wondering if there is a way to get them all, like `Select *` in SQL. Thx.\n\n========================================\n\nTop Answer:\nShort Answer: No, by design.\n\nGraphQL was designed to have the client explicitly define the data required, leading to one of the primary benefits of GraphQL, which is preventing over fetching. \n\nTechnically you can use GraphQL fragments somewhere in your application for every field type, but if you don't know which fields you are trying to get it wouldn't help you.\n\n========================================\n\nCode:\n```text\nSelect *\n```\n\n```text\nquery{\n __type(name:\"Repository\") {\n fields {\n name\n description\n type {\n kind\n name\n description\n }\n args {\n name\n description\n type {\n kind\n name\n description\n }\n defaultValue\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- This Q/A helped me find a better Github search approach, FYI.","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":57,"estimatedTokens":390}}438{"id":"stack-51602305","source":"stackoverflow","questionId":51602305,"title":"appsync subscription with arguments","tags":["amazon-web-services","graphql","subscription","aws-appsync"],"text":"Title: appsync subscription with arguments\nTags: amazon-web-services, graphql, subscription, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nWe are having huge troubles with subscriptions with arguments\n\nto simplify the problem Here are the steps to reproduce\n\ncreate a simpleSchema\n\n```\ntype Mutation {\n testSubMutation(param: String!): String\n}\n\ntype Query {\n testQuery: String\n}\n\ntype Subscription {\n testSubs(param: String): String\n @aws_subscribe(mutations: [\"testSubMutation\"])\n}\n```\n\nI attached a local resolver to the mutation which returns the timestamp.\n\nin one window open the app sync query tab and make the subscription\n\n```\nsubscription sub{\n testSubs\n}\n```\n\nin the other window make a mutation\n\n```\nmutation mut{\n testSubMutation(param:\"123\")\n}\n```\n\nworks like a charm\n\nnow change the subscription to listen to a parameter\n\n```\nsubscription sub{\n testSubs(param:\"123\")\n}\n```\n\nDoes not work any more. :( \n\nAny help is appreciated.\n\n========================================\n\nTop Answer:\nI'm doing same as above for subscription but not getting response, It's only working with one argument `room` \n\n```\nmutation addMessage {\n addMessage(input: { \n room: \"45a87f5b-ef9e-41cd-9cd7-f3e2f4946d31\", \n receiver: \"3cea9c02-1cf5-4248-8ebe-3580a7a47b8b\" }) {\n id\n room\n receiver {\n id\n userName\n }\n }\n }\n\nsubscription roomMessage {\n roomMessage(room: \"45a87f5b-ef9e-41cd-9cd7-f3e2f4946d31\", \n receiver: \"3cea9c02-1cf5-4248-8ebe-3580a7a47b8b\") {\n id\n room\n receiver {\n id\n userName\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\ntype Mutation {\n testSubMutation(param: String!): String\n}\n\ntype Query {\n testQuery: String\n}\n\ntype Subscription {\n testSubs(param: String): String\n @aws_subscribe(mutations: [\"testSubMutation\"])\n}\n```\n\n```text\nsubscription sub{\n testSubs\n}\n```\n\n```text\nmutation mut{\n testSubMutation(param:\"123\")\n}\n```\n\n```text\nsubscription sub{\n testSubs(param:\"123\")\n}\n```\n\n```text\nmutation mut{\n testSubMutation(param:\"123\") {\n param\n }\n}\n```\n\n```text\nmutation addMessage {\n addMessage(input: { \n room: \"45a87f5b-ef9e-41cd-9cd7-f3e2f4946d31\", \n receiver: \"3cea9c02-1cf5-4248-8ebe-3580a7a47b8b\" }) {\n id\n room\n receiver {\n id\n userName\n }\n }\n }\n\nsubscription roomMessage {\n roomMessage(room: \"45a87f5b-ef9e-41cd-9cd7-f3e2f4946d31\", \n receiver: \"3cea9c02-1cf5-4248-8ebe-3580a7a47b8b\") {\n id\n room\n receiver {\n id\n userName\n }\n }\n}\n```\n\n```text\nroom\n```\n\n========================================\n\nComments:\n- Is it written somewhere in the documentation? It does work perfectly, but just a bit weird, that response of a mutation depends on it's arguments\n- Can you subscribe to changes in the database that were made through the DynamoDB GUI and not a GraphQL mutation?\n- @hgale I don't think so, just because AppSync and Dyanmo are two different systems. AppSync doesn't know or care if requests are being processed by a Dynamo endpoint or a Lambda or something else. You could hook up to the dynamo stream for the table to fire when the table is modified and use that to send a non-AppSync websocket message to a browser. But as far as AppSync is concerned, it just sees requests coming in and out without much intelligence about how they are being resolved underneath.\n- Sorry for being slow, I missed your question, @hgale. Hober is correct.\n- Wow... That is so silly. And as mentioned by @Rax Wunter I did not find this in the documentation.","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":173,"estimatedTokens":863}}439{"id":"stack-62182837","source":"stackoverflow","questionId":62182837,"title":"How to add a `resolveType` to GraphQL?","tags":["node.js","mongodb","express","graphql"],"text":"Title: How to add a `resolveType` to GraphQL?\nTags: node.js, mongodb, express, graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to query a single MongoDB document (`trivia`) using GraphQL, but am having trouble with one of the document fields. It's the `trivia.rounds` field that should return an array of objects (either `LightningRound` or `MultipleChoiceRound`).\n\n`schema.graphql`\n\n```\ntype Trivia {\n _id: String!\n createdAt: String!\n rounds: [Round]!\n}\n\ninterface Round {\n type: String!\n theme: String!\n pointValue: Int!\n}\n\ntype LightningRound implements Round {\n type: String!\n theme: String!\n pointValue: Int!\n questions: [LightningRoundQuestion]\n}\n\ntype MultipleChoiceRound implements Round {\n type: String!\n theme: String!\n pointValue: Int!\n questions: [MultipleChoiceRoundQuestion]\n}\n\n// ...\n```\n\n`trivia.js // resolver`\n\n```\nrequire('dotenv').config()\nconst { ObjectId } = require('mongodb')\n\nconst trivia = (app) => {\n return async (root, { _id }) => {\n return app\n .get('db')\n .collection(process.env.DB_COLLECTION_TRIVIA)\n .findOne(ObjectId(_id))\n }\n}\n\nmodule.exports = {\n trivia\n}\n```\n\n`graphql query`\n\n```\nquery {\n trivia(_id: \"5e827a4e1c9d4400009fea32\") {\n _id\n createdAt\n rounds {\n __typename\n ... on MultipleChoiceRound {\n type\n theme\n }\n ... on PictureRound {\n type\n theme\n }\n ... on LightningRound {\n type\n theme\n }\n }\n }\n}\n```\n\nI keep getting the error:\n\n```\n\"message\": \"Abstract type \\\"Round\\\" must resolve to an Object type at runtime for field \\\"Trivia.rounds\\\" with value { questions: [[Object], [Object]] }, received \\\"undefined\\\". Either the \\\"Round\\\" type should provide a \\\"resolveType\\\" function or each possible type should provide an \\\"isTypeOf\\\" function.\"\n```\n\nI don't understand what it means by `resolveType` or `isTypeOf`. I've seen this in other questions, but have no clue what to implement in my setup. The db connection and resolver works fine if I remove the `rounds` field, so it's something there...\n\n========================================\n\nCode:\n```text\ntype Trivia {\n _id: String!\n createdAt: String!\n rounds: [Round]!\n}\n\ninterface Round {\n type: String!\n theme: String!\n pointValue: Int!\n}\n\ntype LightningRound implements Round {\n type: String!\n theme: String!\n pointValue: Int!\n questions: [LightningRoundQuestion]\n}\n\ntype MultipleChoiceRound implements Round {\n type: String!\n theme: String!\n pointValue: Int!\n questions: [MultipleChoiceRoundQuestion]\n}\n\n// ...\n```\n\n```text\nrequire('dotenv').config()\nconst { ObjectId } = require('mongodb')\n\nconst trivia = (app) => {\n return async (root, { _id }) => {\n return app\n .get('db')\n .collection(process.env.DB_COLLECTION_TRIVIA)\n .findOne(ObjectId(_id))\n }\n}\n\nmodule.exports = {\n trivia\n}\n```\n\n```text\nquery {\n trivia(_id: \"5e827a4e1c9d4400009fea32\") {\n _id\n createdAt\n rounds {\n __typename\n ... on MultipleChoiceRound {\n type\n theme\n }\n ... on PictureRound {\n type\n theme\n }\n ... on LightningRound {\n type\n theme\n }\n }\n }\n}\n```\n\n```text\n\"message\": \"Abstract type \\\"Round\\\" must resolve to an Object type at runtime for field \\\"Trivia.rounds\\\" with value { questions: [[Object], [Object]] }, received \\\"undefined\\\". Either the \\\"Round\\\" type should provide a \\\"resolveType\\\" function or each possible type should provide an \\\"isTypeOf\\\" function.\"\n```\n\n```text\ntrivia\n```\n\n```text\ntrivia.rounds\n```\n\n```text\nLightningRound\n```\n\n```text\nMultipleChoiceRound\n```\n\n```text\nschema.graphql\n```\n\n```text\ntrivia.js // resolver\n```\n\n```text\ngraphql query\n```\n\n```text\nresolveType\n```\n\n```text\nisTypeOf\n```\n\n```text\nrounds\n```\n\n```text\nconst resolvers = {\n Round: {\n __resolveType: (round) => {\n // your code here\n },\n },\n}\n```\n\n```text\nconst resolvers = {\n Round: {\n __resolveType: (round) => {\n return round.type\n },\n },\n}\n```\n\n```text\nRound\n```\n\n```text\nLightningRound\n```\n\n```text\nMultipleChoiceRound\n```\n\n```text\nRound\n```\n\n```text\nLightningRound\n```\n\n```text\nMultipleChoiceRound\n```\n\n```text\nresolveType\n```\n\n```text\nresolveType\n```\n\n```text\ngraphql-tools\n```\n\n```text\napollo-server\n```\n\n```text\nresolveType\n```\n\n```text\nrounds\n```\n\n```text\ntype\n```\n\n```text\nresolveType\n```\n\n```text\nisTypeOf\n```\n\n```text\nresolveType\n```\n\n```text\nisTypeOf\n```\n\n```text\nisTypeOf\n```\n\n```text\nresolveType\n```\n\n========================================\n\nComments:\n- resolver for `trivia` returns an object (from db) but it doesn't contain `rounds` property ... and no resolver to return value (array of objects) for this\n- @xadm The object returned from `trivia` does have the `rounds` array with the rounds in them.\n- @xadm thanks for the tip. I'm coming at this completely new, trying to wrap my head around GraphQL. I tried union stuff, didn't quite work. I just don't know how to do it. Oh well.\n- Thanks for the in-depth response! I really appreciate it. Only thing, I have no idea where to insert or execute the resolver function... I'm using `graphql-tools` and not apollo, if that helps.\n- If you're using `makeExecutableSchema`, then you're passing a `resolvers` option to it. That `resolvers` object should look as shown above (or in the docs).\n- I'm using `addResolversToSchema`, and the resolver would make it return the string \"MultipleChoice\" for example, and not actually have any data. I'm so lost. This is too confusing.\n- I would use `makeExecutableSchema` as shown in the `graphql-tools` docs here. Then modify the resolvers object to include the `Round.__resolveType` function as I've shown.\n- One of the best written answers I've read in a long time.\n- ^^^ correction: incredible [LONG] answer for a simple question that shouldn't even exist because GQL creates more problems than it solves.","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":35,"totalLines":320,"estimatedTokens":1440}}440{"id":"stack-50242492","source":"stackoverflow","questionId":50242492,"title":"Gatsby: Multiple Content Types","tags":["reactjs","graphql","gatsby"],"text":"Title: Gatsby: Multiple Content Types\nTags: reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nIm trying to get up to speed on Gatsby and have great success with the demos, but am running into a wall with what I feel like is a relatively common and simple use case. I would like to have multiple content types that I can write in Markdown, each that has different Frontmatter, and each that has a different template.\n\nFor example, I would like a BlogPost content type and and a Project content type:\n\n### BlogPost Content Type\n\n```\n---\ntitle: My Post\ndate: \"2017-09-21\"\n---\n\nThis is my blog body\n```\n\n### Project Content Type\n\n```\n---\nprojectName: My Project\nstartDate: \"2017-09-21\"\nendDate: \"2017-10-21\"\n---\n\nThis is my project description\n```\n\nAnd then to have them render in the relevant Template, I had to do some hacky stuff in `gatsby-node.js` using regular expressions:\n\n```\nconst components = {\n blog: `./src/templates/blog-post.js`,\n projects: `./src/templates/project-post.js`,\n}\nexports.createPages = ({ graphql, boundActionCreators }) => {\n const { createPage } = boundActionCreators\n RE_DIR = new RegExp(\"\\/pages\\/([a-z]+)\\/.*\\.md$\");\n return new Promise((resolve, reject) => {\n graphql(`\n {\n allMarkdownRemark {\n edges {\n node {\n fileAbsolutePath\n fields {\n slug\n }\n }\n }\n }\n }\n `).then(result => {\n result.data.allMarkdownRemark.edges.forEach(({ node }) => {\n // console.log(RE_DIR.exec(node.fileAbsolutePath))\n\n const postType = RE_DIR.exec(node.fileAbsolutePath)[1]\n\n if (postType) {\n createPage({\n path: node.fields.slug,\n component: path.resolve(components[postType]),\n context: {\n // Data passed to context is available in page queries as GraphQL variables.\n slug: node.fields.slug,\n },\n })\n }\n\n })\n resolve()\n })\n })\n};\n```\n\nThe problem Im having now, is since the frontmatter is inconsistent, it appears GraphQL only picks up the frontmatter schema from one of the sources. \n\nIs there an easier way to have multiple content types?\n\n========================================\n\nTop Answer:\nAdding my answer in which is based on @nicokant but seems to have changed a bit. I also use mdx here but just swap out for `MarkdownRemark` if that is what you use:\n\nGive each source a name option:\n\n```\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/posts`,\n name: 'post',\n },\n},\n```\n\nThen when the node is created, assign it a custom field:\n\n```\nexports.onCreateNode = ({ node, actions, getNode }) => {\n const { createNodeField } = actions\n if (node.internal.type === `MarkdownRemark` || node.internal.type === `Mdx`) {\n createNodeField({\n name: `collection`,\n node,\n value: getNode(node.parent).sourceInstanceName\n });\n })\n};\n```\n\nThen you can query it based on a custom field:\n\n```\nquery {\n allMdx(filter: { fields: { collection: { eq: \"post\"}}}) {\n edges {\n node {\n fields {\n collection\n }\n frontmatter {\n title\n }\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n---\ntitle: My Post\ndate: \"2017-09-21\"\n---\n\nThis is my blog body\n```\n\n```text\n---\nprojectName: My Project\nstartDate: \"2017-09-21\"\nendDate: \"2017-10-21\"\n---\n\nThis is my project description\n```\n\n```text\nconst components = {\n blog: `./src/templates/blog-post.js`,\n projects: `./src/templates/project-post.js`,\n}\nexports.createPages = ({ graphql, boundActionCreators }) => {\n const { createPage } = boundActionCreators\n RE_DIR = new RegExp(\"\\/pages\\/([a-z]+)\\/.*\\.md$\");\n return new Promise((resolve, reject) => {\n graphql(`\n {\n allMarkdownRemark {\n edges {\n node {\n fileAbsolutePath\n fields {\n slug\n }\n }\n }\n }\n }\n `).then(result => {\n result.data.allMarkdownRemark.edges.forEach(({ node }) => {\n // console.log(RE_DIR.exec(node.fileAbsolutePath))\n\n\n const postType = RE_DIR.exec(node.fileAbsolutePath)[1]\n\n if (postType) {\n createPage({\n path: node.fields.slug,\n component: path.resolve(components[postType]),\n context: {\n // Data passed to context is available in page queries as GraphQL variables.\n slug: node.fields.slug,\n },\n })\n }\n\n\n })\n resolve()\n })\n })\n};\n```\n\n```text\ngatsby-node.js\n```\n\n```text\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `project`,\n path: `${__dirname}/src/project/`,\n},\n},\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `posts`,\n path: `${__dirname}/src/blog-posts/`,\n },\n},\n```\n\n```text\nexports.onCreateNode =({ node, getNode, boundActionCreators }) => {\n if (node.internal.type === 'MarkdownRemark') {\n const { createNodeField } = boundActionCreators;\n node.collection = getNode(node.parent).sourceInstanceName;\n }\n}\n```\n\n```text\nquery postsOnly {\n allMarkdownRemark(filter: { collection: { eq: \"posts\" } }) {\n edges {\n node {\n id\n collection\n }\n }\n }\n}\n```\n\n```text\ngatsby-config\n```\n\n```text\nsrc/projects\n```\n\n```text\nscr/blog-posts\n```\n\n```text\ngatsby-node\n```\n\n```text\ngatsby-node\n```\n\n```text\ncreateNodeField\n```\n\n```text\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/posts`,\n name: 'post',\n },\n},\n```\n\n```text\nexports.onCreateNode = ({ node, actions, getNode }) => {\n const { createNodeField } = actions\n if (node.internal.type === `MarkdownRemark` || node.internal.type === `Mdx`) {\n createNodeField({\n name: `collection`,\n node,\n value: getNode(node.parent).sourceInstanceName\n });\n })\n};\n```\n\n```text\nquery {\n allMdx(filter: { fields: { collection: { eq: \"post\"}}}) {\n edges {\n node {\n fields {\n collection\n }\n frontmatter {\n title\n }\n }\n }\n }\n}\n```\n\n```text\nMarkdownRemark\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":315,"estimatedTokens":1483}}441{"id":"stack-72471939","source":"stackoverflow","questionId":72471939,"title":"@UseGuards for @ResolveField in NestJS GraphQL","tags":["graphql","nestjs"],"text":"Title: @UseGuards for @ResolveField in NestJS GraphQL\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI want to use @UseGuards functionality for a @ResolveField, because I want the main query to be public, but specific things to be visible only for specific users.\nI don't want to use another query or another type of guard.\n\n========================================\n\nCode:\n```text\nGraphQLModule.forRoot({\n fieldResolverEnhancers: ['guards'],\n ...\n}\n```\n\n========================================\n\nComments:\n- Thanks! It helped a lot, another thing is should I use another custom guard or my current authGuard throwing unauthorised is good enough?","metadata":{"transformedAt":"2026-08-18T18:32:36.057Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":22,"estimatedTokens":164}}442{"id":"stack-46809066","source":"stackoverflow","questionId":46809066,"title":"Auto-generating a graphql schema for relay (Graphene server)","tags":["reactjs","graphql","relayjs","graphene-python"],"text":"Title: Auto-generating a graphql schema for relay (Graphene server)\nTags: reactjs, graphql, relayjs, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI am new to Relay and am trying to put together my first app. I already have a GraphQL server (using Graphene) that is backed by a PostgreSQL DB via SQLAlchemy automap, and published as a Flask app. Now, I'm trying to put together the front end, and it looks like the relay-compiler is expecting a GraphQL schema file on the client-side. I'm wondering if there is a way to have this schema file be dynamically auto generated, and how that could be set up.\n\nI'm using https://github.com/kriasoft/react-static-boilerplate as the starting point for my app.\n\nThanks.\n\n========================================\n\nTop Answer:\nFor me, https://docs.graphene-python.org/projects/django/en/latest/introspection/ was helpful.\nIn my case schema was defined in the schema.py file of apiApp, and so the command to retrieve schema.json was as following.\n\n```\n./manage.py graphql_schema --schema apiApp.schema.schema --out schema.json\n```\n\n========================================\n\nCode:\n```text\nimport json\nfrom schema import schema\nimport sys\nfrom graphql.utils import schema_printer\n\nmy_schema_str = schema_printer.print_schema(schema)\nfp = open(\"schema.graphql\", \"w\")\nfp.write(my_schema_str)\nfp.close()\n```\n\n```text\n./manage.py graphql_schema --schema apiApp.schema.schema --out schema.json\n```\n\n========================================\n\nComments:\n- How to run this script?","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":44,"estimatedTokens":378}}443{"id":"stack-62636193","source":"stackoverflow","questionId":62636193,"title":"Using multiple mutations in one call","tags":["graphql","shopify"],"text":"Title: Using multiple mutations in one call\nTags: graphql, shopify\nSource: Stack Overflow\n\nQuestion:\nI have written my first script that utilises GraphQL (Still a learning curve)\n\nCurrently i am making 3 calls using GraphQL,\nFirst is a product lookup,\nSecond is a Price Update,\nThird is a Inventory Update.\n\nTo reduce the number of calls to the end point i wanted to merge both Price update and Inventory, But i am having 0 luck, i dont know if its bad formatting.\n\nHere is my GraphQL Code (I am using Postman to help ensure the schema is correct before taking it to PHP)\n\n```\nmutation productVariantUpdate($input: ProductVariantInput!) {\n productVariantUpdate(input: $input) {\n product {\n id\n }\n productVariant {\n id\n price\n }\n userErrors {\n field\n message\n }}\n\n second: inventoryActivate($inventoryItemId: ID!, $locationId: ID!, $available: Int) {\n inventoryActivate(inventoryItemId: $inventoryItemId, locationId: $locationId, available: $available) {\n inventoryLevel {\n id\n available\n }\n userErrors {\n field\n message\n }\n }\n}\n}\n```\n\nVariables:\n\n```\n{\n\"inventoryItemId\": \"gid://shopify/InventoryItem/XXXXXXXXXXX\",\n\"locationId\": \"gid://shopify/Location/XXXXXXXXXX\",\n\"available\": 11 ,\n \"input\": {\n \"id\": \"gid://shopify/ProductVariant/XXXXXXXXX\",\n \"price\": 55\n }\n}\n```\n\nError i keep getting:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Parse error on \\\"$\\\" (VAR_SIGN) at [29, 29]\",\n \"locations\": [\n {\n \"line\": 29,\n \"column\": 29\n }\n ]\n }\n ]\n}\n```\n\n========================================\n\nCode:\n```text\nmutation productVariantUpdate($input: ProductVariantInput!) {\n productVariantUpdate(input: $input) {\n product {\n id\n }\n productVariant {\n id\n price\n }\n userErrors {\n field\n message\n }}\n\n second: inventoryActivate($inventoryItemId: ID!, $locationId: ID!, $available: Int) {\n inventoryActivate(inventoryItemId: $inventoryItemId, locationId: $locationId, available: $available) {\n inventoryLevel {\n id\n available\n }\n userErrors {\n field\n message\n }\n }\n}\n}\n```\n\n```text\n{\n\"inventoryItemId\": \"gid://shopify/InventoryItem/XXXXXXXXXXX\",\n\"locationId\": \"gid://shopify/Location/XXXXXXXXXX\",\n\"available\": 11 ,\n \"input\": {\n \"id\": \"gid://shopify/ProductVariant/XXXXXXXXX\",\n \"price\": 55\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Parse error on \\\"$\\\" (VAR_SIGN) at [29, 29]\",\n \"locations\": [\n {\n \"line\": 29,\n \"column\": 29\n }\n ]\n }\n ]\n}\n```\n\n```text\nmutation batchProductUpdates(\n $input: ProductVariantInput!\n $inventoryItemId: ID!\n $locationId: ID!\n $available: Int\n) {\n \n productVariantUpdate(input: $input) {\n product { id }\n productVariant { id price }\n ...\n }\n \n inventoryActivate(\n inventoryItemId: $inventoryItemId\n locationId: $locationId\n available: $available\n ) {\n inventoryLevel { id available }\n ...\n }\n\n}\n```\n\n```js\nfetch(\"https://example.com/graphql\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n query: `\n mutation MyMutation($firstId: Int, $secondId: Int) {\n m1: ToggleLike(id: $firstId) {\n id\n }\n m2: ToggleLike(id: $secondId) {\n id\n }\n }\n `,\n variables: {\n firstId: 1,\n secondId: 2\n }\n })\n})\n```\n\n```text\nmutation\n```\n\n```text\nProductVariantInput\n```\n\n```text\nfetch\n```\n\n```text\nJavaScript\n```\n\n========================================\n\nComments:\n- Perfect thank you so much, Explains some other messages i was getting with various formatting. Thanks for the example too, makes more sense now.\n- Thanks for the answer, are you able to use a value returned from the first call and use it in the second one?\n- @BradyEdgar youβd have to make 2 separate calls, so if you use `fetch`, you can make your second call inside the `.then` callback and use returned values from the first call.\n- @goto1 OK thanks for the update, I am doing that now, I was just hoping I could squeeze it into one call. Thanks","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":211,"estimatedTokens":1019}}444{"id":"stack-33509643","source":"stackoverflow","questionId":33509643,"title":"Generate schema.json with GraphiQL or GraphQL endpoint","tags":["reactjs","graphql","relayjs","graphql-js"],"text":"Title: Generate schema.json with GraphiQL or GraphQL endpoint\nTags: reactjs, graphql, relayjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm having issues creating a schema.json file that can be parsed with babel-relay-plugin without running into an error. Taking a look at the schema.json file included in relay's example folder, I tried to copy the query in GraphiQL but I can't seem to get it right. I'm using Laravel as the backend. Is this something I can accomplish through GraphiQL or sending a request to the GraphQL endpoint and saving the response?\n\nThe error occurring when attempting to parse the schema.json file:\n\n```\nCannot read property 'reduce' of undefined while parsing file: /Users/username/Sites/Homestead/Code/ineedmg-graphql/resources/assets/js/app.js\n```\n\nLast attempt using GraphiQL:\n\n```\n{\n __schema {\n queryType { \n name\n },\n types {\n kind,\n name,\n description,\n fields {\n name,\n description,\n type {\n name,\n kind,\n ofType {\n name\n description\n }\n }\n isDeprecated,\n deprecationReason,\n },\n inputFields {\n name\n description\n }\n interfaces {\n kind\n name\n description\n },\n enumValues {\n name\n description\n isDeprecated\n deprecationReason\n }\n },\n mutationType { \n name\n },\n directives {\n name,\n description,\n onOperation,\n onFragment,\n onField,\n args {\n name\n description\n defaultValue\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nCannot read property 'reduce' of undefined while parsing file: /Users/username/Sites/Homestead/Code/ineedmg-graphql/resources/assets/js/app.js\n```\n\n```text\n{\n __schema {\n queryType { \n name\n },\n types {\n kind,\n name,\n description,\n fields {\n name,\n description,\n type {\n name,\n kind,\n ofType {\n name\n description\n }\n }\n isDeprecated,\n deprecationReason,\n },\n inputFields {\n name\n description\n }\n interfaces {\n kind\n name\n description\n },\n enumValues {\n name\n description\n isDeprecated\n deprecationReason\n }\n },\n mutationType { \n name\n },\n directives {\n name,\n description,\n onOperation,\n onFragment,\n onField,\n args {\n name\n description\n defaultValue\n }\n }\n }\n}\n```\n\n```text\nschema.json\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":143,"estimatedTokens":611}}445{"id":"stack-40743273","source":"stackoverflow","questionId":40743273,"title":"GitHub GraphQL API Problems parsing JSON","tags":["python","python-requests","github-api","graphql"],"text":"Title: GitHub GraphQL API Problems parsing JSON\nTags: python, python-requests, github-api, graphql\nSource: Stack Overflow\n\nQuestion:\nWhat is wrong here?\n\n```\nquery='{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }'\n\nheaders = {'Authorization': 'token xxx'}\n\nr2=requests.post('https://api.github.com/graphql', '{\"query\": \\\"'+query+'\\\"}',headers=headers)\n\nprint (r2.json())\n```\n\nI've got\n\n```\n{'message': 'Problems parsing JSON', 'documentation_url': 'https://developer.github.com/v3'}\n```\n\nbut this snippet of code below works correctly\n\n```\nquery1= '''{ viewer { login name } }''' \n\nheaders = {'Authorization': 'token xxx'} \n\nr2=requests.post('https://api.github.com/graphql', '{\"query\": \\\"'+query1+'\\\"}',headers=headers) \n\nprint (r2.json())\n```\n\nI've tried out to change quotes (from \" into ' or with \" and so on) but it doesn't work.\n\n========================================\n\nCode:\n```text\nquery='{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }'\n\nheaders = {'Authorization': 'token xxx'}\n\nr2=requests.post('https://api.github.com/graphql', '{\"query\": \\\"'+query+'\\\"}',headers=headers)\n\nprint (r2.json())\n```\n\n```text\n{'message': 'Problems parsing JSON', 'documentation_url': 'https://developer.github.com/v3'}\n```\n\n```text\nquery1= '''{ viewer { login name } }''' \n\nheaders = {'Authorization': 'token xxx'} \n\nr2=requests.post('https://api.github.com/graphql', '{\"query\": \\\"'+query1+'\\\"}',headers=headers) \n\nprint (r2.json())\n```\n\n```text\n{\"query\": \"{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }\"}\n```\n\n```text\n{\"query\": \"{ viewer { login name } }\"}\n```\n\n```text\nimport json\n\nquery='{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }'\nheaders = {'Authorization': 'token xxx'}\n\nr2=requests.post('https://api.github.com/graphql', json.dumps({\"query\": query}), headers=headers)\n\nprint (r2.json())\n```\n\n```text\nquery='{ repositoryOwner(login : \\\"ALEXSSS\\\") { login repositories (first : 30){ edges { node { name } } } } }'\nheaders = {'Authorization': 'token xxx'}\n\nr2=requests.post('https://api.github.com/graphql', '{\"query\": \"'+query1+'\"}', headers=headers)\n\nprint (r2.json())\n```\n\n```text\n'{\"query\": \\\"'+query+'\\\"}'\n```\n\n```text\n\"ALEXSSS\"\n```\n\n========================================\n\nComments:\n- why then the second code snippet work correctly in my example?\n- Updated the original answer to include the explanation.\n- @AdrianoMartins can please have a look at this question [stackoverflow.com/questions/42063825/…","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":106,"estimatedTokens":660}}446{"id":"stack-49344444","source":"stackoverflow","questionId":49344444,"title":"Github GraphQL Search with Filtering","tags":["search","github","graphql","github-api","github-graphql"],"text":"Title: Github GraphQL Search with Filtering\nTags: search, github, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nBased on my limited searching, it seems GraphQL can only support equal filtering. So, \n\nIs it possible to do Github GraphQL searching with the filtering conditions of, \n\n- stars > 10\n\n- forks > 3\n\n- total commit >= 5\n\n- total issues >= 1\n\n- open issues 2k\n\n- score > 5\n\n- last update is within a year\n\nI.e., filtering will *all* above conditions. Is it possible?\n\n========================================\n\nTop Answer:\nThis is not an answer but an update of what I've collected so far. \n\nAccording to \"Select * for Github GraphQL Search\", not all above criteria might be available in the Repository edge. Namely, the \"total commit\", \"open issues\" and \"score\" might not be available. \n\nThe purpose of the question is obviously to find the valuable repositories and weed off the lower-quality ones. I've **collected** all the available fields that might be helpful for such assessment here. \n\nA copy of it as of 2018-03-18:\n\n```\nquery SearchMostTop10Star($queryString: String!, $number_of_repos:Int!) {\n search(query: $queryString, type: REPOSITORY, first: $number_of_repos) {\n repositoryCount\n edges {\n node {\n ... on Repository {\n name\n url\n description\n# shortDescriptionHTML\n repositoryTopics(first: 12) {nodes {topic {name}}}\n primaryLanguage {name}\n languages(first: 3) { nodes {name} }\n releases {totalCount}\n forkCount\n pullRequests {totalCount}\n stargazers {totalCount}\n issues {totalCount}\n createdAt\n pushedAt\n updatedAt\n }\n }\n }\n }\n}\nvariables {\n \"queryString\": \"language:JavaScript stars:>10000\", \n \"number_of_repos\": 3 \n}\n```\n\nAnyone can try it out as per here.\n\n========================================\n\nCode:\n```text\nquery {\n search(\n type:REPOSITORY, \n query: \"\"\"\n stars:>10\n forks:>3\n size:>2000\n pushed:>=2018-08-08\n \"\"\",\n last: 100\n ) {\n repos: edges {\n repo: node {\n ... on Repository {\n url\n\n allIssues: issues {\n totalCount\n }\n openIssues: issues(states:OPEN) {\n totalCount\n }\n\n # commitsCount: object(expression: \"master\") {\n # ... on Commit {\n # history {\n # totalCount\n # }\n # }\n # }\n }\n }\n }\n }\n}\n```\n\n```text\nquery SearchMostTop10Star($queryString: String!, $number_of_repos:Int!) {\n search(query: $queryString, type: REPOSITORY, first: $number_of_repos) {\n repositoryCount\n edges {\n node {\n ... on Repository {\n name\n url\n description\n# shortDescriptionHTML\n repositoryTopics(first: 12) {nodes {topic {name}}}\n primaryLanguage {name}\n languages(first: 3) { nodes {name} }\n releases {totalCount}\n forkCount\n pullRequests {totalCount}\n stargazers {totalCount}\n issues {totalCount}\n createdAt\n pushedAt\n updatedAt\n }\n }\n }\n }\n}\nvariables {\n \"queryString\": \"language:JavaScript stars:>10000\", \n \"number_of_repos\": 3 \n}\n```\n\n========================================\n\nComments:\n- This Q/A helped me find a better Github search approach, FYI.\n- fwiw, there's a filter that you can apply to the issues field to fetch only open issues: `issues(states:[OPEN])`\n- thanks @DanielRearden, I've updated my gist\n- Terrific! Thanks!!","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":152,"estimatedTokens":866}}447{"id":"stack-59021384","source":"stackoverflow","questionId":59021384,"title":"How to pass cookie from apollo-server to apollo-clenet","tags":["node.js","cookies","graphql","react-apollo","apollo-server"],"text":"Title: How to pass cookie from apollo-server to apollo-clenet\nTags: node.js, cookies, graphql, react-apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\n**Mutation**\n\n```\nMutation: {\n signUp: (_, { res }) => {\n try {\n res.cookie(\"jwt\", \"token\", {\n httpOnly: true\n });\n return \"Amasia\";\n } catch (error) {\n return \"error\";\n }\n };\n}\n```\n\n**Apollo-clenet-react**\n\n```\nconst [addTodo, { loading, error, data }] = useMutation(gql);\n\n const [formSignUp, setFormSignUp] = useState({\n lastName: '',\n firstName: '',\n password: '',\n email: '',\n });\n\n const change = e => {\n const { value, name } = e.target;\n setFormSignUp({ ...formSignUp, [name]: value });\n };\n```\n\nWhen i make a request from react.\nHere is the answer I get from the server.\n\n1)**Data** `{\"data\": {\"signUp\": \"Amasia\"}}`\n\n2) **Network**https://i.sstatic.net/T2Gzf.png\n\n**Application**\n\nWell when I look in Application Cookies, it is empty.\nhttps://i.sstatic.net/T9zem.png\n\nWhat am I doing wrong Why are cookies empty?\n\n========================================\n\nCode:\n```text\nMutation: {\n signUp: (_, { res }) => {\n try {\n res.cookie(\"jwt\", \"token\", {\n httpOnly: true\n });\n return \"Amasia\";\n } catch (error) {\n return \"error\";\n }\n };\n}\n```\n\n```text\nconst [addTodo, { loading, error, data }] = useMutation(gql);\n\n const [formSignUp, setFormSignUp] = useState({\n lastName: '',\n firstName: '',\n password: '',\n email: '',\n });\n\n const change = e => {\n const { value, name } = e.target;\n setFormSignUp({ ...formSignUp, [name]: value });\n };\n```\n\n```text\n{\"data\": {\"signUp\": \"Amasia\"}}\n```\n\n```text\nimport { render } from 'react-dom';\nimport React, { Suspense } from 'react';\nimport { ApolloClient } from 'apollo-client'\nimport { ApolloProvider } from 'react-apollo';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { createHttpLink } from 'apollo-link-http';\nimport './i18n';\n\nimport Loading from './component/loading';\nimport RouteProj from './router';\n\nconst link = createHttpLink({\n uri: 'http://localhost:8000/graphql',\n credentials: 'include'\n});\n\nconst client = new ApolloClient({\n cache: new InMemoryCache(),\n link,\n});\n\n\nrender(\n <ApolloProvider client={client}>\n <Suspense fallback={<Loading />}>\n <RouteProj/>\n </Suspense>\n </ApolloProvider>,\n document.getElementById('root'),\n);\n```\n\n```text\nimport cors from \"cors\";\nimport express from \"express\";\nimport { ApolloServer } from \"apollo-server-express\";\nimport mongoose from \"mongoose\";\n\nimport schema from \"./schema\";\nimport resolvers from \"./resolvers\";\nimport models from \"./models\";\n\n const app = express();\n\n var corsOptions = {\n origin: \"http://localhost:3000\",\n credentials: true\n };\n app.use(cors(corsOptions));\n\n const server = new ApolloServer({\n typeDefs: schema,\n resolvers,\n context: ({ res }) => ({\n res\n })\n });\n\n server.applyMiddleware({ app, path: \"/graphql\", cors: false });\n app.listen({ port: 8000 });\n```\n\n========================================\n\nComments:\n- Thanks so much!!! I've been trying to figure this one out for 2 days...","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":159,"estimatedTokens":773}}448{"id":"stack-65935113","source":"stackoverflow","questionId":65935113,"title":"getting requested fields on resolver level from graphql","tags":["graphql","graphql-java","graphql-java-tools"],"text":"Title: getting requested fields on resolver level from graphql\nTags: graphql, graphql-java, graphql-java-tools\nSource: Stack Overflow\n\nQuestion:\nModel of book from graphql schema\n\n```\ntype Book {\n id: ID\n name: String\n pageCount: Int\n author: Author\n}\n```\n\nSo I am having this resolver for Book\n\n```\npublic class BookResolver implements BookByIdQueryResolver, GraphQLQueryResolver {\n private final MockRepository mockRepository;\n\n public BookResolver(MockRepository mockRepository) {\n this.mockRepository = mockRepository;\n }\n\n @Override\n public BookTO bookById(String id) {\n return mockRepository.getBookById(id);\n }\n}\n```\n\nIt works fine.\n\nNow lets assume that I am using this graphql query, which is requesting only one field of the Book\n\n```\n{\n bookById(id: \"someId\") {\n name\n }\n}\n```\n\nThe question is, how to get info on the bookById method level about the fields which are requested (in this case only the name field)? Is this even possible with the GraphQLQueryResolver concept?\n\nExample with dataFetcher\n\n```\npublic DataFetcher getBookByIdDataFetcher() {\n return dataFetchingEnvironment -> {\n String bookId = dataFetchingEnvironment.getArgument(\"id\");\n List requestedFields = dataFetchingEnvironment.getSelectionSet()\n .getFields()\n .stream()\n .collect(Collectors.toList());\n return books\n .stream()\n .filter(book -> book.get(\"id\").equals(bookId))\n .findFirst()\n .orElse(null);\n };\n }\n```\n\nThis works quite well, but I am interested in the Resolver way. Is it possible?\n\n========================================\n\nTop Answer:\nI tried the solution posted by Mat G, but it didn't work for me. What worked for me is this:\n\n```\npublic BookTO bookById(String id, DataFetchingEnvironment env) throws Exception {\n \n List arguments = env.getField()\n .getSelectionSet()\n .getSelections()\n .parallelStream()\n .map(Field.class::cast)\n .map(Field::getName)\n .collect(Collectors.toList());\n \n // Query using the arguments\n return this.someService.getbookById(id, arguments);\n }\n```\n\n========================================\n\nCode:\n```text\ntype Book {\n id: ID\n name: String\n pageCount: Int\n author: Author\n}\n```\n\n```java\npublic class BookResolver implements BookByIdQueryResolver, GraphQLQueryResolver {\n private final MockRepository mockRepository;\n\n public BookResolver(MockRepository mockRepository) {\n this.mockRepository = mockRepository;\n }\n\n @Override\n public BookTO bookById(String id) {\n return mockRepository.getBookById(id);\n }\n}\n```\n\n```text\n{\n bookById(id: \"someId\") {\n name\n }\n}\n```\n\n```java\npublic DataFetcher getBookByIdDataFetcher() {\n return dataFetchingEnvironment -> {\n String bookId = dataFetchingEnvironment.getArgument(\"id\");\n List<SelectedField> requestedFields = dataFetchingEnvironment.getSelectionSet()\n .getFields()\n .stream()\n .collect(Collectors.toList());\n return books\n .stream()\n .filter(book -> book.get(\"id\").equals(bookId))\n .findFirst()\n .orElse(null);\n };\n }\n```\n\n```text\npublic BookTO bookById(String id, DataFetchingEnvironment dataFetchingEnvironment) {\n\n List<SelectedField> requestedFields = dataFetchingEnvironment.getSelectionSet()\n .getFields()\n .stream()\n .collect(Collectors.toList());\n // Use this for your use cases\n\n\n return mockRepository.getBookById(id);\n}\n```\n\n```text\npublic BookTO bookById(String id, DataFetchingEnvironment env) throws Exception {\n \n List<String> arguments = env.getField()\n .getSelectionSet()\n .getSelections()\n .parallelStream()\n .map(Field.class::cast)\n .map(Field::getName)\n .collect(Collectors.toList());\n \n // Query using the arguments\n return this.someService.getbookById(id, arguments);\n }\n```\n\n========================================\n\nComments:\n- Can you explain your requirement more?\n- added some more details, the thing is that in the resolver I am getting only the parameters info (id in this case) by which I am looking for the book. The thing I want to achieve it that I want to be able to check which fields from book are requested in query\n- Did you check this? stackoverflow.com/questions/48004805/…\n- this is a js solution, I am looking for a solution in java and with specific approach mentioned\n- *'Each DataFetcher is passed a graphql.schema.DataFetchingEnvironment object which contains what field is being fetched, what arguments have been supplied to the field and other information such as the fieldβs parent object, the query root object or the query context object.'*\n- The other question is how to select only the requested fields with JPA. By default it selects all the columns.\n- wow, did not expect that it would be this easy, will check that\n- tested it, works perfectly, no idea why this is not mentioned in any resolver examples which I was looking for thans!","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":182,"estimatedTokens":1267}}449{"id":"stack-60104547","source":"stackoverflow","questionId":60104547,"title":"What is type \"StringQueryOperatorInput\"? How can I get rid of this annoying graphql error?","tags":["javascript","node.js","graphql","gatsby"],"text":"Title: What is type \"StringQueryOperatorInput\"? How can I get rid of this annoying graphql error?\nTags: javascript, node.js, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI am attempting to create Gatsby pages programmatically using the Gatsby API createPages and data from Firebase. I've set up everything successfully up to the point where Firebase data is accessible via GraphQL and now I want to query specifict data for each of the new pages that were created using id (which are in string format). However, when I create the template component and try to query the data i get this error: \n\n```\nVariable \"$clientId\" of type \"String!\" used in position expecting type \"StringQueryOperatorInput\".\n```\n\nI have looked everywhere for a reference of this **StringQueryOperatorInput** and can't find any info on it. Google and graphql docs don't seem to mention the term and this is my first time seeing it. After troubleshooting for an hour I got a different error: \n\n```\nIf you're e.g. filtering for specific nodes make sure that you choose the correct field (that has the same type \"String!\") or adjust the context variable to the type \"StringQueryOperatorInput\".\nFile: src/templates/Homeowner/Homeowner.js:24:9\n```\n\nHowever, I still don't know what a StringQueryOperatorInput is or how to fix this. \nBelow is my code for this component and my gatsby-node.js, and my gatsby-config.js where i use a plugin to source the Firebase data. \nI could really use some help on this, I can't seem to find any reference of this StringQueryOperatorInput. \nEverything else works fine, I just can't get this query on the Homeowner.js template to work. \n\n**gatsby-node.js**\n\n```\nexports.createPages = async ({ graphql, actions }) => {\n const { createPage } = actions;\n const result = await graphql(`\n query {\n allClients {\n nodes {\n firstName\n lastName\n id\n }\n }\n }\n `);\n console.log(JSON.stringify(result, null, 4));\n result.data.allClients.nodes.forEach(node => {\n const slug = `/client/${node.id}`;\n createPage({\n path: slug,\n component: require.resolve(`./src/templates/Homeowner/Homeowner.js`),\n context: { clientId: node.id },\n });\n });\n};\n```\n\n**src/templates/Homeowner/Homeowner.js**\n\n```\nimport React from 'react';\nimport { graphql } from 'gatsby';\nimport { withFirebase } from '../../components/Firebase';\nimport { withStyles } from '@material-ui/core/styles';\nimport Layout from '../../components/layout';\n\nconst Homeowner = ({ data }) => {\n console.log(data.clients, 'data');\n return (\n <>\n \n \n\n### Home Owner Component\n\n {/* \n\n### {client.firstName}\n\n \n\n### {client.lastName}\n\n \n\n### {client.email}\n\n */}\n \n \n );\n};\n\nexport default Homeowner;\n\nexport const query = graphql`\n query($clientId: String!) {\n clients(id: $clientId) {\n firstName\n lastName\n email\n }\n }\n`;\n```\n\n**gatsby-config.js**\n\n```\nrequire('dotenv').config({\n path: `.env.${process.env.NODE_ENV}`,\n});\nmodule.exports = {\n siteMetadata: {\n title: `SiteTitle`,\n siteUrl: `https://www.mysitwe.com`,\n description: `YourSite`,\n },\n plugins: [\n `gatsby-plugin-react-helmet`,\n `gatsby-plugin-sitemap`,\n `gatsby-plugin-styled-components`,\n `gatsby-plugin-sharp`,\n `gatsby-transformer-sharp`,\n {\n resolve: `gatsby-source-firebase`,\n options: {\n credential: require('./firebase-key.json'),\n databaseURL: 'https://firebaseurl/',\n types: [\n {\n type: 'Clients',\n path: 'clients',\n },\n {\n type: 'Users',\n path: 'users',\n },\n ],\n },\n },\n {\n resolve: `gatsby-plugin-prefetch-google-fonts`,\n options: {\n fonts: [\n {\n family: `Nunito Sans`,\n variants: [`400`, `600`, `800`],\n },\n {\n family: `Montserrat`,\n variants: [`300`, `400`, `400i`, `500`, `600`],\n },\n {\n family: `Spectral`,\n variants: [`400`, `600`, `800`],\n },\n {\n family: `Karla`,\n variants: [`400`, `700`],\n },\n ],\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `images`,\n path: `${__dirname}/src/images`,\n },\n },\n `gatsby-plugin-offline`,\n ],\n};\n```\n\nTHank you in advance if anyone can help me out.\n\n========================================\n\nTop Answer:\nActually **literally** right after I posted this question I found the solution. I needed to set up my query like so: \n\n```\nexport const query = graphql`\n query($clientId: String!) {\n clients(id: { eq: $clientId }) {\n firstName\n lastName\n email\n }\n }\n`;\n```\n\nI assume that leaving out the {eq: $clientId} throws that StringQuery error on the GraphQL side. I still do not know what a **StringQueryOperatorInput** is, however, I have successfully generated the pages with the data from firebase.\n\n========================================\n\nCode:\n```text\nVariable \"$clientId\" of type \"String!\" used in position expecting type \"StringQueryOperatorInput\".\n```\n\n```text\nIf you're e.g. filtering for specific nodes make sure that you choose the correct field (that has the same type \"String!\") or adjust the context variable to the type \"StringQueryOperatorInput\".\nFile: src/templates/Homeowner/Homeowner.js:24:9\n```\n\n```text\nexports.createPages = async ({ graphql, actions }) => {\n const { createPage } = actions;\n const result = await graphql(`\n query {\n allClients {\n nodes {\n firstName\n lastName\n id\n }\n }\n }\n `);\n console.log(JSON.stringify(result, null, 4));\n result.data.allClients.nodes.forEach(node => {\n const slug = `/client/${node.id}`;\n createPage({\n path: slug,\n component: require.resolve(`./src/templates/Homeowner/Homeowner.js`),\n context: { clientId: node.id },\n });\n });\n};\n```\n\n```text\nimport React from 'react';\nimport { graphql } from 'gatsby';\nimport { withFirebase } from '../../components/Firebase';\nimport { withStyles } from '@material-ui/core/styles';\nimport Layout from '../../components/layout';\n\nconst Homeowner = ({ data }) => {\n console.log(data.clients, 'data');\n return (\n <>\n <Layout>\n <h1>Home Owner Component</h1>\n {/* <h3>{client.firstName}</h3>\n <h3>{client.lastName}</h3>\n <h3>{client.email}</h3> */}\n </Layout>\n </>\n );\n};\n\nexport default Homeowner;\n\nexport const query = graphql`\n query($clientId: String!) {\n clients(id: $clientId) {\n firstName\n lastName\n email\n }\n }\n`;\n```\n\n```text\nrequire('dotenv').config({\n path: `.env.${process.env.NODE_ENV}`,\n});\nmodule.exports = {\n siteMetadata: {\n title: `SiteTitle`,\n siteUrl: `https://www.mysitwe.com`,\n description: `YourSite`,\n },\n plugins: [\n `gatsby-plugin-react-helmet`,\n `gatsby-plugin-sitemap`,\n `gatsby-plugin-styled-components`,\n `gatsby-plugin-sharp`,\n `gatsby-transformer-sharp`,\n {\n resolve: `gatsby-source-firebase`,\n options: {\n credential: require('./firebase-key.json'),\n databaseURL: 'https://firebaseurl/',\n types: [\n {\n type: 'Clients',\n path: 'clients',\n },\n {\n type: 'Users',\n path: 'users',\n },\n ],\n },\n },\n {\n resolve: `gatsby-plugin-prefetch-google-fonts`,\n options: {\n fonts: [\n {\n family: `Nunito Sans`,\n variants: [`400`, `600`, `800`],\n },\n {\n family: `Montserrat`,\n variants: [`300`, `400`, `400i`, `500`, `600`],\n },\n {\n family: `Spectral`,\n variants: [`400`, `600`, `800`],\n },\n {\n family: `Karla`,\n variants: [`400`, `700`],\n },\n ],\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `images`,\n path: `${__dirname}/src/images`,\n },\n },\n `gatsby-plugin-offline`,\n ],\n};\n```\n\n```text\nStringQueryOperatorInput\n```\n\n```text\nid\n```\n\n```text\nclients\n```\n\n```text\nString\n```\n\n```text\nID\n```\n\n```text\nInt\n```\n\n```text\nStringQueryOperatorInput\n```\n\n```text\neq\n```\n\n```text\nne\n```\n\n```text\nregex\n```\n\n```text\nin\n```\n\n```text\ngt\n```\n\n```text\nregex\n```\n\n```text\nString\n```\n\n```text\nlte\n```\n\n```text\nIntQueryOperatorInput\n```\n\n```text\nBooleanQueryOperatorInput\n```\n\n```text\nexport const query = graphql`\n query($clientId: String!) {\n clients(id: { eq: $clientId }) {\n firstName\n lastName\n email\n }\n }\n`;\n```\n\n========================================\n\nComments:\n- So... worth deleting your question then? If you found it immediately, it's reasonable to assume others will, too.\n- Idk if it's worth deleting, because when I originally searched the term StringQueryOperatorInput, i couldn't find any specific reference or definition. So i think it would be nice to leave this up so others can see Daniel's answer above.\n- Yes! Don't delete! You may have been able to find the answer quickly but that doesn't mean others will. I ran into this issue as well and if it weren't for this answer I would still be confused about why my query wasn't working.\n- @Mike'Pomax'Kamermans same here, glad i found this post as it helped me. i don't understand your condescending comment.\n- No condescension, that is how SO works: if the answer is something you were about find yourself literally immediately after posting, then holding off with posting for literally a few minutes would have made posting not even necessary because it's a problem that has a solution that can already be found as easily as it is to post. In those cases, you should always ask yourself whether that means you should just delete the question again. Sometimes the answer is no. Often it's yes.\n- Also glad you didn't delete. Mike, sometimes people search for hours prior to posting a question on SO. It's unreasonable to assume what you state.\n- It is perplexing for new users, because the very first example in the GraphQL standard's query docs (adapted for one'ss schema) throws this error when working with GraphiQL and Gatsby.","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":421,"estimatedTokens":2441}}450{"id":"stack-62502579","source":"stackoverflow","questionId":62502579,"title":"AppSync subscriptions with ApolloClient in React","tags":["reactjs","graphql","apollo-client","aws-appsync"],"text":"Title: AppSync subscriptions with ApolloClient in React\nTags: reactjs, graphql, apollo-client, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI'm currently using ApolloClient to connect to an AppSync GraphQL API. It all works perfectly for queries and mutations, but I'm having some trouble getting subscriptions to work. I've followed the Apollo docs and my App.js looks like this:\n\n```\nimport React from 'react';\nimport './App.css';\nimport { ApolloClient } from 'apollo-client';\nimport { ApolloProvider } from '@apollo/react-hooks';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { ApolloLink, split } from 'apollo-link';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { getMainDefinition } from 'apollo-utilities';\nimport { createAuthLink } from 'aws-appsync-auth-link';\nimport { createHttpLink } from 'apollo-link-http';\nimport AWSAppSyncClient, { AUTH_TYPE } from \"aws-appsync\";\nimport { useSubscription } from '@apollo/react-hooks';\nimport { gql } from 'apollo-boost';\n\nconst url = \"https://xxx.appsync-api.eu-west-2.amazonaws.com/graphql\"\nconst realtime_url = \"wss://xxx.appsync-realtime-api.eu-west-2.amazonaws.com/graphql\"\nconst region = \"eu-west-2\";\nconst auth = {\n type: AUTH_TYPE.API_KEY,\n apiKey: process.env.REACT_APP_API_KEY\n};\n\nconst wsLink = new WebSocketLink({\n uri: realtime_url,\n options: {\n reconnect: true\n },\n});\n\nconst link = split(\n // split based on operation type\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n ApolloLink.from([\n createAuthLink({ realtime_url, region, auth }), \n wsLink\n ]),\n ApolloLink.from([\n createAuthLink({ url, region, auth }), \n createHttpLink({ uri: url })\n ])\n);\n\nconst client = new ApolloClient({\n link: link,\n cache: new InMemoryCache({\n dataIdFromObject: object => object.id,\n }),\n});\n\nfunction Page() {\n const { loading, error, data } = useSubscription(\n gql`\n subscription questionReleased {\n questionReleased {\n id\n released_date\n }\n }\n `\n )\n\n if (loading) return Loading...\n if (error) return Error!\n if (data) console.log(data)\n\n return (\n {data}\n );\n}\n\nfunction App() {\n return (\n \n \n \n \n \n );\n}\n\nexport default App;\n```\n\nIf I go to the network tab in web inspector, I can see the request:\n\n`wss://xxx.appsync-realtime-api.eu-west-2.amazonaws.com/graphql`\n\nAnd the messages:\n\n```\n{\"type\":\"connection_init\",\"payload\":{}}\n{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{},\"extensions\":{},\"operationName\":\"questionReleased\",\"query\":\"subscription questionReleased {\\n questionReleased {\\n id\\n released_date\\n __typename\\n }\\n}\\n\"}}\n{\"id\":\"2\",\"type\":\"start\",\"payload\":{\"variables\":{},\"extensions\":{},\"operationName\":\"questionReleased\",\"query\":\"subscription questionReleased {\\n questionReleased {\\n id\\n released_date\\n __typename\\n }\\n}\\n\"}}\n{\"payload\":{\"errors\":[{\"message\":\"Both, the \\\"header\\\", and the \\\"payload\\\" query string parameters are missing\",\"errorCode\":400}]},\"type\":\"connection_error\"}\n```\n\nI've searched around a lot and it seems that ApolloClient may not be compatible with AppSync subscriptions - is anybody able to confirm this?\n\nSo as an alternative I've tried to use `AWSAppSyncClient` for subscriptions:\n\n```\nfunction Page() {\n const aws_client = new AWSAppSyncClient({\n region: \"eu-west-2\",\n url: realtime_url,\n auth: {\n type: AUTH_TYPE.API_KEY,\n apiKey: process.env.REACT_APP_API_KEY\n },\n disableOffline: true\n });\n\n const { loading, error, data } = useSubscription(\n gql`\n subscription questionReleased {\n questionReleased {\n id\n released_date\n }\n }\n `,\n {client: aws_client}\n )\n\n if (loading) return Loading...\n if (error) return Error!\n if (data) console.log(data)\n\n return (\n {data}\n );\n}\n```\n\nIt now sends querystrings with the request:\n\n`wss://xxx.appsync-realtime-api.eu-west-2.amazonaws.com/graphql?header=eyJob3N0I...&payload=e30=`\n\nAnd I now get a different error:\n\n```\n{\"type\":\"connection_init\"}\n{\"payload\":{\"errors\":[{\"errorType\":\"HttpNotFoundException\"}]},\"type\":\"connection_error\"}\n```\n\nI've double checked the url and it's ok (if it's not you get `ERR_NAME_NOT_RESOLVED`). The subscription works when I run it manually through the AppSync console, so that should also be ok.\n\nI've also tried `.hydrated()` on the `aws_client` but get another error (`TypeError: this.refreshClient(...).client.subscribe is not a function`)\n\nWhat am I doing wrong? This has been driving me nuts for a few days!\n\n========================================\n\nTop Answer:\nIt would help you https://gist.github.com/wellitongervickas/087fb0d0550c429aae4500e4e4e9f624\n\nlibrary is not implement the payload data properly, just take a look around the following code:\n\n\r\n\r\n\n```\nObject.assign(operation, {\n data: JSON.stringify({\n query: operation.query.loc?.source.body,\n variables: operation.variables\n })\n })\n```\n\n\r\n\r\n\r\n\nit will include your missing props\n\n========================================\n\nCode:\n```text\nimport React from 'react';\nimport './App.css';\nimport { ApolloClient } from 'apollo-client';\nimport { ApolloProvider } from '@apollo/react-hooks';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { ApolloLink, split } from 'apollo-link';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { getMainDefinition } from 'apollo-utilities';\nimport { createAuthLink } from 'aws-appsync-auth-link';\nimport { createHttpLink } from 'apollo-link-http';\nimport AWSAppSyncClient, { AUTH_TYPE } from \"aws-appsync\";\nimport { useSubscription } from '@apollo/react-hooks';\nimport { gql } from 'apollo-boost';\n\nconst url = \"https://xxx.appsync-api.eu-west-2.amazonaws.com/graphql\"\nconst realtime_url = \"wss://xxx.appsync-realtime-api.eu-west-2.amazonaws.com/graphql\"\nconst region = \"eu-west-2\";\nconst auth = {\n type: AUTH_TYPE.API_KEY,\n apiKey: process.env.REACT_APP_API_KEY\n};\n\nconst wsLink = new WebSocketLink({\n uri: realtime_url,\n options: {\n reconnect: true\n },\n});\n\nconst link = split(\n // split based on operation type\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n ApolloLink.from([\n createAuthLink({ realtime_url, region, auth }), \n wsLink\n ]),\n ApolloLink.from([\n createAuthLink({ url, region, auth }), \n createHttpLink({ uri: url })\n ])\n);\n\nconst client = new ApolloClient({\n link: link,\n cache: new InMemoryCache({\n dataIdFromObject: object => object.id,\n }),\n});\n\nfunction Page() {\n const { loading, error, data } = useSubscription(\n gql`\n subscription questionReleased {\n questionReleased {\n id\n released_date\n }\n }\n `\n )\n\n if (loading) return <span>Loading...</span>\n if (error) return <span>Error!</span>\n if (data) console.log(data)\n\n return (\n <div>{data}</div>\n );\n}\n\nfunction App() {\n return (\n <ApolloProvider client={client}>\n <div className=\"App\">\n <Page />\n </div>\n </ApolloProvider>\n );\n}\n\nexport default App;\n```\n\n```text\n{\"type\":\"connection_init\",\"payload\":{}}\n{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{},\"extensions\":{},\"operationName\":\"questionReleased\",\"query\":\"subscription questionReleased {\\n questionReleased {\\n id\\n released_date\\n __typename\\n }\\n}\\n\"}}\n{\"id\":\"2\",\"type\":\"start\",\"payload\":{\"variables\":{},\"extensions\":{},\"operationName\":\"questionReleased\",\"query\":\"subscription questionReleased {\\n questionReleased {\\n id\\n released_date\\n __typename\\n }\\n}\\n\"}}\n{\"payload\":{\"errors\":[{\"message\":\"Both, the \\\"header\\\", and the \\\"payload\\\" query string parameters are missing\",\"errorCode\":400}]},\"type\":\"connection_error\"}\n```\n\n```text\nfunction Page() {\n const aws_client = new AWSAppSyncClient({\n region: \"eu-west-2\",\n url: realtime_url,\n auth: {\n type: AUTH_TYPE.API_KEY,\n apiKey: process.env.REACT_APP_API_KEY\n },\n disableOffline: true\n });\n\n const { loading, error, data } = useSubscription(\n gql`\n subscription questionReleased {\n questionReleased {\n id\n released_date\n }\n }\n `,\n {client: aws_client}\n )\n\n if (loading) return <span>Loading...</span>\n if (error) return <span>Error!</span>\n if (data) console.log(data)\n\n return (\n <div>{data}</div>\n );\n}\n```\n\n```text\n{\"type\":\"connection_init\"}\n{\"payload\":{\"errors\":[{\"errorType\":\"HttpNotFoundException\"}]},\"type\":\"connection_error\"}\n```\n\n```text\nwss://xxx.appsync-realtime-api.eu-west-2.amazonaws.com/graphql\n```\n\n```text\nAWSAppSyncClient\n```\n\n```text\nwss://xxx.appsync-realtime-api.eu-west-2.amazonaws.com/graphql?header=eyJob3N0I...&payload=e30=\n```\n\n```text\nERR_NAME_NOT_RESOLVED\n```\n\n```text\n.hydrated()\n```\n\n```text\naws_client\n```\n\n```text\nTypeError: this.refreshClient(...).client.subscribe is not a function\n```\n\n```text\nimport { createSubscriptionHandshakeLink } from 'aws-appsync-subscription-link';\nconst httpLink = createHttpLink({ uri: url })\nconst link = ApolloLink.from([\n createAuthLink({ url, region, auth }),\n createSubscriptionHandshakeLink(url, httpLink)\n]);\n```\n\n```text\nAWSAppSyncClient\n```\n\n```text\nuseSubscription\n```\n\n```text\naws_client.subscribe()\n```\n\n```text\nuseSubscription\n```\n\n```js\nObject.assign(operation, {\n data: JSON.stringify({\n query: operation.query.loc?.source.body,\n variables: operation.variables\n })\n })\n```\n\n========================================\n\nComments:\n- This should be updated in 2021 to reflect the deprecation of MQTT support by AppSync. `createSubscriptionHandshakeLink(url, httpLink)` will no longer work and instead, you must use `createSubscriptionHandshakeLink({ url, region, auth })`\n- I don't suppose you ever got this working with apollo v2?\n- Sorry, I'm having the same issue and I didn't quiet get it. Did you end up using AWSAppSyncClient or the link strategy? Could someone present the complete client connection?","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":397,"estimatedTokens":2474}}451{"id":"stack-45258466","source":"stackoverflow","questionId":45258466,"title":"Is GraphQL valid GraphQL+?","tags":["graphql","dgraph"],"text":"Title: Is GraphQL valid GraphQL+?\nTags: graphql, dgraph\nSource: Stack Overflow\n\nQuestion:\nThe following is true:\n\n```\nJavascript == Typescript\nTypescript != Javascript\n```\n\nCan the same be said for Dgraph's GraphQL+?\n\n```\nGraphQL == GraphQL+\nGraphQL+ != GraphQL\n```\n\nThe reason for asking, I understand that GraphQL is not sufficient for Dgraph's goals. But does it process GraphQL if needed?\n\n========================================\n\nTop Answer:\nTo add to Sergio's answer, GraphQL+- is not fully compatible with GraphQL. We liked GraphQL and used that as a basis for a new graph query language. \n\nHowever, I think we would likely look at how big of a gap is between GraphQL+- and GraphQL, and if can be bridged, we would (probably close to or after v1.0).\n\n========================================\n\nCode:\n```text\nJavascript == Typescript\nTypescript != Javascript\n```\n\n```text\nGraphQL == GraphQL+\nGraphQL+ != GraphQL\n```\n\n========================================\n\nComments:\n- \"The following is true\" - bad choice of operators. As it is now, the assertions don't make any sense. Equality is a symmetric operation. If a == b, then b == a.\n- Thanks for the input Manish","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":46,"estimatedTokens":292}}452{"id":"stack-55199380","source":"stackoverflow","questionId":55199380,"title":"GraphQL subscription using server-sent events & EventSource","tags":["graphql","server-sent-events","eventsource"],"text":"Title: GraphQL subscription using server-sent events & EventSource\nTags: graphql, server-sent-events, eventsource\nSource: Stack Overflow\n\nQuestion:\nI'm looking into implementing a \"subscription\" type using server-sent events as the backing api.\n\nWhat I'm struggling with is the interface, to be more precise, the http layer of such operation.\n\n**The problem:**\n\nUsing the native EventSource does not support:\n\n- Specifying an HTTP method, \"GET\" is used by default.\n\n- Including a payload (The GraphQL query)\n\nWhile #1 is irrefutable, #2 can be circumvented using query parameters.\n\nQuery parameters have a limit of ~2000 chars (can be debated)\nwhich makes relying solely on them feels too fragile. \n\nThe solution I'm thinking of is to create a dedicated end-point for each possible event. \n\nFor example: A URI for an event representing a completed transaction between parties:\n\n`/graphql/transaction-status/$ID`\n\nWill translate to this query in the server:\n\n```\nsubscription TransactionStatusSubscription {\n status(id: $ID) {\n ready\n }\n}\n```\n\nThe issues with this approach is:\n\n- Creating a handler for each URI-to-GraphQL translation is to be added.\n\n- Deploy a new version of the server\n\n- **Loss of the flexibility offered by GraphQL -> The client should control the query**\n\n- Keep track of all the end-points in the code base (back-end, front-end, mobile)\n\nThere are probably more issues I'm missing.\n\nIs there perhaps a better approach that you can think of?\nOne the would allow a better approach at providing the request payload using EventSource?\n\n========================================\n\nTop Answer:\nAs of now you have multiple Packages for GraphQL subscription over SSE.\n\n### graphql-sse\n\nProvides both client and server for using GraphQL subscription over SSE. This package has a dedicated handler for subscription.\n\nHere is an example usage with express.\n\n```\nimport express from 'express'; // yarn add express\nimport { createHandler } from 'graphql-sse';\n\n// Create the GraphQL over SSE handler\nconst handler = createHandler({ schema });\n\n// Create an express app serving all methods on `/graphql/stream`\nconst app = express();\napp.use('/graphql/stream', handler);\n\napp.listen(4000);\nconsole.log('Listening to port 4000');\n```\n\n### @graphql-sse/server\n\nProvides a server handler for GraphQL subscription. However, the HTTP handling is up to u depending of the framework you use.\n\n**Disclaimer**: I am the author of the @graphql-sse packages\n\nHere is an example with express.\n\n```\nimport express, { RequestHandler } from \"express\";\nimport {\n getGraphQLParameters,\n processSubscription,\n} from \"@graphql-sse/server\";\nimport { schema } from \"./schema\";\n\nconst app = express();\n\napp.use(express.json());\n\napp.post(path, async (req, res, next) => {\n const request = {\n body: req.body,\n headers: req.headers,\n method: req.method,\n query: req.query,\n };\n\n const { operationName, query, variables } = getGraphQLParameters(request);\n if (!query) {\n return next();\n }\n const result = await processSubscription({\n operationName,\n query,\n variables,\n request: req,\n schema,\n });\n\n if (result.type === RESULT_TYPE.NOT_SUBSCRIPTION) {\n return next();\n } else if (result.type === RESULT_TYPE.ERROR) {\n result.headers.forEach(({ name, value }) => res.setHeader(name, value));\n res.status(result.status);\n res.json(result.payload);\n } else if (result.type === RESULT_TYPE.EVENT_STREAM) {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n Connection: 'keep-alive',\n 'Cache-Control': 'no-cache',\n });\n\n result.subscribe((data) => {\n res.write(`data: ${JSON.stringify(data)}\\n\\n`);\n });\n\n req.on('close', () => {\n result.unsubscribe();\n });\n }\n});\n```\n\n### Clients\n\nThe two packages mentioned above have companion clients. Because of the limitation of the `EventSource` API, both packages implement a custom client that provides options for sending HTTP Headers, payload with post, what the `EvenSource` API does not support. The `graphql-sse` comes together with it client while the `@graphql-sse/server` has companion clients in a separate packages.\n\n### graphql-sse client example\n\n```\nimport { createClient } from 'graphql-sse';\n\nconst client = createClient({\n // singleConnection: true, use \"single connection mode\" instead of the default \"distinct connection mode\"\n url: 'http://localhost:4000/graphql/stream',\n});\n\n// query\n\n const result = await new Promise((resolve, reject) => {\n let result;\n client.subscribe(\n {\n query: '{ hello }',\n },\n {\n next: (data) => (result = data),\n error: reject,\n complete: () => resolve(result),\n },\n );\n });\n\n // subscription\n\n const onNext = () => {\n /* handle incoming values */\n };\n\n let unsubscribe = () => {\n /* complete the subscription */\n };\n\n await new Promise((resolve, reject) => {\n unsubscribe = client.subscribe(\n {\n query: 'subscription { greetings }',\n },\n {\n next: onNext,\n error: reject,\n complete: resolve,\n },\n );\n });\n\n;\n```\n\n### @graphql-sse/client\n\nA companion of the `@graphql-sse/server`.\n\nExample\n\n```\nimport {\n SubscriptionClient,\n SubscriptionClientOptions,\n} from '@graphql-sse/client';\n\nconst subscriptionClient = SubscriptionClient.create({\n graphQlSubscriptionUrl: 'http://some.host/graphl/subscriptions'\n});\n\nconst subscription = subscriptionClient.subscribe(\n {\n query: 'subscription { greetings }',\n }\n)\n\nconst onNext = () => {\n /* handle incoming values */\n };\n\nconst onError = () => {\n /* handle incoming errors */\n };\n\nsubscription.susbscribe(onNext, onError)\n```\n\n### @gaphql-sse/apollo-client\n\nA companion package of the `@graph-sse/server` package for Apollo Client.\n\n```\nimport { split, HttpLink, ApolloClient, InMemoryCache } from '@apollo/client';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { ServerSentEventsLink } from '@graphql-sse/apollo-client';\n\nconst httpLink = new HttpLink({\n uri: 'http://localhost:4000/graphql',\n});\n\nconst sseLink = new ServerSentEventsLink({\n graphQlSubscriptionUrl: 'http://localhost:4000/graphql',\n});\n\nconst splitLink = split(\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n sseLink,\n httpLink\n);\n\nexport const client = new ApolloClient({\n link: splitLink,\n cache: new InMemoryCache(),\n});\n```\n\n========================================\n\nCode:\n```text\nsubscription TransactionStatusSubscription {\n status(id: $ID) {\n ready\n }\n}\n```\n\n```text\n/graphql/transaction-status/$ID\n```\n\n```text\nsubscribe\n```\n\n```text\nEventSource\n```\n\n```text\n/graphql-sse\n```\n\n```js\nimport express from 'express'; // yarn add express\nimport { createHandler } from 'graphql-sse';\n\n// Create the GraphQL over SSE handler\nconst handler = createHandler({ schema });\n\n// Create an express app serving all methods on `/graphql/stream`\nconst app = express();\napp.use('/graphql/stream', handler);\n\napp.listen(4000);\nconsole.log('Listening to port 4000');\n```\n\n```js\nimport express, { RequestHandler } from \"express\";\nimport {\n getGraphQLParameters,\n processSubscription,\n} from \"@graphql-sse/server\";\nimport { schema } from \"./schema\";\n\nconst app = express();\n\napp.use(express.json());\n\napp.post(path, async (req, res, next) => {\n const request = {\n body: req.body,\n headers: req.headers,\n method: req.method,\n query: req.query,\n };\n\n const { operationName, query, variables } = getGraphQLParameters(request);\n if (!query) {\n return next();\n }\n const result = await processSubscription({\n operationName,\n query,\n variables,\n request: req,\n schema,\n });\n\n if (result.type === RESULT_TYPE.NOT_SUBSCRIPTION) {\n return next();\n } else if (result.type === RESULT_TYPE.ERROR) {\n result.headers.forEach(({ name, value }) => res.setHeader(name, value));\n res.status(result.status);\n res.json(result.payload);\n } else if (result.type === RESULT_TYPE.EVENT_STREAM) {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n Connection: 'keep-alive',\n 'Cache-Control': 'no-cache',\n });\n\n result.subscribe((data) => {\n res.write(`data: ${JSON.stringify(data)}\\n\\n`);\n });\n\n req.on('close', () => {\n result.unsubscribe();\n });\n }\n});\n```\n\n```js\nimport { createClient } from 'graphql-sse';\n\nconst client = createClient({\n // singleConnection: true, use \"single connection mode\" instead of the default \"distinct connection mode\"\n url: 'http://localhost:4000/graphql/stream',\n});\n\n// query\n\n const result = await new Promise((resolve, reject) => {\n let result;\n client.subscribe(\n {\n query: '{ hello }',\n },\n {\n next: (data) => (result = data),\n error: reject,\n complete: () => resolve(result),\n },\n );\n });\n\n\n // subscription\n\n const onNext = () => {\n /* handle incoming values */\n };\n\n let unsubscribe = () => {\n /* complete the subscription */\n };\n\n await new Promise((resolve, reject) => {\n unsubscribe = client.subscribe(\n {\n query: 'subscription { greetings }',\n },\n {\n next: onNext,\n error: reject,\n complete: resolve,\n },\n );\n });\n\n;\n```\n\n```js\nimport {\n SubscriptionClient,\n SubscriptionClientOptions,\n} from '@graphql-sse/client';\n\nconst subscriptionClient = SubscriptionClient.create({\n graphQlSubscriptionUrl: 'http://some.host/graphl/subscriptions'\n});\n\nconst subscription = subscriptionClient.subscribe(\n {\n query: 'subscription { greetings }',\n }\n)\n\nconst onNext = () => {\n /* handle incoming values */\n };\n\nconst onError = () => {\n /* handle incoming errors */\n };\n\nsubscription.susbscribe(onNext, onError)\n```\n\n```js\nimport { split, HttpLink, ApolloClient, InMemoryCache } from '@apollo/client';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { ServerSentEventsLink } from '@graphql-sse/apollo-client';\n\nconst httpLink = new HttpLink({\n uri: 'http://localhost:4000/graphql',\n});\n\nconst sseLink = new ServerSentEventsLink({\n graphQlSubscriptionUrl: 'http://localhost:4000/graphql',\n});\n\nconst splitLink = split(\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n sseLink,\n httpLink\n);\n\nexport const client = new ApolloClient({\n link: splitLink,\n cache: new InMemoryCache(),\n});\n```\n\n```text\nEventSource\n```\n\n```text\nEvenSource\n```\n\n```text\ngraphql-sse\n```\n\n```text\n@graphql-sse/server\n```\n\n```text\n@graphql-sse/server\n```\n\n```text\n@graph-sse/server\n```\n\n========================================\n\nComments:\n- I'm currently building an app that uses notifications. I have already set up one RESTful endpoint with SSE and it's working well. Does it make sense to continue using SSE for notifications inside the app? I also am using GraphQL for my all my other resources but I'm not seeing a reason to use Websockets","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":502,"estimatedTokens":2754}}453{"id":"stack-56900332","source":"stackoverflow","questionId":56900332,"title":"Access requested fields in resolver mapping template","tags":["graphql","aws-appsync"],"text":"Title: Access requested fields in resolver mapping template\nTags: graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nWhen we request a GraphQL query, for instance,\n\n```\nquery GetPost {\n singlePost(id: 123) {\n id\n title\n }\n}\n```\n\nand we have configured a Lambda resolver in AWS AppSync, the request mapping template,\n\n```\n{\n \"version\": \"2017-02-28\",\n \"operation\": \"Invoke\",\n \"payload\": {\n \"resolve\": \"singlePost\",\n \"query\": $utils.toJson($context.arguments)\n }\n}\n```\n\nallows us to define the event object passed to the lambda handler.\n\nFor the above example, our Lambda handler would be invoked with an event `event` wherein `event.payload.query.id == 123` or the like.\n\nAccording to the docs the `$context` object comprises,\n\n```\n{\n \"arguments\" : { ... },\n \"source\" : { ... },\n \"result\" : { ... },\n \"identity\" : { ... },\n \"request\" : { ... }\n}\n```\n\n**That said, the documentation does not mention where I can access the requested fields of the GraphQL query**.\n\nFor the former example, these fields would correspond to `[\"id\", \"title\"]`.\n\nIn the case that I need to resolve some nested properties, e.g. a tags array, of an object through an expensive operation, e.g. a SQL join, it would be beneficial if I could check if this nested property is actually requested.\n\nThis question relates to How to get requested fields inside GraphQL resolver?, however, it differs from in the GraphQL implementation `graphql-tools` vs AppSync.\n\n========================================\n\nTop Answer:\nThere is now a `$context.info.selectionSetList` field that includes the requested field names. The official docs provide an example and explain some special use cases around interfaces and aliases.\n\n========================================\n\nCode:\n```text\nquery GetPost {\n singlePost(id: 123) {\n id\n title\n }\n}\n```\n\n```json\n{\n \"version\": \"2017-02-28\",\n \"operation\": \"Invoke\",\n \"payload\": {\n \"resolve\": \"singlePost\",\n \"query\": $utils.toJson($context.arguments)\n }\n}\n```\n\n```json\n{\n \"arguments\" : { ... },\n \"source\" : { ... },\n \"result\" : { ... },\n \"identity\" : { ... },\n \"request\" : { ... }\n}\n```\n\n```text\nevent\n```\n\n```text\nevent.payload.query.id == 123\n```\n\n```text\n$context\n```\n\n```text\n[\"id\", \"title\"]\n```\n\n```text\ngraphql-tools\n```\n\n```text\n{\n \"version\" : \"2017-02-28\",\n \"operation\" : \"Invoke\",\n \"payload\": {\n \"resolve\": \"$ctx.info.fieldName\",\n \"query\": $utils.toJson($context.arguments)\n }\n}\n```\n\n```text\ninfo\n```\n\n```text\n$context.info.selectionSetList\n```\n\n========================================\n\nComments:\n- Is there any update on this feature? It's something that would GREATLY reduce mapping template bloat in our application.. haven't seen any ongoing conversation about this feature.\n- docs.aws.amazon.com/appsync/latest/devguide/…\n- `info.fieldName` is the field on the `parent` that this resolver is being asked to resolve, not the array of field names being requested on the final object that the original question is asking for.\n- Note that when using `$utils.toJson()` on `context.info`, the values that `selectionSetList` return are not serialized by default. See also github.com/aws-amplify/amplify-cli/issues/4869","metadata":{"transformedAt":"2026-08-18T18:32:36.058Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":137,"estimatedTokens":800}}454{"id":"stack-56097187","source":"stackoverflow","questionId":56097187,"title":"Nestjs Apollo graphql upload scalar","tags":["javascript","node.js","graphql","apollo","nestjs"],"text":"Title: Nestjs Apollo graphql upload scalar\nTags: javascript, node.js, graphql, apollo, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using nestjs graphql framework and I want to use apollo scalar upload\n\nI have been able to use the scalar in another project that did not include nestjs.\n\nschema.graphql\nApp.module.ts register graphql\n\n```\nGraphQLModule.forRoot({\n typePaths: ['./**/*.graphql'],\n resolvers: { Upload: GraphQLUpload },\n installSubscriptionHandlers: true,\n context: ({ req }) => ({ req }),\n playground: true,\n definitions: {\n path: join(process.cwd(), './src/graphql.classes.ts'),\n outputAs: 'class',\n },\n uploads: {\n maxFileSize: 10000000, // 10 MB\n maxFiles: 5\n }\n }),\n```\n\npets.resolver.ts mutation createPet\n\n```\n@Mutation('uploadFile')\n async uploadFile(@Args('fileUploadInput') fileUploadInput: FileUploadInput) {\n console.log(\"TCL: PetsResolver -> uploadFile -> file\", fileUploadInput);\n return {\n id: '123454',\n path: 'www.wtf.com',\n filename: fileUploadInput.file.filename,\n mimetype: fileUploadInput.file.mimetype\n }\n }\n```\n\npets.type.graphql\n\n```\ntype Mutation {\n uploadFile(fileUploadInput: FileUploadInput!): File!\n}\ninput FileUploadInput{\n file: Upload!\n}\n\ntype File {\n id: String!\n path: String!\n filename: String!\n mimetype: String!\n}\n```\n\nI expect that scalar works with nestjs but my actual result is\n\n```\n{\"errors\":[{\"message\":\"Promise resolver undefined is not a function\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"createPet\"],\"extensions\":{\"code\":\"INTERNAL_SERVER_ERROR\",\"exception\":{\"stacktrace\":[\"TypeError: Promise resolver undefined is not a function\",\" at new Promise ()\",\" at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:119:32)\",\" at E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:62:40\",\" at Array.forEach ()\",\" at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:41:30)\",\" at _loop_1 (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:226:43)\",\" at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\class-transformer\\\\TransformOperationExecutor.js:240:17)\",\" at ClassTransformer.plainToClass (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\ClassTransformer.ts:43:25)\",\" at Object.plainToClass (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\index.ts:37:29)\",\" at ValidationPipe.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\@nestjs\\\\common\\\\pipes\\\\validation.pipe.js:50:41)\",\" at transforms.reduce (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\@nestjs\\\\core\\\\pipes\\\\pipes-consumer.js:15:28)\",\" at process._tickCallback (internal/process/next_tick.js:68:7)\"]}}}],\"data\":null}\n```\n\n========================================\n\nTop Answer:\n**Use** import {GraphQLUpload} from \"**apollo-server-express**\"\n\n**Not** from 'graphql-upload'\n\n```\nimport { Resolver, Mutation, Args } from '@nestjs/graphql';\nimport { createWriteStream } from 'fs';\n\nimport {GraphQLUpload} from \"apollo-server-express\"\n\n@Resolver('Download')\nexport class DownloadResolver {\n @Mutation(() => Boolean)\n async uploadFile(@Args({name: 'file', type: () => GraphQLUpload})\n {\n createReadStream,\n filename\n }): Promise {\n return new Promise(async (resolve, reject) => \n createReadStream()\n .pipe(createWriteStream(`./uploads/${filename}`))\n .on('finish', () => resolve(true))\n .on('error', () => reject(false))\n );\n }\n \n}\n```\n\nhttps://i.sstatic.net/bgm01.png\n\n========================================\n\nCode:\n```text\nGraphQLModule.forRoot({\n typePaths: ['./**/*.graphql'],\n resolvers: { Upload: GraphQLUpload },\n installSubscriptionHandlers: true,\n context: ({ req }) => ({ req }),\n playground: true,\n definitions: {\n path: join(process.cwd(), './src/graphql.classes.ts'),\n outputAs: 'class',\n },\n uploads: {\n maxFileSize: 10000000, // 10 MB\n maxFiles: 5\n }\n }),\n```\n\n```text\n@Mutation('uploadFile')\n async uploadFile(@Args('fileUploadInput') fileUploadInput: FileUploadInput) {\n console.log(\"TCL: PetsResolver -> uploadFile -> file\", fileUploadInput);\n return {\n id: '123454',\n path: 'www.wtf.com',\n filename: fileUploadInput.file.filename,\n mimetype: fileUploadInput.file.mimetype\n }\n }\n```\n\n```text\ntype Mutation {\n uploadFile(fileUploadInput: FileUploadInput!): File!\n}\ninput FileUploadInput{\n file: Upload!\n}\n\ntype File {\n id: String!\n path: String!\n filename: String!\n mimetype: String!\n}\n```\n\n```text\n{\"errors\":[{\"message\":\"Promise resolver undefined is not a function\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"createPet\"],\"extensions\":{\"code\":\"INTERNAL_SERVER_ERROR\",\"exception\":{\"stacktrace\":[\"TypeError: Promise resolver undefined is not a function\",\" at new Promise (<anonymous>)\",\" at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:119:32)\",\" at E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:62:40\",\" at Array.forEach (<anonymous>)\",\" at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:41:30)\",\" at _loop_1 (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\TransformOperationExecutor.ts:226:43)\",\" at TransformOperationExecutor.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\class-transformer\\\\TransformOperationExecutor.js:240:17)\",\" at ClassTransformer.plainToClass (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\ClassTransformer.ts:43:25)\",\" at Object.plainToClass (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\src\\\\index.ts:37:29)\",\" at ValidationPipe.transform (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\@nestjs\\\\common\\\\pipes\\\\validation.pipe.js:50:41)\",\" at transforms.reduce (E:\\\\projectos\\\\Gitlab\\\\latineo\\\\latineo-api\\\\node_modules\\\\@nestjs\\\\core\\\\pipes\\\\pipes-consumer.js:15:28)\",\" at process._tickCallback (internal/process/next_tick.js:68:7)\"]}}}],\"data\":null}\n```\n\n```text\nimport { Scalar } from '@nestjs/graphql';\n\nimport { GraphQLUpload } from 'graphql-upload';\n\n@Scalar('Upload')\nexport class Upload {\n description = 'Upload custom scalar type';\n\n parseValue(value) {\n return GraphQLUpload.parseValue(value);\n }\n\n serialize(value: any) {\n return GraphQLUpload.serialize(value);\n }\n\n parseLiteral(ast) {\n return GraphQLUpload.parseLiteral(ast);\n }\n}\n```\n\n```text\n@Module({\n imports: [\n ...\n DateScalar,\n Upload,\n GraphQLModule.forRoot({\n typePaths: ['./**/*.graphql'],\n ...\n uploads: {\n maxFileSize: 10000000, // 10 MB\n maxFiles: 5,\n },\n }),\n ...\n ],\n...\n})\nexport class ApplicationModule {}\n```\n\n```text\nscalar Upload\n...\ntype Mutation {\n uploadFile(file: Upload!): String\n}\n```\n\n```text\n@Mutation()\n async uploadFile(@Args('file') file,) {\n console.log('Hello file',file)\n return \"Nice !\";\n }\n```\n\n```text\ngraphql-upload\n```\n\n```text\nGraphQLUpload\n```\n\n```text\ngraphql-upload\n```\n\n```text\nimport { Resolver, Mutation, Args } from '@nestjs/graphql';\nimport { createWriteStream } from 'fs';\n\nimport {GraphQLUpload} from \"apollo-server-express\"\n\n@Resolver('Download')\nexport class DownloadResolver {\n @Mutation(() => Boolean)\n async uploadFile(@Args({name: 'file', type: () => GraphQLUpload})\n {\n createReadStream,\n filename\n }): Promise<boolean> {\n return new Promise(async (resolve, reject) => \n createReadStream()\n .pipe(createWriteStream(`./uploads/${filename}`))\n .on('finish', () => resolve(true))\n .on('error', () => reject(false))\n );\n }\n \n}\n```\n\n```js\nimport { graphqlUploadExpress } from \"graphql-upload\"\nimport { MiddlewareConsumer, Module, NestModule } from \"@nestjs/common\"\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n uploads: false, // disable built-in upload handling (for apollo 3+ not needed)\n }),\n ],\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(graphqlUploadExpress()).forRoutes(\"graphql\")\n }\n}\n```\n\n```text\n// import { GraphQLUpload } from \"apollo-server-core\" <-- remove this\nimport { FileUpload, GraphQLUpload } from \"graphql-upload\"\n```\n\n```text\nGraphQLUpload\n```\n\n```text\napollo-server-core\n```\n\n```text\ngraphql-upload\n```\n\n========================================\n\nComments:\n- Hello, did you solve your problem? i'm in the exact same situation :)\n- no sorry, there was a guy that have it working but he was busy and i just change to rest :D. try in the discord discordapp.com/channels/520622812742811698/60153692626826039‌​2\n- Lary you encounter a problem with parseLiteral expect 2 arguments ?parseLiteral(valueNode: ValueNode, variables: Maybe) { return GraphQLUpload.parseLiteral(valueNode, variables); }\n- maybe you can help in this discord channel discordapp.com/channels/520622812742811698/52064948792498588‌​5\n- no, i used : \"apollo-server-express\": \"2.8.0\", \"graphql-upload\": \"^8.0.7\" \"@types/graphql-upload\": \"^8.0.0\", What about you? (im already on this discord PM me if you want @Lard-man )\n- For those trying this now, `graphql-upload` is included in `apollo-server-express`.\n- Can't find GraphQLUpload with apollo-server-fastify, do you know if this can work with Fastify ? Thanks in advance\n- Apollo Server 3 has removed \"GraphQLUpload\" in favor of enabling users to provide their own mechanisms for these features.","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":300,"estimatedTokens":2429}}455{"id":"stack-45253671","source":"stackoverflow","questionId":45253671,"title":"Add an array of Objects to a mutation in apollo-react","tags":["reactjs","graphql","apollo","graphcool"],"text":"Title: Add an array of Objects to a mutation in apollo-react\nTags: reactjs, graphql, apollo, graphcool\nSource: Stack Overflow\n\nQuestion:\nI am using react-apollo on the front-end and graphcool on the backend. I have a mutation that creates a tutorial like so:\n\n```\nconst CREATE_TUTORIAL_MUTATION = gql`\n mutation CreateTutorialMutation(\n $author: String\n $link: String\n $title: String!\n $postedById: ID!\n $completed: Boolean!\n ) {\n createTutorial(\n author: $author\n link: $link\n title: $title\n postedById: $postedById\n completed: $completed\n ) {\n author\n link\n title\n postedBy {\n id\n name\n }\n completed\n }\n }\n`\n```\n\nIt gets called in a submit handler like so...\n\n```\nthis.props.createTutorialMutation({\n variables: {\n author,\n link,\n title,\n completed: false,\n postedById\n }\n })\n```\n\nEverything works wonderfully. \n\nNow I want to add a set of tags to when I create a new tutorial. I created the input field and connected it so that the tags variable is an array of objects, each with a tag **id** and the tag **text**.\n\nIf I try and add the tags field to the mutation it needs a scalar type. But there is doesn't seem to be a scalar type for an array of objects.\n\nIf I pass the tag variable in as a parameter when I call the mutation how do I fill in the Scalar type field in the mutation ( on line 148 here https://github.com/joshpitzalis/path/blob/graphQL/src/components/Add.js) and in the schema?\n\nI am new to graphQL and I understand that I might be approaching this completely the wrong way. If that is the case, how do I add an array of objects to a mutation in graphQL?\n\n========================================\n\nTop Answer:\nWhat i understand by your requirement is that if you have the following code\n\n```\nconst user = {\n name:\"Rohit\", \n age:27, \n marks: [10,15], \n subjects:[\n {name:\"maths\"},\n {name:\"science\"}\n ]\n};\n\nconst query = `mutation {\n createUser(user:${user}) {\n name\n }\n}`\n```\n\nyou must be getting something like \n\n```\n\"mutation {\n createUser(user:[object Object]) {\n name\n }\n}\"\n```\n\ninstead of the expected \n\n```\n\"mutation {\n createUser(user:{\n name: \"Rohit\" ,\n age: 27 ,\n marks: [10 ,15 ] ,\n subjects: [\n {name: \"maths\" } ,\n {name: \"science\" } \n ] \n }) {\n name\n }\n}\"\n```\n\nIf this is what you wanted to achieve, then gqlast is a nice tag function which you can use to get the expected result\n\nSimply grab the js file from here and use it as: \n\n```\nconst user = {\n name:\"Rohit\", \n age:27, \n marks: [10,15], \n subjects:[\n {name:\"maths\"},\n {name:\"science\"}\n ]\n};\n\nconst query = gqlast`mutation {\n createUser(user:${user}) {\n name\n }\n}`\n```\n\nThe result stored in the variable `query` will be :\n\n```\n\"mutation {\n createUser(user:{\n name: \"Rohit\" ,\n age: 27 ,\n marks: [10 ,15 ] ,\n subjects: [\n {name: \"maths\" } ,\n {name: \"science\" } \n ] \n }) {\n name\n }\n}\"\n```\n\n========================================\n\nCode:\n```text\nconst CREATE_TUTORIAL_MUTATION = gql`\n mutation CreateTutorialMutation(\n $author: String\n $link: String\n $title: String!\n $postedById: ID!\n $completed: Boolean!\n ) {\n createTutorial(\n author: $author\n link: $link\n title: $title\n postedById: $postedById\n completed: $completed\n ) {\n author\n link\n title\n postedBy {\n id\n name\n }\n completed\n }\n }\n`\n```\n\n```text\nthis.props.createTutorialMutation({\n variables: {\n author,\n link,\n title,\n completed: false,\n postedById\n }\n })\n```\n\n```text\ntype Tutorial {\n author: String\n completed: Boolean\n link: String\n title: String!\n id: ID! @isUnique\n createdAt: DateTime!\n updatedAt: DateTime!\n postedBy: User @relation(name: \"UsersTutorials\")\n tags: [Tag!]! @relation(name: \"TutorialTags\")\n}\n\ntype Tag {\n id: ID!\n tag: String!\n number: Int!\n tutorials: [Tutorial!]! @relation(name: \"TutorialTags\")\n}\n```\n\n```text\nconst CREATE_TUTORIAL_MUTATION = gql`\n mutation CreateTutorialMutation(\n $author: String\n $link: String\n $title: String!\n $tags: [TutorialtagsTag!]!\n $completed: Boolean!\n $postedById: ID!\n ) {\n createTutorial(\n author: $author\n link: $link\n title: $title\n tags: $tags\n completed: $completed\n postedById: $postedById\n ) {\n author\n link\n title\n postedBy {\n id\n name\n }\n completed\n tags {\n id\n text\n }\n }\n }\n`\n```\n\n```text\nTag\n```\n\n```text\nTutorial\n```\n\n```text\nconst user = {\n name:\"Rohit\", \n age:27, \n marks: [10,15], \n subjects:[\n {name:\"maths\"},\n {name:\"science\"}\n ]\n};\n\nconst query = `mutation {\n createUser(user:${user}) {\n name\n }\n}`\n```\n\n```text\n\"mutation {\n createUser(user:[object Object]) {\n name\n }\n}\"\n```\n\n```text\n\"mutation {\n createUser(user:{\n name: \"Rohit\" ,\n age: 27 ,\n marks: [10 ,15 ] ,\n subjects: [\n {name: \"maths\" } ,\n {name: \"science\" } \n ] \n }) {\n name\n }\n}\"\n```\n\n```text\nconst user = {\n name:\"Rohit\", \n age:27, \n marks: [10,15], \n subjects:[\n {name:\"maths\"},\n {name:\"science\"}\n ]\n};\n\nconst query = gqlast`mutation {\n createUser(user:${user}) {\n name\n }\n}`\n```\n\n```text\n\"mutation {\n createUser(user:{\n name: \"Rohit\" ,\n age: 27 ,\n marks: [10 ,15 ] ,\n subjects: [\n {name: \"maths\" } ,\n {name: \"science\" } \n ] \n }) {\n name\n }\n}\"\n```\n\n```text\nquery\n```\n\n========================================\n\nComments:\n- Hey man, could you do me a massive favor and take a look at a question I just posted. I think I need to add @relation to a post and shots schema. I am pretty fresh at Apollo, so maybe a silly question: But can can I simply differentiate my client schema from my server schema as long as they match? Coz my server has no idea what \"@relation\" is. And my client doesn't seem to like it when I start adding local schemas to interface with the server: even when they match stackoverflow.com/questions/62113955/…\n- This really worked for my case thank you very much basically one thing to add on for anyone in need of this is to use `gql''YOUR GQLASTSTRING''` as this will generate the document node. Kudos!!","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":344,"estimatedTokens":1596}}456{"id":"stack-44740058","source":"stackoverflow","questionId":44740058,"title":"How can a graphql mutation automatically refresh a query being watched by Apollo Client?","tags":["angular","graphql","apollo"],"text":"Title: How can a graphql mutation automatically refresh a query being watched by Apollo Client?\nTags: angular, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nrecently started playing around with graphQL and Apollo - apollo-client.\n\nI built a web service on top of graphQL and it's working just fine. The only issue I'm facing is on the client side of the project. For example (please refer to code below), after running createVideo() the `data` property of my component which is an observable which is watching the query doesn't refresh automatically and calling apollo.query manually on the callback doesn't seem to take any effect because the query returns the cached results, not the ones from the server.\n\nAm I missing something?\n\n```\napp.component.ts\n import {Component, OnInit} from '@angular/core';\n import {Apollo, ApolloQueryObservable} from 'apollo-angular';\n import 'rxjs/Rx';\n import gql from 'graphql-tag';\n\n // http://dev.apollodata.com/angular2/mutations.html\n const NewVideoQuery = gql`\n mutation AddVideoQuery($title: String!,$duration: Int!, $watched: Boolean!){\n createVideo(video: { title: $title, duration: $duration, watched: $watched } ){\n id,\n title\n }\n }\n `;\n const VideoQuery = gql`\n {\n videos {\n id,\n title\n }\n }\n `;\n @Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n })\n export class AppComponent implements OnInit {\n data: ApolloQueryObservable;\n video: any = {};\n\n constructor(private apollo: Apollo) {\n }\n\n ngOnInit() {\n this.data = this.apollo.watchQuery({query: VideoQuery});\n }\n\n createVideo() {\n /**\n * This will send a mutate query to the server.\n */\n // @todo After running the mutate, the watch query doesn't refresh\n this.apollo.mutate({\n mutation: NewVideoQuery,\n variables: {\n 'title': this.video.title || 'Some Video' + Math.floor(Math.random() * 10),\n 'duration': 123213,\n 'watched': true\n }\n }).subscribe((afterMutation) => {\n console.log(afterMutation);\n // This fires but query doesn't hit the server since it's coming from cache.\n\n // @todo Not even by re-running it here\n this.apollo.query({query: VideoQuery})\n .subscribe((data) => {\n console.log(data);\n });\n }, (err) => alert(err));\n }\n }\n```\n\n```\n//app.component.html\n\n \n **{{x.id}}**{{x.title}}\n \n\n \n Title\n \n \n\n {{title}}\n```\n\n========================================\n\nTop Answer:\nI suggest you fetchPolicy: 'cache-and-network' as it fetches data already stored but also updates the cache making your queries faster but still updating your cache. you can read more about Understanding Apollo Fetch Policies here --> https://medium.com/@galen.corey/understanding-apollo-fetch-policies-705b5ad71980\n\n========================================\n\nCode:\n```text\napp.component.ts\n import {Component, OnInit} from '@angular/core';\n import {Apollo, ApolloQueryObservable} from 'apollo-angular';\n import 'rxjs/Rx';\n import gql from 'graphql-tag';\n\n // http://dev.apollodata.com/angular2/mutations.html\n const NewVideoQuery = gql`\n mutation AddVideoQuery($title: String!,$duration: Int!, $watched: Boolean!){\n createVideo(video: { title: $title, duration: $duration, watched: $watched } ){\n id,\n title\n }\n }\n `;\n const VideoQuery = gql`\n {\n videos {\n id,\n title\n }\n }\n `;\n @Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n })\n export class AppComponent implements OnInit {\n data: ApolloQueryObservable<any>;\n video: any = {};\n\n constructor(private apollo: Apollo) {\n }\n\n ngOnInit() {\n this.data = this.apollo.watchQuery({query: VideoQuery});\n }\n\n createVideo() {\n /**\n * This will send a mutate query to the server.\n */\n // @todo After running the mutate, the watch query doesn't refresh\n this.apollo.mutate({\n mutation: NewVideoQuery,\n variables: {\n 'title': this.video.title || 'Some Video' + Math.floor(Math.random() * 10),\n 'duration': 123213,\n 'watched': true\n }\n }).subscribe((afterMutation) => {\n console.log(afterMutation);\n // This fires but query doesn't hit the server since it's coming from cache.\n\n // @todo Not even by re-running it here\n this.apollo.query({query: VideoQuery})\n .subscribe((data) => {\n console.log(data);\n });\n }, (err) => alert(err));\n }\n }\n```\n\n```text\n//app.component.html\n\n <div *ngFor=\"let x of data | async | select: 'videos'\">\n <div><b>{{x.id}}</b>{{x.title}}</div>\n </div>\n\n <label>\n Title\n <input type=\"text\" [(ngModel)]=\"video.title\">\n </label>\n\n <button (click)=\"createVideo()\">{{title}}</button>\n```\n\n```text\ndata\n```\n\n```text\n'cache-first' | 'cache-and-network' | 'network-only' | 'cache-only' | 'standby'\n```\n\n```text\nthis.apollo.query({query: VideoQuery, fetchPolicy: 'network-only'})\n.subscribe(()=>{ console.log('refresh done, our watchQuery will update') })\n```\n\n```text\nthis.data = this.apollo.watchQuery({query: VideoQuery, pollInterval: 10000});\n```\n\n========================================\n\nComments:\n- Hey! Sorry to bother you, but I have encountered a similar problem as you had (stackoverflow.com/questions/48491160/…). Could you recommend something to read about Apollo Client caching, watched queries and subscriptions? Official docs seem quite vague about these topics and Apollo Client module in general, I can't make much sense of it. You answer helped me to solve a problem but don't understand what stand behind the mechanism you described.\n- As of now, the recommended way of handling this is probably using writeQuery apollographql.com/docs/react/basics/…\n- Actually, it looks like the automatic caching would easily work here: apollographql.com/docs/react/advanced/… the catch is that if you're not querying both `__typename` and `id`, you'll have to define `dataIdFromObject` yourself: apollographql.com/docs/react/advanced/…","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":204,"estimatedTokens":1507}}457{"id":"stack-53665761","source":"stackoverflow","questionId":53665761,"title":"GraphQL using nested query arguments on parent or parent arguments on nested query","tags":["graphql","graphql-js"],"text":"Title: GraphQL using nested query arguments on parent or parent arguments on nested query\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have a product and items\n\nProduct:\n\n```\n{\n id: Int\n style_id: Int\n items: [items]\n}\n```\n\nItems:\n\n```\n{\n id: Int\n product_id: Int\n size: String\n}\n```\n\nI want to query products but only get back products that have an item with a size.\n\nSo a query could look like this:\n\n```\nproducts(size: [\"S\",\"M\"]) {\n id\n style_id\n items(size: [\"S\",\"M\"]) {\n id\n size\n }\n}\n```\n\nBut it seems like there should be a way where I can just do\n\n```\nproducts {\n id\n style_id\n items(size: [\"S\",\"M\"]) {\n id\n size\n }\n}\n```\n\nAnd in the resolver for the products I can grab arguments from the nested query and use them. In this case add the check to only return products that have those sizes. This way I have the top level returned with pagination correct instead of a lot of empty products.\n\nIs this possible or atleast doing it the other way around:\n\n```\nproducts(size: [\"S\",\"M\"]) {\n id\n style_id\n items {\n id\n size\n }\n}\n```\n\nAnd sending the size argument down to the items resolver? Only way I know would be through context but the one place I found this they said that it is not a great idea because context spans the full query in all depths.\n\n========================================\n\nTop Answer:\nI found this useful #reference\n\n\r\n\r\n\n```\n//the typedef:\n\ntype Post {\n _id: String\n title: String\n private: Boolean\n author(username: String): Author\n}\n//the resolver:\nPost: {\n author(post, {username}){\n //response\n },\n }\n// usage\n{\n posts(private: true){\n _id,\n title,\n author(username: \"theara\"){\n _id,\n username\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n id: Int\n style_id: Int\n items: [items]\n}\n```\n\n```text\n{\n id: Int\n product_id: Int\n size: String\n}\n```\n\n```text\nproducts(size: [\"S\",\"M\"]) {\n id\n style_id\n items(size: [\"S\",\"M\"]) {\n id\n size\n }\n}\n```\n\n```text\nproducts {\n id\n style_id\n items(size: [\"S\",\"M\"]) {\n id\n size\n }\n}\n```\n\n```text\nproducts(size: [\"S\",\"M\"]) {\n id\n style_id\n items {\n id\n size\n }\n}\n```\n\n```text\nproducts {\n id\n style_id\n items(size: [\"S\",\"M\"]) {\n id\n size\n }\n}\n```\n\n```text\n(obj, args, context, info) => {}\n```\n\n```text\nproducts(size: [\"S\",\"M\"]) {\n id\n style_id\n items {\n id\n size\n }\n}\n```\n\n```text\n(parent, args) => {\n ...\n return {\n id: '',\n style_id: ''\n }\n}\n```\n\n```text\n(parent, args) => {\n ...\n return {\n id: '',\n style_id: '',\n size: [\"S\", \"M\"]\n }\n}\n```\n\n```text\n(product, args) => {\n const size = product.size\n}\n```\n\n```text\ninfo\n```\n\n```text\nproducts\n```\n\n```text\nsize\n```\n\n```text\nproducts\n```\n\n```text\nproducts.items\n```\n\n```text\nsize\n```\n\n```text\nimport { GraphQLList, GraphQLString } from 'graphql';\n\nconst ProductFilterInputType = new GraphQLInputObjectType({\n name: 'ProductFilter',\n fields: () => ({\n size: {\n type: GraphQLList(GraphQLString),\n description: 'list of sizes',\n }\n }),\n});\n```\n\n```text\nProductFilterInputType\n```\n\n```text\nGraphQLList(GraphQLString)\n```\n\n```text\nproducts\n```\n\n```js\n//the typedef:\n\ntype Post {\n _id: String\n title: String\n private: Boolean\n author(username: String): Author\n}\n//the resolver:\nPost: {\n author(post, {username}){\n //response\n },\n }\n// usage\n{\n posts(private: true){\n _id,\n title,\n author(username: \"theara\"){\n _id,\n username\n }\n }\n}\n```\n\n```text\n{\n id: Int! # i would rather to use uuid which its type is String in gql.\n styleId: Int\n items: [items!] # list can be optional but if is not, better have item. but better design is below: \n items(after: String, before: String, first: Int, last: Int, filter: ItemsFilterInput, orderBy: [ItemsOrderInput]): ItemsConnection\n}\n```\n\n```text\nenum Size {\n SMALL\n MEDIUM\n}\n```\n\n```text\n{\n id: Int!\n size: Size\n productId: Int\n product: Product # you need to resolve this if you want to get product from item.productId\n}\n```\n\n```text\ninput ItemFilterInput {\n and: [ItemFilterInput!]\n or: [ItemFilterInput!]\n id: Int # you can use same for parent id like productId \n idIn: [Int!]\n idNot: Int\n idNotIn: [Int!]\n size: Size \n sizeIn: [Size!]\n sizeNotIn: [Size!]\n sizeGt: Size # since sizes are not in alphabetic order and not sortable this wont be meaningful, but i keep it here to be used for other attributes. or you can also trick to add a number before size enums line 1SMALL, 2MEDIUM.\n sizeGte: Size\n sizeLt: Size\n sizeLte: Size \n sizeBetween: [Size!, Size!]\n}\n```\n\n```text\n{\n product {\n items(filter: {sizeIn:[SMALL, MEDIUM]}) {\n id \n }\n }\n}\n# if returning `ItemsConnection` resolve it this way: \n{\n product {\n id \n items {\n edges {\n node { # node will be an item.\n id \n size\n }\n }\n }\n }\n}\n```\n\n```text\nfilter\n```\n\n```text\nedges\n```\n\n```text\nnode\n```\n\n```text\nconnection\n```\n\n```text\nproduct {items:[item]}\n```\n\n========================================\n\nComments:\n- try \"items: [items!]!\" in the product schema.\n- GraphQL doesnβt natively support what youβre asking for; if you want to filter which top-level items you get back it needs to be controlled by parameters on that top-level query field and not something lower.\n- @DavidMaze That's incorrect. See my answer.\n- didn't realize you could return fields not setup in your return object and get them on the child. That makes perfect sense and the way I am going to go about it.\n- The `info` solution is cool! IMO the second one is a little bit weird, but yeah it should work as well!","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":32,"totalLines":387,"estimatedTokens":1419}}458{"id":"stack-67883223","source":"stackoverflow","questionId":67883223,"title":"How to detect disconnect and reconnect for subscription(websocket) in apollo client","tags":["reactjs","graphql","apollo-client","graphql-subscriptions"],"text":"Title: How to detect disconnect and reconnect for subscription(websocket) in apollo client\nTags: reactjs, graphql, apollo-client, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nI am building a chat service and **I want to handle the cases when the subscription(websocket) connection is disconnected.** Apollo client is configured like bellow. I removed unnecessary code like cache, authLink etc.\n\nHow do I do this with react, apollo client? If its disconnected, I would like to show that to the chat page and when the user reconnects, I would like to fetch all the missed chat messages. This is why I need to know the disconnect, connect events\n\nBelow are the relevant packages used in this app:\n\n```\n\"@apollo/client\": \"^3.3.7\",\n\"subscriptions-transport-ws\": \"^0.9.18\",\n\"react\": \"^17.0.1\"\n```\n\n```\nconst httpLink = new BatchHttpLink({ uri: config.API_URL })\nconst wsLink = new WebSocketLink({\n uri: config.WS_URL,\n options: {\n reconnect: true,\n connectionParams:{ \n authToken: accessToken,\n },\n },\n})\n\nconst splitLink = split(\n ({ query }) => {\n const definition = getMainDefinition(query) \n return definition.kind === 'OperationDefinition' && definition.operation === 'subscription'\n },\n wsLink,\n httpLink\n)\nconst client = new ApolloClient({\n cache,\n link: from([new SentryLink(), authLink, errorLink, splitLink]),\n})\n```\n\n========================================\n\nTop Answer:\nIt appears that the option you'll want to use to target the WS connect/disconnect event is `connectionCallback` (see the full list of WebSocketLink options here).\n\nTake a look at lines 620-635 of the WebSocketLink source and you can see that the provided `connectionCallback` is called both for `GQL_CONNECTION_ERROR` and `GQL_CONNECTION_ACK` received message types. Therefore, you should be able to target both events using this callback.\n\nI haven't used Apollo's WebSocketLink yet, So I am unable to confirm that this will work fully as expected. Additionally, the behavior to fetch all missing chat messages upon reconnect is something you may need to build yourself as it doesn't appear to be part of the default reconnect behavior (will depend on server implementation; see Apollo Server docs). Conversely, it does appear that WebSocketLink will forward all unsent messages to the server upon reconnect by default.\n\n========================================\n\nCode:\n```text\n\"@apollo/client\": \"^3.3.7\",\n\"subscriptions-transport-ws\": \"^0.9.18\",\n\"react\": \"^17.0.1\"\n```\n\n```text\nconst httpLink = new BatchHttpLink({ uri: config.API_URL })\nconst wsLink = new WebSocketLink({\n uri: config.WS_URL,\n options: {\n reconnect: true,\n connectionParams:{ \n authToken: accessToken,\n },\n },\n})\n\nconst splitLink = split(\n ({ query }) => {\n const definition = getMainDefinition(query) \n return definition.kind === 'OperationDefinition' && definition.operation === 'subscription'\n },\n wsLink,\n httpLink\n)\nconst client = new ApolloClient({\n cache,\n link: from([new SentryLink(), authLink, errorLink, splitLink]),\n})\n```\n\n```text\nimport { WebSocketLink } from '@apollo/client/link/ws'\nimport { SubscriptionClient } from 'subscriptions-transport-ws' // <- import this\n\nconst wsClient = new SubscriptionClient(config.WS_URL, {\n reconnect: true,\n connectionParams: {\n authToken: accessToken,\n },\n})\n\nconst wsLink = new WebSocketLink(wsClient)\n```\n\n```text\nwsClient.onConnected(() => console.log(\"websocket connected!!\"))\nwsClient.onDisconnected(() => console.log(\"websocket disconnected!!\"))\nwsClient.onReconnected(() => console.log(\"websocket reconnected!!\"))\n```\n\n```text\nSubscriptionClient\n```\n\n```text\nWebSocketLink\n```\n\n```text\nWebSocketLink\n```\n\n```text\nWebsocketLink\n```\n\n```text\nSubscriptionClient\n```\n\n```text\nwsClient\n```\n\n```text\ndisconnectTimestamp\n```\n\n```text\nonReconnected\n```\n\n```text\ndisconnectTimestamp\n```\n\n```text\nconnectionCallback\n```\n\n```text\nconnectionCallback\n```\n\n```text\nGQL_CONNECTION_ERROR\n```\n\n```text\nGQL_CONNECTION_ACK\n```\n\n========================================\n\nComments:\n- I tried connectionCallback and it does run when it establishes new connection, but it does not run when the websocket is disconnected. This is definitely an improvement, but ideally I would also like to know when it got disconencted, so that I can only fetch chat messages that occured during that period\n- Note that `subscriptions-transport-ws` is the older, unmaintained library used for Apollo Client subscriptions: apollographql.com/docs/react/data/subscriptions/…","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":164,"estimatedTokens":1123}}459{"id":"stack-48255528","source":"stackoverflow","questionId":48255528,"title":"Programmatically create Gatsby pages from Contentful data","tags":["javascript","reactjs","graphql","contentful","gatsby"],"text":"Title: Programmatically create Gatsby pages from Contentful data\nTags: javascript, reactjs, graphql, contentful, gatsby\nSource: Stack Overflow\n\nQuestion:\nI am looking for help with GatsbyJS and Contentful. The docs aren't quite giving me enough info.\n\nI am looking to programmatically create pages based on contentful data. In this case, the data type is a retail \"Store\" with a gatsby page at /retail_store_name\n\nThe index.js for each store is basically a couple of react components with props passed in e.g. shop name and google place ID.\n\nAdd data to contentful. Here is my example data model:\n\n```\n{\n \"name\": \"Store\"\n \"displayField\": \"shopName\",\n \"fields\": [\n {\n \"id\": \"shopName\",\n \"name\": \"Shop Name\",\n \"type\": \"Symbol\",\n \"localized\": false,\n \"required\": true,\n \"validations\": [\n {\n \"unique\": true\n }\n ],\n \"disabled\": false,\n \"omitted\": false\n },\n {\n \"id\": \"placeId\",\n \"name\": \"Place ID\",\n \"type\": \"Symbol\",\n \"localized\": false,\n \"required\": true,\n \"validations\": [\n {\n \"unique\": true\n }\n ],\n \"disabled\": false,\n \"omitted\": false\n }\n}\n```\n\nI've added the contentful site data to gatsby-config.js\n\n```\n// In gatsby-config.js\nplugins: [\n {\n resolve: `gatsby-source-contentful`,\n options: {\n spaceId: `your_space_id`,\n accessToken: `your_access_token`\n },\n },\n];\n```\n\nQuery contentful - I'm not sure where this should happen. I've got a template file that would be the model for each store webpage created from contentful data.\n\nAs mentioned this is just some components with props passed in. Example: \n\n```\nimport React, { Component } from \"react\";\n\nexport default class IndexPage extends Component {\nconstructor(props) {\n super(props);\n this.state = {\n placeId: \"\",\n shopName: \"\",\n };\n}\nrender (){\n return (\n \n \n );\n}\n```\n\nI'm really not sure how to go about this. The end goal is auto publishing for non-tech users, who post new stores in Contentful to be updated on the production site.\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"Store\"\n \"displayField\": \"shopName\",\n \"fields\": [\n {\n \"id\": \"shopName\",\n \"name\": \"Shop Name\",\n \"type\": \"Symbol\",\n \"localized\": false,\n \"required\": true,\n \"validations\": [\n {\n \"unique\": true\n }\n ],\n \"disabled\": false,\n \"omitted\": false\n },\n {\n \"id\": \"placeId\",\n \"name\": \"Place ID\",\n \"type\": \"Symbol\",\n \"localized\": false,\n \"required\": true,\n \"validations\": [\n {\n \"unique\": true\n }\n ],\n \"disabled\": false,\n \"omitted\": false\n }\n}\n```\n\n```text\n// In gatsby-config.js\nplugins: [\n {\n resolve: `gatsby-source-contentful`,\n options: {\n spaceId: `your_space_id`,\n accessToken: `your_access_token`\n },\n },\n];\n```\n\n```text\nimport React, { Component } from \"react\";\n\nexport default class IndexPage extends Component {\nconstructor(props) {\n super(props);\n this.state = {\n placeId: \"\",\n shopName: \"\",\n };\n}\nrender (){\n return (\n <ComponentExampleOne shopName={this.state.shopName} />\n <ComponentExampleTwo placeId={this.state.placeId} />\n );\n}\n```\n\n```text\nconst path = require('path')\n\nexports.createPages = ({graphql, boundActionCreators}) => {\n const {createPage} = boundActionCreators\n return new Promise((resolve, reject) => {\n const storeTemplate = path.resolve('src/templates/store.js')\n resolve(\n graphql(`\n {\n allContentfulStore (limit:100) {\n edges {\n node {\n id\n name\n slug\n }\n }\n }\n }\n `).then((result) => {\n if (result.errors) {\n reject(result.errors)\n }\n result.data.allContentfulStore.edges.forEach((edge) => {\n createPage ({\n path: edge.node.slug,\n component: storeTemplate,\n context: {\n slug: edge.node.slug\n }\n })\n })\n return\n })\n )\n })\n}\n```\n\n```text\ngatsby-node.js\n```\n\n```text\ncreatePages\n```\n\n```text\nallContentfulStore\n```\n\n```text\nstore\n```\n\n========================================\n\nComments:\n- Getting `GraphQLError: Syntax Error GraphQL request (16:6) Expected Name, found ` when running this. Any reason as to why?\n- try deleting `.cache` and `public` folder also you can check the query in the GrapiQL server that gatsby spawns with your dev build it should be `localhost:port/___grapql` Maybe the ContentType is named differently not store\n- @KhaledGarbaya , your YouTube video is truly awesome! Thank you for your help. It is greatly appreciated.","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":222,"estimatedTokens":1204}}460{"id":"stack-60197851","source":"stackoverflow","questionId":60197851,"title":"Apollo Client is not reading variables passed in using useQuery hook","tags":["reactjs","graphql","apollo-client"],"text":"Title: Apollo Client is not reading variables passed in using useQuery hook\nTags: reactjs, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nHaving a weird issue passing variables into the useQuery hook.\n\nThe query:\n\n```\nconst GET_USER_BY_ID= gql`\n query($id: ID!) {\n getUser(id: $id) {\n id\n fullName\n role\n }\n }\n`;\n```\n\nCalling the query:\n\n```\nconst DisplayUser: React.FC = ({ id }) => {\n const { data, error } = useQuery(GET_USER_BY_ID, {\n variables: { id },\n });\n\n return {JSON.stringify({ data, error })};\n};\n```\n\nRendering the component:\n\n```\n\n```\n\nThis yields the error: \n\n```\n\"Argument \\\"id\\\" of required type \\\"ID!\\\" was provided the variable \\\"$id\\\" which was not provided a runtime value.\"\n```\n\nCalling the query from GraphQL Playground returns the expected result:\n\n```\n{\n \"data\": {\n \"getUser\": {\n \"id\": \"5e404fa72b819d1410a3164c\",\n \"fullName\": \"Test 1\",\n \"role\": \"USER\"\n }\n }\n}\n```\n\nAnd calling the query without a variable but instead hard-coding the id:\n\n```\nconst GET_USER_BY_ID = gql`\n query {\n getUser(id: \"5e404fa72b819d1410a3164c\") {\n id\n fullName\n role\n }\n }\n`;\n\nconst DisplayUser: React.FC = () => {\n const { data, error } = useQuery(GET_USER_BY_ID);\n\n return {JSON.stringify({ data, error })};\n};\n```\n\nAlso returns the expected result.\n\nI have also attempted to test a similar query that takes `firstName: String!` as a parameter which also yields an error saying that the variable was not provided a runtime value. This query also works as expected when hard-coding a value in the query string.\n\nThis project was started today and uses `\"apollo-boost\": \"^0.4.7\"`, `\"graphql\": \"^14.6.0\"`, and `\"react-apollo\": \"^3.1.3\"`.\n\n========================================\n\nTop Answer:\nI had also ran into a similar issue and was not really sure what was happening.\nThere seems to be similar problem reported here - https://github.com/apollographql/graphql-tools/issues/824\n\nWe have 2 options to fix the issue.\n\nFirst one is a simple fix, where in you don't make the `ID` mandatory when it takes only a single parameter ( which is not an object )\n\nconst GET_USER_BY_ID= gql`\nquery($id: ID) {\n\nSecond option is to use input type as a parameter instead of a primitive. The input type and id property can both be required in this case.\n// On the client\n\n\r\n\r\n\n```\nconst GET_USER_BY_ID= gql`\n query($input: GetUserInput!) {\n getUser(input: $input) {\n id\n fullName\n role\n }\n}`; \n \nconst { data, error } = useQuery(GET_USER_BY_ID, {\n variables: { input: { id }},\n});\n```\n\n\r\n\r\n\r\n\n// In the server, define the input type\n\n```\ninput GetUserInput {\n id: ID!\n }\n```\n\n========================================\n\nCode:\n```text\nconst GET_USER_BY_ID= gql`\n query($id: ID!) {\n getUser(id: $id) {\n id\n fullName\n role\n }\n }\n`;\n```\n\n```text\nconst DisplayUser: React.FC<{ id: string }> = ({ id }) => {\n const { data, error } = useQuery(GET_USER_BY_ID, {\n variables: { id },\n });\n\n return <div>{JSON.stringify({ data, error })}</div>;\n};\n```\n\n```text\n<DisplayUser id=\"5e404fa72b819d1410a3164c\" />\n```\n\n```text\n\"Argument \\\"id\\\" of required type \\\"ID!\\\" was provided the variable \\\"$id\\\" which was not provided a runtime value.\"\n```\n\n```text\n{\n \"data\": {\n \"getUser\": {\n \"id\": \"5e404fa72b819d1410a3164c\",\n \"fullName\": \"Test 1\",\n \"role\": \"USER\"\n }\n }\n}\n```\n\n```text\nconst GET_USER_BY_ID = gql`\n query {\n getUser(id: \"5e404fa72b819d1410a3164c\") {\n id\n fullName\n role\n }\n }\n`;\n\nconst DisplayUser: React.FC = () => {\n const { data, error } = useQuery(GET_USER_BY_ID);\n\n return <div>{JSON.stringify({ data, error })}</div>;\n};\n```\n\n```text\nfirstName: String!\n```\n\n```text\n\"apollo-boost\": \"^0.4.7\"\n```\n\n```text\n\"graphql\": \"^14.6.0\"\n```\n\n```text\n\"react-apollo\": \"^3.1.3\"\n```\n\n```text\ngraphql-query-complexity\n```\n\n```html\nconst GET_USER_BY_ID= gql`\n query($input: GetUserInput!) {\n getUser(input: $input) {\n id\n fullName\n role\n }\n}`; \n \nconst { data, error } = useQuery(GET_USER_BY_ID, {\n variables: { input: { id }},\n});\n```\n\n```text\ninput GetUserInput {\n id: ID!\n }\n```\n\n```text\nID\n```\n\n```text\nconst { data, error } = useQuery(GET_USER_BY_ID, { id });\n```\n\n========================================\n\nComments:\n- That hook looks correct, so I suspect it's either a bug with `react-apollo` or something else is going on with your code. If you log the value of `id` to the console inside the component, is it defined?\n- Yes that's correct, the id logs as expected.\n- test in playground version with variables ... check with name `User` after `query`: `query User($id: ID!) { getUser ....`\n- @xadm hmm it's not liking the variables there either. I guess that would mean it's an issue with my server? I'm running typeorm and type-graphql.\n- how playground/docs defines ID type ?\n- I tried this solution, however unfortunately I am still getting the error that my variable is not being provided a runtime value.","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":252,"estimatedTokens":1230}}461{"id":"stack-63436277","source":"stackoverflow","questionId":63436277,"title":"How to generate GraphQL operations from GraphQL schema","tags":["typescript","graphql","apollo-client","graphql-codegen"],"text":"Title: How to generate GraphQL operations from GraphQL schema\nTags: typescript, graphql, apollo-client, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nI am looking for a way to make the developer workflow more efficient while GraphQL.\n\nCurrently, using `graphql-code-generator` to generate types from my GraphQL server on the frontend.\n\nThis is great, but this is only generating types. In order to generate methods for mutations, queries and subscriptions, I need to create a GraphQL document for each operation in my frontend project, for example:\n\n```\nfile addPost.graphql\n\nmutation addPost {\n...\n}\n...\n```\n\nI find having to create an extra `addPost.graphql` to generate the method a bit redundant as it is already declared on my GraphQL server.\n\nIs there a plugin/configuration that will generate these methods that I can use in my project without having to manually create the additional GraphQL documents?\n\nHere is my GraphQL generator yml file\n\n```\n# graphql-generator.yml\noverwrite: true\nschema: https://localhost:8088/query\ndocuments: ./libs/**/*.graphql <----- generating these *.graphql files would be great! \ngenerates:\n libs/graphql/src/lib/generated/graphql.ts:\n plugins:\n - \"typescript\"\n - \"typescript-resolvers\"\n - \"typescript-operations\"\n - \"typescript-apollo-angular\"\n ./graphql.schema.json:\n plugins:\n - \"introspection\"\n```\n\n========================================\n\nTop Answer:\nSee also https://github.com/timqian/gql-generator\n\nGenerate queries from graphql schema, used for writing api test.\n\nThis tool generate 3 folders holding the queries: mutations, queries and subscriptions\n\n========================================\n\nCode:\n```text\nfile addPost.graphql\n\nmutation addPost {\n...\n}\n...\n```\n\n```text\n# graphql-generator.yml\noverwrite: true\nschema: https://localhost:8088/query\ndocuments: ./libs/**/*.graphql <----- generating these *.graphql files would be great! \ngenerates:\n libs/graphql/src/lib/generated/graphql.ts:\n plugins:\n - \"typescript\"\n - \"typescript-resolvers\"\n - \"typescript-operations\"\n - \"typescript-apollo-angular\"\n ./graphql.schema.json:\n plugins:\n - \"introspection\"\n```\n\n```text\ngraphql-code-generator\n```\n\n```text\naddPost.graphql\n```\n\n```text\nimport {\n buildClientSchema,\n DocumentNode,\n getIntrospectionQuery,\n GraphQLSchema,\n OperationTypeNode,\n parse,\n print,\n} from 'graphql';\n\nimport { buildOperationNodeForField } from '@graphql-tools/utils';\n\n/**\n * @description Method to get schema from URL.\n * @param {string} url\n * @return {Promise<GraphQLSchema>}\n */\nasync function getSchemaFromUrl(url: string): Promise<GraphQLSchema> {\n // eslint-disable-next-line no-useless-catch\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n query: getIntrospectionQuery().toString(),\n }),\n });\n\n const { data } = await response.json();\n\n return buildClientSchema(data);\n } catch (e) {\n throw e;\n }\n}\n\n/**\n * @description Get operations from schema.\n * See: https://github.com/nestjs/graphql/issues/679\n * @param {string} url\n * @return {Promise<DocumentNode>}\n */\nasync function operationsFromSchema(url: string): Promise<DocumentNode> {\n const schema: GraphQLSchema = await getSchemaFromUrl(url);\n\n const operationsDictionary = {\n query: { ...(schema.getQueryType()?.getFields() || {}) },\n mutation: { ...(schema.getMutationType()?.getFields() || {}) },\n subscription: { ...(schema.getSubscriptionType()?.getFields() || {}) },\n };\n\n let documentString: string = '';\n\n Object.keys(operationsDictionary).forEach((kind: string) => {\n Object.keys((operationsDictionary as any)[kind]).forEach((field: string) => {\n const operationAST = buildOperationNodeForField({\n schema,\n kind: kind as OperationTypeNode,\n field,\n });\n\n documentString += print(operationAST);\n });\n });\n\n return parse(documentString);\n}\n\nexport default operationsFromSchema;\n```\n\n```text\nimport { CodegenConfig } from '@graphql-codegen/cli'\n\nconst config: CodegenConfig = {\n schema: process.env.REACT_APP_ADMIN_API_URL,\n overwrite: true,\n generates: {\n './src/graphql/schema.tsx': {\n documents: {\n [process.env.REACT_APP_ADMIN_API_URL]: {\n loader: './src/graphql/operationsFromSchema.ts',\n }\n },\n plugins: [\n 'typescript',\n 'typescript-operations',\n 'typescript-react-apollo'\n ],\n config: {\n dedupeOperationSuffix: true,\n omitOperationSuffix: true,\n },\n },\n }\n}\n\nexport default config\n```\n\n========================================\n\nComments:\n- Just to add, we needed something like that on GraphQL Mesh, so we've created a very simple tool that does that on GraphQL Tools. If anyone is interested, you could extract this code into a separate package, maybe the community could improve it: github.com/ardatan/graphql-tools/blob/master/packages/utils/‌​src/… Here are the tests to see usage: github.com/ardatan/graphql-tools/blob/master/packages/utils/‌​…\n- Or simply document how to import it from GraphQL Tools and example usages","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":197,"estimatedTokens":1304}}462{"id":"stack-51717277","source":"stackoverflow","questionId":51717277,"title":"How to chain together Mutations in apollo client","tags":["reactjs","graphql","apollo","react-apollo","apollo-client"],"text":"Title: How to chain together Mutations in apollo client\nTags: reactjs, graphql, apollo, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have a bunch of information stored in my state that I need to pass to my graphQL server using mutations, but I need to use the results of each mutation before I call the next one since I need to:\n\n- Create a new object in my database\n\n- Use the id generated for that object to create another object\n\n- Modify the original object to store the id generated by the second object\n\nI noticed that apollo Mutation components have an onCompleted callback, but I don't know how to use this callback to fire off another mutation or whether it's the right way solve my problem. I also looked into batching my mutations to send them all at once but it doesn't seem like that is the solution either. Any help would be appreciated\n\n========================================\n\nTop Answer:\nAll you need to do is nest these mutations depending on the data being passed.\n\nThe `onCompleted` and `onError` props can be used in your case, and they have access to the new data result too. But I personally think a nested format is more readable and easier to debug later.\n\nIt would be something like:\n\n```\nconst Mutations = () => (\n \n {(mutation1, { loading, error, data }) => (\n if (loading) return `Loading...`\n if (error) return `Error...`\n\n const id = get(data, 'result.id')\n\n return (\n \n {(mutation2, { loading, error, data }) => (\n\n if (loading) return `Loading...`\n if (error) return `Error...`\n\n (...)\n )}\n \n )}\n \n)\n```\n\n========================================\n\nCode:\n```text\nconst handleClick = async (mutation1Fn, mutation2Fn, mutation3Fn) => {\n const data1 = await mutation1Fn()\n const data2 = await mutation2Fn()\n const data3 = await mutation3Fn()\n}\n\nconst Mutations = () => (\n <Composer\n components={[\n <Mutation mutation={mutation1} />,\n <Mutation mutation={mutation2} />,\n <Mutation mutation={mutation3} />\n ]}\n >\n {([mutation1Fn, mutation2Fn, mutation3Fn]) => (\n <button\n onClick={() => handleClick(mutation1Fn, mutation2Fn, mutation3Fn)}\n >\n exec!\n </button>\n )}\n </Composer>\n)\n```\n\n```jsx\nconst Mutations = () => (\n <Mutation mutation={m1}>\n {(mutation1, { loading, error, data }) => (\n if (loading) return `Loading...`\n if (error) return `Error...`\n\n const id = get(data, 'result.id')\n\n return (\n <Mutation mutation={m2} variables={id} />\n {(mutation2, { loading, error, data }) => (\n\n if (loading) return `Loading...`\n if (error) return `Error...`\n\n (...)\n )}\n </Mutation>\n )}\n </Mutation>\n)\n```\n\n```text\nonCompleted\n```\n\n```text\nonError\n```\n\n========================================\n\nComments:\n- Do you have any control over the server? Is it possible for you to change the API?\n- @CarlosRufo , doesn't the Mutation component need a children prop? How would one handle this?\n- @CarlosRudo , also, how can I access the errors, loading, etc. props that the Mutation component passes to its render function\n- Thank you for your response, but I think I prefer Carlos's answer in terms of formatting and readability.","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":116,"estimatedTokens":809}}463{"id":"stack-47028381","source":"stackoverflow","questionId":47028381,"title":"GraphQL conditiontal Filter","tags":["graphql","graphql-js","graphcool"],"text":"Title: GraphQL conditiontal Filter\nTags: graphql, graphql-js, graphcool\nSource: Stack Overflow\n\nQuestion:\nUsing a GraphCool backend, is there a way to have conditional filter in a query?\n\nlet's say I have a query like this:\n\n```\nquery ($first: Int, $skip: Int, $favorited: Boolean) {\n allPhotos (\n first: $first\n skip: $skip\n filter: {\n favorited: $favorited\n }\n )\n {\n id\n url\n title\n favorited\n }\n}\n\n//variables: { \"first\": 10, \"skip\", \"favorited\": true }\n```\n\nThe query above would either: \n\n1) Fetch only photos that are favorited.\n\n2) Fetch only photos that are not favorited.\n\nMy problem is I want to be able to either:\n\n1) query photos that are ONLY either favorited OR not favorited.\n\n2) query photos regardless of whether or not they're favorited.\n\nHow do I conditionally include filters? Can I? I'm doing something with react-apollo in Javascript and I could figure out a solution with code, but I was wondering if there was a way to do it in graphql land.\n\n========================================\n\nCode:\n```text\nquery ($first: Int, $skip: Int, $favorited: Boolean) {\n allPhotos (\n first: $first\n skip: $skip\n filter: {\n favorited: $favorited\n }\n )\n {\n id\n url\n title\n favorited\n }\n}\n\n//variables: { \"first\": 10, \"skip\", \"favorited\": true }\n```\n\n```text\nquery ($first: Int, $skip: Int, $filter: PhotoFilter) {\n allPhotos (\n first: $first\n skip: $skip\n filter: $filter\n )\n {\n #requested fields\n }\n}\n```\n\n```text\n{ favorited: true }\n```\n\n```text\nfilter\n```\n\n```text\nfavorited\n```\n\n```text\n{ favorited: true }\n```\n\n```text\n{ favorited: false }\n```\n\n```text\n{}\n```\n\n```text\nPhotoFilter\n```\n\n========================================\n\nComments:\n- Thank you so much. I did not know variables did not have to be scalars! I had a hack in javascript where I would make the favorited variable be undefined (not null) and it would behave the way I want it to. I think if a variable is undefined then it is simply ignored. This is much better. I'm using GraphqlCool so this is quite easy. I just have to give the $photoFilter the type of PhotoFIlter.","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":111,"estimatedTokens":524}}464{"id":"stack-67863725","source":"stackoverflow","questionId":67863725,"title":"Apollo readQuery, get data from cache","tags":["graphql","apollo","apollo-client","react-apollo"],"text":"Title: Apollo readQuery, get data from cache\nTags: graphql, apollo, apollo-client, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get data from Apollo cache. I know that data is there because in Apollo dev tools specified records are available.\nIn my react app I making a simple click and set Id which later passes to the query. Result from `client.readQuery(...)` is `null`. I'm spinning around because don't know why. I'm using code exactly the same way as in docs.\n\nHere's a QUERY:\n\n```\nexport const RECRUIT_QUERY = gql`\n query Recruit($id: ID!) {\n Recruit(_id: $id) {\n _id\n firstName\n }\n }\n`;\n```\n\nUsage of apollo hooks in component:\n\n```\nconst client = useApolloClient();\nconst recruit = client.readQuery({\n query: RECRUIT_QUERY,\n variables: { id: selectedId }\n})\n```\n\nConfiguration of apollo:\n\n```\nexport const client = new ApolloClient({\n link: concat(\n authMiddleware,\n new HttpLink({\n uri: process.env.REACT_APP_API_URL,\n }),\n ),\n cache: new InMemoryCache(),\n});\n```\n\nHere's apollo store preview:\nhttps://i.sstatic.net/kEe9l.png\n\n========================================\n\nCode:\n```text\nexport const RECRUIT_QUERY = gql`\n query Recruit($id: ID!) {\n Recruit(_id: $id) {\n _id\n firstName\n }\n }\n`;\n```\n\n```text\nconst client = useApolloClient();\nconst recruit = client.readQuery({\n query: RECRUIT_QUERY,\n variables: { id: selectedId }\n})\n```\n\n```text\nexport const client = new ApolloClient({\n link: concat(\n authMiddleware,\n new HttpLink({\n uri: process.env.REACT_APP_API_URL,\n }),\n ),\n cache: new InMemoryCache(),\n});\n```\n\n```text\nclient.readQuery(...)\n```\n\n```text\nnull\n```\n\n```text\nclient.readFragment({\n id: '4587d3c2-b3e7-4ade-8736-709dc69ad31b',\n fragment: RECRUIT_FRAGMENT,\n });\n```\n\n```text\nclient.readFragment({\n id: 'Recruit:4587d3c2-b3e7-4ade-8736-709dc69ad31b',\n fragment: RECRUIT_FRAGMENT,\n})\n```\n\n```text\nreadFragment\n```\n\n========================================\n\nComments:\n- insert `debugger` and check if cache really contains these entries (don't trust dev tool) ... there is a difference between query and normalized type entries ... you're looking for `readFragment` ... why not simply use `useQuery` with `cache-only` field policy?\n- what if you only have the name and are looking for the id? I'm also always getting null\n- @DamianGreen in this case you may customize your key take a look at this official docs apollographql.com/docs/react/caching/…","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":610}}465{"id":"stack-60068428","source":"stackoverflow","questionId":60068428,"title":"How to send a GraphQL query to AWS AppSync from the commandline?","tags":["graphql","aws-cli","aws-appsync"],"text":"Title: How to send a GraphQL query to AWS AppSync from the commandline?\nTags: graphql, aws-cli, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nThe AWS CLI for AppSync has a lovely array of functions to manage it remotely from the command line of my workstation such that mostly I do not have to use the browser console.\n\nBut to do a query I have to go into the web browser console and find GraphQl queries under AppSync. I can change all manner of things via the CLI, but I can't find a command that simply issues a graphql query.\n\nHave I missed it? Is it there?\n\nI don't want to look at this screen anymore...\n\nhttps://i.sstatic.net/QeGvg.png\n\n========================================\n\nTop Answer:\nThe Appsync queries page is actually a conjunction of several things together. You cannot issue queries from the CLI according to (https://docs.aws.amazon.com/cli/latest/reference/appsync/index.html)\n\nYou can however use a GUI Client tool to send a POST to your Appsync endpoint. Like Postman or Insomnia (my personal favorite). However is your goal is to truly send GraphQL compliant queries through the CLI, then you will have to resort to 'curl's\n\nHere is an example python script I have that sends a curl request to my Appsync API.\n\n```\n#!/usr/bin/env python3\nimport os\n\ncmd = \"\"\"curl -i -H 'Content-Type: application/json' -H \"x-api-key: \" -H \"Host: \" -X POST -d '{\"query\": \"query {listEvents {items {id}}}\"}' https:///graphql\"\"\"\n\ndef doGraphqlRequest(): \n os.system(cmd)\n\nprint(\"Starting request to Appsync endpoint\")\ndoGraphQLRequest()\nprint(\"Finsihed request to Appsync endpoint\")\n```\n\nTo explain a bit, you are making a POST request with your query to your appsync given '/graphql/ endpoint.\nYou have 3 headers (Denoted by the -H flag)\n\n- The x-api-key: Only applicable if you use API KEY as the auth type. Other auth types work too, you might have a AuthToken: Bearer , and Cognito works too but is significantly more complicated from CLI\n\n- The host: This is the name of the ec2 host given by your api. You can find it by looking at your assigned endpoint and deleteing the https:// and /graphql\n\n- The Content-Type: application/json. This is kinda standard, not super sure why but it's a must have.\n\nHope this helps!\n\n========================================\n\nCode:\n```sh\n# Put the request in a file\n$ echo 'mutation createMessage($message: String!) {\n createMessage(input: {message: $message}) {\n id\n message\n createdAt\n }\n}' > mutation.graphql\n\n# Execute the request using gql-cli with --transport appsync_http\n$ cat mutation.graphql | gql-cli $AWS_GRAPHQL_API_ENDPOINT --transport appsync_http -V message:\"Hello world!\"\n```\n\n```sh\necho \"subscription{onCreateMessage{message}}\" | gql-cli $AWS_GRAPHQL_API_ENDPOINT --transport appsync_websockets\n```\n\n```text\n--transport appsync_http\n```\n\n```text\n--transport appsync_websockets\n```\n\n```text\n#!/usr/bin/env python3\nimport os\n\ncmd = \"\"\"curl -i -H 'Content-Type: application/json' -H \"x-api-key: <ENTER YOUR API KEY FROM THE APPSYNC SETTINGS PAGE>\" -H \"Host: <ENTER YOUR HOST ENDPOINT FROM THE APPSYNC API SETTINGS PAGE >\" -X POST -d '{\"query\": \"query {listEvents {items {id}}}\"}' https://<ENTER YOUR HOST ENDPOINT FROM THE APPSYNC API SETTINGS PAGE>/graphql\"\"\"\n\ndef doGraphqlRequest(): \n os.system(cmd)\n\nprint(\"Starting request to Appsync endpoint\")\ndoGraphQLRequest()\nprint(\"Finsihed request to Appsync endpoint\")\n```\n\n```text\n$ curl -H 'x-api-key: <API KEY>' -d '{\"query\":\"query {...}\"}' <API URL>\n```\n\n```text\ncurl -XPOST -H \"Content-Type:application/graphql\" -H \"x-api-key:ABC123\" -d '{ \"query\": \"query { movies { id } }\" }' https://YOURAPPSYNCENDPOINT/graphql\n```\n\n```text\ncurl -XPOST -H \"Content-Type:application/graphql\" -H \"x-api-key:**YOUR_API_KEY**\" -d **'{ \"query\":\"query { listTodos { items { title } } }\" }'** https://**YOUR_END_POINT**.amazonaws.com/graphql\n```\n\n```text\ncurl -XPOST -H \"Content-Type:application/graphql\" -H \"x-api-key:**YOUR_API_KEY**\" -d **\"{ \\\\\"query\\\\\":\\\\\"query { listTodos { items { title } } }\\\\\" }\"** https://**YOUR_END_POINT**.amazonaws.com/graphql\n```\n\n```text\n# gql.sh \nTOKEN=$1\n\nAPI_URL='insert api url from AWS console here'\nQUERY='your query here'\nVARIABLES='{\"id\":\"5\"}' \n\necho \"vars:\"\necho \"TOKEN $TOKEN\"\necho\necho \"QUERY $QUERY\"\necho\necho \"VARIABLES $VARIABLES\"\necho\necho \"API_URL $API_URL\"\necho\n\ncurl $API_URL \\\n-s -X POST \\\n-H \"Authorization: Bearer $TOKEN\" \\\n-H 'content-type: application/json' \\\n-d '{\"query\": \"'\"$QUERY\"'\", \"variables\": '$VARIABLES'}'\n```\n\n```text\ngql.sh [insert token here]\n```\n\n========================================\n\nComments:\n- Rather than forking curl, python could use `requests`, unless you know of a python graphql client that will do this with similar ease?\n- Thx. Just making sure I hadn't overlooked the command. You confirmed I haven't and thus I can now proceed to loudly complain about it :-)\n- No worries John. Complain away to the AppSync team as a feature request. What I think we would be further interested in know from you is 'What is the problem you are trying to solve that you believe an Appsync cli command for querying would fix? Is the problem with the graphiql page we host on the aws console? What exactly are your painpoints?' Would absolutely love to hear them if you could DM me or send and email to baladavi@amazon.com. Also, absolutely you can use the 'requests' library, it's just my style to do it the dumb way. First test with cli only, then scriptify the cli command:)\n- Three pains: 1) TESTING: if I can script it I can write tests to run against endpoints to check that everything is up and working as expected 2) DEV: when the browser times out it usually forgets the query I was working on; remembering to periodically saving my query to a scratch file is painful; forgetting is worse 3) DEV: I generally prefer to develop on files in an IDE, rather than a browser text input, which I do, but the dev cycle is (hack backend in IDE -> deploy -> hack query in browser)(repeat). It's a slow and sucky cycle.\n- Too simplistic for my purposes; i need to get through Cognito. Got any guides? Is there nothing in boto which will v4 sign a requests object, or calculate the credentials, for us?\n- Hey John. If you need to get through Cognito then you can still make an HTTP call like this but instead of an x-api-key you will pass an \"Authorization: \" When Auth is done with Cognito (I'm simplifying here a lot but to explain), Cognito returns 3 tokens, an AccessToken, an IDToken, and a RefreshToken. Each request to the AppSync API which sets auth to be Cognito requires the access token passed in the http headers. For development, if you need an access token to use, look into 'admin initiate auth' from Cognito docs. It will give you an admin token for dev use\n- Thanks, I reframed the question as python over here, and finally made some progress: stackoverflow.com/questions/60293311\n- Works! However, update for 2022, I had to remove the -H \"Host: \"\n- I think that should be `-X POST` (space)","metadata":{"transformedAt":"2026-08-18T18:32:36.059Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":149,"estimatedTokens":1744}}466{"id":"stack-39381436","source":"stackoverflow","questionId":39381436,"title":"GraphQL + Django: resolve queries using raw PostgreSQL query","tags":["python","django","postgresql","graphql","graphene-python"],"text":"Title: GraphQL + Django: resolve queries using raw PostgreSQL query\nTags: python, django, postgresql, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\n**What is the best way to use GraphQL with Django when using an external database to fetch data from multiple tables (i.e., creating a Django Model to represent the data would not correspond to a single table in my database)?**\n\nMy approach was to temporarily abandon using Django models since I don't think I fully understand them yet. (I'm completely new to Django as well as GraphQL.) I've set up a simple project with an app with a connected external Postgres DB. I followed all the setup from the Graphene Django tutorial and then hit a road block when I realized the model I created was an amalgam of several tables.\n\nI have a query that sends back the proper columns mapped to the fields in my model, but I don't know how to make this a dynamic connection such that when my API is hit, it queries my database and maps the rows to the model schema I've defined in Django.\n\nMy approach since has been to avoid models and use the simpler method demonstrated in Steven Luscher's talk: Zero to GraphQL in 30 Minutes.\n\n**TLDR;**\n\nThe goal is to be able to hit my GraphQL endpoint, use a cursor object from my django.db.connection to get a list of dictionaries that should resolve to a GraphQLList of OrderItemTypes (see below).\n\nThe problem is I am getting nulls for every value when I hit the following endpoint with a query:\n\n```\nlocalhost:8000/api?query={orderItems{date,uuid,orderId}}\n```\n\nreturns:\n\n```\n{ \"data\":{ \"orderItems\":[ {\"date\":null, \"uuid\":null, \"orderId\":null }, ... ] } }\n```\n\nproject/main/**app/schema.py**\n\n```\nimport graphene\nfrom django.db import connection\n\nclass OrderItemType(graphene.ObjectType):\n date = graphene.core.types.custom_scalars.DateTime()\n order_id = graphene.ID()\n uuid = graphene.String()\n\nclass QueryType(graphene.ObjectType):\n name = 'Query'\n order_items = graphene.List(OrderItemType)\n\n def resolve_order_items(root, args, info):\n data = get_order_items()\n\n # data prints out properly in my terminal\n print data\n # data does not resolve properly\n return data\n\ndef get_db_dicts(sql, args=None):\n cursor = connection.cursor()\n cursor.execute(sql, args)\n columns = [col[0] for col in cursor.description]\n data = [\n dict(zip(columns, row))\n for row in cursor.fetchall() ]\n\n cursor.close()\n return data\n\ndef get_order_items():\n return get_db_dicts(\"\"\"\n SELECT j.created_dt AS date, j.order_id, j.uuid\n FROM job AS j\n LIMIT 3;\n \"\"\")\n```\n\nIn my terminal, I print from QueryType's resolve method and I can see the data successfully comes back from my Postgres connection. However, the GraphQL gives me nulls so it has to be in the resolve method that some mapping is getting screwed up.\n\n```\n[ { 'uuid': u'7584aac3-ab39-4a56-9c78-e3bb1e02dfc1', 'order_id': 25624320, 'date': datetime.datetime(2016, 1, 30, 16, 39, 40, 573400, tzinfo=) }, ... ]\n```\n\nHow do I properly map my data to the fields I've defined in my OrderItemType?\n\nHere are some more references:\n\nproject/main/**schema.py**\n\n```\nimport graphene\n\nfrom project.app.schema import QueryType AppQuery\n\nclass Query(AppQuery):\n pass\n\nschema = graphene.Schema(\n query=Query, name='Pathfinder Schema'\n)\n```\n\n**file tree**\n\n```\n|-- project\n |-- manage.py\n |-- main\n |-- app\n |-- models.py\n |-- schema.py\n |-- schema.py\n |-- settings.py\n |-- urls.py\n```\n\n========================================\n\nTop Answer:\nHere is temporary workaround, although I'm hoping there is something cleaner to handle the snake_cased fieldnames.\n\n project/main/**app/schema.py**\n\n```\nfrom graphene import (\n ObjectType, ID, String, Int, Float, List\n)\nfrom graphene.core.types.custom_scalars import DateTime\nfrom django.db import connection\n\n''' Generic resolver to get the field_name from self's _root '''\ndef rslv(self, args, info):\n return self.get(info.field_name)\n\nclass OrderItemType(ObjectType):\n date = DateTime(resolver=rslv)\n order_id = ID()\n uuid = String(resolver=rslv)\n place_id = ID()\n\n ''' Special resolvers for camel_cased field_names '''\n def resolve_order_id(self, args, info):\n return self.get('order_id')\n\n def resolve_place_id(self, args, info):\n return self.get('place_id')\n\nclass QueryType(ObjectType):\n name = 'Query'\n order_items = List(OrderItemType)\n\n def resolve_order_items(root, args, info):\n return get_order_items()\n```\n\n========================================\n\nCode:\n```text\nlocalhost:8000/api?query={orderItems{date,uuid,orderId}}\n```\n\n```text\n{ \"data\":{ \"orderItems\":[ {\"date\":null, \"uuid\":null, \"orderId\":null }, ... ] } }\n```\n\n```python\nimport graphene\nfrom django.db import connection\n\n\nclass OrderItemType(graphene.ObjectType):\n date = graphene.core.types.custom_scalars.DateTime()\n order_id = graphene.ID()\n uuid = graphene.String()\n\nclass QueryType(graphene.ObjectType):\n name = 'Query'\n order_items = graphene.List(OrderItemType)\n\n def resolve_order_items(root, args, info):\n data = get_order_items()\n\n # data prints out properly in my terminal\n print data\n # data does not resolve properly\n return data\n\n\ndef get_db_dicts(sql, args=None):\n cursor = connection.cursor()\n cursor.execute(sql, args)\n columns = [col[0] for col in cursor.description]\n data = [\n dict(zip(columns, row))\n for row in cursor.fetchall() ]\n\n cursor.close()\n return data\n\ndef get_order_items():\n return get_db_dicts(\"\"\"\n SELECT j.created_dt AS date, j.order_id, j.uuid\n FROM job AS j\n LIMIT 3;\n \"\"\")\n```\n\n```text\n[ { 'uuid': u'7584aac3-ab39-4a56-9c78-e3bb1e02dfc1', 'order_id': 25624320, 'date': datetime.datetime(2016, 1, 30, 16, 39, 40, 573400, tzinfo=<UTC>) }, ... ]\n```\n\n```python\nimport graphene\n\nfrom project.app.schema import QueryType AppQuery\n\nclass Query(AppQuery):\n pass\n\nschema = graphene.Schema(\n query=Query, name='Pathfinder Schema'\n)\n```\n\n```text\n|-- project\n |-- manage.py\n |-- main\n |-- app\n |-- models.py\n |-- schema.py\n |-- schema.py\n |-- settings.py\n |-- urls.py\n```\n\n```text\ndef resolver(root, args, context, info):\n return getattr(root, 'order_items', None)\n```\n\n```text\nimport graphene\nfrom django.db import connection\nfrom collections import namedtuple\n\n\nclass OrderItemType(graphene.ObjectType):\n date = graphene.core.types.custom_scalars.DateTime()\n order_id = graphene.ID()\n uuid = graphene.String()\n\nclass QueryType(graphene.ObjectType):\n class Meta:\n type_name = 'Query' # This will be name in graphene 1.0\n\n order_items = graphene.List(OrderItemType)\n\n def resolve_order_items(root, args, info):\n return get_order_items() \n\n\ndef get_db_rows(sql, args=None):\n cursor = connection.cursor()\n cursor.execute(sql, args)\n columns = [col[0] for col in cursor.description]\n RowType = namedtuple('Row', columns)\n data = [\n RowType(*row) # Edited by John suggestion fix\n for row in cursor.fetchall() ]\n\n cursor.close()\n return data\n\ndef get_order_items():\n return get_db_rows(\"\"\"\n SELECT j.created_dt AS date, j.order_id, j.uuid\n FROM job AS j\n LIMIT 3;\n \"\"\")\n```\n\n```text\norder_items\n```\n\n```text\ngetattr\n```\n\n```text\ndict\n```\n\n```text\nNone\n```\n\n```text\n__getitem__\n```\n\n```text\ndict[key]\n```\n\n```text\ndicts\n```\n\n```text\nnamedtuples\n```\n\n```python\nfrom graphene import (\n ObjectType, ID, String, Int, Float, List\n)\nfrom graphene.core.types.custom_scalars import DateTime\nfrom django.db import connection\n\n''' Generic resolver to get the field_name from self's _root '''\ndef rslv(self, args, info):\n return self.get(info.field_name)\n\n\nclass OrderItemType(ObjectType):\n date = DateTime(resolver=rslv)\n order_id = ID()\n uuid = String(resolver=rslv)\n place_id = ID()\n\n ''' Special resolvers for camel_cased field_names '''\n def resolve_order_id(self, args, info):\n return self.get('order_id')\n\n def resolve_place_id(self, args, info):\n return self.get('place_id')\n\nclass QueryType(ObjectType):\n name = 'Query'\n order_items = List(OrderItemType)\n\n def resolve_order_items(root, args, info):\n return get_order_items()\n```\n\n```text\nfrom graphene.types.resolver import dict_resolver\n\nclass OrderItemType(ObjectType):\n\n class Meta:\n default_resolver = dict_resolver\n\n date = DateTime()\n order_id = ID()\n uuid = String()\n place_id = ID()\n```\n\n```text\ndict_resolver\n```\n\n========================================\n\nComments:\n- It should be noted that having all of these resolvers makes GraphQL incredibly slow.\n- That was incredibly helpful, thank you for taking the time! One minor edit is the row list should be spread before passed to the namedtuple `RowType(*row)`. In general, is this good practice or is there a better approach to fetching the external data?\n- If you see my second attempt (the other answer posted to this question), I used a resolver for each field using the dict[key] approach you suggested. From a couple of tests I just ran, it seems both methods return the data in the same amount of time. I wonder if the somewhat slow return time from GraphQL is normal (1000 records ~ 3-4 seconds after caching; before cachine, it takes ~6 seconds for the same dataset).\n- If you use the development version, the query will be resolved at least 10x times faster (300ms?). You can install it with `pip install graphene-django>=1.0.dev`. Hope this helps!","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":367,"estimatedTokens":2367}}467{"id":"stack-59920760","source":"stackoverflow","questionId":59920760,"title":"Python GraphQL gql client authentication","tags":["python","oauth","graphql","graphql-python"],"text":"Title: Python GraphQL gql client authentication\nTags: python, oauth, graphql, graphql-python\nSource: Stack Overflow\n\nQuestion:\nIΒ΄m having a hard time using GraphQL with Python,\nbecause the suggested library\n(gql)\nis completely undocumented.\n\nI found out that to provide the API URL,\nI need to pass an `RequestsHTTPTransport` object to `Client` like this:\n\n```\nclient = Client(transport=RequestsHTTPTransport(\n url='https://some.api.com/v3/graphql'))\n```\n\nbut how to provide credentials like the Bearer Key?\n\nI noticed that `RequestsHTTPTransport` also accepts an `auth` param,\nwhich is described as:\n\n:param auth: Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth\n\nHowever, I still can not find out how to create this tuple or callable to work with a `Bearer Key`. :(\n\n========================================\n\nTop Answer:\nI am able to authenticate using the Bearer Access Token and retrieve the data of a Graphql query successfully using the below Python script.\n\n```\nimport requests\nimport json\nimport urllib3\nfrom urllib3.util.ssl_ import create_urllib3_context\n\nctx = create_urllib3_context()\nctx.load_default_certs()\nctx.options |= 0x4 \n\nBASE_URL = 'url_here'\n\n \ndef authenticate():\n query = \"\"\"\n query here\n \"\"\"\n access_token = \"access token here\"\n\n # print(f'Access token: {access_token}')\n headers = {'Authorization': f'Bearer {access_token}'}\n\n \n with urllib3.PoolManager(ssl_context=ctx) as http:\n req = http.request(\"POST\", BASE_URL, json = {'query': query}, headers = headers)\n print(req.data) \n \n\nif __name__==\"__main__\":\n authenticate()\n```\n\n========================================\n\nCode:\n```py\nclient = Client(transport=RequestsHTTPTransport(\n url='https://some.api.com/v3/graphql'))\n```\n\n```text\nRequestsHTTPTransport\n```\n\n```text\nClient\n```\n\n```text\nRequestsHTTPTransport\n```\n\n```text\nauth\n```\n\n```text\nBearer Key\n```\n\n```text\nreqHeaders = {\n 'x-api-key' : API_KEY,\n 'Authorization': 'Bearer ' + TOKEN_KEY // This is the key\n}\n\n_transport = RequestsHTTPTransport(\n url=API_ENDPOINT,\n headers = reqHeaders,\n use_json=True,\n)\n\nclient = Client(\n transport = _transport,\n fetch_schema_from_transport=True,\n)\n```\n\n```text\nimport requests\nimport json\nimport urllib3\nfrom urllib3.util.ssl_ import create_urllib3_context\n\nctx = create_urllib3_context()\nctx.load_default_certs()\nctx.options |= 0x4 \n\nBASE_URL = 'url_here'\n\n \ndef authenticate():\n query = \"\"\"\n query here\n \"\"\"\n access_token = \"access token here\"\n\n # print(f'Access token: {access_token}')\n headers = {'Authorization': f'Bearer {access_token}'}\n\n \n with urllib3.PoolManager(ssl_context=ctx) as http:\n req = http.request(\"POST\", BASE_URL, json = {'query': query}, headers = headers)\n print(req.data) \n \n\n\nif __name__==\"__main__\":\n authenticate()\n```\n\n========================================\n\nComments:\n- What is the difference between API_KEY and TOKEN_KEY here?","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":147,"estimatedTokens":734}}468{"id":"stack-49829531","source":"stackoverflow","questionId":49829531,"title":"How to import GraphQL query?","tags":["reactjs","graphql","react-apollo"],"text":"Title: How to import GraphQL query?\nTags: reactjs, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have my project setup to import `.graphql` files. That works fine. But my problem is I don't know how to define a query in a `.graphql` file and import that into a component to use with `react-apollo`'s `` component.\n\nIn this example the author defines the query in JavaScript variable using `gql`:\n\n```\nimport gql from \"graphql-tag\";\nimport { Query } from \"react-apollo\";\n\nconst GET_DOGS = gql`\n {\n dogs {\n id\n breed\n }\n }\n`;\n\nconst Dogs = ({ onDogSelected }) => (\n \n {({ loading, error, data }) => {\n if (loading) return \"Loading...\";\n if (error) return `Error! ${error.message}`;\n\n return (\n \n {data.dogs.map(dog => (\n \n {dog.breed}\n \n ))}\n \n );\n }}\n \n);\n```\n\nBut, I instead want to store that query in a separate `.graphql` file and import it into the component.\n\nHere's what I have tried in my project. Here is a component, and I attempt to import `UserQuery` from my schema.\n\n```\nimport React from 'react'\nimport { Query } from 'react-apollo'\n\nimport { UserQuery } from '../api/schema.graphql'\n\nexport default () => \n \n {({ loading, error, data }) => {\n if (loading) return 'Loading...'\n if (error) return `Error! ${error.message}`\n return\n \n {data.users.map(name => \n- {name})}\n \n }}\n \n```\n\nHere is the `schema`:\n\n```\n# schema.graphql\n\nquery UserQuery {\n user {\n name,\n age,\n gender \n }\n}\n\ntype User {\n name: String,\n age: Int,\n gender: String\n}\n\ntype Query {\n say: String,\n users: [User]!\n}\n```\n\nWhen I try to import and use I get an error:\n\n modules.js?hash=e9c17311fe52dd0e0eccf0d792c40c73a832db48:28441 Warning: Failed prop type: The prop `query` is marked as required in `Query`, but its value is `undefined`.\n\nHow can I import queries this way?\n\n========================================\n\nCode:\n```text\nimport gql from \"graphql-tag\";\nimport { Query } from \"react-apollo\";\n\nconst GET_DOGS = gql`\n {\n dogs {\n id\n breed\n }\n }\n`;\n\nconst Dogs = ({ onDogSelected }) => (\n <Query query={GET_DOGS}>\n {({ loading, error, data }) => {\n if (loading) return \"Loading...\";\n if (error) return `Error! ${error.message}`;\n\n return (\n <select name=\"dog\" onChange={onDogSelected}>\n {data.dogs.map(dog => (\n <option key={dog.id} value={dog.breed}>\n {dog.breed}\n </option>\n ))}\n </select>\n );\n }}\n </Query>\n);\n```\n\n```text\nimport React from 'react'\nimport { Query } from 'react-apollo'\n\nimport { UserQuery } from '../api/schema.graphql'\n\nexport default () => \n <Query query={ UserQuery }>\n {({ loading, error, data }) => {\n if (loading) return 'Loading...'\n if (error) return `Error! ${error.message}`\n return\n <ul>\n {data.users.map(name => <li>{name}</li>)}\n </ul>\n }}\n </Query>\n```\n\n```text\n# schema.graphql\n\nquery UserQuery {\n user {\n name,\n age,\n gender \n }\n}\n\ntype User {\n name: String,\n age: Int,\n gender: String\n}\n\ntype Query {\n say: String,\n users: [User]!\n}\n```\n\n```text\n.graphql\n```\n\n```text\n.graphql\n```\n\n```text\nreact-apollo\n```\n\n```text\n<Query ...>\n```\n\n```text\ngql\n```\n\n```text\n.graphql\n```\n\n```text\nUserQuery\n```\n\n```text\nschema\n```\n\n```text\nquery\n```\n\n```text\nQuery\n```\n\n```text\nundefined\n```\n\n```text\nimport UserQuery from 'UserQuery.graphql';\n```\n\n```text\nimport * as file from 'UserQuery.graphql';\nconsole.log(file);\n```\n\n```text\ngraphql-tag/loader\n```\n\n```text\ndefault\n```\n\n```text\nconsole.log\n```\n\n========================================\n\nComments:\n- The message you posted is just a warning regarding Query component's proptypes. This won't break your build, but it is advisable to fix it. Your problem is caused by something else.\n- The Query component isn't receiving the `query`. It's undefined. `UserQuery` is not being imported.\n- On the server-side, if you don't want to use webpack, you can use `babel` along with `babel-plugin-inline-import`, which will allow you to import your schema as text","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":246,"estimatedTokens":1023}}469{"id":"stack-51935902","source":"stackoverflow","questionId":51935902,"title":"React-Apollo Mutation returns empty response","tags":["reactjs","graphql","apollo","react-apollo","aws-appsync"],"text":"Title: React-Apollo Mutation returns empty response\nTags: reactjs, graphql, apollo, react-apollo, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI am using AWS Appsync where I want to get a response from a successfully executed mutation. When I try my setup in the Appsync Graphql console I get a filled `\"data\": { \"mutateMeeting\" }` response: https://i.sstatic.net/Qp8bP.png\n\nWhen I try the same in my react application I can see in the dynamodb database, that the mutations happen, but *react-apollo* does not return the mutation response. As you can see in the apollo dev tool, the `\"data\": { \"mutateMeeting\" }` is **null** :https://i.sstatic.net/LxHvW.png\n\nWhat am I missing?\n\nThe corresponding **graphql schema** reads:\n\n```\ninput MeetingInput {\n id: String,\n start: String!,\n end: String!,\n agreements: [AgreementInput]!\n}\n\ntype Meeting {\n id: String!\n start: String!\n end: String!\n agreements: [Agreement]\n}\n\ntype Mutation { \n mutateMeeting (\n companyId: String!,\n meeting: MeetingInput!\n ): Meeting!\n}\n```\n\nthe **graphql-tag mutation** reads:\n\n```\nimport gql from 'graphql-tag'\n\nexport default gql`\n mutation mutateMeeting($companyId: String!, $meeting: MeetingInput!) {\n mutateMeeting(companyId: $companyId, meeting: $meeting) {\n id,\n start,\n end\n }\n }\n`\n```\n\nand the **react-apollo** inklusion is given by:\n\n```\nimport React, { Component } from 'react'\n// antd\nimport { Spin } from 'antd'\n// graphql\nimport { compose, graphql } from 'react-apollo'\nimport mutateMeeting from '../queries/mutateMeeting'\n\nclass MeetingStatus extends Component {\n componentDidMount() {\n const { mutateMeeting, meeting } = this.props\n console.log(meeting)\n const variables = {\n companyId: meeting.company.id,\n meeting: {\n start: meeting.start.toISOString(),\n end: meeting.end.toISOString(),\n agreements: meeting.agreements,\n }\n }\n console.log(variables)\n\n mutateMeeting({\n variables\n }).then(({data}) => console.log('got data', data))\n .catch(err => console.log(err))\n }\n\n render() {\n console.log(this.props)\n return convocado\n }\n}\n\nconst MeetingStatusWithInfo = compose(\n graphql(mutateMeeting, { name: 'mutateMeeting' })\n)(MeetingStatus)\n\nexport default (MeetingStatusWithInfo)\n```\n\n**Appsync request**\n\n```\n#set($uuid = $util.autoId())\n#set($batchData = [])\n#set( $meeting = ${context.arguments.meeting} )\n\n## Company\n#set( $meetingMap = {\n \"PK\" : $context.arguments.companyId,\n \"SK\" : \"Meeting-$uuid\",\n \"start\" : $meeting.start,\n \"end\" : $meeting.end\n} )\n$util.qr($batchData.add($util.dynamodb.toMapValues($meetingMap)))\n\n## Meeting\n$util.qr($meetingMap.put(\"PK\", $meetingMap.SK))\n$util.qr($batchData.add($util.dynamodb.toMapValues($meetingMap)))\n\n## Agreements\n#foreach($agreement in $meeting.agreements)\n #set( $agreementId = $util.autoId())\n #set( $agreementMap = {\n \"PK\" : $meetingMap.SK,\n \"SK\" : \"Agreement-$agreementId\",\n \"name\" : $agreement.name\n } )\n\n $util.qr($batchData.add($util.dynamodb.toMapValues($agreementMap)))\n#end\n\n{\n \"version\" : \"2018-05-29\",\n \"operation\" : \"BatchPutItem\",\n \"tables\": {\n \"Vysae\": $utils.toJson($batchData)\n }\n}\n```\n\n**Appsync response**:\n\n```\n#set( $meeting = $context.result.data.Vysae[1] )\n{\n \"id\": \"$meeting.PK\",\n \"start\": \"$meeting.start\",\n \"end\": \"$meeting.end\"\n}\n```\n\n========================================\n\nTop Answer:\nIn my case, I had to write an `update` function in the mutation in order to get the data returned.\n\nTry changing your mutation to this and look in the console to see if this changes anything:\n\n```\nmutateMeeting({\n variables,\n update: (proxy, {data: {mutateMeeting}}) => {\n console.log(\"Update: \", mutateMeeting);\n }\n}).then(({data}) => console.log('got data', data))\n .catch(err => console.log(err))\n}\n```\n\nThe `update` function might be called a couple of times, but you should eventually see your data being returned as you expect it.\n\nThis is what worked for me. If you want, you can look at my question and see if that helps: React Apollo - Strange Effect When Making Mutation?\n\n========================================\n\nCode:\n```text\ninput MeetingInput {\n id: String,\n start: String!,\n end: String!,\n agreements: [AgreementInput]!\n}\n\ntype Meeting {\n id: String!\n start: String!\n end: String!\n agreements: [Agreement]\n}\n\ntype Mutation { \n mutateMeeting (\n companyId: String!,\n meeting: MeetingInput!\n ): Meeting!\n}\n```\n\n```text\nimport gql from 'graphql-tag'\n\nexport default gql`\n mutation mutateMeeting($companyId: String!, $meeting: MeetingInput!) {\n mutateMeeting(companyId: $companyId, meeting: $meeting) {\n id,\n start,\n end\n }\n }\n`\n```\n\n```text\nimport React, { Component } from 'react'\n// antd\nimport { Spin } from 'antd'\n// graphql\nimport { compose, graphql } from 'react-apollo'\nimport mutateMeeting from '../queries/mutateMeeting'\n\nclass MeetingStatus extends Component {\n componentDidMount() {\n const { mutateMeeting, meeting } = this.props\n console.log(meeting)\n const variables = {\n companyId: meeting.company.id,\n meeting: {\n start: meeting.start.toISOString(),\n end: meeting.end.toISOString(),\n agreements: meeting.agreements,\n }\n }\n console.log(variables)\n\n mutateMeeting({\n variables\n }).then(({data}) => console.log('got data', data))\n .catch(err => console.log(err))\n }\n\n render() {\n console.log(this.props)\n return <div>convocado</div>\n }\n}\n\nconst MeetingStatusWithInfo = compose(\n graphql(mutateMeeting, { name: 'mutateMeeting' })\n)(MeetingStatus)\n\nexport default (MeetingStatusWithInfo)\n```\n\n```text\n#set($uuid = $util.autoId())\n#set($batchData = [])\n#set( $meeting = ${context.arguments.meeting} )\n\n## Company\n#set( $meetingMap = {\n \"PK\" : $context.arguments.companyId,\n \"SK\" : \"Meeting-$uuid\",\n \"start\" : $meeting.start,\n \"end\" : $meeting.end\n} )\n$util.qr($batchData.add($util.dynamodb.toMapValues($meetingMap)))\n\n## Meeting\n$util.qr($meetingMap.put(\"PK\", $meetingMap.SK))\n$util.qr($batchData.add($util.dynamodb.toMapValues($meetingMap)))\n\n## Agreements\n#foreach($agreement in $meeting.agreements)\n #set( $agreementId = $util.autoId())\n #set( $agreementMap = {\n \"PK\" : $meetingMap.SK,\n \"SK\" : \"Agreement-$agreementId\",\n \"name\" : $agreement.name\n } )\n\n $util.qr($batchData.add($util.dynamodb.toMapValues($agreementMap)))\n#end\n\n{\n \"version\" : \"2018-05-29\",\n \"operation\" : \"BatchPutItem\",\n \"tables\": {\n \"Vysae\": $utils.toJson($batchData)\n }\n}\n```\n\n```text\n#set( $meeting = $context.result.data.Vysae[1] )\n{\n \"id\": \"$meeting.PK\",\n \"start\": \"$meeting.start\",\n \"end\": \"$meeting.end\"\n}\n```\n\n```text\n\"data\": { \"mutateMeeting\" }\n```\n\n```text\n\"data\": { \"mutateMeeting\" }\n```\n\n```text\nmutateMeeting({\n variables,\n update: (proxy, {data: {mutateMeeting}}) => {\n console.log(\"Update: \", mutateMeeting);\n }\n}).then(({data}) => console.log('got data', data))\n .catch(err => console.log(err))\n}\n```\n\n```text\nupdate\n```\n\n```text\nupdate\n```\n\n========================================\n\nComments:\n- Can you please provide your resolvers? Because they might not properly be returning information with the expected property names in the right nesting, also, you might need to run an update, or updateQueries on the client after the data is returned.\n- I'll have a look at the update functionality and added the resolvers ;)\n- Your quickest start will be here: apollographql.com/docs/react/essentials/mutations.html#updat‌​e\n- @BenjaminCharais the from you mentioned update functions is for refreshing the cache. I want the ID, created by my request resolver, as a response from the mutation.\n- Ah I misunderstood, but where are your resolvers, because if you are passing back the appropriate information from them, then the response from the mutation will appropriately map to the request. I can add an answer to.... dummy data out the flow of information.\n- I am having this exact same problem. If anyone could please look at my post: stackoverflow.com/questions/52789125/… This would help me a lot","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":334,"estimatedTokens":1982}}470{"id":"stack-42882777","source":"stackoverflow","questionId":42882777,"title":"Schema is not configured for mutations","tags":["node.js","graphql","graphql-js"],"text":"Title: Schema is not configured for mutations\nTags: node.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have the following schema : \n\n```\nimport {\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLInt,\n GraphQLString\n} from 'graphql';\nlet counter = 100;\nconst schema = new GraphQLSchema({\n // Browse: http://localhost:3000/graphql?query={counter,message}\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n counter: {\n type: GraphQLInt,\n resolve: () => counter\n },\n message: {\n type: GraphQLString,\n resolve: () => 'Salem'\n }\n })\n }),\n mutiation: new GraphQLObjectType({\n name: 'Mutation',\n fields: () => ({\n incrementCounter: {\n type: GraphQLInt,\n resolve: () => ++counter\n }\n })\n })\n})\nexport default schema;\n```\n\nThe following query works fine: \n\n```\n{counter, message}\n```\n\nHowever, `mutation {incrementCounter}` throws the following errors : \n\n```\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Schema is not configured for mutations\",\n \"locations\": [\n {\n \"line\": 1,\n \"column\": 1\n }\n ]\n }\n ]\n}\n```\n\nKnown that the server is : \n\n```\nimport GraphQLHTTP from 'express-graphql';\nconst app = express();\napp.use('/graphql',GraphQLHTTP({schema}));\n```\n\nWhat's the missing thing that makes mutation configured ?\n\n========================================\n\nCode:\n```text\nimport {\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLInt,\n GraphQLString\n} from 'graphql';\nlet counter = 100;\nconst schema = new GraphQLSchema({\n // Browse: http://localhost:3000/graphql?query={counter,message}\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n counter: {\n type: GraphQLInt,\n resolve: () => counter\n },\n message: {\n type: GraphQLString,\n resolve: () => 'Salem'\n }\n })\n }),\n mutiation: new GraphQLObjectType({\n name: 'Mutation',\n fields: () => ({\n incrementCounter: {\n type: GraphQLInt,\n resolve: () => ++counter\n }\n })\n })\n})\nexport default schema;\n```\n\n```text\n{counter, message}\n```\n\n```text\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Schema is not configured for mutations\",\n \"locations\": [\n {\n \"line\": 1,\n \"column\": 1\n }\n ]\n }\n ]\n}\n```\n\n```text\nimport GraphQLHTTP from 'express-graphql';\nconst app = express();\napp.use('/graphql',GraphQLHTTP({schema}));\n```\n\n```text\nmutation {incrementCounter}\n```\n\n```text\nconst schema = new GraphQLSchema({\n // Browse: http://localhost:3000/graphql?query={counter,message}\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n counter: {\n type: GraphQLInt,\n resolve: () => counter\n },\n message: {\n type: GraphQLString,\n resolve: () => 'Salem'\n }\n })\n }),\n mutation: new GraphQLObjectType({ //β οΈ NOT mutiation\n name: 'Mutation',\n fields: () => ({\n incrementCounter: {\n type: GraphQLInt,\n resolve: () => ++counter\n }\n })\n })\n})\n```\n\n```text\nmutation\n```\n\n```text\nmutiation\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":183,"estimatedTokens":750}}471{"id":"stack-61246764","source":"stackoverflow","questionId":61246764,"title":"Nest.JS graphql get requested fields","tags":["typescript","graphql","nestjs"],"text":"Title: Nest.JS graphql get requested fields\nTags: typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nIn Nest.js Graphql, is it possible to fetch the required list of fields from a resolver? To determine which joins to executed, and which not to, for example for this db schema:\n\n```\nEmployee\n id\n employer_id\n name\n\nEmployer\n id\n name\n```\n\nIn case of the following graphql query:\n\n```\nquery {\n employees {\n id\n name\n employer {\n id\n }\n }\n }\n```\n\nIt is not necessary to fetch/join the employer data from the database, since the employer id can be accessed from the employee table.\n\n========================================\n\nTop Answer:\nIn your case, I recommend you to use FieldResolver in order to resolve the employer field.\nYou can get more information in resolvers article\n\n\r\n\r\n\n```\n#...\n\n@ResolveField()\nasync employer(@Parent() employee) {\n const { employer_id } = employee;\n return this.employerService.findById(employer_id);\n}\n\n#...\n```\n\n========================================\n\nCode:\n```text\nEmployee\n id\n employer_id\n name\n\nEmployer\n id\n name\n```\n\n```text\nquery {\n employees {\n id\n name\n employer {\n id\n }\n }\n }\n```\n\n```text\n@Query(() => [PostObject])\nasync posts(\n @FieldMap() fieldMap: FieldMap,\n) {\n console.log(fieldMap);\n}\n```\n\n```text\n{\n \"posts\": {\n \"id\": {},\n \"title\": {},\n \"body\": {},\n \"author\": {\n \"id\": {},\n \"username\": {},\n \"firstName\": {},\n \"lastName\": {}\n },\n \"comments\": {\n \"id\": {},\n \"body\": {},\n \"author\": {\n \"id\": {},\n \"username\": {},\n \"firstName\": {},\n \"lastName\": {}\n }\n }\n }\n}\n```\n\n```text\n{\n post { # post: [Post]\n id\n author: {\n id\n firstName\n lastName\n }\n }\n}\n```\n\n```text\nimport { fieldsList, fieldsMap } from 'graphql-fields-list';\nimport { Query, Info } from '@nestjs/graphql';\n\n@Query(() => [Post])\nasync post(\n @Info() info,\n) {\n console.log(fieldsList(info)); // [ 'id', 'firstName', 'lastName' ]\n console.log(fieldsMap(info)); // { id: false, firstName: false, lastName: false }\n console.log(fieldsProjection(info)); // { id: 1, firstName: 1, lastName: 1 };\n}\n```\n\n```text\ninfo\n```\n\n```js\n#...\n\n@ResolveField()\nasync employer(@Parent() employee) {\n const { employer_id } = employee;\n return this.employerService.findById(employer_id);\n}\n\n#...\n```\n\n========================================\n\nComments:\n- docs.nestjs.com/graphql/resolvers#graphql-argument-decorator‌​s - info?\n- This is basically a non-answer. The question was about how can one determine the necessity and avoid making this query if the only requested field is the id (which is already present in the `Employee` table.\n- I understand the point, but it is more convenient for FieldResolver to request all fields to EmployerService.getEmployerById. In that method, the result for the requested employer should be cached. EmployerService.getEmployerById is probably invoked from another part of the system and this is where we will really save execution cost in the database. On the other hand, if you really want to know what fields are requested to the api, you should add this argument decorator \"@Info (param ?: string)\" And get the list of selected attributes in this property: info.operation.selectionSet","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":165,"estimatedTokens":827}}472{"id":"stack-56032660","source":"stackoverflow","questionId":56032660,"title":"Converting .NET Enum to GraphQL EnumerationGraphType","tags":["c#",".net-core","graphql","graphql-dotnet"],"text":"Title: Converting .NET Enum to GraphQL EnumerationGraphType\nTags: c#, .net-core, graphql, graphql-dotnet\nSource: Stack Overflow\n\nQuestion:\nHow do I convert an enum to the EnumerationGraphType that GraphQL uses?\nHere is an example to illustrate what I'm talking about:\n\n```\npublic enum MeetingStatusType\n{\n Tentative,\n Unconfirmed,\n Confirmed,\n}\n```\n\n```\npublic class MeetingDto\n{\n public string Id { get; set; }\n public string Name { get; set; }\n public MeetingStatusType Status { get; set; }\n}\n```\n\n```\npublic class MeetingStatusEnumType : EnumerationGraphType\n{\n public MeetingStatusEnumType()\n {\n Name = \"MeetingStatusType\";\n }\n}\n```\n\n```\npublic class MeetingType : ObjectGraphType\n{\n public MeetingType()\n {\n Field(m => m.Id);\n Field(m => m.Name, nullable: true);\n Field(m => m.Status); // Fails here\n }\n}\n```\n\nObviously this doesn't work because there's no implicit conversion from `MeetingStatusType` to `MeetingStatusEnumType`. In the documentation, the models that they were mapping would rely directly on `MeetingStatusEnumType`, but it doesn't seem good to introduce the dependency on GraphQL on something like your domain types and objects. \nI feel like I'm missing a painfully easy way to register this field, but I can't figure it out for the life of me. Any help would be greatly appreciated!\n\n========================================\n\nTop Answer:\nYou need to tell graphql dotnet how to map the `Enum` type to the `EnumerationGraphType`.\n\n```\nGraphTypeTypeRegistry.Register(typeof(MeetingStatusType), typeof(EnumerationGraphType));\n```\n\n========================================\n\nCode:\n```text\npublic enum MeetingStatusType\n{\n Tentative,\n Unconfirmed,\n Confirmed,\n}\n```\n\n```text\npublic class MeetingDto\n{\n public string Id { get; set; }\n public string Name { get; set; }\n public MeetingStatusType Status { get; set; }\n}\n```\n\n```text\npublic class MeetingStatusEnumType : EnumerationGraphType<MeetingStatusType>\n{\n public MeetingStatusEnumType()\n {\n Name = \"MeetingStatusType\";\n }\n}\n```\n\n```text\npublic class MeetingType : ObjectGraphType<MeetingDto>\n{\n public MeetingType()\n {\n Field(m => m.Id);\n Field(m => m.Name, nullable: true);\n Field<MeetingStatusEnumType>(m => m.Status); // Fails here\n }\n}\n```\n\n```text\nMeetingStatusType\n```\n\n```text\nMeetingStatusEnumType\n```\n\n```text\nMeetingStatusEnumType\n```\n\n```text\nField(e => e.Id);\nField(e => e.Name, nullable: true);\nField<MeetingStatusEnumType>(\"meetingStatus\", resolve: e => e.Source.Status);\n```\n\n```text\nGraphTypeTypeRegistry.Register(typeof(MeetingStatusType), typeof(EnumerationGraphType<MeetingStatusType>));\n```\n\n```text\nEnum\n```\n\n```text\nEnumerationGraphType\n```\n\n```text\nField(m => m.Status, type: typeof(EnumerationGraphType<MeetingStatusType>));\n```\n\n========================================\n\nComments:\n- Can you show the defination of `Field` or the exact error message? I can only find one with first parameter is string.\n- Two errors show up: `Cannot implicitly convert type 'MeetingStatusType' to 'MeetingStatusEnumType'` `Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type` This is the definition of the Field overload I'm using: `public FieldType Field(string name, string description = null, QueryArguments arguments = null, Func, object> resolve = null, string deprecationReason = null) where TGraphType : IGraphType;`\n- Is this a typo? I don't see anything like `GraphTypeTypeRegistry`\n- Here it is, not a typo... GraphTypeTypeRegistry","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":144,"estimatedTokens":899}}473{"id":"stack-48338289","source":"stackoverflow","questionId":48338289,"title":"Tracking online user with GraphQL Apollo","tags":["node.js","websocket","graphql","apollo","apollo-server"],"text":"Title: Tracking online user with GraphQL Apollo\nTags: node.js, websocket, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI need to handle events \"user is now online\" and \"user is now offline\" on GraphQL Apollo Node.js server. What's the best way to do it?\n\n**My investigation**: I pretty sure that I don't need to implement any heartbeat logic, because subscriptions are working on WebSockets. But I didn't find any info in their docs how to handle WebSockets events like \"connecting\" and \"disconnecting\" from the subscription... Actually I can handle those events from the outside of actual subscription:\n\n```\nSubscriptionServer.create({\n execute,\n subscribe,\n schema,\n onConnect = (...args) => {\n console.log('User connected')\n },\n onDisconnect = (...args) => {\n console.log('User disconnected')\n }\n}, {\n server: ws,\n path: '/subscriptions'\n})\n```\n\nBut can't determine which user is connected via this socket.\n\n**My implementation**: for now I made it work like that:\n\nWe have express middleware for all the calls, it is pushing user object from jsonwebtoken to `req` object. Here I can trigger \"user is now online\" logic.\n\nI've created separate subscription, client subscribes on it on login and unsubscribes on logout. Since there is no *unsubscribe* handler, I manage to determine that filter function gets called on user disconnect without payload, so I did this approach:\n\n```\nuserOnlineSubscription: {\n subscribe: withFilter(\n () => pubSub.asyncIterator('userOnlineSubscription'),\n async (payload, variables) => {\n if (!payload) {\n // set user offline\n }\n return false\n }\n )\n}\n```\n\nAs for me, the solution above is ugly. Can someone recommend the better approach?\n\n========================================\n\nCode:\n```text\nSubscriptionServer.create({\n execute,\n subscribe,\n schema,\n onConnect = (...args) => {\n console.log('User connected')\n },\n onDisconnect = (...args) => {\n console.log('User disconnected')\n }\n}, {\n server: ws,\n path: '/subscriptions'\n})\n```\n\n```text\nuserOnlineSubscription: {\n subscribe: withFilter(\n () => pubSub.asyncIterator('userOnlineSubscription'),\n async (payload, variables) => {\n if (!payload) {\n // set user offline\n }\n return false\n }\n )\n}\n```\n\n```text\nreq\n```\n\n```text\nonConnect (connectionParams, webSocket) {\n const userPromise = new Promise((resolve, reject) => {\n if (connectionParams.jwt) {\n jsonwebtoken.verify(\n connectionParams.jwt,\n JWT_SECRET,\n (err, decoded) => {\n if (err) {\n reject(new Error('Invalid Token'))\n }\n\n resolve(\n User.findOne({\n where: { id: decoded.id }\n })\n )\n }\n )\n } else {\n reject(new Error('No Token'))\n }\n })\n\n return userPromise.then(user => {\n if (user) {\n return { user: Promise.resolve(user) }\n }\n\n return Promise.reject(new Error('No User'))\n })\n}\n```\n\n========================================\n\nComments:\n- Unfortunately with this approach \"jsonwebtoken.verify\" will be called twice: in this handler and inside the graphQL subscriptions. But I couldn't find better solution, so it must be the accepted answer since it works fine.","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":126,"estimatedTokens":826}}474{"id":"stack-52868759","source":"stackoverflow","questionId":52868759,"title":"Difference in usage of graphql-java vs graphql-java-tools","tags":["java","graphql","graphql-java-tools"],"text":"Title: Difference in usage of graphql-java vs graphql-java-tools\nTags: java, graphql, graphql-java-tools\nSource: Stack Overflow\n\nQuestion:\nIm new to graphql found 2 java implementation \nusing from official graphql: https://www.graphql-java.com/documentation/v10/\n\nand \n\nhttps://github.com/graphql-java-kickstart/graphql-java-tools\n\nLike whats their difference in implementing graphql in java?\n\n========================================\n\nCode:\n```text\ngraphql-java-tools\n```\n\n```text\ngraphql-Java\n```\n\n========================================\n\nComments:\n- what do you call \"Spring Graphql Common\"? I can't see any such thing in the repo you pointed at...\n- OK found in *this* example: github.com/graphql-java-kickstart/graphql-spring-boot/tree/…","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":30,"estimatedTokens":188}}475{"id":"stack-59417171","source":"stackoverflow","questionId":59417171,"title":"what's difference between schema and documents in Graphql?","tags":["graphql","code-generation"],"text":"Title: what's difference between schema and documents in Graphql?\nTags: graphql, code-generation\nSource: Stack Overflow\n\nQuestion:\nwhat's the difference between schema and documents in Graphql?\n\nschema is like this:\n\n```\ntype Query {\n fo: String\n}\n```\n\nbut the document is like:\n\n```\nquery SomeQuery {\n foo {\n bar\n }\n}\n```\n\nthe spec is really confusing https://graphql.github.io/graphql-spec/June2018/#sec-Language.Document\n\nI always use schema but for client-side type generation in graphql-code-generator it needs document file. https://graphql-code-generator.com/docs/getting-started/documents-field\n\n========================================\n\nCode:\n```text\ntype Query {\n fo: String\n}\n```\n\n```text\nquery SomeQuery {\n foo {\n bar\n }\n}\n```\n\n```text\nquery UsersQuery {\n users {\n id\n email\n }\n}\n```\n\n```text\nfragment UserFragment on User {\n id\n email\n}\n```\n\n```text\ntype User {\n id: ID!\n email: String!\n}\n```\n\n```text\nextend type User {\n name: String\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":74,"estimatedTokens":244}}476{"id":"stack-60852061","source":"stackoverflow","questionId":60852061,"title":"Recommended way to use GraphQL in Next.js app","tags":["reactjs","graphql","next.js","react-apollo","strapi"],"text":"Title: Recommended way to use GraphQL in Next.js app\nTags: reactjs, graphql, next.js, react-apollo, strapi\nSource: Stack Overflow\n\nQuestion:\nIn my apps, I am using following **NPM modules** to play with Strapi, GraphQL and Next.js:\n\n- react-apollo\n\n- next-apollo\n\n- graphql\n\n- gql\n\n- recompose\n\nIn the next step, I am creating Apollo config file, example below:\n\n```\nimport { HttpLink } from \"apollo-link-http\";\nimport { withData } from \"next-apollo\";\n\nconst config = {\n link: new HttpLink({\n uri: \"http://localhost:1337/graphql\",\n })\n};\nexport default withData(config);\n```\n\nand then inside a class component, I am using a static method `getInitialProps()` to fetch data from the Strapi via GraphQL query.\n\nEverything is fine but maybe there is another, better way via React hooks or any other?\n\n========================================\n\nTop Answer:\nI have found one more interestng solution with using apollo-server-micro and lodash\n\n**Quick guide:**\n\ncreate Next.js app (example name: *next-app*) and install required packages\n\n```\nnpm i apollo-server-micro lodash\n```\n\ncreate required files in you Next.js app (*next-app*)\n\n- /next-app/pages/api/graphql/**index.js**\n\n- /next-app/pages/api/graphql/**resolvers.js**\n\n- /next-app/pages/api/graphql/**typeDefs.js**\n\nadd code to **index.js**\n\n```\nimport { ApolloServer } from 'apollo-server-micro';\nimport resolvers from './resolvers';\nimport typeDefs from './TypeDef';\n\nconst apolloServer = new ApolloServer({\n typeDefs,\n resolvers,\n});\n\nexport const config = {\n api: {\n bodyParser: false\n }\n};\n\nexport default apolloServer.createHandler({ path: '/api/graphql' });\n```\n\nadd code to **typeDefs.js**\n\n```\nimport { gql } from 'apollo-server-micro';\n\nconst typeDefs = gql`\n type User {\n id: Int!\n name: String!\n age: Int\n active: Boolean!\n }\n type Query {\n getUser(id: Int): User\n }\n`;\n\nexport default typeDefs;\n```\n\nadd code to **resolvers.js**\n\n```\nimport lodash from 'lodash/collection';\n\nconst users = [\n { id: 1, name: 'Mario', age: 38, active: true },\n { id: 2, name: 'Luigi', age: 40, active: true},\n { id: 3, name: 'Wario', age: 36, active: false }\n];\n\nconst resolvers = {\n Query: {\n getUser: (_, { id }) => {\n return lodash.find(users, { id });\n }\n }\n};\n\nexport default resolvers;\n```\n\ntest your Next.js app (*next-app*) by running below command and checking graphql URL http://localhost:3000/api/graphql\n\n```\nnpm run dev\n```\n\n========================================\n\nCode:\n```text\nimport { HttpLink } from \"apollo-link-http\";\nimport { withData } from \"next-apollo\";\n\nconst config = {\n link: new HttpLink({\n uri: \"http://localhost:1337/graphql\",\n })\n};\nexport default withData(config);\n```\n\n```text\ngetInitialProps()\n```\n\n```text\nnpm install --save @apollo/react-hooks apollo-cache-inmemory apollo-client apollo-link-http graphql graphql-tag isomorphic-unfetch next-with-apollo\n```\n\n```text\nimport { ApolloClient } from \"apollo-client\";\nimport { InMemoryCache } from \"apollo-cache-inmemory\";\nimport withApollo from \"next-with-apollo\";\nimport { createHttpLink } from \"apollo-link-http\";\nimport fetch from \"isomorphic-unfetch\";\n\nconst GRAPHQL_URL = process.env.BACKEND_URL || \"https://api.graphql.url\";\n\nconst link = createHttpLink({\n fetch,\n uri: GRAPHQL_URL\n});\n\nexport default withApollo(\n ({ initialState }) =>\n new ApolloClient({\n link: link,\n cache: new InMemoryCache()\n .restore(initialState || {})\n })\n);\n```\n\n```text\nimport React from \"react\";\nimport Head from \"next/head\";\nimport { ApolloProvider } from \"@apollo/react-hooks\";\nimport withData from \"../config/apollo\";\n\nconst App = ({ Component, pageProps, apollo }) => {\n return (\n <ApolloProvider client={apollo}>\n <Head>\n <title>App Title</title>\n </Head>\n <Component {...pageProps} />\n </ApolloProvider>\n )\n};\n\nexport default withData(App);\n```\n\n```text\nimport React from \"react\"; \nimport { useQuery } from \"@apollo/react-hooks\";\n\nconst Query = ({ children, query, id }) => { \n const { data, loading, error } = useQuery(query, {\n variables: { id: id }\n });\n\n if (loading) return <p>Loading...</p>;\n if (error) return <p>Error: {JSON.stringify(error)}</p>;\n return children({ data });\n};\n\nexport default Query;\n```\n\n```text\nimport React from \"react\";\nimport Query from \"../components/query\";\nimport GRAPHQL_TEST_QUERY from \"../queries/test-query\";\n\nconst Example = () => { \n return (\n <div>\n <Query query={GRAPHQL_TEST_QUERY} id={null}>\n {({ data: { graphqlData } }) => {\n return (\n <div>\n {graphqlData.map((fetchedItem, i) => {\n return (\n <div key={fetchedItem.id}>\n {fetchedItem.name}\n </div>\n );\n })}\n </div>\n );\n }}\n </Query>\n </div>\n );\n};\n\nexport default Example;\n```\n\n```text\nimport gql from \"graphql-tag\";\n\nconst GRAPHQL_TEST_QUERY = gql`\n query graphQLData {\n exampleTypeOfData {\n id\n name\n }\n }\n`;\n\nexport default GRAPHQL_TEST_QUERY;\n```\n\n```text\nimport Example from './components/example';\n\nconst Index = () => <div><Example /></div>\n\nexport default Index;\n```\n\n```text\n./config\n```\n\n```text\nappollo.js\n```\n\n```text\n_app.js\n```\n\n```text\n./pages\n```\n\n```text\n./queries/test-query\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\nindex.js\n```\n\n```text\n./pages\n```\n\n```text\nnpm i apollo-server-micro lodash\n```\n\n```text\nimport { ApolloServer } from 'apollo-server-micro';\nimport resolvers from './resolvers';\nimport typeDefs from './TypeDef';\n\nconst apolloServer = new ApolloServer({\n typeDefs,\n resolvers,\n});\n\nexport const config = {\n api: {\n bodyParser: false\n }\n};\n\nexport default apolloServer.createHandler({ path: '/api/graphql' });\n```\n\n```text\nimport { gql } from 'apollo-server-micro';\n\nconst typeDefs = gql`\n type User {\n id: Int!\n name: String!\n age: Int\n active: Boolean!\n }\n type Query {\n getUser(id: Int): User\n }\n`;\n\nexport default typeDefs;\n```\n\n```text\nimport lodash from 'lodash/collection';\n\nconst users = [\n { id: 1, name: 'Mario', age: 38, active: true },\n { id: 2, name: 'Luigi', age: 40, active: true},\n { id: 3, name: 'Wario', age: 36, active: false }\n];\n\nconst resolvers = {\n Query: {\n getUser: (_, { id }) => {\n return lodash.find(users, { id });\n }\n }\n};\n\nexport default resolvers;\n```\n\n```text\nnpm run dev\n```\n\n========================================\n\nComments:\n- Take a look at github.com/UnlyEd/next-right-now, it's a boilerplate with built-in GraphQL support, you may find it easier to get started with, or could use it as a learning resource. See github.com/UnlyEd/next-right-now/blob/master/src/pages/… for GraphQL query usage. Also, it uses TypeScript and has built-in GraphQL autocompletion in WebStorm.\n- Also check out the 1st party examples: github.com/zeit/next.js/tree/canary/examples. There are several stripped down graphql examples (they have graphql in their name)","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":368,"estimatedTokens":1754}}477{"id":"stack-43471623","source":"stackoverflow","questionId":43471623,"title":"Apollo client mutation error handling","tags":["graphql","apollo","apollo-client"],"text":"Title: Apollo client mutation error handling\nTags: graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm using GraphQL and mongoose on the server.\n\nWhen a validation error occurs the GraphQL mutation sends a response with status code 200. On the client side the response looks like this:\n\n\r\n\r\n\n```\n{\r\n \"data\": null,\r\n \"errors\": [{\r\n \"message\": \"error for id...\",\r\n \"path\": \"_id\"\r\n }]\r\n}\n```\n\n\r\n\r\n\r\n\nI would like to get access to the validation error using the `catch` functionality of the apollo-client mutation promise. Something like:\n\n\r\n\r\n\n```\nthis.props.deleteProduct(this.state.selectedProductId).then(response => {\r\n // handle successful mutation\r\n }).catch(response => {\r\n const errors = response.errors; // does not work\r\n this.setState({ errorMessages: errors.map(error => error.message) });\r\n });\n```\n\n\r\n\r\n\r\n\nHow can this be done?\n\n========================================\n\nTop Answer:\nThe previous answer from @stubailo does not seem to cover all use cases. If I throw an error on my server side code the response code will be different than 200 and the error will be handled using `.catch()` and not using `.then()`.\n\nLink to the issue on GitHub.\n\nThe best is probably to handle the error on both `.then()` and `.catch()`.\n\n```\nconst { deleteProduct } = this.props;\nconst { selectedProductId } = this.state;\n\ndeleteProduct(selectedProductId)\n .then(res => {\n if (!res.errors) {\n // handle success\n } else {\n // handle errors with status code 200\n }\n })\n .catch(e => {\n // GraphQL errors can be extracted here\n if (e.graphQLErrors) {\n // reduce to get message\n _.reduce(\n e.graphQLErrors,\n (res, err) => [...res, error.message],\n []\n );\n }\n })\n```\n\n========================================\n\nCode:\n```js\n{\n \"data\": null,\n \"errors\": [{\n \"message\": \"error for id...\",\n \"path\": \"_id\"\n }]\n}\n```\n\n```js\nthis.props.deleteProduct(this.state.selectedProductId).then(response => {\n // handle successful mutation\n }).catch(response => {\n const errors = response.errors; // does not work\n this.setState({ errorMessages: errors.map(error => error.message) });\n });\n```\n\n```text\ncatch\n```\n\n```text\n// The container\nconst withData = graphql(SUBMIT_REPOSITORY_MUTATION, {\n props: ({ mutate }) => ({\n submit: repoFullName => mutate({\n variables: { repoFullName },\n }),\n }),\n});\n\n// Where it's called\nreturn submit(repoFullName).then((res) => {\n if (!res.errors) {\n browserHistory.push('/feed/new');\n } else {\n this.setState({ errors: res.errors });\n }\n});\n```\n\n```text\ncatch\n```\n\n```text\nerrors\n```\n\n```text\nthen\n```\n\n```text\ncatch\n```\n\n```js\nconst { deleteProduct } = this.props;\nconst { selectedProductId } = this.state;\n\ndeleteProduct(selectedProductId)\n .then(res => {\n if (!res.errors) {\n // handle success\n } else {\n // handle errors with status code 200\n }\n })\n .catch(e => {\n // GraphQL errors can be extracted here\n if (e.graphQLErrors) {\n // reduce to get message\n _.reduce(\n e.graphQLErrors,\n (res, err) => [...res, error.message],\n []\n );\n }\n })\n```\n\n```text\n.catch()\n```\n\n```text\n.then()\n```\n\n```text\n.then()\n```\n\n```text\n.catch()\n```\n\n```text\n<Mutation mutation={UPDATE_TODO} key={id}>\n {(updateTodo, { loading, error }) => (\n <div>\n <p>{type}</p>\n <form\n onSubmit={e => {\n e.preventDefault();\n updateTodo({ variables: { id, type: input.value } });\n\n input.value = \"\";\n }}\n >\n <input\n ref={node => {\n input = node;\n }}\n />\n <button type=\"submit\">Update Todo</button>\n </form>\n {loading && <p>Loading...</p>}\n {error && <p>Error :( Please try again</p>}\n </div>\n )}\n </Mutation>\n```\n\n========================================\n\nComments:\n- try using `throw` statement by creating `Error` instance\n- This does not work. Error is handled on .catch() and not on .then()\n- Yeah this comment is posted before an API change in Apollo Client.\n- Wonder why there isn't a more graceful way to extract error messages and error codes out.","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":217,"estimatedTokens":1072}}478{"id":"stack-35757593","source":"stackoverflow","questionId":35757593,"title":"What is the idiomatic, performant way to resolve related objects?","tags":["relational-database","graphql"],"text":"Title: What is the idiomatic, performant way to resolve related objects?\nTags: relational-database, graphql\nSource: Stack Overflow\n\nQuestion:\nHow do you write query resolvers in GraphQL that perform well against a relational database?\n\nUsing the example schema from this tutorial, let's say I have a simple database with `users` and `stories`. Users can author multiple stories but stories only have one user as their author (for simplicity). \n\nWhen querying for a user, one might also want to get a list of all stories authored by that user. One possible definition a GraphQL query to handle that (stolen from the above linked tutorial):\n\n```\nconst Query = new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n user: {\n type: User,\n args: {\n id: {\n type: new GraphQLNonNull(GraphQLID)\n }\n },\n resolve(parent, {id}, {db}) {\n return db.get(`\n SELECT * FROM User WHERE id = $id\n `, {$id: id});\n }\n },\n })\n});\n\nconst User = new GraphQLObjectType({\n name: 'User',\n fields: () => ({\n id: {\n type: GraphQLID\n },\n name: {\n type: GraphQLString\n },\n stories: {\n type: new GraphQLList(Story),\n resolve(parent, args, {db}) {\n return db.all(`\n SELECT * FROM Story WHERE author = $user\n `, {$user: parent.id});\n }\n }\n })\n});\n```\n\nThis will work as expected; if I query a specific user, I'll be able to get that user's stories as well if needed. However, this does not perform ideally. It requires two trips to the database, when a single query with a `JOIN` would have sufficed. The problem is amplified if I query multiple users -- every additional user will result in an additional database query. The problem gets worse exponentially the deeper I traverse my object relationships.\n\nHas this problem been solved? Is there a way to write a query resolver that won't result in inefficient SQL queries being generated?\n\n========================================\n\nCode:\n```text\nconst Query = new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n user: {\n type: User,\n args: {\n id: {\n type: new GraphQLNonNull(GraphQLID)\n }\n },\n resolve(parent, {id}, {db}) {\n return db.get(`\n SELECT * FROM User WHERE id = $id\n `, {$id: id});\n }\n },\n })\n});\n\nconst User = new GraphQLObjectType({\n name: 'User',\n fields: () => ({\n id: {\n type: GraphQLID\n },\n name: {\n type: GraphQLString\n },\n stories: {\n type: new GraphQLList(Story),\n resolve(parent, args, {db}) {\n return db.all(`\n SELECT * FROM Story WHERE author = $user\n `, {$user: parent.id});\n }\n }\n })\n});\n```\n\n```text\nusers\n```\n\n```text\nstories\n```\n\n```text\nJOIN\n```\n\n```js\n// Pass this to graphql-js context\nconst storyLoader = new DataLoader((authorIds) => {\n return db.all(\n `SELECT * FROM Story WHERE author IN (${authorIds.join(',')})`\n ).then((rows) => {\n // Order rows so they match orde of authorIds\n const result = {};\n for (const row of rows) {\n const existing = result[row.author] || [];\n existing.push(row);\n result[row.author] = existing;\n }\n const array = [];\n for (const author of authorIds) {\n array.push(result[author] || []);\n }\n return array;\n });\n});\n\n// Then use dataloader in your type\nconst User = new GraphQLObjectType({\n name: 'User',\n fields: () => ({\n id: {\n type: GraphQLID\n },\n name: {\n type: GraphQLString\n },\n stories: {\n type: new GraphQLList(Story),\n resolve(parent, args, {rootValue: {storyLoader}}) {\n return storyLoader.load(parent.id);\n }\n }\n })\n});\n```\n\n```js\nconst User = new GraphQLObjectType({\n name: 'User',\n fields: () => ({\n id: {\n type: GraphQLID\n },\n name: {\n type: GraphQLString\n },\n stories: {\n type: new GraphQLList(Story),\n resolve(parent, args, {rootValue: {storyLoader}}) {\n // if stories were pre-fetched use that\n if (parent.stories) {\n return parent.stories;\n } else {\n // otherwise request them normally\n return db.all(`\n SELECT * FROM Story WHERE author = $user\n `, {$user: parent.id});\n }\n }\n }\n })\n});\n\nconst Query = new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n user: {\n type: User,\n args: {\n id: {\n type: new GraphQLNonNull(GraphQLID)\n }\n },\n resolve(parent, {id}, {rootValue: {db}, fieldASTs}) {\n // find names of all child fields\n const childFields = fieldASTs[0].selectionSet.selections.map(\n (set) => set.name.value\n );\n if (childFields.includes('stories')) {\n // use join to optimize\n return db.all(`\n SELECT * FROM User INNER JOIN Story ON User.id = Story.author WHERE User.id = $id\n `, {$id: id}).then((rows) => {\n if (rows.length > 0) {\n return {\n id: rows[0].author,\n name: rows[0].name,\n stories: rows\n };\n } else {\n return db.get(`\n SELECT * FROM User WHERE id = $id\n `, {$id: id}\n );\n }\n });\n } else {\n return db.get(`\n SELECT * FROM User WHERE id = $id\n `, {$id: id}\n );\n }\n }\n },\n })\n});\n```\n\n```text\nfieldASTs\n```\n\n========================================\n\nComments:\n- Ah, I noticed that `fieldASTs` param before but it makes a lot more sense now that I see a concrete use case. Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":233,"estimatedTokens":1385}}479{"id":"stack-60211779","source":"stackoverflow","questionId":60211779,"title":"apollo graphql mutation - Unexpected end of JSON input","tags":["javascript","reactjs","graphql","apollo","apollo-client"],"text":"Title: apollo graphql mutation - Unexpected end of JSON input\nTags: javascript, reactjs, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm making a simple test with `@apollo/react-hooks`, and I'm getting this error:\n\n```\nApolloError.ts:46 Uncaught (in promise) Error: Network error: Unexpected end of JSON input\n at new ApolloError (ApolloError.ts:46)\n at Object.error (QueryManager.ts:255)\n at notifySubscription (Observable.js:140)\n at onNotify (Observable.js:179)\n at SubscriptionObserver.error (Observable.js:240)\n at observables.ts:15\n at Set.forEach ()\n at Object.error (observables.ts:15)\n at notifySubscription (Observable.js:140)\n at onNotify (Observable.js:179)\n at SubscriptionObserver.error (Observable.js:240)\n at Object.error (index.ts:81)\n at notifySubscription (Observable.js:140)\n at onNotify (Observable.js:179)\n at SubscriptionObserver.error (Observable.js:240)\n at httpLink.ts:184\n```\n\nWhen I try to use a mutation like this:\n\n```\nimport React from 'react';\nimport { Button } from 'antd';\nimport { gql } from 'apollo-boost';\nimport { useMutation } from '@apollo/react-hooks';\n\nconst LOGIN = gql`\n mutation authentication($accessToken: String!) {\n login(accessToken: $accessToken) {\n id\n name\n email\n groups\n }\n }\n`;\n\nfunction Authenticating() {\n const [login] = useMutation(LOGIN);\n\n function handleClick() {\n const variables = { variables: { accessToken: 'access_token_here' } };\n\n azureLogin(variables).then(data => {\n console.log(data); \n }).catch(err => {\n console.log(err)\n });\n }\n\n return (\n Test\n );\n}\n\nexport default Authenticating;\n```\n\nMy Apollo client looks like this:\n\n```\nimport ApolloClient from 'apollo-boost';\n\nconst client = new ApolloClient({\n uri: ,\n fetchOptions: {\n mode: 'no-cors',\n },\n headers: {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': true,\n },\n fetch,\n});\n\nexport default client;\n```\n\nAnd the `Authenticating` component is wrapped by an `ApolloProvider`.\n\n```\nimport React from 'react';\nimport { ApolloProvider } from '@apollo/react-hooks';\nimport Authenticating from './Authenticating';\nimport apolloClient from './apolloClient';\n\nconst App = () => {\n \n \n \n}\n\nexport default App;\n```\n\nI have no clue why I'm getting this error.\n\n========================================\n\nCode:\n```text\nApolloError.ts:46 Uncaught (in promise) Error: Network error: Unexpected end of JSON input\n at new ApolloError (ApolloError.ts:46)\n at Object.error (QueryManager.ts:255)\n at notifySubscription (Observable.js:140)\n at onNotify (Observable.js:179)\n at SubscriptionObserver.error (Observable.js:240)\n at observables.ts:15\n at Set.forEach (<anonymous>)\n at Object.error (observables.ts:15)\n at notifySubscription (Observable.js:140)\n at onNotify (Observable.js:179)\n at SubscriptionObserver.error (Observable.js:240)\n at Object.error (index.ts:81)\n at notifySubscription (Observable.js:140)\n at onNotify (Observable.js:179)\n at SubscriptionObserver.error (Observable.js:240)\n at httpLink.ts:184\n```\n\n```js\nimport React from 'react';\nimport { Button } from 'antd';\nimport { gql } from 'apollo-boost';\nimport { useMutation } from '@apollo/react-hooks';\n\nconst LOGIN = gql`\n mutation authentication($accessToken: String!) {\n login(accessToken: $accessToken) {\n id\n name\n email\n groups\n }\n }\n`;\n\nfunction Authenticating() {\n const [login] = useMutation(LOGIN);\n\n function handleClick() {\n const variables = { variables: { accessToken: 'access_token_here' } };\n\n azureLogin(variables).then(data => {\n console.log(data); \n }).catch(err => {\n console.log(err)\n });\n }\n\n return (\n <Button onClick={handleClick}>Test</Button>\n );\n}\n\nexport default Authenticating;\n```\n\n```js\nimport ApolloClient from 'apollo-boost';\n\nconst client = new ApolloClient({\n uri: <graphql_server>,\n fetchOptions: {\n mode: 'no-cors',\n },\n headers: {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': true,\n },\n fetch,\n});\n\nexport default client;\n```\n\n```text\nimport React from 'react';\nimport { ApolloProvider } from '@apollo/react-hooks';\nimport Authenticating from './Authenticating';\nimport apolloClient from './apolloClient';\n\nconst App = () => {\n <ApolloProvider client={apolloClient}>\n <Authenticating/>\n </ApolloProvider>\n}\n\nexport default App;\n```\n\n```text\n@apollo/react-hooks\n```\n\n```text\nAuthenticating\n```\n\n```text\nApolloProvider\n```\n\n```js\nimport ApolloClient from 'apollo-boost';\n\nconst client = new ApolloClient({\n uri: <graphql_server>,\n headers: {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': true,\n },\n fetch,\n});\n\nexport default client;\n```\n\n```js\nfetchOptions: {\n mode: 'no-cors',\n}\n```\n\n```text\nfetchOptions\n```\n\n```text\nmode: 'no-cors'\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":243,"estimatedTokens":1235}}480{"id":"stack-69408456","source":"stackoverflow","questionId":69408456,"title":"How to map a custom scalar type to a typescript type when using graphql code generator?","tags":["typescript","graphql","graphql-codegen"],"text":"Title: How to map a custom scalar type to a typescript type when using graphql code generator?\nTags: typescript, graphql, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nA custom scalar type named `Date` which is an ISO 8601 string is defined in the backend.\n\nIn the frontend \"GraphQL Code Generator\" (https://www.graphql-code-generator.com/) is used to generate typescript types from the schema.\n\nThe `codegen.yml` looks like this:\n\n```\noverwrite: true\nschema: 'http://mybackenurl/graphql'\ndocuments: 'src/**/*.graphql'\ngenerates:\n src/generated/graphql.ts:\n config:\n exposeQueryKeys: true\n exposeFetcher: true\n fetcher: '../GraphQLFetcher#fetcher'\n scalars: \n Date: Date\n plugins:\n - 'typescript'\n - 'typescript-operations'\n - 'typescript-react-query'\n```\n\nThis gives types where all fields with the custom scalar type `Date` in the graphql schema corresponds to the typescript type `Date` in the generated typescript types. However at runtime it is still a `string`. If the part with `Date: Date` under scalars in the configuration is removed, the corresponding type is `Any`.\n\nThe guess is that we need to specify some kind of mapper which converts from the ISO 8601 string we get from the backend to a typescript `Date`, but I do not understand how this is can be done.\n\n========================================\n\nCode:\n```yaml\noverwrite: true\nschema: 'http://mybackenurl/graphql'\ndocuments: 'src/**/*.graphql'\ngenerates:\n src/generated/graphql.ts:\n config:\n exposeQueryKeys: true\n exposeFetcher: true\n fetcher: '../GraphQLFetcher#fetcher'\n scalars: \n Date: Date\n plugins:\n - 'typescript'\n - 'typescript-operations'\n - 'typescript-react-query'\n```\n\n```text\nDate\n```\n\n```text\ncodegen.yml\n```\n\n```text\nDate\n```\n\n```text\nDate\n```\n\n```text\nstring\n```\n\n```text\nDate: Date\n```\n\n```text\nAny\n```\n\n```text\nDate\n```\n\n```text\nDate: number\n```\n\n```text\nDate\n```\n\n========================================\n\nComments:\n- I thought that was what resolvers could do, but I might be wrong? graphql-code-generator.com/docs/plugins/typescript-resolvers\n- Resolvers are on the backend not the frontend, your cannot transmit a `Date` over the wire. Everything is JSON in the end.","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":99,"estimatedTokens":568}}481{"id":"stack-46818041","source":"stackoverflow","questionId":46818041,"title":"Static values in GraphQL","tags":["graphql"],"text":"Title: Static values in GraphQL\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nIs there a way to produce static values in a graphql query? \n\nFor example, let's say that I have a `user` object with a name and email field. For some reason, I *always* want the status of a user to be \"ACCEPTED\". How can I write a query that accomplishes this?\n\nWhat I want to do:\n\n```\nquery {\n user(id: 1) {\n email\n name\n status: \"ACCEPTED\"\n }\n}\n```\n\nThe result I want:\n\n```\n{\n \"data\": {\n \"user\": {\n \"email\": \"me@myapp.com\",\n \"name\": \"me\",\n \"status\": \"ACCEPTED\"\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n user(id: 1) {\n email\n name\n status: \"ACCEPTED\"\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"user\": {\n \"email\": \"me@myapp.com\",\n \"name\": \"me\",\n \"status\": \"ACCEPTED\"\n }\n }\n}\n```\n\n```text\nuser\n```\n\n```js\nconst HomeWorldType = new GraphQLObjectType({\n name: 'HomeWorld',\n fields: () => {\n return {\n id: {\n type: GraphQLInt,\n resolve: () => 7,\n },\n name: { type: GraphQLString },\n climate: { type: GraphQLString },\n population: { type: GraphQLString },\n }\n }\n})\n```\n\n========================================\n\nComments:\n- have you found a pure GraphQL solution ?","metadata":{"transformedAt":"2026-08-18T18:32:36.060Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":85,"estimatedTokens":312}}482{"id":"stack-61064861","source":"stackoverflow","questionId":61064861,"title":"How can I create a GraphQL partial update with HotChocolate and EFCore","tags":["c#","graphql","entity-framework-core","json-patch","hotchocolate"],"text":"Title: How can I create a GraphQL partial update with HotChocolate and EFCore\nTags: c#, graphql, entity-framework-core, json-patch, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI am trying to create an ASP.NET Core 3.1 application using Entity Framework Core and Hot Chocolate.\nThe application needs to support creating, querying, updating and deleting objects through GraphQL.\nSome fields are required to have values.\n\nCreating, Querying and Deleting objects is not a problem, however updating objects is more tricky.\nThe issue that I am trying to resolve is that of partial updates.\n\nThe following model object is used by Entity Framework to create the database table through code first.\n\n```\npublic class Warehouse\n{\n [Key]\n public int Id { get; set; }\n\n [Required]\n public string Code { get; set; }\n public string CompanyName { get; set; }\n [Required]\n public string WarehouseName { get; set; }\n public string Telephone { get; set; }\n public string VATNumber { get; set; }\n}\n```\n\nI can create an record in the database with a mutation defined something like this:\n\n```\npublic class WarehouseMutation : ObjectType\n{\n protected override void Configure(IObjectTypeDescriptor descriptor)\n {\n descriptor.Field(\"create\")\n .Argument(\"input\", a => a.Type>())\n .Type>()\n .Resolver(async context =>\n {\n var input = context.Argument(\"input\");\n var provider = context.Service();\n\n return await provider.CreateWarehouse(input);\n });\n }\n}\n```\n\nAt the moment, the objects are small, but they will have far more fields before the project is finished. I need to leaverage the power of GraphQL to only send data for those fields that have changed, however if I use the same InputObjectType for updates, I encounter 2 problems.\n\n- The update must include all \"Required\" fields.\n\n- The update tries to set all non-provided values to their default.\n\nThe avoid this issue I have looked at the `Optional<>` generic type provided by HotChocolate.\nThis requires defining a new \"Update\" type like the following\n\n```\npublic class WarehouseUpdate\n{\n public int Id { get; set; } // Must always be specified\n public Optional Code { get; set; }\n public Optional CompanyName { get; set; }\n public Optional WarehouseName { get; set; }\n public Optional Telephone { get; set; }\n public Optional VATNumber { get; set; }\n}\n```\n\nAdding this to the mutation\n\n```\ndescriptor.Field(\"update\")\n .Argument(\"input\", a => a.Type>())\n .Type>()\n .Resolver(async context =>\n {\n var input = context.Argument(\"input\");\n var provider = context.Service();\n\n return await provider.UpdateWarehouse(input);\n });\n```\n\nThe UpdateWarehouse method then needs to update only those fields that have been provided with a value.\n\n```\npublic async Task UpdateWarehouse(WarehouseUpdate input)\n{\n var item = await _context.Warehouses.FindAsync(input.Id);\n if (item == null)\n throw new KeyNotFoundException(\"No item exists with specified key\");\n\n if (input.Code.HasValue)\n item.Code = input.Code;\n if (input.WarehouseName.HasValue)\n item.WarehouseName = input.WarehouseName;\n if (input.CompanyName.HasValue)\n item.CompanyName = input.CompanyName;\n if (input.Telephone.HasValue)\n item.Telephone = input.Telephone;\n if (input.VATNumber.HasValue)\n item.VATNumber = input.VATNumber;\n\n await _context.SaveChangesAsync();\n\n return item;\n}\n```\n\nWhile this works, it does have a couple of major downsides.\n\n- Because Enity Framework does not understand the `Optional<>` generic types, every model will require 2 classes\nThe Update method needs to have conditional code for **every** field to be updated\nThis is obviously not ideal.\n\nEntity Framework can be used along with the `JsonPatchDocument<>` generic class. This allows partial updates to be applied to an entity without requiring custom code. \nHowever I am struggling to find a way of combining this with the Hot Chocolate GraphQL implemention.\n\nIn order to make this work I am trying to create a custom InputObjectType that behaves as if the properties are defined using `Optional<>` and maps to a CLR type of `JsonPatchDocument<>`. This would work by creating custom mappings for every property in the model class with the help of reflection. I am finding however that some of the properties (`IsOptional`) that define the way the framework processes the request are internal to the Hot Chocolate framework and cannot be accessed from the overridable methods in the custom class.\n\nI have also considered ways of\n\n- Mapping the `Optional<>` properties of the UpdateClass into a `JsonPatchDocument<>` object\n\n- Using code weaving to generate a class with `Optional<>` versions of every property\n\n- Overriding EF Code first to handle `Optional<>` properties\n\nI am looking for any ideas as to how I can implement this using a generic approach and avoid needing to write 3 separate code blocks for each type - which need to be kept in sync with each other.\n\n========================================\n\nTop Answer:\nI ran into the same problem with Hot Chocolate and have huge tables (one of them has 129 columns) mapped to the objects. Writing if checks for each optional property of each table would be too much pain so, have written a generic helper method below to make it easier:\n\n```\n/// \n/// Checks which of the optional properties were passed and only sets those on the db Entity. Also, handles the case where explicit null\n/// value was passed in an optional/normal property and such property would be set to the default value of the property's type on the db entity\n/// Recommendation: Validate the dbEntityObject afterwards before saving to db\n/// \n/// The input object received in the mutation which has Optional properties as well as normal properties\n/// The database entity object to update\npublic void PartialUpdateDbEntityFromGraphQLInputType(object inputTypeObject, object dbEntityObject)\n{\n var inputObjectProperties = inputTypeObject.GetType().GetProperties();\n var dbEntityPropertiesMap = dbEntityObject.GetType().GetProperties().ToDictionary(x => x.Name);\n foreach (var inputObjectProperty in inputObjectProperties)\n {\n //For Optional Properties\n if (inputObjectProperty.PropertyType.Name == \"Optional`1\")\n {\n dynamic hasValue = inputObjectProperty.PropertyType.GetProperty(\"HasValue\").GetValue(inputObjectProperty.GetValue(inputTypeObject));\n if (hasValue == true)\n {\n var value = inputObjectProperty.PropertyType.GetProperty(\"Value\").GetValue(inputObjectProperty.GetValue(inputTypeObject));\n //If the field was passed as null deliberately to set null in the column, setting it to the default value of the db type in this case.\n if (value == null)\n {\n dbEntityPropertiesMap[inputObjectProperty.Name].SetValue(dbEntityObject, default);\n }\n else\n {\n dbEntityPropertiesMap[inputObjectProperty.Name].SetValue(dbEntityObject, value);\n }\n }\n }\n //For normal required Properties\n else\n {\n var value = inputObjectProperty.GetValue(inputTypeObject);\n //If the field was passed as null deliberately to set null in the column, setting it to the default value of the db type in this case.\n if (value == null)\n {\n dbEntityPropertiesMap[inputObjectProperty.Name].SetValue(dbEntityObject, default);\n }\n else\n {\n dbEntityPropertiesMap[inputObjectProperty.Name].SetValue(dbEntityObject, value);\n }\n }\n }\n}\n```\n\nThen, in your example just call it like below and reuse it for all other entity update mutations:\n\n```\npublic async Task UpdateWarehouse(WarehouseUpdate input)\n{\n var item = await _context.Warehouses.FindAsync(input.Id);\n if (item == null)\n throw new KeyNotFoundException(\"No item exists with specified key\");\n\n PartialUpdateDbEntityFromGraphQLInputType(input, item);\n\n await _context.SaveChangesAsync();\n\n return item;\n}\n```\n\nHope this helps. Please mark it as answer if it does.\n\n========================================\n\nCode:\n```text\npublic class Warehouse\n{\n [Key]\n public int Id { get; set; }\n\n [Required]\n public string Code { get; set; }\n public string CompanyName { get; set; }\n [Required]\n public string WarehouseName { get; set; }\n public string Telephone { get; set; }\n public string VATNumber { get; set; }\n}\n```\n\n```text\npublic class WarehouseMutation : ObjectType\n{\n protected override void Configure(IObjectTypeDescriptor descriptor)\n {\n descriptor.Field(\"create\")\n .Argument(\"input\", a => a.Type<InputObjectType<Warehouse>>())\n .Type<ObjectType<Warehouse>>()\n .Resolver(async context =>\n {\n var input = context.Argument<Warehouse>(\"input\");\n var provider = context.Service<IWarehouseStore>();\n\n return await provider.CreateWarehouse(input);\n });\n }\n}\n```\n\n```text\npublic class WarehouseUpdate\n{\n public int Id { get; set; } // Must always be specified\n public Optional<string> Code { get; set; }\n public Optional<string> CompanyName { get; set; }\n public Optional<string> WarehouseName { get; set; }\n public Optional<string> Telephone { get; set; }\n public Optional<string> VATNumber { get; set; }\n}\n```\n\n```text\ndescriptor.Field(\"update\")\n .Argument(\"input\", a => a.Type<InputObjectType<WarehouseUpdate>>())\n .Type<ObjectType<Warehouse>>()\n .Resolver(async context =>\n {\n var input = context.Argument<WarehouseUpdate>(\"input\");\n var provider = context.Service<IWarehouseStore>();\n\n return await provider.UpdateWarehouse(input);\n });\n```\n\n```text\npublic async Task<Warehouse> UpdateWarehouse(WarehouseUpdate input)\n{\n var item = await _context.Warehouses.FindAsync(input.Id);\n if (item == null)\n throw new KeyNotFoundException(\"No item exists with specified key\");\n\n if (input.Code.HasValue)\n item.Code = input.Code;\n if (input.WarehouseName.HasValue)\n item.WarehouseName = input.WarehouseName;\n if (input.CompanyName.HasValue)\n item.CompanyName = input.CompanyName;\n if (input.Telephone.HasValue)\n item.Telephone = input.Telephone;\n if (input.VATNumber.HasValue)\n item.VATNumber = input.VATNumber;\n\n await _context.SaveChangesAsync();\n\n return item;\n}\n```\n\n```text\nOptional<>\n```\n\n```text\nOptional<>\n```\n\n```text\nJsonPatchDocument<>\n```\n\n```text\nOptional<>\n```\n\n```text\nJsonPatchDocument<>\n```\n\n```text\nIsOptional\n```\n\n```text\nOptional<>\n```\n\n```text\nJsonPatchDocument<>\n```\n\n```text\nOptional<>\n```\n\n```text\nOptional<>\n```\n\n```text\nmutation\n{ \n updateUser(input: {\n id: 1 \n phone: null\n email: null\n }) {\n result\n }\n}\n```\n\n```text\npublic class SetValueInput<TValue>\n{\n public TValue Value { get; set; }\n}\n\npublic class SetNullableValueInput<T> where T : notnull\n{\n public T? Value { get; set; }\n\n public static implicit operator SetValueInput<T?>?(SetNullableValueInput<T>? value) => value == null ? null : new() { Value = value.Value };\n}\n```\n\n```text\npublic class UpdateUserInput\n {\n int Id { get; set; }\n \n public SetValueInput<string>? setEmail { get; set; }\n\n public SetValueInput<decimal?>? setSalary { get; set; }\n\n public SetNullableValueInput<string>? setPhone { get; set; }\n }\n```\n\n```text\npublic class CreateUserInput\n { \n public SetValueInput<string>? setEmail { get; set; }\n\n public SetValueInput<decimal?> setSalary { get; set; }\n\n public SetValueInput<string> setPhone { get; set; }\n }\n```\n\n```text\nif (input.setEmail != null)\n user.Email = input.setEmail.Value;\n```\n\n```text\npublic class MapsterConfig\n{\n public static void Config()\n {\n TypeAdapterConfig<WarehouseUpdate , Warehouse>\n .ForType()\n .IgnoreNullValues(true);\n }\n}\n```\n\n```text\nMapsterConfig.Config();\n```\n\n```text\n/// <summary>\n/// Checks which of the optional properties were passed and only sets those on the db Entity. Also, handles the case where explicit null\n/// value was passed in an optional/normal property and such property would be set to the default value of the property's type on the db entity\n/// Recommendation: Validate the dbEntityObject afterwards before saving to db\n/// </summary>\n/// <param name=\"inputTypeObject\">The input object received in the mutation which has Optional properties as well as normal properties</param>\n/// <param name=\"dbEntityObject\">The database entity object to update</param>\npublic void PartialUpdateDbEntityFromGraphQLInputType(object inputTypeObject, object dbEntityObject)\n{\n var inputObjectProperties = inputTypeObject.GetType().GetProperties();\n var dbEntityPropertiesMap = dbEntityObject.GetType().GetProperties().ToDictionary(x => x.Name);\n foreach (var inputObjectProperty in inputObjectProperties)\n {\n //For Optional Properties\n if (inputObjectProperty.PropertyType.Name == \"Optional`1\")\n {\n dynamic hasValue = inputObjectProperty.PropertyType.GetProperty(\"HasValue\").GetValue(inputObjectProperty.GetValue(inputTypeObject));\n if (hasValue == true)\n {\n var value = inputObjectProperty.PropertyType.GetProperty(\"Value\").GetValue(inputObjectProperty.GetValue(inputTypeObject));\n //If the field was passed as null deliberately to set null in the column, setting it to the default value of the db type in this case.\n if (value == null)\n {\n dbEntityPropertiesMap[inputObjectProperty.Name].SetValue(dbEntityObject, default);\n }\n else\n {\n dbEntityPropertiesMap[inputObjectProperty.Name].SetValue(dbEntityObject, value);\n }\n }\n }\n //For normal required Properties\n else\n {\n var value = inputObjectProperty.GetValue(inputTypeObject);\n //If the field was passed as null deliberately to set null in the column, setting it to the default value of the db type in this case.\n if (value == null)\n {\n dbEntityPropertiesMap[inputObjectProperty.Name].SetValue(dbEntityObject, default);\n }\n else\n {\n dbEntityPropertiesMap[inputObjectProperty.Name].SetValue(dbEntityObject, value);\n }\n }\n }\n}\n```\n\n```text\npublic async Task<Warehouse> UpdateWarehouse(WarehouseUpdate input)\n{\n var item = await _context.Warehouses.FindAsync(input.Id);\n if (item == null)\n throw new KeyNotFoundException(\"No item exists with specified key\");\n\n PartialUpdateDbEntityFromGraphQLInputType(input, item);\n\n await _context.SaveChangesAsync();\n\n return item;\n}\n```\n\n```text\npublic void ApplyTo(TModel objectToApplyTo)\n{\n var targetProperties = typeof(TModel).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public).ToDictionary(p => p.Name);\n var updateProperties = GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);\n\n // OK this is going to use reflection - bad boy - but lets see if we can get it to work\n // TODO: Sub types\n foreach (var prop in updateProperties)\n {\n Type? propertyType = prop?.PropertyType;\n if (propertyType is { }\n && propertyType.IsGenericType\n && propertyType.GetGenericTypeDefinition() == typeof(Optional<>))\n {\n var hasValueProp = propertyType.GetProperty(\"HasValue\");\n var valueProp = propertyType.GetProperty(\"Value\");\n var value = prop?.GetValue(this);\n if (valueProp !=null && (bool)(hasValueProp?.GetValue(value) ?? false))\n {\n if (targetProperties.ContainsKey(prop?.Name ?? string.Empty))\n {\n var targetProperty = targetProperties[prop.Name];\n if (targetProperty.PropertyType.IsValueType || targetProperty.PropertyType == typeof(string) ||\n targetProperty.PropertyType.IsArray || (targetProperty.PropertyType.IsGenericType && targetProperty.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))\n targetProperty.SetValue(objectToApplyTo, valueProp?.GetValue(value));\n else\n {\n var targetValue = targetProperty.GetValue(objectToApplyTo);\n if (targetValue == null)\n {\n targetValue = Activator.CreateInstance(targetProperty.PropertyType);\n targetProperty.SetValue(objectToApplyTo, targetValue);\n }\n\n var innerType = propertyType.GetGenericArguments().First();\n var mi = innerType.GetMethod(nameof(ApplyTo));\n mi?.Invoke(valueProp?.GetValue(value), new[] { targetValue });\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- We solved this with AutoMapper in graphql-dotnet, where you can get the argument as a dictionary and then map that to the entity. That way properties not passed in will not be in the dictionary and thus not mapped and properties passed in with value null are set to null. However I cannot figure out how to get the arguments out of the IResolverContext in hotchoclate as a dictionary.\n- Unfortunately this approach does not solve the underlying issue. One of the requirements is that certain fields may not have values on create, but when updating the fields they may be omitted. In addition, some fields must be able to be explicitly populated with . So far the solution I have working until Hot Chocolate support this properly, is a custom generic InputType<> combined with a TypeBuilder to create the class with Optional<> typed properties mirroring the base type.\n- I ended up with something very similar, but more strongly typed. See below.\n- Solution is good, but not working for collections. For example, if mutation contains something like: `items: [{itemId: \"0360daf9-a4cd-4700-896f-e7709a9e7de2\"}]`. It is rise exception: `The given key 'Items' was not present in the dictionary.`\n- Thank you for the comprehensive analysis. I agree that the specification is vague and does not lead to particularly good solutions. My key requirements were: * Input types where all required values had to be specified. * Update types where only *changed* values need to be sent. While I did get this working I was never happy with it and have been looking at alternatives. I have had some success using JSONPatch formatted payloads instead, but there is room for improvement. I have had to shelve the project for a while because of other work demands.\n- In our API we had the same requirements as you. But that's exactly what we made with SetValue. If \"SetValue\" field defined as nullable it is not required, if it is non-nullable - it is required.\n- Note also that manually creating the Input types and adding update logic for each field is *not* an option. There are way too many fields and I want to avoid having to change multiple places in the code for each new field. I ideally want something that can be generated from attributes of the EF database fields.\n- Then, you could use the code generation (.tt or whatever) to run through your EF types and create input types over them with the generic logic.\n- Btw, can you provide a template of such method? Is it something like: entity = dbContext.Load(input.Id); if (input.setPhone != null) entity.Phone = input.setPhone.Value; dbContext.Save(entity);","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":530,"estimatedTokens":4875}}483{"id":"stack-51291386","source":"stackoverflow","questionId":51291386,"title":"Apollo response from mutation is undefined","tags":["graphql","apollo","apollo-client"],"text":"Title: Apollo response from mutation is undefined\nTags: graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI use Apollo-client 2.3.5 to to add some data and then update the local cache. The mutation works but the return from the mutation is undefined in the Apollo client, but the response in the network request is correct. \n\nSo I have two querys, one for fetching all bookings and one for adding a booking. \n\n```\nconst addBookingGQL = gql`\nmutation createBooking($ref: String, $title: String, $description: String, $status: String!){\n createBooking(ref: $ref, title: $title, description: $description, status: $status){\n id\n ref\n title\n description\n status\n }\n\n }\n`;\n\nconst GET_BOOKINGS = gql`\n query {\n bookings {\n id\n ref\n title\n status\n description\n }\n }\n`;\n```\n\nI then have a Apollo mutation wrapper where I use the update prop. addBooking should be populated with the result of the mutation, but unfortunately it is undefined.\n\n```\n {\n const { bookings } = cache.readQuery({ query: GET_BOOKINGS });\n console.log(\"cache read query bookings: \", cache);\n cache.writeQuery({\n query: GET_BOOKINGS,\n data: { bookings: bookings.concat([addBooking]) }\n });\n }}\n >\n {(addBooking, { loading, error }) => (\n \n {\n addBooking({\n variables: {\n ref: this.state.ref,\n title: this.state.title,\n description: this.state.description,\n status: \"BOOK_BOX\",\n }\n });\n\n this.handleClose();\n\n }} \n color=\"primary\">\n Create\n \n {loading && Loading...\n\n}\n {error && Error :( Please try again\n\n}\n \n )}\n\n \n```\n\nThis results in following error in the console:\n\n```\nerrorHandling.js:7 Error: Error writing result to store for query:\n {\n bookings {\n id\n ref\n title\n status\n description\n __typename\n }\n}\n\nCannot read property '__typename' of undefined\n at Object.defaultDataIdFromObject [as dataIdFromObject] (inMemoryCache.js:33)\n at writeToStore.js:347\n at Array.map ()\n at processArrayValue (writeToStore.js:337)\n at writeFieldToStore (writeToStore.js:244)\n at writeToStore.js:120\n at Array.forEach ()\n at writeSelectionSetToStore (writeToStore.js:113)\n at writeResultToStore (writeToStore.js:91)\n at InMemoryCache.webpackJsonp../node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.write (inMemoryCache.js:96)\n```\n\nI tried running the mutation in the Graphiql dev tool receiving the expected response:\n\n```\n{\n \"data\": {\n \"createBooking\": {\n \"id\": \"bd954579-144b-41b4-9c76-5e3c176fe66a\",\n \"ref\": \"test\",\n \"title\": \"test\",\n \"description\": \"test\",\n \"status\": \"test\"\n }\n }\n}\n```\n\nLast I looked at the actual response from the graphql server:\n\n```\n{\n \"data\":{\n \"createBooking\":{\n \"id\":\"6f5ed8df-1c4c-4039-ae59-6a8c0f86a0f6\",\n \"ref\":\"test\",\n \"title\":\"test\",\n \"description\":\"test\",\n \"status\":\"BOOK_BOX\",\n \"__typename\":\"BookingType\"\n }\n }\n}\n```\n\nIf i use the Apollo dev tool for chrome i can see that the new data is actually appended to the cache, which confuses me.\n\n========================================\n\nCode:\n```text\nconst addBookingGQL = gql`\nmutation createBooking($ref: String, $title: String, $description: String, $status: String!){\n createBooking(ref: $ref, title: $title, description: $description, status: $status){\n id\n ref\n title\n description\n status\n }\n\n\n }\n`;\n\nconst GET_BOOKINGS = gql`\n query {\n bookings {\n id\n ref\n title\n status\n description\n }\n }\n`;\n```\n\n```text\n<Mutation \n mutation={addBookingGQL}\n update={(cache, { data: { addBooking } }) => {\n const { bookings } = cache.readQuery({ query: GET_BOOKINGS });\n console.log(\"cache read query bookings: \", cache);\n cache.writeQuery({\n query: GET_BOOKINGS,\n data: { bookings: bookings.concat([addBooking]) }\n });\n }}\n >\n {(addBooking, { loading, error }) => (\n <div>\n <Button \n onClick={() => {\n addBooking({\n variables: {\n ref: this.state.ref,\n title: this.state.title,\n description: this.state.description,\n status: \"BOOK_BOX\",\n }\n });\n\n this.handleClose();\n\n }} \n color=\"primary\">\n Create\n </Button>\n {loading && <p>Loading...</p>}\n {error && <p>Error :( Please try again</p>}\n </div>\n )}\n\n </Mutation>\n```\n\n```text\nerrorHandling.js:7 Error: Error writing result to store for query:\n {\n bookings {\n id\n ref\n title\n status\n description\n __typename\n }\n}\n\nCannot read property '__typename' of undefined\n at Object.defaultDataIdFromObject [as dataIdFromObject] (inMemoryCache.js:33)\n at writeToStore.js:347\n at Array.map (<anonymous>)\n at processArrayValue (writeToStore.js:337)\n at writeFieldToStore (writeToStore.js:244)\n at writeToStore.js:120\n at Array.forEach (<anonymous>)\n at writeSelectionSetToStore (writeToStore.js:113)\n at writeResultToStore (writeToStore.js:91)\n at InMemoryCache.webpackJsonp../node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.write (inMemoryCache.js:96)\n```\n\n```text\n{\n \"data\": {\n \"createBooking\": {\n \"id\": \"bd954579-144b-41b4-9c76-5e3c176fe66a\",\n \"ref\": \"test\",\n \"title\": \"test\",\n \"description\": \"test\",\n \"status\": \"test\"\n }\n }\n}\n```\n\n```text\n{\n \"data\":{\n \"createBooking\":{\n \"id\":\"6f5ed8df-1c4c-4039-ae59-6a8c0f86a0f6\",\n \"ref\":\"test\",\n \"title\":\"test\",\n \"description\":\"test\",\n \"status\":\"BOOK_BOX\",\n \"__typename\":\"BookingType\"\n }\n }\n}\n```\n\n```text\nfunction createOmitTypenameLink() {\n return new ApolloLink((operation, forward) => {\n if (operation.variables) {\n operation.variables = JSON.parse(JSON.stringify(operation.variables), omitTypename)\n }\n\n return forward(operation)\n })\n}\n\nfunction omitTypename(key, value) {\n return key === '__typename' ? undefined : value\n}\n```\n\n```text\napollo-link\n```\n\n```text\n__typename\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":289,"estimatedTokens":1603}}484{"id":"stack-65840539","source":"stackoverflow","questionId":65840539,"title":"Prisma: Query across multiple schemas in a database","tags":["node.js","graphql","prisma","prisma-graphql","prisma2"],"text":"Title: Prisma: Query across multiple schemas in a database\nTags: node.js, graphql, prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nDoes prisma support the ability to fetch data from multiple schemas from within a single database?\n\n========================================\n\nTop Answer:\nPrisma `multiSchema` is now supported as a preview feature.\n\nSee here https://www.prisma.io/docs/guides/database/multi-schema\n\nIt was introduced in version 4.3.0 https://github.com/prisma/prisma/issues/1122#issuecomment-1231773471\n\nAs the docs say you would add the preview feature...\n\n```\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"multiSchema\"]\n}\n```\n\nThen in your datasource you note the schemas...\n\n```\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n schemas = [\"schema1\", \"schema2\"]\n}\n```\n\nAnd finally in each model you add the `@@schema` attribute...\n\n```\nmodel User {\n id Int @id\n orders Order[]\n profile Profile?\n\n @@schema(\"schema1\")\n}\n\nmodel Order {\n id Int @id\n user User @relation(fields: [id], references: [id])\n user_id Int\n\n @@schema(\"schema2\")\n}\n```\n\n========================================\n\nCode:\n```text\ngenerator client {\n provider = \"prisma-client-js\"\n previewFeatures = [\"multiSchema\"]\n}\n```\n\n```text\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n schemas = [\"schema1\", \"schema2\"]\n}\n```\n\n```text\nmodel User {\n id Int @id\n orders Order[]\n profile Profile?\n\n @@schema(\"schema1\")\n}\n\nmodel Order {\n id Int @id\n user User @relation(fields: [id], references: [id])\n user_id Int\n\n @@schema(\"schema2\")\n}\n```\n\n```text\nmultiSchema\n```\n\n```text\n@@schema\n```\n\n========================================\n\nComments:\n- Hey! What do you mean exactly with this? With \"schema\", do you mean a \"GraphQL schema\" or a \"PostgreSQL schema\" or something else?\n- the latter one. @nburk\n- Did you find a solution for using multiple Postgres schema's with Prisma? This is one thing that is preventing me from using it.\n- @Jonathan, we'd to drop Prisma just because of this limitations. I haven't checked Prisma after it, whether they support it now or not.\n- What did you end up using?\n- GraphQL with simple Sequelize in one product (that required multi-tenancy) and GraphQL and Dynamo DB using AWS SAM at another. @Jonathan","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":108,"estimatedTokens":583}}485{"id":"stack-50253877","source":"stackoverflow","questionId":50253877,"title":"How to throw errors from inside a serverless lambda","tags":["lambda","graphql","serverless","apollo-server"],"text":"Title: How to throw errors from inside a serverless lambda\nTags: lambda, graphql, serverless, apollo-server\nSource: Stack Overflow\n\nQuestion:\nCan someone help me understand how to throw authentication errors in a graphQL lambda app? I'm using graphQL-yoga with serverless and I can authenticate a request and either return a user that I get from the jwt, a `{}` for no token, or throw an authentication error if the token is old. When I throw an error it gets caught in the catch statement of my authenticate block, but I have no idea how to actually return that from the lambda. \n\n```\nconst lambda = new GraphQLServerLambda({\n typeDefs,\n context: ({ event, context }) =>\n authenticate(event.headers.Authorization)\n .then(user => ({ db: mainDb, user}))\n .catch(e => {\n console.log('Caught the auth error here');\n throw e;\n }),\n Query: { \\\\ some queries here.... },\n Mutation: { \\\\ some mutations here...}\n });\n```\n\nHow can I either format the error or throw it from the right spot so that I get an actual formatted error? Instead I get a `Unexpected token I in JSON...` error in the client. Clearly I need to do some sort of formatting during my `throw` but it isn't totally obvious to me how to do that.\n\nIf it is helpful, here in my exports part. I'm trying everything from try/catch to then/catch and at this point I have seemed to already miss catching the error. Is there a better way to be doing this? The main thing I need is the ability to either authenticate, reject bad tokens, and otherwise just return a `{}` for a non-logged in user. I'm having the hardest time finding custom authorizers that allow non-logged in users so that's why I am doing the auth directly in my graphQL endpoint\n\n```\nexports.server = (event, context, callback) => {\n try {\n return lambda\n .graphqlHandler(event, context, callback)\n .then(b => b)\n .catch(e => console.log(`can't catch it here ${e}`));\n } catch (e) {\n console.log('or here');\n callback(e);\n }\n};\n```\n\n========================================\n\nTop Answer:\nOne option to customize your error message would be to create a new instance of the `Error` class. \n\nAn example would be:\n\n```\n.catch(e => {\n console.log('Caught the auth error here');\n throw new Error('Authentication Failed');\n }),\n```\n\nBecause the first parameter of the callback function is going to be the error message, you could also stick a generic error directly into the handler function:\n\n```\ncallback(\"An error happened!\");\n```\n\nYou can also use a middleware such as Middy to help with error handling:\n\nhttps://github.com/middyjs/middy/blob/master/docs/middlewares.md#httperrorhandler\n\nA helpful link on NodeJS error handling:\n\nhttps://www.joyent.com/node-js/production/design/errors\n\n========================================\n\nCode:\n```text\nconst lambda = new GraphQLServerLambda({\n typeDefs,\n context: ({ event, context }) =>\n authenticate(event.headers.Authorization)\n .then(user => ({ db: mainDb, user}))\n .catch(e => {\n console.log('Caught the auth error here');\n throw e;\n }),\n Query: { \\\\ some queries here.... },\n Mutation: { \\\\ some mutations here...}\n });\n```\n\n```text\nexports.server = (event, context, callback) => {\n try {\n return lambda\n .graphqlHandler(event, context, callback)\n .then(b => b)\n .catch(e => console.log(`can't catch it here ${e}`));\n } catch (e) {\n console.log('or here');\n callback(e);\n }\n};\n```\n\n```text\n{}\n```\n\n```text\nUnexpected token I in JSON...\n```\n\n```text\nthrow\n```\n\n```text\n{}\n```\n\n```text\nexports.server = (event, context, callback) => {\n const modifiedCallback = (error, output) => {\n if (output.body.includes('401')) {\n callback(null, {\n statusCode: 401,\n headers: { 'Content-Type': 'application/javascript' },\n body: JSON.stringify({ message: 'Unauthorized' })\n });\n } else {\n callback(error, output);\n }\n };\n return lambda.graphqlHandler(event, context, modifiedCallback);\n};\n```\n\n```text\n.catch(e => {\n console.log('Caught the auth error here');\n throw new Error('Authentication Failed');\n }),\n```\n\n```text\ncallback(\"An error happened!\");\n```\n\n```text\nError\n```\n\n========================================\n\nComments:\n- Thanks for the reply. I tried throwing errors and I can get a 500 error but nothing else. I am wondering if this might be due to a configuration issue with API gateway. When I use the middy I actually get a 200 code even if I am throwing an error, putting it in a middy callback (as a string, object, or stringified object).\n- Are you receiving the custom message as a 500 error? Or is it a generic internal server error? If its the former, I believe you can set a custom error code using square brackets in your message like so: `callback(\"[418] Your error message\");` If its the latter, then you might need to double check that whether you are using the lambda integration with or without proxy - stackoverflow.com/questions/42474264/…","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":153,"estimatedTokens":1235}}486{"id":"stack-49238490","source":"stackoverflow","questionId":49238490,"title":"Pass variable from input to GraphQL search call","tags":["javascript","reactjs","graphql","react-apollo"],"text":"Title: Pass variable from input to GraphQL search call\nTags: javascript, reactjs, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI am in the process of learning graphql and react-apollo. I have set up a search query in my code. I am unsure how to pass a variable from my code (i.e. `this.state.search`) to my grapnql call.\n\nI have looked at many answers including this one, but it seems a bit different.\n\nThe docs also don't seem to give any guidance on how to use state as the variable.\n\nMy code is below.\n\nCan anyone advise how to connect both of these?\n\n```\nimport React, { Component} from 'react'\nimport { graphql } from 'react-apollo'\nimport gql from 'graphql-tag'\n\nclass Search extends Component {\n\n constructor(props) {\n super(props)\n this.state = {\n search: ''\n }\n }\n\n updateSearch = (e) => {\n this.setState({\n search: e.target.value\n })\n }\n\n submitSearch = (e) => {\n e.preventDefault()\n console.log(this.state)\n }\n\n render() {\n\n const { search } = this.state;\n\n return (\n \n \n \n )\n }\n}\n\nexport default graphql(gql`\n{\n search(query: \"Manchester\", type: TEAM) {\n name\n }\n}`)(Search)\n```\n\n========================================\n\nCode:\n```text\nimport React, { Component} from 'react'\nimport { graphql } from 'react-apollo'\nimport gql from 'graphql-tag'\n\nclass Search extends Component {\n\n constructor(props) {\n super(props)\n this.state = {\n search: ''\n }\n }\n\n updateSearch = (e) => {\n this.setState({\n search: e.target.value\n })\n }\n\n submitSearch = (e) => {\n e.preventDefault()\n console.log(this.state)\n }\n\n render() {\n\n const { search } = this.state;\n\n return (\n <form onSubmit={ this.submitSearch }>\n <input \n type='text'\n onChange={ this.updateSearch }\n value={ search }\n placeholder='Search' \n />\n </form>\n )\n }\n}\n\n\nexport default graphql(gql`\n{\n search(query: \"Manchester\", type: TEAM) {\n name\n }\n}`)(Search)\n```\n\n```text\nthis.state.search\n```\n\n```text\nimport React, {Component} from 'react'\nimport {graphql} from 'react-apollo'\nimport gql from 'graphql-tag'\n\nclass Results extends Component {\n render() {\n // apollo provides results under the data prop\n const {data} = this.props;\n return <h1>{data.search.namej}</h1>\n }\n}\n\nconst ResultsWithQuery = graphql(gql`\nquery FindTeam($query: String!) {\n search(query: $query, type: TEAM) {\n name\n }\n}\n`, {skip: (ownProps) => !ownProps.query})(Results);\n\nexport class Search extends Component {\n\nconstructor(props) {\n super(props)\n this.state = {\n search: ''\n }\n}\n\nupdateSearch = (e) => {\n this.setState({\n search: e.target.value\n })\n}\n\nsubmitSearch = (e) => {\n e.preventDefault()\n console.log(this.state)\n}\n\nrender() {\n\n const {search} = this.state;\n\n return (\n <div>\n\n <form onSubmit={this.submitSearch}>\n <input\n type='text'\n onChange={this.updateSearch}\n value={search}\n placeholder='Search'\n />\n <ResultsWithQuery query={search} />\n </form>\n </div>\n\n )\n}\n}\n```\n\n```text\nimport React, { Component} from 'react'\nimport { Query } from 'react-apollo'\nimport gql from 'graphql-tag'\n\nconst SearchQuery = gql`\nquery FindTeam($query: String!) {\n search(query: $query, type: TEAM) {\n name\n }\n}\n`;\n\nexport default class Search extends Component {\n\nconstructor(props) {\n super(props)\n this.state = {\n search: ''\n }\n}\n\nupdateSearch = (e) => {\n this.setState({\n search: e.target.value\n })\n}\n\nsubmitSearch = (e) => {\n e.preventDefault()\n console.log(this.state)\n}\n\nrender() {\n\n const { search } = this.state;\n\n return (\n <form onSubmit={ this.submitSearch }>\n <input\n type='text'\n onChange={ this.updateSearch }\n value={ search }\n placeholder='Search'\n />\n <Query query={SearchQuery} skip={!search} variables={{query: search}}>\n {({loading, error, data}) => {\n if (loading) return null;\n if (error) throw err;\n return <h1>{data.search.namej}</h1>\n }}\n </Query>\n </form>\n )\n}\n}\n```\n\n========================================\n\nComments:\n- is this the only way to do this?\n- Passing a prop as the query param into the apollo higher order component? Yes that is the only way to write a dynamic query based on user input. *How* you pass the prop (using redux, context whatever) is up to you.\n- thanks for the answer, it kind of seems like overkill that you would have to create an extra component for this","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":246,"estimatedTokens":1178}}487{"id":"stack-55132782","source":"stackoverflow","questionId":55132782,"title":"Appsync & GraphQL: how to filter a list by nested value","tags":["graphql","aws-appsync","aws-amplify"],"text":"Title: Appsync & GraphQL: how to filter a list by nested value\nTags: graphql, aws-appsync, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI have an Appsync API generated by Amplify from a basic schema. On the `Article` model, a `category` field is nested within a `metadata` field. I want to build a Query that provides a list of Articles filtered by category. It is not clear to me how to filter on a nested value... I have seen similar questions but the analogous answer has not worked.\n\n**AWS GraphQL Transform Schema**\n\n```\ntype Article @model {\n id: ID!\n title: String!\n description: String!\n text: String!\n metadata: ArticleMetadata!\n}\n\ntype ArticleMetadata {\n category: Category!\n lastModified: String!\n creationDate: String!\n}\n\nenum Category {\n javascript\n java\n ruby\n python\n haskell\n}\n```\n\n**Generated List Query**\n\n```\nexport const listArticles = `query ListArticles(\n $filter: ModelArticleFilterInput\n $limit: Int\n $nextToken: String\n) {\n listArticles(filter: $filter, limit: $limit, nextToken: $nextToken) {\n items {\n id\n title\n description\n text\n metadata {\n category\n lastModified\n creationDate\n }\n }\n nextToken\n }\n}\n`;\n```\n\n**Failing filter query**\n\n```\nquery listArticlesByCategory($category: String!) {\n listArticles(filter: {category: {eq: $category}}) { \n items {\n title\n description\n text\n metadata {\n category\n creationDate\n lastModified\n }\n }\n }\n}\n```\n\nThe Appsync console error states that the `category` in `filter: {category: ... }` is an unknown field.\n\n========================================\n\nCode:\n```text\ntype Article @model {\n id: ID!\n title: String!\n description: String!\n text: String!\n metadata: ArticleMetadata!\n}\n\ntype ArticleMetadata {\n category: Category!\n lastModified: String!\n creationDate: String!\n}\n\nenum Category {\n javascript\n java\n ruby\n python\n haskell\n}\n```\n\n```text\nexport const listArticles = `query ListArticles(\n $filter: ModelArticleFilterInput\n $limit: Int\n $nextToken: String\n) {\n listArticles(filter: $filter, limit: $limit, nextToken: $nextToken) {\n items {\n id\n title\n description\n text\n metadata {\n category\n lastModified\n creationDate\n }\n }\n nextToken\n }\n}\n`;\n```\n\n```text\nquery listArticlesByCategory($category: String!) {\n listArticles(filter: {category: {eq: $category}}) { \n items {\n title\n description\n text\n metadata {\n category\n creationDate\n lastModified\n }\n }\n }\n}\n```\n\n```text\nArticle\n```\n\n```text\ncategory\n```\n\n```text\nmetadata\n```\n\n```text\ncategory\n```\n\n```text\nfilter: {category: ... }\n```\n\n```text\nModelArticleFilterInput\n```\n\n```text\nmetadata.category = :category\n```\n\n========================================\n\nComments:\n- It looks like you're generating a data type backed by a DynamoDB table, which isn't going to have a filter argument available to it. Try looking into the @searchable directive\n- It is backed by DynamoDB, but the auto-generated code for the `list` op includes `$filter: ModelArticleFilterInput`. Examining the `ModelArticleFilterInput` revealed that `metadata` is not included. Not sure why only top-level fields can be filtered upon.\n- I didn't have an opportunity to personally verify this, but it aligns with my understanding of Appsync resolvers and Amplify's generated code.\n- @Aaron_H can you give or point to an example on how to do this?\n- @aaron-h would you please provide example? github.com/aws-amplify/amplify-cli/issues/6467","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":184,"estimatedTokens":867}}488{"id":"stack-56176752","source":"stackoverflow","questionId":56176752,"title":"Next.js - understanding getInitialProps","tags":["javascript","reactjs","graphql","next.js","isomorphic-javascript"],"text":"Title: Next.js - understanding getInitialProps\nTags: javascript, reactjs, graphql, next.js, isomorphic-javascript\nSource: Stack Overflow\n\nQuestion:\nI have an app that uses next.js along with Apollo/ Graphql and i'm trying to fully understand how the `getInitialProps` lifecycle hook works. \n\nThe lifecycle `getInitialProps` in my understanding is used to set some initial props that will render server side for when the app first loads which can be used prefetch data from a database in order to help SEO or simply to enhance page load time.\n\nMy question is this:\n\n Every time I have a `query` component that fetches some data in my\n components across my app, do I have to use `getInitialProps` to be\n sure that data will be rendered server side?\n\nMy understanding is also that `getInitialProps` will only work in the page index components (as well as in `_app.js`), this would mean that any component lower down in the component tree would not have access to this lifecycle and would need to get some initial props from way up at the page level and then have them passed down the component tree. (would be great if someone could confirm this assumption)\n\nHere is my code:\n\n**_app.js** (in `/pages` folder)\n\n```\nimport App, { Container } from 'next/app';\nimport { ApolloProvider } from 'react-apollo';\n\nclass AppComponent extends App {\n static async getInitialProps({ Component, ctx }) {\n let pageProps = {};\n if (Component.getInitialProps) {\n pageProps = await Component.getInitialProps(ctx)\n }\n // this exposes the query to the user\n pageProps.query = ctx.query;\n return { pageProps };\n }\n render() {\n const { Component, apollo, pageProps } = this.props;\n\n return (\n \n \n \n \n \n );\n }\n}\n\nexport default AppComponent;\n```\n\n**Index.js** (in `/pages/users` folder)\n\n```\nimport React, { PureComponent } from 'react';\nimport { Query } from 'react-apollo';\nimport gql from 'graphql-tag';\n\nconst USERS_QUERY = gql`\n query USERS_QUERY {\n users {\n id\n firstName\n } \n }\n`;\n\nclass Index extends PureComponent {\n render() {\n return (\n \n {({data}) => {\n return data.map(user => {user.firstName});\n }}\n \n );\n }\n}\n\nexport default Index;\n```\n\n========================================\n\nCode:\n```text\nimport App, { Container } from 'next/app';\nimport { ApolloProvider } from 'react-apollo';\n\nclass AppComponent extends App {\n static async getInitialProps({ Component, ctx }) {\n let pageProps = {};\n if (Component.getInitialProps) {\n pageProps = await Component.getInitialProps(ctx)\n }\n // this exposes the query to the user\n pageProps.query = ctx.query;\n return { pageProps };\n }\n render() {\n const { Component, apollo, pageProps } = this.props;\n\n return (\n <Container>\n <ApolloProvider client={apollo}> \n <Component client={client} {...pageProps} /> \n </ApolloProvider>\n </Container>\n );\n }\n}\n\nexport default AppComponent;\n```\n\n```text\nimport React, { PureComponent } from 'react';\nimport { Query } from 'react-apollo';\nimport gql from 'graphql-tag';\n\nconst USERS_QUERY = gql`\n query USERS_QUERY {\n users {\n id\n firstName\n } \n }\n`;\n\nclass Index extends PureComponent {\n render() {\n return (\n <Query query={USERS_QUERY}>\n {({data}) => {\n return data.map(user => <div>{user.firstName}</div>);\n }}\n </Query>\n );\n }\n}\n\nexport default Index;\n```\n\n```text\ngetInitialProps\n```\n\n```text\ngetInitialProps\n```\n\n```text\nquery\n```\n\n```text\ngetInitialProps\n```\n\n```text\ngetInitialProps\n```\n\n```text\n_app.js\n```\n\n```text\n/pages\n```\n\n```text\n/pages/users\n```\n\n```text\nstatic async getInitialProps({ Component, ctx }) {\n let pageProps = {};\n if (Component.getInitialProps) {\n pageProps = await Component.getInitialProps(ctx)\n }\n // this exposes the query to the user\n pageProps.query = ctx.query;\n return { pageProps };\n }\n```\n\n```text\nconst request = (operation) => {\n operation.setContext({\n fetchOptions: {\n credentials: 'include'\n },\n headers: { cookie: headers.cookie }\n });\n };\n```\n\n```text\ngetInitialProps\n```\n\n```text\ngetInitialProps\n```\n\n```text\n<Query>\n```\n\n```text\ngetInitialProps\n```\n\n========================================\n\nComments:\n- Some quick notes, `getInitialProps` works on every page, not only the index.js. - any route that is rendered by the next.js router I guess. Yes you need to pass properties manually down the tree, or use some helper like `React. createContext`- you can resolve graphql queries on the server side, but, yes, unfortunately you need to do that manually in `getInitialProps`.\n- It's a mess, unfortunately.","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":220,"estimatedTokens":1153}}489{"id":"stack-53682698","source":"stackoverflow","questionId":53682698,"title":"mutate() got multiple values for argument 'name'","tags":["python","flask","graphql","mutation"],"text":"Title: mutate() got multiple values for argument 'name'\nTags: python, flask, graphql, mutation\nSource: Stack Overflow\n\nQuestion:\nI want to query createThemes to my graphql.\nMy graphql query is:\n\n```\nmutation{\n createTheme(name: \"qwe\"){\n theme{\n id\n }\n }\n}\n```\n\nSo it errors: `mutate() got multiple values for argument 'name'` Can you solve and explain why its printing such error.\n\nMy code below:\n\n```\nfrom models import Theme as ThemeModel, Topic as TopicModel, Article as ArticleModel\n\n ...\n\nclass CreateTheme(graphene.Mutation):\n class Arguments:\n id = graphene.Int()\n name = graphene.String()\n\n theme = graphene.Field(lambda: Theme)\n\n def mutate(self, name):\n theme = ThemeModel(name = name)\n theme.insert()\n\n return CreateTheme(theme = theme)\n\n ...\n\nclass Mutation(graphene.ObjectType):\n create_theme = CreateTheme.Field()\n\n ...\n\nschema = graphene.Schema(query=Query, mutation = Mutation)\n```\n\n========================================\n\nTop Answer:\nIt's missing **info** parameter.\n\nInfo parameter provides two things:\n\nreference to meta information about the execution of the current GraphQL Query (fields, schema, parsed query, etc.)\naccess to per-request context which can be used to store user authentication, data loader instances or anything else useful for resolving the query.\n\nSource: https://docs.graphene-python.org/en/latest/types/objecttypes/\n\n========================================\n\nCode:\n```text\nmutation{\n createTheme(name: \"qwe\"){\n theme{\n id\n }\n }\n}\n```\n\n```text\nfrom models import Theme as ThemeModel, Topic as TopicModel, Article as ArticleModel\n\n ...\n\nclass CreateTheme(graphene.Mutation):\n class Arguments:\n id = graphene.Int()\n name = graphene.String()\n\n theme = graphene.Field(lambda: Theme)\n\n def mutate(self, name):\n theme = ThemeModel(name = name)\n theme.insert()\n\n return CreateTheme(theme = theme)\n\n ...\n\nclass Mutation(graphene.ObjectType):\n create_theme = CreateTheme.Field()\n\n ...\n\nschema = graphene.Schema(query=Query, mutation = Mutation)\n```\n\n```text\nmutate() got multiple values for argument 'name'\n```\n\n```text\ndef mutate(self, name):\n```\n\n```text\ndef mutate(self, info, name):\n```\n\n========================================\n\nComments:\n- And if you're like me, I added a `@staticmethod` decorator per PyCharm's suggestion (which also removes the `self` parameter). Removing the `@staticmethod` and adding the `self` parameter back in fixed it for me :\\\n- @OozeMeister Graphene executes resolvers as staticmethod implicitly so there's no need to add static decorator. You can read: docs.graphene-python.org/en/latest/types/objecttypes/…\n- @SherSanginov, rather it executes the function as an unbound method and explicitly passes the `root` or `parent` parameter. Because this is such a surprising gotcha, I decorate all of my resolvers with `@staticmethod` and then use type annotations to explicitly declare the expected type of that `root`. I've learned a lot in the 2 or so years since I left the comment XD Thanks for the link to the docs!","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":121,"estimatedTokens":765}}490{"id":"stack-56266542","source":"stackoverflow","questionId":56266542,"title":"handling GraphQL field arguments using Dataloader?","tags":["javascript","sql","graphql","apollo-server"],"text":"Title: handling GraphQL field arguments using Dataloader?\nTags: javascript, sql, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm wondering if there's any consensus out there with regard to how best to handle GraphQL field arguments when using Dataloader. The `batchFn` batch function that Dataloader needs expects to receive `Array` and returns an `Array`, and usually one would just call `load( parent.id )` where `parent` is the first parameter of the resolver for a given field. In most cases, this is fine, but what if you need to provide arguments to a nested field?\n\nFor example, say I have a SQL database with tables for `Users`, `Books`, and a relationship table called `BooksRead` that represent a 1:many relationship between Users:Books.\n\nI might run the following query to see, for all users, what books they have read:\n\n```\nquery {\n users {\n id\n first_name\n books_read {\n title\n author {\n name\n }\n year_published\n }\n }\n}\n```\n\nLet's say that there's a `BooksReadLoader` available within the `context`, such that the resolver for `books_read` might look like this:\n\n```\nconst UserResolvers = {\n books_read: async function getBooksRead( user, args, context ) {\n return await context.loaders.booksRead.load( user.id );\n }\n};\n```\n\nThe batch load function for the `BooksReadLoader` would make an `async` call to a data access layer method, which would run some SQL like:\n\n```\nSELECT B.* FROM Books B INNER JOIN BooksRead BR ON B.id = BR.book_id WHERE BR.user_id IN(?);\n```\n\nWe would create some `Book` instances from the resulting rows, group by `user_id`, then return `keys.map(fn)` to make sure we assign the right books to each `user_id` key in the loader's cache.\n\nNow suppose I add an argument to `books_read`, asking for all the books a user has read that were published before 1950:\n\n```\nquery {\n users {\n id\n first_name\n books_read(published_before: 1950) {\n title\n author {\n name\n }\n year_published\n }\n }\n}\n```\n\nIn theory, we could run the same SQL statement, and handle the argument in the resolver:\n\n```\nconst UserResolvers = {\n books_read: async function getBooksRead( user, args, context ) {\n const books_read = await context.loaders.booksRead.load( user.id );\n return books_read.filter( function ( book ) { \n return book.year_published But, this isn't ideal, because we're still fetching a potentially huge number of rows from the `Books` table, when maybe only a handful of rows actually satisfy the argument. Much better to execute this SQL statement instead:\n\n```\nSELECT B.* FROM Books B INNER JOIN BooksRead BR ON B.id = BR.book_id WHERE BR.user_id IN(?) AND B.year_published My question is, does the `cacheKeyFn` option available via `new DataLoader( batchFn[, options] )` allow the field's argument to be passed down to construct a dynamic SQL statement in the data access layer? I've reviewed https://github.com/graphql/dataloader/issues/75 but I'm still unclear if `cacheKeyFn` is the way to go. I'm using `apollo-server-express`. There is this other SO question: Passing down arguments using Facebook's DataLoader but it has no answers and I'm having a hard time finding other sources that get into this.\n\nThanks!\n\n========================================\n\nCode:\n```text\nquery {\n users {\n id\n first_name\n books_read {\n title\n author {\n name\n }\n year_published\n }\n }\n}\n```\n\n```text\nconst UserResolvers = {\n books_read: async function getBooksRead( user, args, context ) {\n return await context.loaders.booksRead.load( user.id );\n }\n};\n```\n\n```text\nSELECT B.* FROM Books B INNER JOIN BooksRead BR ON B.id = BR.book_id WHERE BR.user_id IN(?);\n```\n\n```text\nquery {\n users {\n id\n first_name\n books_read(published_before: 1950) {\n title\n author {\n name\n }\n year_published\n }\n }\n}\n```\n\n```text\nconst UserResolvers = {\n books_read: async function getBooksRead( user, args, context ) {\n const books_read = await context.loaders.booksRead.load( user.id );\n return books_read.filter( function ( book ) { \n return book.year_published < args.published_before; \n });\n }\n};\n```\n\n```text\nSELECT B.* FROM Books B INNER JOIN BooksRead BR ON B.id = BR.book_id WHERE BR.user_id IN(?) AND B.year_published < ?;\n```\n\n```text\nbatchFn\n```\n\n```text\nArray<key>\n```\n\n```text\nArray<Promise>\n```\n\n```text\nload( parent.id )\n```\n\n```text\nparent\n```\n\n```text\nUsers\n```\n\n```text\nBooks\n```\n\n```text\nBooksRead\n```\n\n```text\nBooksReadLoader\n```\n\n```text\ncontext\n```\n\n```text\nbooks_read\n```\n\n```text\nBooksReadLoader\n```\n\n```text\nasync\n```\n\n```text\nBook\n```\n\n```text\nuser_id\n```\n\n```text\nkeys.map(fn)\n```\n\n```text\nuser_id\n```\n\n```text\nbooks_read\n```\n\n```text\nBooks\n```\n\n```text\ncacheKeyFn\n```\n\n```text\nnew DataLoader( batchFn[, options] )\n```\n\n```text\ncacheKeyFn\n```\n\n```text\napollo-server-express\n```\n\n```text\nconst UserResolvers = {\n books_read: async function getBooksRead( user, args, context ) {\n return context.loaders.booksRead.load({id: user.id, ...args});\n }\n};\n```\n\n========================================\n\nComments:\n- As an aside, do you really need dataloader in this context? Unless the client is actually requesting `books_read` for the *same* user more than once in the same request, there is no benefit to implementing dataloader for that field.\n- Hi @DanielRearden How do you mean? In my query example I'm assuming that the response will be an array (`[User]`), not a single `User`. Apologies if I wasn't clear on that in my question. Since the query is for many users, I would assume I want dataloader to collect all `user_id`s so I can send them to a SQL statement like `SELECT id, first_name FROM User WHERE id IN(?);` Since `books_read` is a field on each individual user, and the `parent` for the resolver is a single `User`, wouldn't I also want dataloader to batch those `user_id`s?\n- Let's continue this conversation in chat\n- You could also pass a custom cacheKeyFn or cacheMap to Dataloader which does something like JSON stringifying the cache key, then you wouldn't need to memoise.\n- while it's a good hack but this breaks typing, not compatible with typescript","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":30,"totalLines":247,"estimatedTokens":1526}}491{"id":"stack-35632915","source":"stackoverflow","questionId":35632915,"title":"GraphQL: How do you pass args to to sub objects","tags":["graphql"],"text":"Title: GraphQL: How do you pass args to to sub objects\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI am using GraphQL to query an object that will be composed from about 15 different REST calls. This is my root query in which I pass in in the ID from the query. This works fine for the main student object that resolves correctly. However, I need to figure out how to pass the ID down to the address resolver. I tried adding args to the address object but I get an error that indicates that the args are not passed down from the Student object. So my question is: How do I pass arguments from the client query to sub objects in a GraphQL server?\n\n```\nlet rootQuery = new GraphQLObjectType({\n name: 'Query',\n description: `The root query`,\n fields: () => ({\n Student : {\n type: Student ,\n args: {\n id: {\n name: 'id',\n type: new GraphQLNonNull(GraphQLString)\n }\n },\n resolve: (obj, args, ast) => {\n return Resolver(args.id).Student();\n }\n }\n })\n});\n\nexport default rootQuery;\n```\n\nThis is my primary student object that I link the other objects. In this case I have attached the ADDRESS object. \n\n```\nimport {\nGraphQLInt,\nGraphQLObjectType,\nGraphQLString,\nGraphQLNonNull,\nGraphQLList\n} from 'graphql';\n\nimport Resolver from '../../resolver.js'\nimport iAddressType from './address.js'\n\nlet Student = new GraphQLObjectType({\n name: 'STUDENT',\n fields: () => ({\n SCHOOLCODE: { type: GraphQLString },\n LASTNAME: { type: GraphQLString },\n ACCOUNTID: { type: GraphQLInt },\n ALIENIDNUMBER: { type: GraphQLInt },\n MIDDLEINITIAL: { type: GraphQLString },\n DATELASTCHANGED: { type: GraphQLString },\n ENROLLDATE: { type: GraphQLString },\n FIRSTNAME: { type: GraphQLString },\n DRIVERSLICENSESTATE: { type: GraphQLString },\n ENROLLMENTSOURCE: { type: GraphQLString },\n ADDRESSES: {\n type: new GraphQLList(Address),\n resolve(obj, args, ast){\n return Resolver(args.id).Address();\n }}\n })\n});\n```\n\nHere is my address object that is resolved by a second REST call:\n\n```\nlet Address = new GraphQLObjectType({\n name: 'ADDRESS',\n fields: () => ({\n ACTIVE: { type: GraphQLString },\n ADDRESS1: { type: GraphQLString },\n ADDRESS2: { type: GraphQLString },\n ADDRESS3: { type: GraphQLString },\n CAMPAIGN: { type: GraphQLString },\n CITY: { type: GraphQLString },\n STATE: { type: GraphQLString },\n STATUS: { type: GraphQLString },\n TIMECREATED: { type: GraphQLString },\n TYPE: { type: GraphQLString },\n ZIP: { type: GraphQLString },\n })\n\n});\n\nexport default Address;\n```\n\nThese are my resolver\n\n```\nvar Resolver = (id) => {\n\n var options = {\n hostname: \"myhostname\",\n port: 4000\n };\n\n var GetPromise = (options, id, path) => {\n return new Promise((resolve, reject) => {\n http.get(options, (response) => {\n var completeResponse = '';\n response.on('data', (chunk) => {\n completeResponse += chunk;\n });\n response.on('end', () => {\n parser.parseString(completeResponse, (err, result) => {\n let pathElements = path.split('.'); \n resolve(result[pathElements[0]][pathElements[1]]);\n });\n });\n }).on('error', (e) => { });\n });\n };\n\n let Student= () => {\n options.path = '/Student/' + id;\n return GetPromise(options, id, 'GetStudentResult.StudentINFO');\n }\n\n let Address= () => {\n options.path = '/Address/' + id + '/All';\n return GetPromise(options, id, 'getAddressResult.ADDRESS');\n };\n\n return {\n Student,\n Address\n };\n}\n\nexport default Resolver;\n```\n\n========================================\n\nCode:\n```text\nlet rootQuery = new GraphQLObjectType({\n name: 'Query',\n description: `The root query`,\n fields: () => ({\n Student : {\n type: Student ,\n args: {\n id: {\n name: 'id',\n type: new GraphQLNonNull(GraphQLString)\n }\n },\n resolve: (obj, args, ast) => {\n return Resolver(args.id).Student();\n }\n }\n })\n});\n\nexport default rootQuery;\n```\n\n```text\nimport {\nGraphQLInt,\nGraphQLObjectType,\nGraphQLString,\nGraphQLNonNull,\nGraphQLList\n} from 'graphql';\n\nimport Resolver from '../../resolver.js'\nimport iAddressType from './address.js'\n\nlet Student = new GraphQLObjectType({\n name: 'STUDENT',\n fields: () => ({\n SCHOOLCODE: { type: GraphQLString },\n LASTNAME: { type: GraphQLString },\n ACCOUNTID: { type: GraphQLInt },\n ALIENIDNUMBER: { type: GraphQLInt },\n MIDDLEINITIAL: { type: GraphQLString },\n DATELASTCHANGED: { type: GraphQLString },\n ENROLLDATE: { type: GraphQLString },\n FIRSTNAME: { type: GraphQLString },\n DRIVERSLICENSESTATE: { type: GraphQLString },\n ENROLLMENTSOURCE: { type: GraphQLString },\n ADDRESSES: {\n type: new GraphQLList(Address),\n resolve(obj, args, ast){\n return Resolver(args.id).Address();\n }}\n })\n});\n```\n\n```text\nlet Address = new GraphQLObjectType({\n name: 'ADDRESS',\n fields: () => ({\n ACTIVE: { type: GraphQLString },\n ADDRESS1: { type: GraphQLString },\n ADDRESS2: { type: GraphQLString },\n ADDRESS3: { type: GraphQLString },\n CAMPAIGN: { type: GraphQLString },\n CITY: { type: GraphQLString },\n STATE: { type: GraphQLString },\n STATUS: { type: GraphQLString },\n TIMECREATED: { type: GraphQLString },\n TYPE: { type: GraphQLString },\n ZIP: { type: GraphQLString },\n })\n\n});\n\nexport default Address;\n```\n\n```text\nvar Resolver = (id) => {\n\n var options = {\n hostname: \"myhostname\",\n port: 4000\n };\n\n\n var GetPromise = (options, id, path) => {\n return new Promise((resolve, reject) => {\n http.get(options, (response) => {\n var completeResponse = '';\n response.on('data', (chunk) => {\n completeResponse += chunk;\n });\n response.on('end', () => {\n parser.parseString(completeResponse, (err, result) => {\n let pathElements = path.split('.'); \n resolve(result[pathElements[0]][pathElements[1]]);\n });\n });\n }).on('error', (e) => { });\n });\n };\n\n let Student= () => {\n options.path = '/Student/' + id;\n return GetPromise(options, id, 'GetStudentResult.StudentINFO');\n }\n\n let Address= () => {\n options.path = '/Address/' + id + '/All';\n return GetPromise(options, id, 'getAddressResult.ADDRESS');\n };\n\n\n return {\n Student,\n Address\n };\n}\n\nexport default Resolver;\n```\n\n```text\nADDRESSES: {\n type: new GraphQLList(Address),\n resolve(obj, args, ast){\n return Resolver(args.id).Address();\n }\n}\n```\n\n```text\nobj\n```\n\n```text\nid\n```\n\n```text\nreturn Resolver(obj.id).Address();\n```\n\n========================================\n\nComments:\n- FallFast: did you find any solution\n- Did you find a good solution for this?","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":290,"estimatedTokens":1727}}492{"id":"stack-64281594","source":"stackoverflow","questionId":64281594,"title":"Single table db architecture with AWS Amplify","tags":["amazon-web-services","graphql","nosql","amazon-dynamodb","aws-amplify"],"text":"Title: Single table db architecture with AWS Amplify\nTags: amazon-web-services, graphql, nosql, amazon-dynamodb, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nBy default AWS Amplify transformers creating tables per each graphql type.\n\nBut according DynamoDB documentation it's best practice to\n\n- Keep tables few as possible\n\n- Keep often queried together entries within a same table\n\nI have an impression Amplify way of doing things stays in contradiction with the statement above.\n\nI am new to both NoSQL and Amplify\nCan someone suggest ways to address those issues?\n\n========================================\n\nCode:\n```text\n@auth\n```\n\n```text\n@model\n```\n\n```text\n@model\n```\n\n```text\ntype query {}\n```\n\n```text\nschema.graphql\n```\n\n========================================\n\nComments:\n- You should check out this accepted answer of a similar question: stackoverflow.com/a/56438716/13549664\n- Thanks! That was usefull\n- I am trying to assess same thing. As far as I was able to assess for now Amplify does not support single-table architecture well.\n- Honestly, I'd expect a product like Amplify to auto-build a single table from your schema and keep it in sync with your single tables automatically for performance enhancement. Seems like an interesting feature request.","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":48,"estimatedTokens":318}}493{"id":"stack-43796121","source":"stackoverflow","questionId":43796121,"title":"How to force update data cache in react-apollo?","tags":["reactjs","graphql","apollo","react-apollo"],"text":"Title: How to force update data cache in react-apollo?\nTags: reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nHow to `refetch` fresh data when you revisit a page whose data is powered by `react-apollo`?\n\nSay, I visit a listing page for the first time. `apollo` will fetch the query and caches it by default. So, when you visit the same page again during the session, it will populate the data from its cache store. How to force `apollo` to refetch data every time when the component mounts?\n\n========================================\n\nTop Answer:\nAdding to Pranesh's answer: the `fetchPolicy` you're looking for is `network-only`.\n\n========================================\n\nCode:\n```text\nrefetch\n```\n\n```text\nreact-apollo\n```\n\n```text\napollo\n```\n\n```text\napollo\n```\n\n```text\nconst graphQLOptions = {\n name: 'g_schemas',\n options: (props) => {\n return {\n variables: {\n name: props.name,\n },\n fetchPolicy: 'cache-and-network',\n }\n },\n}\n```\n\n```text\napollo\n```\n\n```text\nfetchPolicy\n```\n\n```text\nnetwork-only\n```\n\n```text\nimport { Query } from \"react-apollo\";\n```\n\n```text\nimport gql from 'graphql-tag';\nimport React from 'react';\nimport { Query } from 'react-apollo';\n\nconst CounterView = ({ counter }) => (\n <div>{counter}</div>\n);\n\nconst GET_COUNTER = gql`\n {\n counter\n }\n`;\n\nconst Counter = () => (\n <Query query={GET_COUNTER} fetchPolicy={'network-only'}>\n {({ data }) => {\n return <CounterView {...data} />;\n }}\n </Query>\n);\n\nexport default Counter;\n```\n\n```text\nreact-apollo\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.061Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":92,"estimatedTokens":389}}494{"id":"stack-57468031","source":"stackoverflow","questionId":57468031,"title":"missing attribute on result, Vue, Apollo and GraphQL","tags":["vue.js","graphql","apollo"],"text":"Title: missing attribute on result, Vue, Apollo and GraphQL\nTags: vue.js, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nIm totally new to developing with Apollo & GraphQL in Vue applications, and have been stuck on a small problem for some time now.\n\nI keep getting the error: **Missing clients attribute on result** \n\nI can see that the request returns data in the Network tab, so it seems to be something else than the query, when it's failing, but cant quite figure out what it is.\n\nCurrently im doing this query:\nMyQuery.js\n\n```\nimport gql from 'graphql-tag';\n\nexport const allClientsQuery = gql`\nquery clients {\n client: client {\n id\n name,\n subDomain,\n color,\n logo\n }\n}\n`;\n```\n\nAnd in my Vue Component:\n\n```\n\n 0\">\n Loading\n \n \n Output data: {{clients}}\n \n\n```\n\n```\n\nimport {allClientsQuery} from './graphql/queries/Clients';\nimport {VApp} from 'vuetify/lib';\n\nexport default {\n data() {\n return {\n loading: 0,\n clients: []\n };\n },\n components: {\n VApp\n },\n apollo: {\n clients: {\n query: allClientsQuery,\n loadingKey: 'i am loading '\n }\n }\n};\n\n```\n\nIn the network tab and inspecting the API call, it returns the following:\n\nhttps://i.sstatic.net/X2bYZ.png\n\n========================================\n\nTop Answer:\nYou can also change variable name\n\n```\napollo: {\n clients: {\n query() {\n return gql`\n query clients {\n client: client {\n id\n name\n subDomain\n color\n logo\n }\n }\n `\n },\n update: data => data.client\n }\n }\n```\n\n========================================\n\nCode:\n```text\nimport gql from 'graphql-tag';\n\nexport const allClientsQuery = gql`\nquery clients {\n client: client {\n id\n name,\n subDomain,\n color,\n logo\n }\n}\n`;\n```\n\n```text\n<template>\n<div id=\"app\">\n<v-app>\n <template v-if=\"loading > 0\">\n Loading\n </template>\n <template v-else>\n Output data: {{clients}}\n </template>\n</v-app>\n```\n\n```text\n<script>\nimport {allClientsQuery} from './graphql/queries/Clients';\nimport {VApp} from 'vuetify/lib';\n\nexport default {\n data() {\n return {\n loading: 0,\n clients: []\n };\n },\n components: {\n VApp\n },\n apollo: {\n clients: {\n query: allClientsQuery,\n loadingKey: 'i am loading '\n }\n }\n};\n</script>\n```\n\n```text\napollo: {\n client: {\n query: allClientsQuery,\n loadingKey: 'i am loading '\n }\n}\n```\n\n```text\napollo\n```\n\n```text\nclient\n```\n\n```text\nclients\n```\n\n```text\napollo\n```\n\n```text\nclient\n```\n\n```text\napollo: {\n clients: {\n query() {\n return gql`\n query clients {\n client: client {\n id\n name\n subDomain\n color\n logo\n }\n }\n `\n },\n update: data => data.client\n }\n }\n```\n\n```text\nthis.$apollo.addSmartQuery('listSomeItems', { <---\n query: ListItems,\n result: (data) => {\n ...\n },\n });\n```\n\n```text\ngql`\n query ListItems() {\n---> listOnlyItems() {\n ...\n }\n }`\n```\n\n```text\nthis.$apollo.addSmartQuery('listOnlyItems', { <---\n ...\n```\n\n========================================\n\nComments:\n- What if you return multplie entities in your query?\n- This was the answer I needed. :) Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":233,"estimatedTokens":808}}495{"id":"stack-60360260","source":"stackoverflow","questionId":60360260,"title":"Auto-update of apollo client cache after mutation not affecting existing queries","tags":["graphql","react-apollo","apollo-client"],"text":"Title: Auto-update of apollo client cache after mutation not affecting existing queries\nTags: graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have a mutation (UploadTransaction) returning certain list of certain object named Transaction. \n\n```\n#import \"TransactionFields.gql\" \nmutation UploadTransaction($files: [Upload!]!) {\n uploadFile(files: $files){\n transactions {\n ...TransactionFields\n }\n }\n}\n```\n\nTransaction returned from backend (graphene) has id and typename field. Hence it should automatically update Transaction in the cache. In chrome dev tools for Apollo, I can see new transactions: \n\nhttps://i.sstatic.net/O6j5l.png\n\nI also have a query GetTransactions fetching all Transaction objects.\n\n```\n#import \"TransactionFields.gql\"\nquery GetTransactions {\n transactions {\n ...TransactionFields\n }\n}\n```\n\nHowever I don't see newly added Transaction being returned by the query. During initial load, Apollo client loaded 292 transactions which it shows under ROOT_QUERY. It keeps returning same 292 transactions. UploadTransaction mutation add new object of type \"Transaction\" in cache in dev-tools without affecting ROOT_QUERY in dev-tools or my query in code.\n\nhttps://i.sstatic.net/rpraT.png\n\nTransactionFields.gql is \n\n```\nfragment TransactionFields on Transaction {\n id\n timestamp\n description\n amount\n category {\n id\n name\n }\n currency\n}\n```\n\nAny idea what am I doing wrong? I am new to apollo client and graphql\n\n========================================\n\nCode:\n```text\n#import \"TransactionFields.gql\" \nmutation UploadTransaction($files: [Upload!]!) {\n uploadFile(files: $files){\n transactions {\n ...TransactionFields\n }\n }\n}\n```\n\n```text\n#import \"TransactionFields.gql\"\nquery GetTransactions {\n transactions {\n ...TransactionFields\n }\n}\n```\n\n```text\nfragment TransactionFields on Transaction {\n id\n timestamp\n description\n amount\n category {\n id\n name\n }\n currency\n}\n```\n\n```js\nupdate (cache, { data: { addTodo } }) {\n const { todos } = cache.readQuery({ query: GET_TODOS });\n cache.writeQuery({\n query: GET_TODOS,\n data: { todos: todos.concat([addTodo]) },\n });\n}\n```\n\n```text\nrefetchQueries\n```\n\n```text\nuseMutation\n```\n\n```text\nrefetch\n```\n\n```text\nupdate\n```\n\n```text\nuseMutation\n```\n\n```text\nupdate\n```\n\n========================================\n\nComments:\n- Thanks Daniel. I had seen that update function is required for mutations modifying multiple entries. But missed that creation/deletion also requires it.\n- Is there any way you can manually update the cache for existing entities?\n- \"If a mutation updates a single existing entity, Apollo Client can automatically update that entity's value in its cache when the mutation returns. \" -- but how does Apollo know is what is really confusing. Some of my mutations seem to update the cache, some don't, and yet they update only one entry. It's a really opaque system.","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":132,"estimatedTokens":731}}496{"id":"stack-42133424","source":"stackoverflow","questionId":42133424,"title":"How to create nested nodes in one mutation?","tags":["graphql","react-apollo","apollo-client","graphcool"],"text":"Title: How to create nested nodes in one mutation?\nTags: graphql, react-apollo, apollo-client, graphcool\nSource: Stack Overflow\n\nQuestion:\nHi I am trying to write data on my https://www.graph.cool/ db with a mutation.\nMy project is a React web-app and I am using Apollo as graphql client and graphql-tag npm package as template literal parser.\n\nThe problem is that i don't know how to arrange the gql template string for the correct mutation with nested data.\nMy schema looks like this, for example note the field \"Addresses\" for the type \"Company\" is an array of \"Address\" objects type.\n\n```\ntype Company {\n name: String!\n website: String\n Owner: User\n Addresses: [Addresses]\n}\n\ntype User {\n name: String!\n email: String\n}\n\ntype Address {\n street: String!\n city: String!\n country: String\n contacts: [Contact]\n}\n\ntype Contact {\n name: String\n email: String\n phone: String\n}\n```\n\nFor example, I want to create a new company, its new owner and multiple addresses at the same time in one mutation. For the addresses I need to create a new contact as well.\n\n========================================\n\nCode:\n```text\ntype Company {\n name: String!\n website: String\n Owner: User\n Addresses: [Addresses]\n}\n\ntype User {\n name: String!\n email: String\n}\n\ntype Address {\n street: String!\n city: String!\n country: String\n contacts: [Contact]\n}\n\ntype Contact {\n name: String\n email: String\n phone: String\n}\n```\n\n```text\nmutation createNestedCompany {\n createCompany(\n owner: {\n name: \"Mickey\"\n email: \"mickey@mouse.com\"\n }\n addresses: [{\n street: \"A street\"\n city: \"A city\"\n country: \"A country\"\n contacts: [{\n name: \"Mickey\"\n email: \"mickey@mouse.com\"\n phone: \"+1 23456789\"\n }]\n }, {\n street: \"B street\"\n city: \"B city\"\n country: \"B country\"\n contacts: [{\n name: \"Minney\"\n email: \"minney@mouse.com\"\n phone: \"+9 87654321\"\n }]\n }]\n ) {\n id\n owner {\n id\n }\n addresses {\n id\n contacts {\n id\n }\n }\n }\n}\n```\n\n```text\nconst createNestedCompany = gql`\n mutation createNestedCompany(\n $owner: CompanyownerUser\n $addresses: [CompanyaddressesAddress!]\n ) {\n createCompany(\n owner: $owner\n addresses: $addresses\n ) {\n id\n owner {\n id\n }\n addresses {\n id\n contacts {\n id\n }\n }\n }\n }\n`\n```\n\n```text\nconst variables = {\n owner: {\n name: \"Mickey\"\n email: \"mickey@mouse.com\"\n }, \n addresses: [{\n street: \"A street\"\n city: \"A city\"\n country: \"A country\"\n contacts: [{\n name: \"Mickey\"\n email: \"mickey@mouse.com\"\n phone: \"+1 23456789\"\n }]\n }, {\n street: \"A street\"\n city: \"A city\"\n country: \"A country\"\n contacts: [{\n name: \"Minney\"\n email: \"minney@mouse.com\"\n phone: \"+9 87654321\"\n }]\n }]\n}\n```\n\n```text\nthis.props.createNestedCompany({ variables })\n .then((response) => {\n console.log('Company, owner and addresses plus contacts created');\n }).catch((e) => {\n console.error(e)\n })\n```\n\n```text\ncreateCompany\n```\n\n```text\nowner\n```\n\n```text\naddresses\n```\n\n```text\naddresses\n```\n\n```text\ncontacts\n```\n\n```text\nCompanyownerUser\n```\n\n```text\n[CompanyaddressesAddress!]\n```\n\n```text\nCompany\n```\n\n```text\nUser\n```\n\n```text\nCompany\n```\n\n```text\nAddress\n```\n\n```text\nowner\n```\n\n```text\naddresses\n```\n\n```text\ncreateCompany\n```\n\n========================================\n\nComments:\n- I wrote this article with the solution: hackernoon.com/…","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":233,"estimatedTokens":888}}497{"id":"stack-40137736","source":"stackoverflow","questionId":40137736,"title":"After a mutation, how do I update the affected data across views?","tags":["graphql","apollostack","react-apollo"],"text":"Title: After a mutation, how do I update the affected data across views?\nTags: graphql, apollostack, react-apollo\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/E8F1p.jpg\n\nI have both the `getMovies` query and `addMovie` mutation working. When `addMovie` happens though, I'm wondering how to best update the list of movies in \"Edit Movies\" and \"My Profile\" to reflect the changes. I just need a general/high-level overview, or even just the name of a concept if it's simple, on how to make this happen.\n\nMy initial thought was just to hold all of the movies in my Redux store. When the mutation finishes, it should return the newly added movie, which I can concatenate to the movies of my store. \n\nAfter \"Add Movie\", it would pop back to the \"Edit Movies\" screen where you should be able to see the newly added movie, then if you go back to \"My Profile\", it'd be there too.\n\nIs there a better way to do this than holding it all in my own Redux store? Is there any Apollo magic I don't know about that could possibly handle this update for me?\n\n**EDIT**: I discovered the idea of `updateQueries`: http://dev.apollodata.com/react/cache-updates.html#updateQueries I think this is what I want (please let me know if this is not the right approach). This seems better than the traditional way of using my own Redux store.\n\n```\n// this represents the 3rd screen in my picture\nconst AddMovieWithData = compose(\n graphql(searchMovies, {\n props: ({ mutate }) => ({\n search: (query) => mutate({ variables: { query } }),\n }),\n }),\n graphql(addMovie, {\n props: ({ mutate }) => ({\n addMovie: (user_id, movieId) => mutate({\n variables: { user_id, movieId },\n updateQueries: {\n getMovies: (prev, { mutationResult }) => {\n // my mutation returns just the newly added movie\n const newMovie = mutationResult.data.addMovie;\n\n return update(prev, {\n getMovies: {\n $unshift: [newMovie],\n },\n });\n },\n },\n }),\n }),\n })\n)(AddMovie);\n```\n\nAfter `addMovie` mutation, this properly updates the view in \"My Profile\" because it uses the `getMovies` query (woah)! I'm then passing these movies as props into \"Edit Movies\", so how do I update it there as well? Should I just have them both use the `getMovies` query? Is there a way to pull the new result of `getMovies` out of the store, so I can reuse it on \"Edit Movies\" without doing the query again?\n\n**EDIT2:** Wrapping `MyProfile` and `EditMovies` both with `getMovies` query container seems to work fine. After `addMovie`, it's updated in both places due to `updateQueries` on `getMovies`. It's fast too. I think it's being cached?\n\n**It all works, so I guess this just becomes a question of: Was this the best approach?**\n\n========================================\n\nTop Answer:\nThe Apollo Client only updates the store on update mutations. So when you use create or delete mutations you need to tell Apollo Client how to update. I had expected the store to update automatically but it doesnβtβ¦\n\nI have founded a workaround with `resetStore` just after doing your mutation.\nYou reset the store just after doing the mutation. Then when you will need to query, the store is empty, so apollo refetch fresh data.\n\nhere is the code:\n\n```\nimport { withApollo } from 'react-apollo'\n\n...\n\n deleteCar = async id => {\n await this.props.deleteCar({\n variables: { where: {\n id: id\n } },\n })\n this.props.client.resetStore().then(data=> {\n this.props.history.push('/cars')\n })\n }\n\n...\n\nexport default compose(\n graphql(POST_QUERY, {\n name: 'carQuery',\n options: props => ({\n fetchPolicy: 'network-only',\n variables: {\n where: {\n id: props.match.params.id,\n }\n },\n }),\n }),\n graphql(DELETE_MUTATION, {\n name: 'deleteCar',\n }),\n withRouter,\n withApollo\n)(DetailPage)\n```\n\nThe full code is here: https://github.com/alan345/naperg\nTher error before the hack `resetStore`\nhttps://i.sstatic.net/zkKvJ.gif\n\n========================================\n\nCode:\n```text\n// this represents the 3rd screen in my picture\nconst AddMovieWithData = compose(\n graphql(searchMovies, {\n props: ({ mutate }) => ({\n search: (query) => mutate({ variables: { query } }),\n }),\n }),\n graphql(addMovie, {\n props: ({ mutate }) => ({\n addMovie: (user_id, movieId) => mutate({\n variables: { user_id, movieId },\n updateQueries: {\n getMovies: (prev, { mutationResult }) => {\n // my mutation returns just the newly added movie\n const newMovie = mutationResult.data.addMovie;\n\n return update(prev, {\n getMovies: {\n $unshift: [newMovie],\n },\n });\n },\n },\n }),\n }),\n })\n)(AddMovie);\n```\n\n```text\ngetMovies\n```\n\n```text\naddMovie\n```\n\n```text\naddMovie\n```\n\n```text\nupdateQueries\n```\n\n```text\naddMovie\n```\n\n```text\ngetMovies\n```\n\n```text\ngetMovies\n```\n\n```text\ngetMovies\n```\n\n```text\nMyProfile\n```\n\n```text\nEditMovies\n```\n\n```text\ngetMovies\n```\n\n```text\naddMovie\n```\n\n```text\nupdateQueries\n```\n\n```text\ngetMovies\n```\n\n```text\nupdateQueries\n```\n\n```text\nupdateQueries\n```\n\n```text\nimport { withApollo } from 'react-apollo'\n\n...\n\n deleteCar = async id => {\n await this.props.deleteCar({\n variables: { where: {\n id: id\n } },\n })\n this.props.client.resetStore().then(data=> {\n this.props.history.push('/cars')\n })\n }\n\n\n...\n\n\nexport default compose(\n graphql(POST_QUERY, {\n name: 'carQuery',\n options: props => ({\n fetchPolicy: 'network-only',\n variables: {\n where: {\n id: props.match.params.id,\n }\n },\n }),\n }),\n graphql(DELETE_MUTATION, {\n name: 'deleteCar',\n }),\n withRouter,\n withApollo\n)(DetailPage)\n```\n\n```text\nresetStore\n```\n\n```text\nresetStore\n```\n\n========================================\n\nComments:\n- for Apollo magic, show some code..\n- When you say \"Was this the best approach?\" you risk getting your question closed due to it being opinion based. However, I came here to write the answer that you came up with based on the question in the title (a well written title BTW!) so I'll do that ;)\n- Thanks! Yeah, when I discovered `updateQueries`, I was pretty amazed at how well it just worked, but being a newbie, I can't help but feel a little uncomfortable when things actually work, especially with bleeding edge tech! Do you have any thoughts for my side-question? Originally, only \"My Profile\" had the `getMovies` query, and I was just passing movies as props into \"Edit Movies\". Of course, this means that after the mutation, it only updates where `getMovies` is... so only on \"My Profile\". Was adding `getMovies` to \"Edit Movies\", so it updates there too, the right thing to do here?\n- This is what I allude to in the \"careful design and use of queries\" :) I think the answer is \"yes\". Note that other options include having both those components inside another one that is the container, and does the query, and passes the move list as props. This is only an option if it makes sense in the UI design though (in my app that looks just like yours, \"edit movies\" is a modal and so can take props from \"my profile\" and gets updated when \"my profile\" container does... but modals are often not a great idea :O ). Maybe see you in apollostack.slack.com/archives/react-apollo\n- From the official docs: \"We recommend using `update` instead of `updateQueries`. updateQueries will be removed in the next version of Apollo Client.\" src","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":258,"estimatedTokens":1842}}498{"id":"stack-55145237","source":"stackoverflow","questionId":55145237,"title":"In graphql schema, how can I create a parent/child relationship of same model?","tags":["graphql","aws-amplify"],"text":"Title: In graphql schema, how can I create a parent/child relationship of same model?\nTags: graphql, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI'm needing to create a searchable listing table where some records are of type `ORGANIZATION` or `RESOURCE`. The relationshipis one-to-many. So, an Organization can have many Resources. How can I create this relationship under one model?\n\nUsing AWS Amplify GraphQL API...\n\nLike this? `schema.graphql`\n\n```\nenum ListingType {\n ORGANIZATION\n RESOURCE\n}\ntype Listing @model {\n id: ID!\n title: String!\n type: ListingType!\n orginzation: Listing\n}\n```\n\nYet, in Mutations, I can't reference a parent organization when creating my first Resource:\n\nhttps://i.sstatic.net/NuHMv.png\n\n========================================\n\nCode:\n```text\nenum ListingType {\n ORGANIZATION\n RESOURCE\n}\ntype Listing @model {\n id: ID!\n title: String!\n type: ListingType!\n orginzation: Listing\n}\n```\n\n```text\nORGANIZATION\n```\n\n```text\nRESOURCE\n```\n\n```text\nschema.graphql\n```\n\n```text\ntype Listing @model {\n id: ID!\n title: String!\n type: ListingType!\n organization: Listing @connection\n}\n```\n\n```text\n@connection\n```\n\n========================================\n\nComments:\n- Don't you still need a @connection directive on the organization field?\n- Hmm, good point. For a One-To-One, @connection would reference the Organization. I'll try it...\n- @DanielRearden, that did it. Thank you! Submit your answer and I'll mark that as the answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":75,"estimatedTokens":366}}499{"id":"stack-68795743","source":"stackoverflow","questionId":68795743,"title":"Apollo Server executeOperation with authorization headers","tags":["node.js","graphql","jwt","apollo-server"],"text":"Title: Apollo Server executeOperation with authorization headers\nTags: node.js, graphql, jwt, apollo-server\nSource: Stack Overflow\n\nQuestion:\nHow do we pass headers to Apollo server `executeOperation` in tests?\n\nThere is mention about passing a headers object here\n\nI'm trying to pass an auth header with or without a JWT token to test access control.\n\n```\nconst result = await server.executeOperation({ query: query, http: { headers: { authorization: \"\" } } })\n\n// Type '{ authorization: string; }' is not assignable to type 'Headers'.\n// Object literal may only specify known properties, and 'authorization' does not exist in type 'Headers'.ts(2322)\n```\n\nThis results in a type error. There is a Headers class defined in the Apollo server types in `fetch.d.ts` but I'm un able to import to instantiate it.\n\nUsing `\"apollo-server\": \"^2.25.2\"`. Any hints or links to get this going?\n\nUpdate: as a work around I'm decrypting and decoding the JWT in the server context and passing an authenticated user around in there. Then I'm able to mock the whole context and create a new test server with the mocked context. It'd be nice to be able to user headers for more production like experience but this works for now.\n\n```\nimport { mockDeep, mockReset } from 'jest-mock-extended'\n\ninterface Context {\n prisma: PrismaClient\n user: () => User|null\n}\n\nexport const context = mockDeep()\n\nexport const testServer = new ApolloServer({\n typeDefs,\n resolvers,\n context\n});\n\n// ...\n\ncontext.user.mockReturnValue({\n id: 1,\n name: \"Foo\",\n slug: \"foo\",\n})\n\nconst res = await testServer.executeOperation({ query: query })\n```\n\n========================================\n\nTop Answer:\nTo solve this, I have created a 'fake' request object with the already decrypted JWT token that I used to initialize my third party auth object (keycloak) and pass to the apollo context. I need to initialize the keycloak object because I have authentication schema directives that require the keycloak object to be initialized.\n\n```\nconst req = {\n kauth: {\n grant: {\n access_token: {\n isExpired: () => {\n return false;\n },\n token: \"abc\",\n content: {\n email: \"me@me.com\",\n resource_access: {\n \"my-api\": {\n roles: [\"admin\"],\n },\n },\n },\n },\n },\n },\n };\n\n server = new ApolloServer({\n schema,\n resolvers,\n dataSources: () => ({\n users,\n }),\n context: () => {\n return { kauth: new KeycloakContext({ req }) };\n },\n });\n });\n```\n\nStill, I would like a solution that is more native to apollo and not a work around.\n\n========================================\n\nCode:\n```js\nconst result = await server.executeOperation({ query: query, http: { headers: { authorization: \"\" } } })\n\n// Type '{ authorization: string; }' is not assignable to type 'Headers'.\n// Object literal may only specify known properties, and 'authorization' does not exist in type 'Headers'.ts(2322)\n```\n\n```js\nimport { mockDeep, mockReset } from 'jest-mock-extended'\n\ninterface Context {\n prisma: PrismaClient\n user: () => User|null\n}\n\nexport const context = mockDeep<Context>()\n\nexport const testServer = new ApolloServer({\n typeDefs,\n resolvers,\n context\n});\n\n// ...\n\ncontext.user.mockReturnValue({\n id: 1,\n name: \"Foo\",\n slug: \"foo\",\n})\n\nconst res = await testServer.executeOperation({ query: query })\n```\n\n```text\nexecuteOperation\n```\n\n```text\nfetch.d.ts\n```\n\n```text\n\"apollo-server\": \"^2.25.2\"\n```\n\n```text\nconst result = await server.executeOperation(\n { query: query },\n { req: { headers: { authorization: '...' } } }\n );\n```\n\n```text\nexpress.Request\n```\n\n```text\nconst req = {\n kauth: {\n grant: {\n access_token: {\n isExpired: () => {\n return false;\n },\n token: \"abc\",\n content: {\n email: \"me@me.com\",\n resource_access: {\n \"my-api\": {\n roles: [\"admin\"],\n },\n },\n },\n },\n },\n },\n };\n\n server = new ApolloServer({\n schema,\n resolvers,\n dataSources: () => ({\n users,\n }),\n context: () => {\n return { kauth: new KeycloakContext({ req }) };\n },\n });\n });\n```\n\n========================================\n\nComments:\n- docs are very thin on this. Also seeking some info\n- Thanks for the notification. I'll give it a try","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":193,"estimatedTokens":1076}}500{"id":"stack-45329217","source":"stackoverflow","questionId":45329217,"title":"Error: RootQueryType.resolve field config must be an object","tags":["node.js","graphql","graphql-js"],"text":"Title: Error: RootQueryType.resolve field config must be an object\nTags: node.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nim new to GraphQl, just created my first schema to see this error\n\n```\nError: RootQueryType.resolve field config must be an object\n at invariant (/Applications/Node/users/node_modules/graphql/jsutils/invariant.js:19:11)\n at /Applications/Node/users/node_modules/graphql/type/definition.js:360:56\n at Array.forEach (native)\n at defineFieldMap (/Applications/Node/users/node_modules/graphql/type/definition.js:357:14)\n at GraphQLObjectType.getFields (/Applications/Node/users/node_modules/graphql/type/definition.js:311:44)\n at typeMapReducer (/Applications/Node/users/node_modules/graphql/type/schema.js:209:25)\n at Array.reduce (native)\n at new GraphQLSchema (/Applications/Node/users/node_modules/graphql/type/schema.js:98:34)\n at Object. (/Applications/Node/users/schema/schema.js:39:18)\n at Module._compile (module.js:569:30)\n```\n\nthis is my schema\n\n```\nconst graphql = require('graphql');\nconst _ = require('lodash');\nconst{\n GraphQLObjectType,\n GraphQLInt, \n GraphQLString,\n GraphQLSchema\n} = graphql;\n\nconst users = [\n {id:'23', firstName:'Bill', age:20},\n {id:'47', firstName:'Samantha', age:21}\n];\n\nconst UserType = new GraphQLObjectType({\n name: 'User',\n fields:{\n id: {type: GraphQLString},\n firstName: {type: GraphQLString},\n age:{type: GraphQLInt}\n }\n});\n\nconst RootQuery = new GraphQLObjectType({\n name: 'RootQueryType',\n fields:{\n user: {\n type: UserType,\n args:{\n id: {type: GraphQLString}\n }\n },\n resolve(parentValue, args){\n return _.find(users, {id: args.id});\n }\n }\n});\n\nmodule.exports = new GraphQLSchema({\n query: RootQuery\n});\n```\n\n========================================\n\nCode:\n```text\nError: RootQueryType.resolve field config must be an object\n at invariant (/Applications/Node/users/node_modules/graphql/jsutils/invariant.js:19:11)\n at /Applications/Node/users/node_modules/graphql/type/definition.js:360:56\n at Array.forEach (native)\n at defineFieldMap (/Applications/Node/users/node_modules/graphql/type/definition.js:357:14)\n at GraphQLObjectType.getFields (/Applications/Node/users/node_modules/graphql/type/definition.js:311:44)\n at typeMapReducer (/Applications/Node/users/node_modules/graphql/type/schema.js:209:25)\n at Array.reduce (native)\n at new GraphQLSchema (/Applications/Node/users/node_modules/graphql/type/schema.js:98:34)\n at Object.<anonymous> (/Applications/Node/users/schema/schema.js:39:18)\n at Module._compile (module.js:569:30)\n```\n\n```text\nconst graphql = require('graphql');\nconst _ = require('lodash');\nconst{\n GraphQLObjectType,\n GraphQLInt, \n GraphQLString,\n GraphQLSchema\n} = graphql;\n\nconst users = [\n {id:'23', firstName:'Bill', age:20},\n {id:'47', firstName:'Samantha', age:21}\n];\n\nconst UserType = new GraphQLObjectType({\n name: 'User',\n fields:{\n id: {type: GraphQLString},\n firstName: {type: GraphQLString},\n age:{type: GraphQLInt}\n }\n});\n\nconst RootQuery = new GraphQLObjectType({\n name: 'RootQueryType',\n fields:{\n user: {\n type: UserType,\n args:{\n id: {type: GraphQLString}\n }\n },\n resolve(parentValue, args){\n return _.find(users, {id: args.id});\n }\n }\n});\n\nmodule.exports = new GraphQLSchema({\n query: RootQuery\n});\n```\n\n```text\nconst RootQuery = new GraphQLObjectType({\n name: 'RootQueryType',\n fields:{\n user: {\n type: UserType,\n args:{\n id: {type: GraphQLString}\n },\n resolve(parentValue, args){ // move the resolve function to here\n return _.find(users, {id: args.id});\n }\n },\n\n }\n});\n```\n\n========================================\n\nComments:\n- Looks like you are following Stephen Girder's course. Is that right ? :)\n- I'm taking the course now. I had no idea that it was 5...almost 6 yrs old.\n- Thank you. that was the problem. you saved me from days of debugging","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":152,"estimatedTokens":1014}}501{"id":"stack-68839829","source":"stackoverflow","questionId":68839829,"title":"How can I get the open graph image for a GitHub repository?","tags":["github","graphql","github-api"],"text":"Title: How can I get the open graph image for a GitHub repository?\nTags: github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nI have been trying to get the open graph images from my repositories through the GraphQL API that GitHub exposes, but I always get my avatar back. I have tried querying the repositories node, the search, and the user node to no avail.\n\nFor example, for the query:\n\n```\nquery {\n repository(name: \"rust-algorithms\", owner: \"alexfertel\") {\n openGraphImageUrl\n nameWithOwner\n }\n}\n```\n\nI get:\n\n```\n\"repository\": {\n \"openGraphImageUrl\": \"https://avatars.githubusercontent.com/u/22298999?s=400&v=4\",\n \"nameWithOwner\": \"alexfertel/rust-algorithms\"\n},\n```\n\nWhich you can tell gives an avatar and not the open graph image generated by GitHub for the repository.\n\nIs there a way to get this image that doesn't involve scraping GitHub?\n\n========================================\n\nTop Answer:\nYou can also get it for issue and pull request\n\n**Issue**\n\n```\nhttps://opengraph.githubassets.com////issue/\n```\n\n**PR**\n\n```\nhttps://opengraph.githubassets.com////pull/\n```\n\n**any_hash_number**\n\nWe can use any number or string here. This is actually to tell the API that this is the version. It's better to use `hash` because then it will always give the updated image.But we can use any string like `1`, `a`, or `1a`. If we always use `1` or `a` it will not give updated image.\n\n========================================\n\nCode:\n```text\nquery {\n repository(name: \"rust-algorithms\", owner: \"alexfertel\") {\n openGraphImageUrl\n nameWithOwner\n }\n}\n```\n\n```json\n\"repository\": {\n \"openGraphImageUrl\": \"https://avatars.githubusercontent.com/u/22298999?s=400&v=4\",\n \"nameWithOwner\": \"alexfertel/rust-algorithms\"\n},\n```\n\n```text\nhttps://opengraph.githubassets.com/<any_hash_number>/<owner>/<repo>\n```\n\n```text\n1\n```\n\n```text\na\n```\n\n```text\n1a\n```\n\n```text\n1\n```\n\n```text\na\n```\n\n```text\nhttps://opengraph.githubassets.com/<any_hash_number>/<owner>/<repo>/issue/<issue_number>\n```\n\n```text\nhttps://opengraph.githubassets.com/<any_hash_number>/<owner>/<repo>/pull/<pr_number>\n```\n\n```text\nhash\n```\n\n```text\n1\n```\n\n```text\na\n```\n\n```text\n1a\n```\n\n```text\n1\n```\n\n```text\na\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":126,"estimatedTokens":546}}502{"id":"stack-60922054","source":"stackoverflow","questionId":60922054,"title":"How to query all languages from GitHubs graphql","tags":["github","graphql","github-api","github-graphql"],"text":"Title: How to query all languages from GitHubs graphql\nTags: github, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to query GitHub for information about repositories using their v4 graphql. One of the things I want to query is the breakdown of all the languages used in the repo. Or if possible, the breakdown of the languages across all of a user's repos. I have tried the following snippet, but it returns null, where as primary language returns the primary language\n\n```\nlanguages: {\n edges: {\n node: {\n name\n }\n }\n}\n```\n\nThe only thing I can find relating to languages is the primary language. But I would like to show stats for a user and the all languages they use either in a single repo or across off their repos.\n\n========================================\n\nTop Answer:\nI wanted to point our something else that may help.\n\nYou can get more details about a language (i.e. primary, secondary etc) by looking at the language `size`. Comparing the `totalSize` for the whole repo to the `size` for each language it has.\n\nThe following query (example for pytorch) will get the data you need. Put it into the GH's GQL Explorer to check it out.\n\n```\n{\n repository(name: \"pytorch\", owner: \"pytorch\") {\n languages(first: 100) {\n totalSize\n edges {\n size\n node {\n name\n id\n }\n }\n }\n }\n}\n```\n\nYou will get an output of the form\n\n```\n{\n \"data\": {\n \"repository\": {\n \"languages\": {\n \"totalSize\": 78666590,\n \"edges\": [\n {\n \"size\": 826272,\n \"node\": {\n \"name\": \"CMake\",\n \"id\": \"MDg6TGFuZ3VhZ2U0NDA=\"\n }\n },\n {\n \"size\": 29256797,\n \"node\": {\n \"name\": \"Python\",\n \"id\": \"MDg6TGFuZ3VhZ2UxNDU=\"\n }\n }, ...\n```\n\nTo get % for each language just do `size` / `totalSize` * 100\n\n========================================\n\nCode:\n```text\nlanguages: {\n edges: {\n node: {\n name\n }\n }\n}\n```\n\n```graphql\n{\n user(login: \"torvalds\") {\n repositories(first: 100) {\n nodes {\n primaryLanguage {\n name\n }\n languages(first: 100) {\n nodes {\n name\n }\n }\n }\n }\n }\n}\n```\n\n```text\nfirst: 100\n```\n\n```text\n{\n repository(name: \"pytorch\", owner: \"pytorch\") {\n languages(first: 100) {\n totalSize\n edges {\n size\n node {\n name\n id\n }\n }\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"repository\": {\n \"languages\": {\n \"totalSize\": 78666590,\n \"edges\": [\n {\n \"size\": 826272,\n \"node\": {\n \"name\": \"CMake\",\n \"id\": \"MDg6TGFuZ3VhZ2U0NDA=\"\n }\n },\n {\n \"size\": 29256797,\n \"node\": {\n \"name\": \"Python\",\n \"id\": \"MDg6TGFuZ3VhZ2UxNDU=\"\n }\n }, ...\n```\n\n```text\nsize\n```\n\n```text\ntotalSize\n```\n\n```text\nsize\n```\n\n```text\nsize\n```\n\n```text\ntotalSize\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":167,"estimatedTokens":712}}503{"id":"stack-52695414","source":"stackoverflow","questionId":52695414,"title":"React-Select with React-Apollo does not work","tags":["reactjs","graphql","apollo","react-apollo","react-select"],"text":"Title: React-Select with React-Apollo does not work\nTags: reactjs, graphql, apollo, react-apollo, react-select\nSource: Stack Overflow\n\nQuestion:\nWe are using react-select and fetching the items as the user types. I am not able to make it work with react-apollo.\n\nCan someone help me provide a guideline?\n\nHere is my unsuccessful attempt:\n\n```\nclass PatientSearchByPhone extends Component {\n updateProp = mobile => {\n if (mobile.length ;\n }\n}\n\nconst FETCH_PATIENT = gql`\n query Patient($input: PatientSearchInput) {\n getPatients(input: $input) {\n id\n first_name\n }\n }\n`;\nexport default graphql(FETCH_PATIENT, {\n options: ({ mobile }) => ({ variables: { input: { mobile } } })\n})(PatientSearchByPhone);\n```\n\nVersions:\n\n\"react-apollo\": \"^2.1.11\",\n\n\"react-select\": \"^2.1.0\"\n\nThanks for your time.\n\n========================================\n\nTop Answer:\nThe other option is to execute the graphql query manually using the `client` that is exposed by wrapping the base component with `withApollo`.\n\nIn the example below, we have,\n\n- BaseComponnent which renders the AsyncSelect `react-select` component\n\n- `loadOptionsIndexes` which executes the async graphql fetch via the `client`\n\n- BaseComponent.propTypes describes the required `client` prop\n\n- `withApollo` wraps the base component to give us the actual component we'll use elsewhere in the react app.\n\n```\nconst BaseComponent = (props) => {\n const loadOptionsIndexes = (inputValue) => {\n let graphqlQueryExpression = {\n query: QUERY_INDEXES,\n variables: {\n name: inputValue\n }\n }\n\n const transformDataIntoValueLabel = (data) => {\n return data.indexes.indexes.map(ix => { return { value: ix.id, label: ix.name }})\n } \n\n return new Promise(resolve => {\n props.client.query(graphqlQueryExpression).then(response => {\n resolve(transformDataIntoValueLabel(response.data))\n })\n });\n\n }\n\n return (\n <>\n \n \n \n \n \n \n )\n}\n\nBaseComponent.propTypes = {\n client: PropTypes.any,\n}\n\nconst ComplementComponent = withApollo(BaseComponent);\n```\n\nSorry if the example is a little off - copy and pasted what I had working rather than moving on without giving back.\n\n========================================\n\nCode:\n```text\nclass PatientSearchByPhone extends Component {\n updateProp = mobile => {\n if (mobile.length < 10) return;\n this.props.data.refetch({ input: { mobile } });\n };\n\n render() {\n console.log(this.props.data);\n return <AsyncSelect cacheOptions loadOptions={this.updateProp} />;\n }\n}\n\nconst FETCH_PATIENT = gql`\n query Patient($input: PatientSearchInput) {\n getPatients(input: $input) {\n id\n first_name\n }\n }\n`;\nexport default graphql(FETCH_PATIENT, {\n options: ({ mobile }) => ({ variables: { input: { mobile } } })\n})(PatientSearchByPhone);\n```\n\n```text\nimport React, { useState } from \"react\";\nimport \"./App.css\";\nimport AsyncSelect from \"react-select/async\";\nimport ApolloClient, { gql } from \"apollo-boost\";\n\nconst client = new ApolloClient({\n uri: \"https://metaphysics-production.artsy.net\"\n});\n\nconst fetchArtists = async (input: string, cb: any) => {\n if (input && input.trim().length < 4) {\n return [];\n }\n const res = await client.query({\n query: gql`\n query {\n match_artist(term: \"${input}\") {\n name\n imageUrl\n }\n }\n `\n });\n\n if (res.data && res.data.match_artist) {\n return res.data.match_artist.map(\n (a: { name: string; imageUrl: string }) => ({\n label: a.name,\n value: a.imageUrl\n })\n );\n }\n\n return [];\n};\n\nconst App: React.FC = () => {\n const [artist, setArtist] = useState({\n label: \"No Name\",\n value: \"https://dummyimage.com/200x200/000/fff&text=No+Artist\"\n });\n return (\n <div className=\"App\">\n <header className=\"App-header\">\n <h4>Search artists and their image (type 4 char or more)</h4>\n <AsyncSelect\n loadOptions={fetchArtists}\n onChange={(opt: any) => setArtist(opt)}\n placeholder=\"Search an Artist\"\n className=\"select\"\n />\n <div>\n <img alt={artist.label} src={artist.value} className=\"aimage\" />\n </div>\n </header>\n </div>\n );\n};\n\nexport default App;\n```\n\n```text\nvinci\n```\n\n```text\nconst BaseComponent = (props) => {\n const loadOptionsIndexes = (inputValue) => {\n let graphqlQueryExpression = {\n query: QUERY_INDEXES,\n variables: {\n name: inputValue\n }\n }\n\n const transformDataIntoValueLabel = (data) => {\n return data.indexes.indexes.map(ix => { return { value: ix.id, label: ix.name }})\n } \n\n return new Promise(resolve => {\n props.client.query(graphqlQueryExpression).then(response => {\n resolve(transformDataIntoValueLabel(response.data))\n })\n });\n\n }\n\n return (\n <>\n <div className=\"chart-buttons-default\">\n <div className=\"select-index-input\" style={{width: 400, display: \"inline-block\"}}>\n <AsyncSelect \n isMulti={true}\n cacheOptions={true}\n defaultOptions={true}\n loadOptions={loadOptionsIndexes} />\n </div>\n </div>\n </>\n )\n}\n\nBaseComponent.propTypes = {\n client: PropTypes.any,\n}\n\nconst ComplementComponent = withApollo(BaseComponent);\n```\n\n```text\nclient\n```\n\n```text\nwithApollo\n```\n\n```text\nreact-select\n```\n\n```text\nloadOptionsIndexes\n```\n\n```text\nclient\n```\n\n```text\nclient\n```\n\n```text\nwithApollo\n```\n\n========================================\n\nComments:\n- Can you reproduce the problem on a sample at codesandbox.io ?\n- Did you end up finding a solution? I've just started looking at this integration and curious how others have approached it.\n- @AllenFuller yeah, I did. Let me create a sandbox example for you later today.\n- @AllenFuller added an answer.\n- This is great @Nishant - how would you go about preselecting an artist based on id?\n- There are `defaultOptions` and `defaultValue` to play with.","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":273,"estimatedTokens":1468}}504{"id":"stack-63525235","source":"stackoverflow","questionId":63525235,"title":"Apollo Boost MockedProvider returns empty object when using fragment on query","tags":["jestjs","graphql","react-apollo","react-testing-library"],"text":"Title: Apollo Boost MockedProvider returns empty object when using fragment on query\nTags: jestjs, graphql, react-apollo, react-testing-library\nSource: Stack Overflow\n\nQuestion:\nI have a working test using Apollo Boost `MockedProvider`, Jest and React Testing Library that, when I change the returned fields to a graphQL `fragment` it stops working. What am I missing?\n\n**TicketGql.js**\n\n```\nexport default class TicketGql {\n static VIEW_FRAGMENT = gql`\n fragment ViewFragment on View {\n viewId\n versionId\n name\n description\n orderedColumns {\n columnId\n name\n descriptions {\n translationId\n lang\n description\n }\n }\n }\n `;\n\n static GET_TICKET_VIEW = gql`\n query getView($viewId: ID!) {\n view(viewId: $viewId) {\n viewId\n versionId\n name\n description\n orderedColumns {\n columnId\n name\n descriptions {\n translationId\n lang\n description\n }\n }\n }\n }\n `;\n}\n```\n\n**TicketGql.test.js**\n\n```\n...\nit('GET_TICKET_VIEW', async () => {\n const currentLang = uniqid('lang_');\n const viewMock = {\n viewId: uniqid('viewId_'),\n versionId: uniqid('versionId_'),\n name: uniqid('name_'),\n description: uniqid('description_'),\n orderedColumns: [],\n };\n _.times(_.random(1, 5), (columnIndex) => {\n viewMock.orderedColumns.push({\n columnId: uniqid('columnId_'),\n name: uniqid('columnId_'),\n descriptions: [],\n });\n _.times(\n _.random(1, 3),\n (descIndex) => viewMock.orderedColumns[columnIndex].descriptions.push({\n translationId: uniqid('translationId_'),\n lang: descIndex === 0 ? currentLang : uniqid('lang_'),\n description: uniqid('description_'),\n }),\n );\n });\n const variables = { viewId: viewMock.viewId };\n const mocks = [\n {\n request: {\n query: TicketGql.GET_TICKET_VIEW,\n variables,\n },\n result: {\n data: {\n view: viewMock,\n },\n },\n },\n ];\n const TicketViewColumns = () => {\n const { data, loading, error } = useQuery(TicketGql.GET_TICKET_VIEW, {\n variables,\n });\n return (\n \n {error}\n \n {\n loading\n ? 'loading...'\n : (\n data.view.orderedColumns.map((column) => (\n \n {column.descriptions.find((d) => d.lang === currentLang).description}\n \n ))\n )\n }\n \n \n );\n };\n render(\n \n \n ,\n );\n await waitFor(() => expect(screen.queryAllByRole('listitem'))\n .toHaveLength(viewMock.orderedColumns.length));\n );\n...\n```\n\nThis test works as it is. But, when I change the GET_TICKET_VIEW to this...\n\n```\nstatic GET_TICKET_VIEW = gql`\n query getView($viewId: ID!) {\n view(viewId: $viewId) {\n ...ViewFragment\n }\n }\n ${TicketGql.VIEW_FRAGMENT}\n`;\n```\n\n... it just stops working. The `MockedProvide` returns `data === { view: {} }` instead of the data provided in `viewMock`, causing error on `data.view.orderedColumns.map` as `data.view.orderedColumns` is `undefined`. I have another test using this fragment on a mutation and it works.\n\nEdit:\n\npackage.json\n\n```\n\"dependencies\": {\n \"@apollo/react-hooks\": \"^4.0.0\",\n \"apollo-boost\": \"^0.4.9\",\n \"graphql\": \"^15.0.0\",\n ...\n}\n\"devDependencies\": {\n \"@apollo/client\": \"^3.1.1\",\n \"@testing-library/jest-dom\": \"^5.8.0\",\n \"@testing-library/react\": \"^10.0.4\",\n...\n}\n```\n\n========================================\n\nCode:\n```js\nexport default class TicketGql {\n static VIEW_FRAGMENT = gql`\n fragment ViewFragment on View {\n viewId\n versionId\n name\n description\n orderedColumns {\n columnId\n name\n descriptions {\n translationId\n lang\n description\n }\n }\n }\n `;\n\n static GET_TICKET_VIEW = gql`\n query getView($viewId: ID!) {\n view(viewId: $viewId) {\n viewId\n versionId\n name\n description\n orderedColumns {\n columnId\n name\n descriptions {\n translationId\n lang\n description\n }\n }\n }\n }\n `;\n}\n```\n\n```js\n...\nit('GET_TICKET_VIEW', async () => {\n const currentLang = uniqid('lang_');\n const viewMock = {\n viewId: uniqid('viewId_'),\n versionId: uniqid('versionId_'),\n name: uniqid('name_'),\n description: uniqid('description_'),\n orderedColumns: [],\n };\n _.times(_.random(1, 5), (columnIndex) => {\n viewMock.orderedColumns.push({\n columnId: uniqid('columnId_'),\n name: uniqid('columnId_'),\n descriptions: [],\n });\n _.times(\n _.random(1, 3),\n (descIndex) => viewMock.orderedColumns[columnIndex].descriptions.push({\n translationId: uniqid('translationId_'),\n lang: descIndex === 0 ? currentLang : uniqid('lang_'),\n description: uniqid('description_'),\n }),\n );\n });\n const variables = { viewId: viewMock.viewId };\n const mocks = [\n {\n request: {\n query: TicketGql.GET_TICKET_VIEW,\n variables,\n },\n result: {\n data: {\n view: viewMock,\n },\n },\n },\n ];\n const TicketViewColumns = () => {\n const { data, loading, error } = useQuery(TicketGql.GET_TICKET_VIEW, {\n variables,\n });\n return (\n <div>\n {error}\n <ul>\n {\n loading\n ? 'loading...'\n : (\n data.view.orderedColumns.map((column) => (\n <li key={column.columnId}>\n {column.descriptions.find((d) => d.lang === currentLang).description}\n </li>\n ))\n )\n }\n </ul>\n </div>\n );\n };\n render(\n <MockedProvider mocks={mocks} addTypename={false}>\n <TicketViewColumns />\n </MockedProvider>,\n );\n await waitFor(() => expect(screen.queryAllByRole('listitem'))\n .toHaveLength(viewMock.orderedColumns.length));\n );\n...\n```\n\n```js\nstatic GET_TICKET_VIEW = gql`\n query getView($viewId: ID!) {\n view(viewId: $viewId) {\n ...ViewFragment\n }\n }\n ${TicketGql.VIEW_FRAGMENT}\n`;\n```\n\n```text\n\"dependencies\": {\n \"@apollo/react-hooks\": \"^4.0.0\",\n \"apollo-boost\": \"^0.4.9\",\n \"graphql\": \"^15.0.0\",\n ...\n}\n\"devDependencies\": {\n \"@apollo/client\": \"^3.1.1\",\n \"@testing-library/jest-dom\": \"^5.8.0\",\n \"@testing-library/react\": \"^10.0.4\",\n...\n}\n```\n\n```text\nMockedProvider\n```\n\n```text\nfragment\n```\n\n```text\nMockedProvide\n```\n\n```text\ndata === { view: {} }\n```\n\n```text\nviewMock\n```\n\n```text\ndata.view.orderedColumns.map\n```\n\n```text\ndata.view.orderedColumns\n```\n\n```text\nundefined\n```\n\n```text\n__typename\n```\n\n========================================\n\nComments:\n- Nowadays I tend to add `__typename` in my mock object generators, and make it an optional field in my TypeScript typings too. So that I get the correct `__typename` all the time, so I can my mock factories between graphql and non graphql contexts. I can also copy-paste actual datas from queries to build those mocks. This creates a slight new dependency to the GraphQL schema typings but it may be worth it.","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":346,"estimatedTokens":1671}}505{"id":"stack-66841847","source":"stackoverflow","questionId":66841847,"title":"Can't figure out is it possible to use multiple schemas in Hot Chocolate for ASP.NET Core","tags":["asp.net-core","graphql","hotchocolate"],"text":"Title: Can't figure out is it possible to use multiple schemas in Hot Chocolate for ASP.NET Core\nTags: asp.net-core, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI'm trying to start developing GraphQL API with Hot Chocolate library on ASP.NET Core but I can't figure out how to use different schemas for different endpoints. I know about schema stitching but it's not what I'm looking for.\nWhat I would like to implement, it is to be able to query different types from different endpoints, for example, I want to query user data from localhost:5000/graphapi and to query different admin data from localhost:5000/admin/graphapi\nYes, it is possible to create to separate servers for this but I would like to have monolith API.\n\n========================================\n\nTop Answer:\nYes as was told above, Banana Cake Pop works well with multiple schemas. Just create new page inside Banana Cake Pop for a new schema and set the HTTP endpoint for this schema in the page connection settings.\nBanana Cake Pop will use the first opened GraphQL endpoint to load UI elements, so you can create a stub (or empty) GraphQL endpoint and redirect users to it by default. Then users can add necessary pages for real schemas.\n\n========================================\n\nCode:\n```cs\npublic void ConfigureServices(IServiceCollection services)\n{\n services\n .AddRouting()\n\n services\n .AddGraphQLServer()\n .AddQueryType<Query>()\n .AddMutationType<Mutation>();\n\n services\n .AddGraphQLServer(\"adminSchema\")\n .AddQueryType<QueryAdmin>()\n .AddMutationType<MutationAdmin>();\n}\n```\n\n```cs\npublic void Configure(IApplicationBuilder app, IWebHostEnvironment env)\n{\n app\n .UseRouting()\n .UseEndpoints(endpoints =>\n {\n endpoints.MapGraphQL();\n endpoints.MapGraphQL(\"/admin/graphql\", schemaName: \"adminSchema\");\n });\n}\n```\n\n========================================\n\nComments:\n- Have you found that Banana Cake Pop doesn't switch between the two schemas correctly unless you clear the browser cache? Or is there a setting or something for this?\n- You will need to change it at the settings in Banana Cake Pop.\n- For anyone else facing this issue, I found out how to fix the Banana Cake Pop wonkiness between multiple schemas. At the top-right, there's a small gear icon labeled \"connection strings\". Click that, update the Schema Endpoint, and click 'Apply'.","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":55,"estimatedTokens":612}}506{"id":"stack-50134657","source":"stackoverflow","questionId":50134657,"title":"How do i define an enum in react native","tags":["javascript","react-native","enums","graphql"],"text":"Title: How do i define an enum in react native\nTags: javascript, react-native, enums, graphql\nSource: Stack Overflow\n\nQuestion:\nBasically what I'm trying to achieve is send info to the server without quotations e.g Admin instead of \"Admin\", but as we all know Graphql will throw an error is the variable is not defined or is not in quotations.\n\n========================================\n\nTop Answer:\nyou can use enum with `typeScript` in `react-native` like describe in the link\n\nsample code is\n\n```\nenum Direction {\n Up = 1,\n Down,\n Left,\n Right,\n}\n```\n\n========================================\n\nCode:\n```text\nconst adminEnum = { Admin: 'Admin'};\n```\n\n```text\nconst result = apolloclient.mutate({\n mutation: reset_password,\n variables: {\n method: 'EMAIL',\n uuid: opts.uuid\n }\n});\n```\n\n```text\nmethod\n```\n\n```text\nenum Direction {\n Up = 1,\n Down,\n Left,\n Right,\n}\n```\n\n```text\ntypeScript\n```\n\n```text\nreact-native\n```\n\n```text\nexport enum TransportTypeEnum {\n OneWay = 0,\n Return = 1,\n }\n```\n\n```text\nimport {TransportTypeEnum} from '../enums/TransportTypeEnum';\n```\n\n========================================\n\nComments:\n- This is not a type. The answer below is thus a better choice in typescript (stackoverflow.com/a/65108763/9611924)","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":76,"estimatedTokens":323}}507{"id":"stack-66441463","source":"stackoverflow","questionId":66441463,"title":"FetchMore : Request executed twice every time","tags":["reactjs","graphql","apollo","apollo-client"],"text":"Title: FetchMore : Request executed twice every time\nTags: reactjs, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement pagination in a comment section.\n\nI have normal visual behavior on the website. When I click the get more button, 10 new comments are added.\n\nMy problem is the request is executed twice every time. I have no idea why. The first time, it is executed with a cursor value, the second time without it. It seems that the useQuery hook is executed after each fetchMore.\n\nAny help would be appreciated. Thanks!\n\n**component :**\n\n```\nexport default ({ event }) => {\n const { data: moreCommentsData, fetchMore } = useQuery(getMoreCommentsQuery, {\n variables: {\n id: event.id,\n },\n fetchPolicy: \"cache-and-network\",\n });\n const getMoreComments = () => {\n const cursor =\n moreCommentsData.event.comments[\n moreCommentsData.event.comments.length - 1\n ];\n fetchMore({\n variables: {\n id: event.id,\n cursor: cursor.id,\n },\n updateQuery: (prev, { fetchMoreResult, ...rest }) => {\n return {\n ...fetchMoreResult,\n event: {\n ...fetchMoreResult.event,\n comments: [\n ...prev.event.comments,\n ...fetchMoreResult.event.comments,\n ],\n commentCount: fetchMoreResult.event.commentCount,\n },\n };\n },\n });\n };\n return (\n \n {moreCommentsData &&\n moreCommentsData.event &&\n moreCommentsData.event.comments\n ? moreCommentsData.event.comments.map((c) => c.text + \" \")\n : \"\"}\n\n getMoreComments()} />\n \n ); \n};\n```\n\n**query :**\n\n```\nconst getMoreCommentsQuery = gql`\n query($id: ID, $cursor: ID) {\n event(id: $id) {\n id\n comments(cursor: $cursor) {\n id\n text\n author {\n id\n displayName\n photoURL\n }\n }\n }\n }\n`;\n```\n\n========================================\n\nTop Answer:\nCould it be that the second request you are seeing is just because of refetchOnWindowFocus, because that happens a lot...\n\n========================================\n\nCode:\n```text\nexport default ({ event }) => {\n const { data: moreCommentsData, fetchMore } = useQuery(getMoreCommentsQuery, {\n variables: {\n id: event.id,\n },\n fetchPolicy: \"cache-and-network\",\n });\n const getMoreComments = () => {\n const cursor =\n moreCommentsData.event.comments[\n moreCommentsData.event.comments.length - 1\n ];\n fetchMore({\n variables: {\n id: event.id,\n cursor: cursor.id,\n },\n updateQuery: (prev, { fetchMoreResult, ...rest }) => {\n return {\n ...fetchMoreResult,\n event: {\n ...fetchMoreResult.event,\n comments: [\n ...prev.event.comments,\n ...fetchMoreResult.event.comments,\n ],\n commentCount: fetchMoreResult.event.commentCount,\n },\n };\n },\n });\n };\n return (\n <Container>\n {moreCommentsData &&\n moreCommentsData.event &&\n moreCommentsData.event.comments\n ? moreCommentsData.event.comments.map((c) => c.text + \" \")\n : \"\"}\n\n <Button content=\"Load More\" basic onClick={() => getMoreComments()} />\n </Container>\n ); \n};\n```\n\n```text\nconst getMoreCommentsQuery = gql`\n query($id: ID, $cursor: ID) {\n event(id: $id) {\n id\n comments(cursor: $cursor) {\n id\n text\n author {\n id\n displayName\n photoURL\n }\n }\n }\n }\n`;\n```\n\n```text\nnextFetchPolicy: \"cache-first\"\n```\n\n```text\nuseQuery\n```\n\n```text\nfetchPolicy\n```\n\n```text\nnetwork-only\n```\n\n```text\n@apollo/client v3.5.x\n```\n\n```text\nv3.6.0+\n```\n\n========================================\n\nComments:\n- It does make two requests. My backend is called 2 times, I have console.logs in the backend.\n- This seems to be an Apollo bug, it's already fixed in a PR and will be hopefully available soon, see: github.com/apollographql/apollo-client/issues/6916\n- not working at all, I don't know why this accepted.\n- Thanks, it works for me, but it must be a bug in Vue Apollo.","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":188,"estimatedTokens":973}}508{"id":"stack-65395564","source":"stackoverflow","questionId":65395564,"title":"Error \"Conflict resolver rejects mutation.\" when Delete in Amplify","tags":["reactjs","graphql","aws-amplify"],"text":"Title: Error \"Conflict resolver rejects mutation.\" when Delete in Amplify\nTags: reactjs, graphql, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI have a simple full-stack amplify app.\n\nHere is my model:\n\n```\ntype Note @model @auth(rules: [{allow: public}]) {\n id: ID!\n name: String!\n description: String\n image: String\n NoteType: NoteType @connection\n}\n\ntype NoteType @model @auth(rules: [{allow: public}]) {\n id: ID!\n name: String!\n}\n```\n\nI'm trying to delete a Note with the following payload:\n\n```\n{\n \"query\": \"mutation DeleteNote($input: DeleteNoteInput!, $condition: ModelNoteConditionInput) {β΅ deleteNote(input: $input, condition: $condition) {β΅ idβ΅ nameβ΅ descriptionβ΅ imageβ΅ createdAtβ΅ updatedAtβ΅ NoteType {β΅ idβ΅ nameβ΅ createdAtβ΅ updatedAtβ΅ }β΅ }β΅}β΅\",\n \"variables\": {\"input\": {\"id\": \"0c5e3ced-ffa3-4de8-9010-40b67d5bab68\"}}\n}\n```\n\nWhat I see in the response is the following json:\n\n```\n{\n \"data\": {\n \"deleteNote\": null\n },\n \"errors\": [\n {\n \"path\": [\n \"deleteNote\"\n ],\n \"data\": {\n \"id\": \"0c5e3ced-ffa3-4de8-9010-40b67d5bab68\",\n \"name\": \"bb\",\n \"description\": \"bb\",\n \"image\": \"icon.png\",\n \"createdAt\": \"2020-12-21T12:00:26.743Z\",\n \"updatedAt\": \"2020-12-21T12:00:26.743Z\"\n },\n \"errorType\": \"ConflictUnhandled\",\n \"errorInfo\": null,\n \"locations\": [\n {\n \"line\": 1,\n \"column\": 88,\n \"sourceName\": null\n }\n ],\n \"message\": \"Conflict resolver rejects mutation.\"\n }\n ]\n}\n```\n\nThe code was working until I tried to add the `NoteType`! Is there any conflict regarding the foreign-key here?\n\n========================================\n\nCode:\n```text\ntype Note @model @auth(rules: [{allow: public}]) {\n id: ID!\n name: String!\n description: String\n image: String\n NoteType: NoteType @connection\n}\n\ntype NoteType @model @auth(rules: [{allow: public}]) {\n id: ID!\n name: String!\n}\n```\n\n```json\n{\n \"query\": \"mutation DeleteNote($input: DeleteNoteInput!, $condition: ModelNoteConditionInput) {β΅ deleteNote(input: $input, condition: $condition) {β΅ idβ΅ nameβ΅ descriptionβ΅ imageβ΅ createdAtβ΅ updatedAtβ΅ NoteType {β΅ idβ΅ nameβ΅ createdAtβ΅ updatedAtβ΅ }β΅ }β΅}β΅\",\n \"variables\": {\"input\": {\"id\": \"0c5e3ced-ffa3-4de8-9010-40b67d5bab68\"}}\n}\n```\n\n```json\n{\n \"data\": {\n \"deleteNote\": null\n },\n \"errors\": [\n {\n \"path\": [\n \"deleteNote\"\n ],\n \"data\": {\n \"id\": \"0c5e3ced-ffa3-4de8-9010-40b67d5bab68\",\n \"name\": \"bb\",\n \"description\": \"bb\",\n \"image\": \"icon.png\",\n \"createdAt\": \"2020-12-21T12:00:26.743Z\",\n \"updatedAt\": \"2020-12-21T12:00:26.743Z\"\n },\n \"errorType\": \"ConflictUnhandled\",\n \"errorInfo\": null,\n \"locations\": [\n {\n \"line\": 1,\n \"column\": 88,\n \"sourceName\": null\n }\n ],\n \"message\": \"Conflict resolver rejects mutation.\"\n }\n ]\n}\n```\n\n```text\nNoteType\n```\n\n```text\n{\n \"query\": \"mutation DeleteNote($input: DeleteNoteInput!, $condition: ModelNoteConditionInput) {β΅ deleteNote(input: $input, condition: $condition) {β΅ idβ΅ nameβ΅ descriptionβ΅ imageβ΅ createdAtβ΅ updatedAtβ΅ NoteType {β΅ idβ΅ nameβ΅ createdAtβ΅ updatedAtβ΅ }β΅ }β΅}β΅\",\n \"variables\": {\"input\": {\"id\": \"0c5e3ced-ffa3-4de8-9010-40b67d5bab68\", \"_version\": \"_version value of your note object\"}}\n}\n```\n\n```text\n_deleted\n```\n\n```text\n_ttl\n```\n\n========================================\n\nComments:\n- After 24 hours, now the same code makes no error and I can delete items. Somehow strange for me. I don't know what can be the reason!?\n- Just be carefull when adding {\"_version\": the value here should be without quotation marks} since it is an integer.","metadata":{"transformedAt":"2026-08-18T18:32:36.062Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":152,"estimatedTokens":949}}509{"id":"stack-59192617","source":"stackoverflow","questionId":59192617,"title":"Mock specific graphql request in cypress when running e2e tests","tags":["graphql","apollo","cypress"],"text":"Title: Mock specific graphql request in cypress when running e2e tests\nTags: graphql, apollo, cypress\nSource: Stack Overflow\n\nQuestion:\nWhen running e2e tests with Cypress, my goal is to mock a specific graphql query.\n\nCurrently, I can mock all requests like this:\n\n```\ncy.server();\ncy.route('POST', '/graphql', {\n data: {\n foo: 'bar'\n },\n});\n```\n\nThe problem is that this mocks *all* `/graphql` queries. It would be awesome if I somehow could say:\n\n```\ncy.route('POST', '/graphql', 'fooQuery', {\n data: {\n foo: 'bar'\n },\n});\n```\n\nIn our application, we are using Apollo Graphql - and thus all queries are named.\n\n========================================\n\nTop Answer:\nOne way to go about it is to provide the mocked data for the graphql operations in question inside one fixture file\n\n`cypress/support/commands.js`\n\n```\nCypress.Commands.add('stubGraphQL', (graphQlFixture) => {\n cy.fixture(graphQlFixture).then((mockedData) => {\n cy.on('window:before:load', (win) => {\n function fetch(path, { body }) {\n const { operationName } = JSON.parse(body)\n return responseStub(mockedData[operationName])\n }\n cy.stub(win, 'fetch', fetch).withArgs(\"/graphql\").as('graphql');\n });\n })\n})\n\nconst responseStub = result => Promise.resolve({\n json: () => Promise.resolve(result),\n text: () => Promise.resolve(JSON.stringify(result)),\n ok: true,\n})\n//TODO how to get it to stop listening and trying to stub once the list of operations provided in fixture have been stubbed?\n```\n\n`example fixture file` *cypress/fixtures/signInOperation.json (note that there are 2 operations in there and that's how you can specify which response to mock)*\n\n```\n{\n \"SIGNIN_MUTATION\": {\n \"data\":{\"signin\":{\"id\":\"ck896k87jac8w09343gs9bl5h\",\"email\":\"sams@automation.com\",\"name\":\"Sam\",\"__typename\":\"User\"}}\n },\n \"CURRENT_USER_QUERY\" : {\n \"data\":{\"me\":{\"id\":\"ck896k87jac8w09343gs9bl5h\",\"email\":\"sams@automation.com\",\"name\":\"!!Sam's Mock\",\"permissions\":[\"USER\"],\"cart\":[{\"id\":\"ck89gebgvse9w0981bhh4a147\",\"quantity\":5,\"item\":{\"id\":\"ck896py6sacox0934lqc8c4bx\",\"price\":62022,\"image\":\"https://res.cloudinary.com/deadrobot/image/upload/v1585253000/sickfitz/ecgqu4i1wgcj41pdlbty.jpg\",\"title\":\"MensShoes\",\"description\":\"Men's Shoes\",\"__typename\":\"Item\"},\"__typename\":\"CartItem\"},{\"id\":\"ck89gec6mb3ei0934lmyxne52\",\"quantity\":5,\"item\":{\"id\":\"ck896os7oacl90934xczopgfa\",\"price\":70052,\"image\":\"https://res.cloudinary.com/deadrobot/image/upload/v1585252932/sickfitz/i7ac6fqhsebxpmnyd2ui.jpg\",\"title\":\"WomensShoes2\",\"description\":\"Women's Shoes\",\"__typename\":\"Item\"},\"__typename\":\"CartItem\"},{\"id\":\"ck89gl45psely0981b2bvk6q5\",\"quantity\":7,\"item\":{\"id\":\"ck89ghqkpb3ng0934l67rzjxk\",\"price\":100000,\"image\":\"https://res.cloudinary.com/deadrobot/image/upload/v1585269417/sickfitz/eecjz883y7ucshlwvsbw.jpg\",\"title\":\"watch\",\"description\":\"Fancy Watch\",\"__typename\":\"Item\"},\"__typename\":\"CartItem\"}],\"__typename\":\"User\"}}\n }\n}\n```\n\n*in your spec file*\n\n```\ncy.stubGraphQL('signInOperation.json')\ncy.visit(yourURL)\ncy.get(loginButton).click()\n```\n\n========================================\n\nCode:\n```js\ncy.server();\ncy.route('POST', '/graphql', {\n data: {\n foo: 'bar'\n },\n});\n```\n\n```js\ncy.route('POST', '/graphql', 'fooQuery', {\n data: {\n foo: 'bar'\n },\n});\n```\n\n```text\n/graphql\n```\n\n```js\ncy.intercept('POST', '/api', (req) => {\n if (req.body.operationName === 'operationName') {\n req.reply({ fixture: 'mockData.json'});\n }\n}\n```\n\n```text\nroute\n```\n\n```text\nroute2\n```\n\n```text\nintercept\n```\n\n```text\nCypress.Commands.add('stubGraphQL', (graphQlFixture) => {\n cy.fixture(graphQlFixture).then((mockedData) => {\n cy.on('window:before:load', (win) => {\n function fetch(path, { body }) {\n const { operationName } = JSON.parse(body)\n return responseStub(mockedData[operationName])\n }\n cy.stub(win, 'fetch', fetch).withArgs(\"/graphql\").as('graphql');\n });\n })\n})\n\n\nconst responseStub = result => Promise.resolve({\n json: () => Promise.resolve(result),\n text: () => Promise.resolve(JSON.stringify(result)),\n ok: true,\n})\n//TODO how to get it to stop listening and trying to stub once the list of operations provided in fixture have been stubbed?\n```\n\n```text\n{\n \"SIGNIN_MUTATION\": {\n \"data\":{\"signin\":{\"id\":\"ck896k87jac8w09343gs9bl5h\",\"email\":\"sams@automation.com\",\"name\":\"Sam\",\"__typename\":\"User\"}}\n },\n \"CURRENT_USER_QUERY\" : {\n \"data\":{\"me\":{\"id\":\"ck896k87jac8w09343gs9bl5h\",\"email\":\"sams@automation.com\",\"name\":\"!!Sam's Mock\",\"permissions\":[\"USER\"],\"cart\":[{\"id\":\"ck89gebgvse9w0981bhh4a147\",\"quantity\":5,\"item\":{\"id\":\"ck896py6sacox0934lqc8c4bx\",\"price\":62022,\"image\":\"https://res.cloudinary.com/deadrobot/image/upload/v1585253000/sickfitz/ecgqu4i1wgcj41pdlbty.jpg\",\"title\":\"MensShoes\",\"description\":\"Men's Shoes\",\"__typename\":\"Item\"},\"__typename\":\"CartItem\"},{\"id\":\"ck89gec6mb3ei0934lmyxne52\",\"quantity\":5,\"item\":{\"id\":\"ck896os7oacl90934xczopgfa\",\"price\":70052,\"image\":\"https://res.cloudinary.com/deadrobot/image/upload/v1585252932/sickfitz/i7ac6fqhsebxpmnyd2ui.jpg\",\"title\":\"WomensShoes2\",\"description\":\"Women's Shoes\",\"__typename\":\"Item\"},\"__typename\":\"CartItem\"},{\"id\":\"ck89gl45psely0981b2bvk6q5\",\"quantity\":7,\"item\":{\"id\":\"ck89ghqkpb3ng0934l67rzjxk\",\"price\":100000,\"image\":\"https://res.cloudinary.com/deadrobot/image/upload/v1585269417/sickfitz/eecjz883y7ucshlwvsbw.jpg\",\"title\":\"watch\",\"description\":\"Fancy Watch\",\"__typename\":\"Item\"},\"__typename\":\"CartItem\"}],\"__typename\":\"User\"}}\n }\n}\n```\n\n```text\ncy.stubGraphQL('signInOperation.json')\ncy.visit(yourURL)\ncy.get(loginButton).click()\n```\n\n```text\ncypress/support/commands.js\n```\n\n```text\nexample fixture file\n```\n\n```text\ncy.route2('/graphql', (req) => {\n if(req.body.includes('operationName')){\n req.reply({ fixture: 'mockData.json'});\n }\n});\n```\n\n```text\nroute2\n```\n\n```text\ncy.route2()\n```\n\n```text\ncy.intercept('POST', '/test_api/graphql', (req) => {\n req.continue((res) => {\n if (req.body.operationName === 'op_name') {\n res.send({ fixture: 'MyFixture/xyz.json' }),\n req.alias = 'graphql'\n }\n })\n})\n```\n\n========================================\n\nComments:\n- There are different workarounds for this issue posted here in the comments of cypress github: github.com/cypress-io/cypress-documentation/issues/122 . Let us know which one worked for you\n- Thank you SO much for providing this information π₯\n- We adopted `intercept` it's great - marking as correct answer.\n- @roberto Tried the intercept function and my test.json file contains the data returned from the query in Apollo Client. Getting the below uncaught exception: \"Uncaught CypressError: The following error originated from your test code, not from Cypress. > A request callback passed to `cy.intercept()` threw an error while intercepting a request: Unexpected token o in JSON at position 1\"\n- @SuperMario, check the JSON file if it has some wrong characters.\n- It seems like I entered an infinite loop there. It tries to load the data from a fixture, and retries again, without any error.","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":206,"estimatedTokens":1745}}510{"id":"stack-57028362","source":"stackoverflow","questionId":57028362,"title":"Laravel Lighthouse GraphQL - Sorting on server side","tags":["php","laravel","graphql","laravel-lighthouse"],"text":"Title: Laravel Lighthouse GraphQL - Sorting on server side\nTags: php, laravel, graphql, laravel-lighthouse\nSource: Stack Overflow\n\nQuestion:\nHi I am new to GraphQL and I am trying to sort my data based on column content. I have an query endpoint where I can send:\n\n```\nquery {\n user(count:20, firstName:\"Foo\") {\n data {\n name\n region\n birthDate\n }\n }\n}\n```\n\nAnd the result is an array of 20 users with the first name `Foo`. But I want to order them by `birthDate`. I already tried so many things, but I just can not figure out. I already tried prepending `sort` and `orderBy` after the firstName, but I always get errors such as:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"sort\\\" on field \\\"user\\\" of type \\\"Query\\\".\",\n \"extensions\": {\n \"category\": \"graphql\"\n },\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 31\n }\n ]\n }\n ]\n}\n```\n\nI am using Laravel Lighthouse as a wapper for GraphQL. I am surprised I could not find any information in regards on how to do this.\n\nMy query:\n\n```\ntype Query {\n user(firstName: String @eq): [User!]! @paginate(type: \"paginator\" model: \"App\\\\User\")\n}\n\ntype User {\n id: ID!\n firstName: String!\n lastName: String!\n birthDate: DateTime!\n email: String!\n created_at: DateTime!\n updated_at: DateTime!\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n user(count:20, firstName:\"Foo\") {\n data {\n name\n region\n birthDate\n }\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Unknown argument \\\"sort\\\" on field \\\"user\\\" of type \\\"Query\\\".\",\n \"extensions\": {\n \"category\": \"graphql\"\n },\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 31\n }\n ]\n }\n ]\n}\n```\n\n```text\ntype Query {\n user(firstName: String @eq): [User!]! @paginate(type: \"paginator\" model: \"App\\\\User\")\n}\n\ntype User {\n id: ID!\n firstName: String!\n lastName: String!\n birthDate: DateTime!\n email: String!\n created_at: DateTime!\n updated_at: DateTime!\n}\n```\n\n```text\nFoo\n```\n\n```text\nbirthDate\n```\n\n```text\nsort\n```\n\n```text\norderBy\n```\n\n```text\ntype Query {\n user(firstName: String @eq orderBy: [OrderByClause!] @orderBy): [User!]! @paginate(type: \"paginator\" model: \"App\\\\User\")\n}\n\ntype User {\n id: ID!\n firstName: String!\n lastName: String!\n birthDate: DateTime!\n email: String!\n created_at: DateTime!\n updated_at: DateTime!\n}\n\ninput OrderByClause{\n field: String!\n order: SortOrder!\n}\n\nenum SortOrder {\n ASC\n DESC\n}\n```\n\n```text\nquery {\n user(count:20, firstName:\"Foo\", orderBy: [\n {\n field: \"birthDate\"\n order: DESC\n }\n ]) {\n data {\n name\n region\n birthDate\n }\n }\n}\n```\n\n========================================\n\nComments:\n- thanks! this saved me from many more hours of angry searching. =)","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":173,"estimatedTokens":703}}511{"id":"stack-45056347","source":"stackoverflow","questionId":45056347,"title":"How to use or resolve enum types with graphql-tools?","tags":["graphql","apollo-server"],"text":"Title: How to use or resolve enum types with graphql-tools?\nTags: graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI cannot find anywhere in the `graphql-tools` documentation how one should go about utilizing `enum` types in schemas that are fed to `makeExecutableSchema`. Anyone have a clue how this done?\n\nExample code:\n\n```\nenum Color {\n RED\n GREEN\n BLUE\n}\n\ntype Car {\n color: Color!\n}\n```\n\nWhat would the resolver for `Color` look like?\n\n========================================\n\nTop Answer:\nBy default, the enum is represented with the same string : `enum Color { RED }` is `'RED'`.\nYou can override this by adding a resolver to the enum:\n\n```\nColor: {\n RED: '#ff0000',\n GREEN: '#00ff00'\n},\nQuery {...\n```\n\nMore info: https://www.apollographql.com/docs/graphql-tools/scalars.html#internal-values\n\n========================================\n\nCode:\n```text\nenum Color {\n RED\n GREEN\n BLUE\n}\n\ntype Car {\n color: Color!\n}\n```\n\n```text\ngraphql-tools\n```\n\n```text\nenum\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nColor\n```\n\n```text\nconst bodyParser = require('body-parser');\nconst { graphqlExpress, graphiqlExpress } = require('graphql-server-express');\nconst { makeExecutableSchema } = require('graphql-tools');\nconst app = require('express')();\n\nconst carsData = [\n {color: 'RED'},\n {color: 'GREEN'},\n {color: 'BLUE'},\n];\n\nconst typeDefs = `\n enum Color {\n RED\n GREEN\n BLUE\n }\n type Car {\n color: Color!\n }\n type Query {\n cars: [Car!]!\n }\n`;\n\nconst resolvers = {\n Query: {\n cars: () => carsData,\n }\n};\n\nconst schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n});\n\napp.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));\napp.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));\n\napp.listen(3000);\n```\n\n```text\n\"Expected a value of type \\\"Color\\\" but received: PINK\"\n```\n\n```text\nCar: {\n color: () => 'RED'\n}\n```\n\n```text\nColor\n```\n\n```text\ncars\n```\n\n```text\n{cars {color}}\n```\n\n```text\nPINK\n```\n\n```text\nBLACK\n```\n\n```text\nColor: {\n RED: '#ff0000',\n GREEN: '#00ff00'\n},\nQuery {...\n```\n\n```text\nenum Color { RED }\n```\n\n```text\n'RED'\n```\n\n========================================\n\nComments:\n- OK, so this simply works out of the box. It was not knowing how the values of the enums are determined that had me thinking I had to set up a resolver for these guys, then I didn't see anything in the docs about it. Thanks for the direction!","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":163,"estimatedTokens":602}}512{"id":"stack-59200152","source":"stackoverflow","questionId":59200152,"title":"GraphQL - POST body missing. Did you forget use body-parser middleware?","tags":["node.js","reactjs","express","graphql"],"text":"Title: GraphQL - POST body missing. Did you forget use body-parser middleware?\nTags: node.js, reactjs, express, graphql\nSource: Stack Overflow\n\nQuestion:\nI keep getting the following error on my `graphql` queries and not sure why:\n\n`POST body missing. Did you forget use body-parser middleware?`\n\nAm I doing something weird here? I have tried different recommendations with body-parser online, but still can't seem to fix it. \n\n### Server:\n\n```\nrequire('babel-polyfill')\n\nconst express = require('express')\nconst router = require('./middleware')\nconst expressStaticGzip = require('express-static-gzip')\nconst app = express()\nconst port = process.env.EXPRESS_PORT || 4000\nconst bodyParser = require('body-parser')\n\napp.use(/\\/((?!graphql).)*/, bodyParser.urlencoded({ extended: true }))\napp.use(/\\/((?!graphql).)*/, bodyParser.json())\napp.use('/search/data', expressStaticGzip('public'))\napp.use('/', router)\n\napp.listen(port, () => {\n console.log(`Server is running on port ${port}`)\n})\n```\n\n### Router\n\n```\nconst router = express.Router()\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n context: ({ req }) => {\n const { authorization = '' } = req.headers\n const universalFetch = (url, opts = {}) => {\n return fetch(url, {\n ...opts,\n headers: {\n ...opts.headers,\n authorization,\n },\n })\n }\n const request = createRpcClient(universalFetch)\n\n const methods = {}\n\n const catalog = Object.keys(methods).reduce((catalog, method) => {\n catalog[method] = params => request(methods[method], params)\n return catalog\n }, {})\n return { catalog, fetch: universalFetch }\n },\n})\n\nrouter.use(bodyParser.json())\nrouter.use(bodyParser.text({ type: 'application/graphql' }))\nrouter.use('*', renderer)\nserver.applyMiddleware({ app: router })\n```\n\n========================================\n\nTop Answer:\nIn my particular case the client just missed \"Content-type\" header with 'application/json' value. After adding that the error message has dissapeared.\n\n========================================\n\nCode:\n```text\nrequire('babel-polyfill')\n\nconst express = require('express')\nconst router = require('./middleware')\nconst expressStaticGzip = require('express-static-gzip')\nconst app = express()\nconst port = process.env.EXPRESS_PORT || 4000\nconst bodyParser = require('body-parser')\n\napp.use(/\\/((?!graphql).)*/, bodyParser.urlencoded({ extended: true }))\napp.use(/\\/((?!graphql).)*/, bodyParser.json())\napp.use('/search/data', expressStaticGzip('public'))\napp.use('/', router)\n\napp.listen(port, () => {\n console.log(`Server is running on port ${port}`)\n})\n```\n\n```text\nconst router = express.Router()\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n context: ({ req }) => {\n const { authorization = '' } = req.headers\n const universalFetch = (url, opts = {}) => {\n return fetch(url, {\n ...opts,\n headers: {\n ...opts.headers,\n authorization,\n },\n })\n }\n const request = createRpcClient(universalFetch)\n\n const methods = {}\n\n const catalog = Object.keys(methods).reduce((catalog, method) => {\n catalog[method] = params => request(methods[method], params)\n return catalog\n }, {})\n return { catalog, fetch: universalFetch }\n },\n})\n\nrouter.use(bodyParser.json())\nrouter.use(bodyParser.text({ type: 'application/graphql' }))\nrouter.use('*', renderer)\nserver.applyMiddleware({ app: router })\n```\n\n```text\ngraphql\n```\n\n```text\nPOST body missing. Did you forget use body-parser middleware?\n```\n\n```text\napplyMiddleware\n```\n\n```text\nbody-parser\n```\n\n```text\napplyMiddleware\n```\n\n```text\nrouter.use('*', renderer)\n```\n\n```text\n/graphql\n```\n\n```text\nimport { json } from 'micro'\nimport { ApolloServer } from 'apollo-server-micro'\n\nconst server = new ApolloServer({/*config*/})\n\nconst raiseBodyLimit: (handler: NextApiHandler) => NextApiHandler = (\n handler\n) => async (req, res) => {\n if (req.headers['content-type'] !== 'application/json') {\n return handler(req, res)\n }\n \n await json(req, { limit: '1gb' }) // This is the trick to raise body limit\n \n return handler(req, res)\n}\n\nexport default raiseBodyLimit(\n server.createHandler({\n path: '/api/graphql',\n })\n)\n```\n\n```text\njson\n```\n\n```text\nmicro\n```\n\n========================================\n\nComments:\n- @DanielRearden Thanks! That was it\n- In curl, make sure to add `-H 'content-type: application/json'`\n- This one solved my problem. +1","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":198,"estimatedTokens":1098}}513{"id":"stack-67125011","source":"stackoverflow","questionId":67125011,"title":"gqlgen - DirectiveResolver not exported by package generated","tags":["go","graphql","gqlgen"],"text":"Title: gqlgen - DirectiveResolver not exported by package generated\nTags: go, graphql, gqlgen\nSource: Stack Overflow\n\nQuestion:\nI am new to GraphQL, gqlgen library. Tried running `go run github.com/99designs/gqlgen init` command but getting `validation failed: packages.Load: C:\\Users\\Aylin\\Desktop\\gqlgen-tutorial\\graph\\prelude.resolvers.go:19:44: __DirectiveResolver not exported by package generated` error. This is the first step of the project setup and is not supposed to cause any errors. Anyone had the same problem and knows how to fix it? Thanks\n\n========================================\n\nCode:\n```text\ngo run github.com/99designs/gqlgen init\n```\n\n```text\nvalidation failed: packages.Load: C:\\Users\\Aylin\\Desktop\\gqlgen-tutorial\\graph\\prelude.resolvers.go:19:44: __DirectiveResolver not exported by package generated\n```\n\n```text\ngo 1.16\nrequire (\n github.com/99designs/gqlgen v0.13.0\n github.com/vektah/gqlparser/v2 v2.2.0\n)\n```\n\n```text\ngithub.com/vektah/gqlparser/v2 v2.1.0\n```\n\n========================================\n\nComments:\n- I have the same issue. `schema: - schema.graphql exec: filename: ../../src/http_app/gql/generated/generated.go package: generated model: filename: ../../src/model/models_gen.go package: model resolver: layout: -schema dir: ../../src/http_app/gql package: gql filename_template: \"{name}.resolvers.go\" type: Resolver autobind: - framegork/src/model omit_slice_element_pointers: true`\n- Worked for me, thanks! Any idea about why this happens in the first place, or when they're going to fix this?","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":35,"estimatedTokens":403}}514{"id":"stack-62851825","source":"stackoverflow","questionId":62851825,"title":"Check for empty arrays in Hasura","tags":["postgresql","graphql","hasura"],"text":"Title: Check for empty arrays in Hasura\nTags: postgresql, graphql, hasura\nSource: Stack Overflow\n\nQuestion:\nI have the following Query:\n\n```\nquery {\n table1(where: {table2: {id: {}}}) {\n id\n }\n}\n```\n\nThere is a relationship between `table1` and `table2` via a foreign key. That is, in `table2` I have a column named `table1_id` and so I can access `table2` from `table1`. I want to query all rows from `table1` that have no related rows in `table2`. That is, if I do the following query:\n\n```\nquery {\n table1 {\n table2 {\n id\n }\n }\n}\n```\n\nI want the rows in `table1` where this query returns an empty array. I have tried the following:\n\n```\nquery {\n table1(where: {table2: {id: {_in: []}}}) {\n id\n }\n}\n```\n\nAnd\n\n```\nquery {\n table1(where: {table2: {id: {_is_null: true}}}) {\n id\n }\n}\n```\n\nBut nothing seems to work (I get back an empty array). What am I doing wrong?\n\n========================================\n\nTop Answer:\nThe selected answer is actually incorrect. It should be the following:\n\n```\nquery {\n table1(where: {_not: { table2: {} } }) {\n id\n }\n}\n```\n\nEdit: The selected answer is good now :)\n\n========================================\n\nCode:\n```text\nquery {\n table1(where: {table2: {id: {}}}) {\n id\n }\n}\n```\n\n```text\nquery {\n table1 {\n table2 {\n id\n }\n }\n}\n```\n\n```text\nquery {\n table1(where: {table2: {id: {_in: []}}}) {\n id\n }\n}\n```\n\n```text\nquery {\n table1(where: {table2: {id: {_is_null: true}}}) {\n id\n }\n}\n```\n\n```text\ntable1\n```\n\n```text\ntable2\n```\n\n```text\ntable2\n```\n\n```text\ntable1_id\n```\n\n```text\ntable2\n```\n\n```text\ntable1\n```\n\n```text\ntable1\n```\n\n```text\ntable2\n```\n\n```text\ntable1\n```\n\n```js\nquery {\n table1(where: {_not: { table2: {} } }) {\n id\n }\n}\n```\n\n```text\nquery {\n table1(where: {_not: { table2: {} } }) {\n id\n }\n}\n```\n\n========================================\n\nComments:\n- It worked not even AI give correct answer btw!!\n- I edited my answer to avoid any confusion. Thanks\n- @LeonardoAlves Ah great. I didn't have permission to edit your answer so had to make a separate answer. I reverted the downvote to an upvote!","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":159,"estimatedTokens":522}}515{"id":"stack-41416005","source":"stackoverflow","questionId":41416005,"title":"Handling Mongoose Populated Fields in GraphQL","tags":["node.js","mongodb","mongoose","graphql","graphql-js"],"text":"Title: Handling Mongoose Populated Fields in GraphQL\nTags: node.js, mongodb, mongoose, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nHow do I represent a field that could be either a simple `ObjectId` string or a populated Object Entity?\n\nI have a Mongoose Schema that represents a 'Device type' as follows\n\n```\n// assetSchema.js\n\nimport * as mongoose from 'mongoose'\nconst Schema = mongoose.Schema;\n\nvar Asset = new Schema({ name : String,\n linked_device: { type: Schema.Types.ObjectId, \n ref: 'Asset'})\n\nexport AssetSchema = mongoose.model('Asset', Asset);\n```\n\nI am trying to model this as a GraphQLObjectType but I am stumped on how to allow the `linked_ue` field take on two types of values, one being an `ObjectId` and the other being a full `Asset` Object (when it is populated)\n\n```\n// graphql-asset-type.js\n\nimport { GraphQLObjectType, GraphQLString } from 'graphql'\n\nexport var GQAssetType = new GraphQLObjectType({\n name: 'Asset',\n fields: () => ({\n name: GraphQLString,\n linked_device: ____________ // stumped by this\n});\n```\n\nI have looked into Union Types but the issue is that a Union Type expects fields to be stipulated as part of its definition, whereas in the case of the above, there are no fields beneath the `linked_device` field when `linked_device` corresponds to a simple `ObjectId`.\n\nAny ideas?\n\n========================================\n\nTop Answer:\nI was trying to solve the general problem of pulling relational data when I came across this article. To be clear, the original question appears to be how to dynamically resolve data when the field may contain either the ObjectId or the Object, however I don't believe it's good design in the first place to have a field store either object or objectId. Accordingly, I was interested in solving the simplified scenario where I keep the fields separated -- one for the Id, and the other for the object. I also, thought employing Unions was overly complex unless you actually have another scenario like those described in the docs referenced above. I figured the solution below may interest others also...\n\nNote: I'm using graphql-tools so my types are written schema language syntax. So, if you have a User Type that has fields like this:\n\n```\ntype User {\n _id: ID\n firstName: String\n lastName: String\n companyId: ID\n company: Company\n}\n```\n\nThen in my user resolver functions code, I add this:\n\n```\nUser: { // The above works alongside the User resolver functions already in place, and allow you write GQL queries like this:\n\n```\nquery getUserById($_id:ID!) \n { getUserById(_id:$_id) {\n _id\n firstName\n lastName\n company {\n name\n }\n companyId\n }}\n```\n\nRegards,\n\nS. Arora\n\n========================================\n\nCode:\n```text\n// assetSchema.js\n\nimport * as mongoose from 'mongoose'\nconst Schema = mongoose.Schema;\n\nvar Asset = new Schema({ name : String,\n linked_device: { type: Schema.Types.ObjectId, \n ref: 'Asset'})\n\nexport AssetSchema = mongoose.model('Asset', Asset);\n```\n\n```text\n// graphql-asset-type.js\n\nimport { GraphQLObjectType, GraphQLString } from 'graphql'\n\nexport var GQAssetType = new GraphQLObjectType({\n name: 'Asset',\n fields: () => ({\n name: GraphQLString,\n linked_device: ____________ // stumped by this\n});\n```\n\n```text\nObjectId\n```\n\n```text\nlinked_ue\n```\n\n```text\nObjectId\n```\n\n```text\nAsset\n```\n\n```text\nlinked_device\n```\n\n```text\nlinked_device\n```\n\n```text\nObjectId\n```\n\n```text\n// graphql-asset-type.js\n\nimport { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql'\n\nvar LinkedDeviceType = new GraphQLUnionType({\n name: 'Linked Device',\n types: [ ObjectIdType, GQAssetType ],\n resolveType(value) {\n if (value instanceof ObjectId) {\n return ObjectIdType;\n }\n if (value instanceof Asset) {\n return GQAssetType;\n }\n }\n});\n\nexport var GQAssetType = new GraphQLObjectType({\n name: 'Asset',\n fields: () => ({\n name: { type: GraphQLString },\n linked_device: { type: LinkedDeviceType },\n })\n});\n```\n\n```text\nlinked_device\n```\n\n```text\nGQAssetType\n```\n\n```text\ntype User {\n _id: ID\n firstName: String\n lastName: String\n companyId: ID\n company: Company\n}\n```\n\n```text\nUser: { // <-- this refers to the User Type in Graphql\n company(u) { // <-- this refers to the company field\n return User.findOne({ _id: u.companyId }); // <-- mongoose User type\n },\n }\n```\n\n```text\nquery getUserById($_id:ID!) \n { getUserById(_id:$_id) {\n _id\n firstName\n lastName\n company {\n name\n }\n companyId\n }}\n```\n\n========================================\n\nComments:\n- Thanks for the help @AhmadFerdous . A question, in the line `value instanceof Objectid`, what is `ObjectId`? Is it `var ObjectId = mongoose.Schema.Types.ObjectId` ? Also how what does `ObjectIdType` look like?\n- Yes, it's mongoose ObjectId. `ObjectIdType` is just a wrapper GraphQL object type, which can have a string field for the id.\n- Thanks @AhmadFerdous this is really helpful. I have also asked another question here that you might be able to help with, really appreciate the support: stackoverflow.com/questions/41427320/…\n- not sure where ObjectIdType come from.. its new ObjectId? can you provide full working example please?\n- This does not look like an answer to this question. If you have an answer to a different question, try and find a question that actually asks the question you want to answer and post your answer there. If no such question exists, you can post one yourself if you think it's a useful one. Note that all answers must be attempts to answer the question on top, not just some related question.\n- Its an attempt to answer what is likely the underlying challenge...the question was asked and answered as asked..but i'm trying to reframe what the right question to ask is, and questioning the premise. It's not good design to have a field store either object or objectId, so i'm suggesting there is a better approach with a simpler answer. Just a thought.\n- Ah ok. You may want to make that more clear in the answer itself.\n- clarified. thanks for the feedback. upvote appreciated!\n- Thanks for the clarification. Unfortunately, I'm not fit to vote on this post as I have no domain knowledge and thus cannot really judge the content.","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":215,"estimatedTokens":1587}}516{"id":"stack-53648431","source":"stackoverflow","questionId":53648431,"title":"Problem with spring boot graphql. Request /graphql results with 404","tags":["java","spring-boot","graphql"],"text":"Title: Problem with spring boot graphql. Request /graphql results with 404\nTags: java, spring-boot, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run simplest graphql example. I created application with spring initializer and only added graphql dependencies. My `build.gradle`\n\n```\nbuildscript {\n ext {\n springBootVersion = '2.1.1.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\napply plugin: 'io.spring.dependency-management'\n\ngroup = 'com.example'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\n\ndependencies {\n implementation('org.springframework.boot:spring-boot-starter-web')\n testImplementation('org.springframework.boot:spring-boot-starter-test')\n\n compile 'com.graphql-java-kickstart:graphql-spring-boot-starter:5.3.1'\n compile 'com.graphql-java-kickstart:graphiql-spring-boot-starter:5.3.1'\n compile 'com.graphql-java-kickstart:voyager-spring-boot-starter:5.3.1'\n}\n```\n\nDemoApplication.java\n\n```\npackage com.example.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class DemoApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n}\n```\n\nWhen I run the project and hit the endpoint `/graphql` it returns `404`. What is missing in my configuration?\n\n========================================\n\nTop Answer:\nI had a equal problem using graphiql and Swagger\nThe page graphiql got me erros 404 on browser console. The problem was that cannot get the js library from vendor resource.\n\nOn `class SwaggerConfig extends WebMvcConfigurationSupport`\n\nI did:\n\n```\n@Override\nprotected void addResourceHandlers(ResourceHandlerRegistry registry) {\nregistry.addResourceHandler(\"swagger-ui.html\")\n .addResourceLocations(\"classpath:/META-INF/resources/\");\n\nregistry.addResourceHandler(\"/webjars/**\")\n .addResourceLocations(\"classpath:/META-INF/resources/webjars/\");\n//This is for graphiql works\nregistry.addResourceHandler(\"/vendor/**\")\n .addResourceLocations(\"classpath:/static/vendor/\");\n```\n\n}\n\n========================================\n\nCode:\n```text\nbuildscript {\n ext {\n springBootVersion = '2.1.1.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\napply plugin: 'io.spring.dependency-management'\n\ngroup = 'com.example'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\n\n\ndependencies {\n implementation('org.springframework.boot:spring-boot-starter-web')\n testImplementation('org.springframework.boot:spring-boot-starter-test')\n\n compile 'com.graphql-java-kickstart:graphql-spring-boot-starter:5.3.1'\n compile 'com.graphql-java-kickstart:graphiql-spring-boot-starter:5.3.1'\n compile 'com.graphql-java-kickstart:voyager-spring-boot-starter:5.3.1'\n}\n```\n\n```text\npackage com.example.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class DemoApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(DemoApplication.class, args);\n }\n}\n```\n\n```text\nbuild.gradle\n```\n\n```text\n/graphql\n```\n\n```text\n404\n```\n\n```text\n@SpringBootApplication\npublic class ApplicationBootConfiguration {\n\n public static void main(String[] args) {\n SpringApplication.run(ApplicationBootConfiguration.class, args);\n }\n\n @Bean\n GraphQLSchema schema() {\n return GraphQLSchema.newSchema()\n .query(GraphQLObjectType.newObject()\n .name(\"query\")\n .field(field -> field\n .name(\"test\")\n .type(Scalars.GraphQLString)\n .dataFetcher(environment -> \"response\")\n )\n .build())\n .build();\n }\n}\n```\n\n```text\n@Override\nprotected void addResourceHandlers(ResourceHandlerRegistry registry) {\nregistry.addResourceHandler(\"swagger-ui.html\")\n .addResourceLocations(\"classpath:/META-INF/resources/\");\n\nregistry.addResourceHandler(\"/webjars/**\")\n .addResourceLocations(\"classpath:/META-INF/resources/webjars/\");\n//This is for graphiql works\nregistry.addResourceHandler(\"/vendor/**\")\n .addResourceLocations(\"classpath:/static/vendor/\");\n```\n\n```text\nclass SwaggerConfig extends WebMvcConfigurationSupport\n```\n\n```text\ntype Query { \n test: String \n}\n```\n\n```text\nhttp://localhost:8989/graphql\n```\n\n```text\n404 NOT_FOUND\n```\n\n```text\nNew\n```\n\n```text\ncurl -X POST --data '{<query-here>}' http://localhost:8080/graphql\n```\n\n```text\ncurl -H \"content-type: application/json\" -X POST --data '{<query-here>}' http://localhost:8080/graphql\n```\n\n========================================\n\nComments:\n- Did you check the port you're requesting on? And does Spring log anything when receiving the request?\n- Yes, I checked the port. 404 means that server received the request.\n- That's true, my bad. And this graphql package you have in your dependencies is supposed to expose the endpoint `/graphql` automatically? I see it's in your deps, but there's no further config regarding graphql api.\n- Docs are quite messy, cant find any minimal working example here github.com/graphql-java-kickstart/graphql-spring-boot. I must have been missed sth important.\n- does not work, throws another error on startup saying that you need a bean of type GraphQL","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":229,"estimatedTokens":1452}}517{"id":"stack-39636435","source":"stackoverflow","questionId":39636435,"title":"Nested query for the new GraphQL buildSchema","tags":["graphql","graphql-js"],"text":"Title: Nested query for the new GraphQL buildSchema\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nHow can I make resolver for my **friendList** with the new GraphQL Schema language? friendList have an array of people _id.\n\nMy new people type with GraphQL Schema language:\n\r\n\r\n\n```\nconst schema = buildSchema(`\r\n type People {\r\n _id: String\r\n firstName: String\r\n lastName: String\r\n demo: String\r\n friendList: [People]\r\n }\r\n type Query {\r\n getPeople(_id: String): People\r\n }\r\n`);\n```\n\n\r\n\r\n\r\n\nMy old people type with GraphQLObjectType:\n\r\n\r\n\n```\nconst PeopleType = new GraphQLObjectType({\r\n name: 'People',\r\n fields: () => ({\r\n _id: {\r\n type: GraphQLString,\r\n },\r\n firstName: {\r\n type: GraphQLString,\r\n },\r\n lastName: {\r\n type: GraphQLString,\r\n },\r\n friendList: {\r\n type: new GraphQLList(PeopleType),\r\n // pass @friends parentValue\r\n resolve: ({ friends }) {\r\n return People.find({ _id: { $in: friends } }).then(res => res);\r\n },\r\n }),\r\n});\n```\n\n\r\n\r\n\r\n\nI want to achieve this query:\n\n```\n{\n people(_id: \"ABC123\") {\n firstName\n lastName\n friendList {\n firstName\n lastName\n }\n }\n```\n\n========================================\n\nTop Answer:\nYour resolver should return a new instance of a class as explained in the updated GraphQL documentation: http://graphql.org/graphql-js/object-types/.\n\n```\nclass People {\n friendList () {}\n}\nvar rootValue = {\n getPeople: function () {\n return new People();\n }\n}\n```\n\n========================================\n\nCode:\n```js\nconst schema = buildSchema(`\n type People {\n _id: String\n firstName: String\n lastName: String\n demo: String\n friendList: [People]\n }\n type Query {\n getPeople(_id: String): People\n }\n`);\n```\n\n```js\nconst PeopleType = new GraphQLObjectType({\n name: 'People',\n fields: () => ({\n _id: {\n type: GraphQLString,\n },\n firstName: {\n type: GraphQLString,\n },\n lastName: {\n type: GraphQLString,\n },\n friendList: {\n type: new GraphQLList(PeopleType),\n // pass @friends parentValue\n resolve: ({ friends }) {\n return People.find({ _id: { $in: friends } }).then(res => res);\n },\n }),\n});\n```\n\n```text\n{\n people(_id: \"ABC123\") {\n firstName\n lastName\n friendList {\n firstName\n lastName\n }\n }\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nclass People {\n friendList () {}\n}\nvar rootValue = {\n getPeople: function () {\n return new People();\n }\n}\n```\n\n========================================\n\nComments:\n- did you ever find the answer to this? Struggling through this myself right now.\n- ok a quick question..what if friendlist is of another type like (friends) friendList: friends. How can you resolve that within the person class.\n- @kweku360 The `friendList` represents a field resolver. I encourage you to check the contextable.js. It can now be used as a GraphQL rootValue resolver.","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":165,"estimatedTokens":713}}518{"id":"stack-57778722","source":"stackoverflow","questionId":57778722,"title":"AWS AppSync + React-Apollo Query/useQuery raising exception this.currentObservable.query.getCurrentResult is not a function","tags":["reactjs","graphql","react-apollo","aws-amplify","aws-appsync"],"text":"Title: AWS AppSync + React-Apollo Query/useQuery raising exception this.currentObservable.query.getCurrentResult is not a function\nTags: reactjs, graphql, react-apollo, aws-amplify, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI'm new to GraphQL/Apollo thing and I'm having a hard time to setup it with a React application.\n\nI have a React component that loads a list from a GraphQL API built using Amplify/AppSync.\n\nIf I call manually to fetch the items, i.e:\n\n```\nconst videosData = await client.query({\n query: gql(queries.listVideos)\n });\n const videosItems = videosData.data.listVideos.items;\n setVideosData(videosItems);\n```\n\nWorks like a charm.\nHowever, if I try to use Apollo Query component or useQuery hook, it raises the following error: \n\n TypeError: this.currentObservable.query.getCurrentResult is not a\n function\n\nIf I just add the line to fetch the query using a hook it already gives me this error\n\nthe hook call:\n\n```\nconst {loading, error, data, refetch} = useQuery(gql(queries.listVideos));\n```\n\nThe called function raising the issue:\n\n```\nQueryData.getQueryResult\nnode_modules/@apollo/react-hooks/lib/react-hooks.esm.js:325\n 322 | called: true\n 323 | });\n 324 | } else {\n> 325 | var currentResult = this.currentObservable.query.getCurrentResult();\n | ^ 326 | var loading = currentResult.loading,\n 327 | partial = currentResult.partial,\n 328 | networkStatus = currentResult.networkStatus,\n```\n\nThe exact same problem happens if I use the `` component\n\nPackages versions:\n\n```\n\"aws-amplify\": \"^1.1.30\",\n\"aws-amplify-react\": \"^2.3.10\",\n\"aws-appsync\": \"^1.8.1\",\n\"graphql-tag\": \"^2.10.1\",\n\"react-apollo\": \"^3.0.1\",\n```\n\nAny idea what I might be doing wrong and how to fix it?\n\n========================================\n\nTop Answer:\nIf you add:\n\n```\n\"resolutions\": {\n \"apollo-client\": \"2.6.3\"\n}\n```\n\nIn your `package.json` and reinstall it should work.\n\nYou might see this warning: \n\n```\nResolution field \"apollo-client@2.6.3\" is incompatible with requested version \"apollo-client@2.4.6\"\n```\n\nit is because Appsync is relying on a old version of react-apollo, but I've found that is working fine.\n\nYou could this issue which hopefully will be resolved soon and we'll not need to do this anymore.\n\n========================================\n\nCode:\n```text\nconst videosData = await client.query({\n query: gql(queries.listVideos)\n });\n const videosItems = videosData.data.listVideos.items;\n setVideosData(videosItems);\n```\n\n```text\nconst {loading, error, data, refetch} = useQuery(gql(queries.listVideos));\n```\n\n```text\nQueryData.getQueryResult\nnode_modules/@apollo/react-hooks/lib/react-hooks.esm.js:325\n 322 | called: true\n 323 | });\n 324 | } else {\n> 325 | var currentResult = this.currentObservable.query.getCurrentResult();\n | ^ 326 | var loading = currentResult.loading,\n 327 | partial = currentResult.partial,\n 328 | networkStatus = currentResult.networkStatus,\n```\n\n```text\n\"aws-amplify\": \"^1.1.30\",\n\"aws-amplify-react\": \"^2.3.10\",\n\"aws-appsync\": \"^1.8.1\",\n\"graphql-tag\": \"^2.10.1\",\n\"react-apollo\": \"^3.0.1\",\n```\n\n```text\n<Query>\n```\n\n```text\nimport { ApolloProvider } from '@apollo/react-hooks';\nimport { ApolloLink } from 'apollo-link';\nimport { createAuthLink } from 'aws-appsync-auth-link';\nimport { createHttpLink } from 'apollo-link-http';\nimport { AppSyncConfig } from '.aws-exports';\nimport ApolloClient from 'apollo-client';\nimport { InMemoryCache } from \"apollo-cache-inmemory\";\n\nconst url = AppSyncConfig.graphqlEndpoint;\nconst region = AppSyncConfig.region;\nconst auth = {\n type: AppSyncConfig.authenticationType,\n apiKey: AppSyncConfig.apiKey\n};\nconst link = ApolloLink.from([\n createAuthLink({ url, region, auth }), \n createHttpLink({ uri: url })\n]);\nconst client = new ApolloClient({\n link,\n cache: new InMemoryCache()\n});\n\nconst WithProvider = () => (\n <ApolloProvider client={client}>\n <App />\n </ApolloProvider>\n)\n\nexport default WithProvider\n```\n\n```text\naws-appsync\n```\n\n```text\napollo-client\n```\n\n```text\n\"resolutions\": {\n \"apollo-client\": \"2.6.3\"\n}\n```\n\n```text\nResolution field \"apollo-client@2.6.3\" is incompatible with requested version \"apollo-client@2.4.6\"\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- I'm having the same issue. Have you found any solutions?\n- @BrianMcDonough Not yet... tbh I ended up with so many issues for setup this serverless graphql api and little support that I'm thinking about getting back to the good and old REST server\n- This doesn't work. The issue referenced in the answer is still open and vividly debated.\n- This works, thanks!!! I used with `jwtToken` auth (Cognito). Maybe add in your answer the missing `import { InMemoryCache } from \"apollo-cache-inmemory\";`\n- Glad it worked for you @sigmus. I noticed and fixed it on my post but I forgot to do the same here, thanks!\n- @GuilleAcosta Great solution thanks. Just a quick question, how to make it work with subscriptions?\n- @SatvikDaga are you having issues to subscribe? which error are you getting? did you these steps? apollographql.com/docs/react/data/subscriptions\n- @GuilleAcosta I followed the steps but got an error. Using a createSubscriptionHandshakeLink solved it\n- Does this also support offline support of mutations?","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":190,"estimatedTokens":1316}}519{"id":"stack-40956614","source":"stackoverflow","questionId":40956614,"title":"Does Apollo Stack support global object identification like the node interface of Relay?","tags":["node.js","graphql","relay","apollostack"],"text":"Title: Does Apollo Stack support global object identification like the node interface of Relay?\nTags: node.js, graphql, relay, apollostack\nSource: Stack Overflow\n\nQuestion:\nI am very new in both Apollo Stack and Relay. I am trying to choose between them to invest my time. After finish reading the book Learning GraphQL and Relay, I turned to Apollo to learn what it has to offer but right now there are not much resources in the internet.\n\nI have this question recently but unable to find the answer: Does Apollo support global object identification like Relay does with the node interface? if not, does it have any alternative solution to support global object identification?\n\n========================================\n\nTop Answer:\nIn `apollo-client` v2, You must pass `dataIdFromObject` to `InMemoryCache` instance instead.\n\n```\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { HttpLink } from 'apollo-link-http';\nimport ApolloClient from 'apollo-client';\n\nconst client = new ApolloClient({\n link: new HttpLink(),\n cache: new InMemoryCache({\n dataIdFromObject: object => object.id,\n }),\n});\n```\n\n========================================\n\nCode:\n```text\nimport ApolloClient from 'apollo-client';\n\nconst client = new ApolloClient({\n dataIdFromObject: o => o.id\n});\n```\n\n```text\nconst client = new ApolloClient({\n dataIdFromObject: (result) => {\n if (result.id && result.__typename) {\n return result.__typename + result.id;\n }\n\n // Make sure to return null if this object doesn't have an ID\n return null;\n },\n});\n```\n\n```text\napollo-client\n```\n\n```text\ndataIdFromObject\n```\n\n```text\nApolloClient\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\n__typename\n```\n\n```text\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { HttpLink } from 'apollo-link-http';\nimport ApolloClient from 'apollo-client';\n\nconst client = new ApolloClient({\n link: new HttpLink(),\n cache: new InMemoryCache({\n dataIdFromObject: object => object.id,\n }),\n});\n```\n\n```text\napollo-client\n```\n\n```text\ndataIdFromObject\n```\n\n```text\nInMemoryCache\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":99,"estimatedTokens":518}}520{"id":"stack-51912470","source":"stackoverflow","questionId":51912470,"title":"GraphQL query complaints in non-page component for GatsbyJS website","tags":["reactjs","jupyter-notebook","graphql","graphql-js","gatsby"],"text":"Title: GraphQL query complaints in non-page component for GatsbyJS website\nTags: reactjs, jupyter-notebook, graphql, graphql-js, gatsby\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add a new template to the gatsby-starter-hero-blog, but my GraphQL query for the new template is being rejected: \n\n```\nwarning The GraphQL query in the non-page component \n\"/Users/mc/workspaces/mc/src/templates/NoteBookTemplate.js\" will not be run.\nQueries are only executed for Page or Layout components. Instead of a query,\nco-locate a GraphQL fragment and compose that fragment into the query (or other\nfragment) of the top-level page or layout that renders this component. \nFor more\ninfo on fragments and composition see: \nhttp://graphql.org/learn/queries/#fragments\n```\n\nThe folder structure is as so:\n\n```\n--src\n --components\n --images\n --pages\n --templates\n --CategoryTemplate.js\n --NotebookTemplate.js\n --PageTemplate.js\n --PostTemplate.js \n --theme\n --utils\n```\n\nNotebookTemplate.js is the new template I'm adding (for rendering Jupyter notebooks using Nteract's Gatsby plugin).\n\nThe syntax of my added template query is identical to the other templates (and I do have a sample notebook in the content which is visible in GraphiQL).\n\n```\nexport const query = graphql`\n query NotebookQuery($slug: String!) {\n jupyterNotebook(fields: { slug: { eq: $slug } }) {\n html\n internal {\n content\n }\n }\n }\n`\n```\n\nI even tried creating a barebones template with a simple query mirroring one of the other templates (even trying an exact copy of a template with the component names changed) and still am getting the same warning (and subsequently no rendering of the notebook. For example, the PageTemplate.js has the following query (which gives no complaints on gatsby build).\n\n```\nexport const pageQuery = graphql`\n query PageByPath($slug: String!) {\n page: markdownRemark(fields: { slug: { eq: $slug } }) {\n id\n html\n frontmatter {\n title\n }\n }\n site {\n siteMetadata {\n facebook {\n appId\n }\n }\n }\n }\n`;\n```\n\nWhy are these queries in files not in the pages or layout folder not also throwing this error? Is there some other file that allows a workaround? FWIW, This is the actual template I'm trying to implement.\n\n```\nimport React from 'react'\nimport PropTypes from \"prop-types\";\nimport 'katex/dist/katex.min.css'\nimport { ThemeContext } from \"../layouts\";\n\nconst NotebookTemplate = ({ data }) => {\n const post = data.jupyterNotebook\n const notebookJSON = JSON.parse(post.internal.content)\n return (\n \n \n This notebook is displayed in the **client-side** using\n react component\n `NotebookPreview`\n from\n \n `@nteract/notebook-preview`.\n \n \n\n \n \n );\n};\n\nNotebookTemplate.propTypes = {\n data: PropTypes.object.isRequired\n};\n\nexport default NotebookTemplate;\n\nexport const query = graphql`\n query NotebookQuery($slug: String!) {\n jupyterNotebook(fields: { slug: { eq: $slug } }) {\n html\n internal {\n content\n }\n }\n }\n`;\n```\n\n========================================\n\nTop Answer:\nI know that this is old, but I also ran into this same issue, and the answers here did not help me.\n\nSince Gatsby uses the debug package,\nwhat helped me track it down was by setting debug's Node logging namespace environment to `gatsby:query-watcher` as specified in query-watcher.ts.\n\nIf anyone else stubmles on this just run your develop server like so and it should help you track it down easier:\n\n`env \"NODE_ENV=development\" \"DEBUG=gatsby:query-watcher\" npm run dev`\n\n========================================\n\nCode:\n```text\nwarning The GraphQL query in the non-page component \n\"/Users/mc/workspaces/mc/src/templates/NoteBookTemplate.js\" will not be run.\nQueries are only executed for Page or Layout components. Instead of a query,\nco-locate a GraphQL fragment and compose that fragment into the query (or other\nfragment) of the top-level page or layout that renders this component. \nFor more\ninfo on fragments and composition see: \nhttp://graphql.org/learn/queries/#fragments\n```\n\n```text\n--src\n --components\n --images\n --pages\n --templates\n --CategoryTemplate.js\n --NotebookTemplate.js\n --PageTemplate.js\n --PostTemplate.js \n --theme\n --utils\n```\n\n```text\nexport const query = graphql`\n query NotebookQuery($slug: String!) {\n jupyterNotebook(fields: { slug: { eq: $slug } }) {\n html\n internal {\n content\n }\n }\n }\n`\n```\n\n```text\nexport const pageQuery = graphql`\n query PageByPath($slug: String!) {\n page: markdownRemark(fields: { slug: { eq: $slug } }) {\n id\n html\n frontmatter {\n title\n }\n }\n site {\n siteMetadata {\n facebook {\n appId\n }\n }\n }\n }\n`;\n```\n\n```text\nimport React from 'react'\nimport PropTypes from \"prop-types\";\nimport 'katex/dist/katex.min.css'\nimport { ThemeContext } from \"../layouts\";\n\nconst NotebookTemplate = ({ data }) => {\n const post = data.jupyterNotebook\n const notebookJSON = JSON.parse(post.internal.content)\n return (\n <React.Fragment>\n <p>\n This notebook is displayed in the <strong>client-side</strong> using\n react component\n <code>NotebookPreview</code>\n from\n <a href=\"https://github.com/nteract/nteract/tree/master/packages/notebook-preview\">\n <code>@nteract/notebook-preview</code>.\n </a>\n </p>\n <NotebookPreview notebook={notebookJSON} />\n </React.Fragment>\n );\n};\n\nNotebookTemplate.propTypes = {\n data: PropTypes.object.isRequired\n};\n\nexport default NotebookTemplate;\n\nexport const query = graphql`\n query NotebookQuery($slug: String!) {\n jupyterNotebook(fields: { slug: { eq: $slug } }) {\n html\n internal {\n content\n }\n }\n }\n`;\n```\n\n```text\ngatsby-node.js\n```\n\n```text\nexports.createPages\n```\n\n```text\ngatsby:query-watcher\n```\n\n```text\nenv \"NODE_ENV=development\" \"DEBUG=gatsby:query-watcher\" npm run dev\n```\n\n```text\ngatsby-node.js\n```\n\n```text\nThe GraphQL query in the non-page component \"C:/GitRepos/gatsby-blog-starter/src/templates/blogPost.js\" will not be run.\n```\n\n```text\npostQuery\n```\n\n```text\ngraphql\n```\n\n```text\nblogPost.js\n```\n\n```text\ngatsby develop\n```\n\n```text\nmarkdownRemark\n```\n\n```text\npostQuery\n```\n\n```text\nblogPost.js\n```\n\n```text\ngraphql\n```\n\n========================================\n\nComments:\n- I am getting this error as well even though the template is working as expected. It is indeed misleading!\n- So what is the fix? Having this issue, but the link you provided state \"For anyone who finds this later, this somehow has resolved itself over the weekend.\", not helpful.\n- The error is indeed misleading. Thanks @stagermane, the link you provided was helpful to me. I had a file in my templates directory that was not in use that exported a page query. I fixed the issue by removing the page query. It hit me when I read this comment on the link `Note to my future self: This error is common when the template is not actually used; a bug in page generation (eg. in gatsby-node.js) will cause it. The instructions in the error are misleading.`\n- @stagermane could you please provide us with your `gatsby-node.js` file please ? your solution lacks explanations and so does the link your provided.\n- The discussion is now a 404. Please clarify this answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":301,"estimatedTokens":1809}}521{"id":"stack-60755236","source":"stackoverflow","questionId":60755236,"title":"Apollo Server: pass arguments to nested resolvers","tags":["javascript","node.js","graphql","apollo-server"],"text":"Title: Apollo Server: pass arguments to nested resolvers\nTags: javascript, node.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nMy GraphQL query looks like this:\n\n```\n{\n p1: property(someArgs: \"some_value\") {\n id\n nestedField {\n id\n moreNestedField {\n id\n }\n }\n }\n}\n```\n\nOn the server side, I'm using Apollo Server.\nI have a resolver for the `property` and other resolvers for `nestedField` and `moreNestedField`.\nI need to retrieve the value of `someArgs` on my nested resolvers. \nI tried to do this using the `context` available on the resolver:\n\n```\nproperty: (_, {someArgs}, ctx) => {\n ctx.someArgs = someArgs;\n\n // Do something\n}\n```\n\nBut this won't work as the context is shared among all resolvers, thus if I have multiple `property`on my query, the context value won't be good. \n\nI also tried to use the `path` available on `info` on my nested resolvers. I'm able to go up to the `property` field but I don't have the arguments here... \n\nI also tried to add some data on `info` but it's not shared on nested resolvers.\n\nAdding arguments on all resolvers is not an option as it would make query very bloated and cumbersome to write, I don't want that.\n\nAny thoughts?\n\nThanks!\n\n========================================\n\nTop Answer:\nDo not pass your argument through `root`, except `IDs` or `parent object`, anything from client, use **field level argument**.\n\nPlease check this answer here on how to pass the arguments:\nhttps://stackoverflow.com/a/63300135/11497165\n\nTo simplify it, you can put args in your field:\n\nExample *Type Definition*\n\nServer defination:\n\n```\ntype Query{\n getCar(color: String): Car\n ... other queries\n}\n\ntype Car{\n door(color: String): Door // client query:\n\n```\nquery getCar(carId:'123'){\n door(color:'grey') // You should be able to access color in your child resolver arguments:\n\nIn your resolver:\n\n```\nCar{\n door(root,args,context){\n const color = args.color // For your example:\n\nit will be like this\n\n```\n{\n p1: property(someArgs: \"some_value\") { // <-- added variable\n id\n nestedField(someArgs: \"some_value\") { // <-- added variable\n id\n moreNestedField(offset: 5) {\n id\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n p1: property(someArgs: \"some_value\") {\n id\n nestedField {\n id\n moreNestedField {\n id\n }\n }\n }\n}\n```\n\n```text\nproperty: (_, {someArgs}, ctx) => {\n ctx.someArgs = someArgs;\n\n // Do something\n}\n```\n\n```text\nproperty\n```\n\n```text\nnestedField\n```\n\n```text\nmoreNestedField\n```\n\n```text\nsomeArgs\n```\n\n```text\ncontext\n```\n\n```text\nproperty\n```\n\n```text\npath\n```\n\n```text\ninfo\n```\n\n```text\nproperty\n```\n\n```text\ninfo\n```\n\n```text\nfunction propertyResolver (parent, args) {\n const property = await getProperty()\n property.propertyArgs = args\n return property\n}\n\n// if this level args required in deeper resolvers\nfunction nestedPropertyResolver (parent, args) {\n const nestedProperty = await getNestedProperty()\n nestedProperty.propertyArgs = parent.propertyArgs\n nestedProperty.nestedPropertyArgs = args\n return nestedProperty\n}\n\nfunction moreNestedPropertyResolver (parent) {\n // do something with parent.propertyArgs.someArgs\n}\n```\n\n```text\nchain\n```\n\n```text\nfunction propertyResolver (parent, { someArgs }) {\n const property = await getProperty()\n property.someArgs = someArgs\n return property\n}\n\nfunction nestedPropertyResolver ({ someArgs }) {\n const nestedProperty = await getNestedProperty()\n nestedProperty.someArgs = someArgs\n return nestedProperty\n}\n\nfunction moreNestedPropertyResolver ({ someArgs }) {\n // do something with someArgs\n}\n```\n\n```text\ntype Query{\n getCar(color: String): Car\n ... other queries\n}\n\ntype Car{\n door(color: String): Door // <-- added args\n id: ID\n previousOwner(offset: Int, limit: Int): Owner // <-- added args\n ...\n}\n```\n\n```text\nquery getCar(carId:'123'){\n door(color:'grey') // <-- add variable\n id\n previousOwner(offset: 3) // <-- added variable\n ... other queries\n}\n```\n\n```text\nCar{\n door(root,args,context){\n const color = args.color // <-- access your arguments here\n }\n previousOwner(root,args,context){\n const offset = args.offset // <-- access your arguments here\n const limit = args.limit // <-- access your arguments here\n }\n ...others\n}\n```\n\n```text\n{\n p1: property(someArgs: \"some_value\") { // <-- added variable\n id\n nestedField(someArgs: \"some_value\") { // <-- added variable\n id\n moreNestedField(offset: 5) {\n id\n }\n }\n }\n}\n```\n\n```text\nroot\n```\n\n```text\nIDs\n```\n\n```text\nparent object\n```\n\n========================================\n\nComments:\n- you can try to assign param to returned value - it should be available by parent [and filtered out from response] in nested resolvers\n- Nailed it! It works like a charm with your solution. Feel free to write a proper answer to get the credit ;)\n- Hi again, I do not know how to use these methods. Do you have a code example where these are being used?\n- Why do you have arguments on the type definition (top code example)? Shouldn't they only be placed on query definitions (middle code example) or are you mixing resolvers and fields in the type definition (top code example)? I do not understand...\n- @goldenmaza that is the way to pass args. You can add it to your nested type. You can try it. It should work. Instead of add it in your parent return. You add your args in your type definition. If there is any confusion, feel free to ask anything.\n- thank you for your help... I would ask way too much if I start... Right now I'm just trying to learn more about GraphQL and Sequelize to make my project better. Before I had separate queries for each type, now I try to nest them and add arguments so I can reduce the amount of code in the frontend (React) to match certain instances with another, luckily with foreign keys and nesting types in queries makes that a lot easier. However, my current source code do not use the arguments correctly, hence my posts here on Stackoverflow.\n- Hi~ i have edited the answer, try and see does it make any sense to you, and for your second question, see if I understand it correctly, do you mean that you join all your quaries and return it via parents to your child resolver?\n- No, I made one query that had each type separately and then returned the result to the frontend, which then had to handle the different arrays based on what the page was asking for. Not the best solution as it required a few loops and if statements to determine what belongs to what (this was before I added associations). These are the improvements I'm now trying to implement by using nested queries. Foreign keys are already set up and now I just want my resolvers, as I believed they were supposed to be used, to return the correct data (based on arguments).\n- So each resolver has its own database access, to get their own field. If that is, it is a valid use case, but if you are query an array of for example: users. Try to batch it with dataloader (which can batch load a bunch of db access.)\n- I think I understand what do you meant, so you were querying different type with seperate queries then combine it in client side, dont seem right to me, as graphql should do the job already. If you need to add argument, use the way suggested in my article, and populate the arguments in client side, much much cleaner, since those are client variable, I dont recommend you to copy the variable again and put it in parent return... then access it via root, except the data only exist in server, eg: server_id for nested field\n- I know. That is how it used to work but at the time I didn't know about how to set up associations. What do you mean with \"...copy the variable again and put it in parent return...\"? But, let's say I use your way of doing things how can I add an argument that is only valid for the nested type that the parent/root type has no idea about?\n- You don't have to add it to the parent. Juz add the arguments to your nested type. Please give it a try, u will know what I am talking about.\n- This is the correct answer. Args shouldn't be shared between resolvers; this leads to coupling and it's very hard to scale up schemas that way","metadata":{"transformedAt":"2026-08-18T18:32:36.063Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":281,"estimatedTokens":2065}}522{"id":"stack-52499428","source":"stackoverflow","questionId":52499428,"title":"How to consume GraphQL Subscription with Flutter?","tags":["dart","flutter","graphql","subscription"],"text":"Title: How to consume GraphQL Subscription with Flutter?\nTags: dart, flutter, graphql, subscription\nSource: Stack Overflow\n\nQuestion:\nI am creating a subscription with GraphQL, and I need to consume that subscription with Flutter, but I don't know how to do that, the thing that I need is something like a UI component that would be tied to a subscription and it will be automatically refreshed.\n\nI will appreciate any feedback.\n\n========================================\n\nTop Answer:\nMy GraphqlServer runs a subscription named `getLogs` which returns the log information in the following format. \n\n```\n{\n \"data\": {\n \"getLogs\": {\n \"timeStamp\": \"18:09:24\",\n \"logLevel\": \"DEBUG\",\n \"file\": \"logger.py\",\n \"function\": \"init\",\n \"line\": \"1\",\n \"message\": \"Hello from logger.py\"\n }\n }\n}\n```\n\nIf you are like me who wants to use only the GraphQL Client directly, then following sample could help.\n\n```\nimport 'package:graphql/client.dart';\nimport 'package:graphql/internal.dart';\nimport 'package:flutter/material.dart';\nimport 'dart:async';\n\nclass LogPuller extends StatefulWidget {\n static final WebSocketLink _webSocketLink = WebSocketLink(\n url: 'ws://localhost:8000/graphql/',\n config: SocketClientConfig(\n autoReconnect: true,\n ),\n );\n\n static final Link _link = _webSocketLink;\n\n @override\n _LogPullerState createState() => _LogPullerState();\n}\n\nclass _LogPullerState extends State {\n final GraphQLClient _client = GraphQLClient(\n link: LogPuller._link,\n cache: InMemoryCache(),\n );\n\n // the subscription query should be of the following format. Note how the 'GetMyLogs' is used as the operation name below.\n final String subscribeQuery = '''\n subscription GetMyLogs{\n getLogs{\n timeStamp\n logLevel\n file\n function\n line\n message\n }\n }\n ''';\n Operation operation;\n\n Stream _logStream;\n\n @override\n void initState() {\n super.initState();\n // note operation name is important. If not provided the stream subscription fails after first pull.\n operation = Operation(document: subscribeQuery, operationName: 'GetMyLogs');\n _logStream = _client.subscribe(operation);\n }\n\n @override\n Widget build(BuildContext context) {\n return StreamBuilder(\n stream: _logStream,\n builder: (context, snapshot) {\n if (snapshot.connectionState == ConnectionState.waiting) {\n return Center(\n child: Container(\n child: CircularProgressIndicator(\n strokeWidth: 1.0,\n ),\n ),\n );\n }\n if (snapshot.hasData) {\n return Center(\n child: Text(\n snapshot.data.data['getLogs']\n ['message'], // This will change according to you needs.\n ),\n );\n }\n return Container();\n },\n );\n }\n}\n```\n\nAs I am using a StreamBuilder to build the widget it will take care of closing the stream. If this is not the case for you, `stream.listen()` method will return a `StreamSubscription` object which you can call the `cancel()` method which can be done inside `dispose()` method of a stateful widget or any such method for a standalone `Dart` client.\n\n========================================\n\nCode:\n```js\n{\n \"data\": {\n \"getLogs\": {\n \"timeStamp\": \"18:09:24\",\n \"logLevel\": \"DEBUG\",\n \"file\": \"logger.py\",\n \"function\": \"init\",\n \"line\": \"1\",\n \"message\": \"Hello from logger.py\"\n }\n }\n}\n```\n\n```dart\nimport 'package:graphql/client.dart';\nimport 'package:graphql/internal.dart';\nimport 'package:flutter/material.dart';\nimport 'dart:async';\n\nclass LogPuller extends StatefulWidget {\n static final WebSocketLink _webSocketLink = WebSocketLink(\n url: 'ws://localhost:8000/graphql/',\n config: SocketClientConfig(\n autoReconnect: true,\n ),\n );\n\n static final Link _link = _webSocketLink;\n\n @override\n _LogPullerState createState() => _LogPullerState();\n}\n\nclass _LogPullerState extends State<LogPuller> {\n final GraphQLClient _client = GraphQLClient(\n link: LogPuller._link,\n cache: InMemoryCache(),\n );\n\n // the subscription query should be of the following format. Note how the 'GetMyLogs' is used as the operation name below.\n final String subscribeQuery = '''\n subscription GetMyLogs{\n getLogs{\n timeStamp\n logLevel\n file\n function\n line\n message\n }\n }\n ''';\n Operation operation;\n\n Stream<FetchResult> _logStream;\n\n @override\n void initState() {\n super.initState();\n // note operation name is important. If not provided the stream subscription fails after first pull.\n operation = Operation(document: subscribeQuery, operationName: 'GetMyLogs');\n _logStream = _client.subscribe(operation);\n }\n\n @override\n Widget build(BuildContext context) {\n return StreamBuilder(\n stream: _logStream,\n builder: (context, snapshot) {\n if (snapshot.connectionState == ConnectionState.waiting) {\n return Center(\n child: Container(\n child: CircularProgressIndicator(\n strokeWidth: 1.0,\n ),\n ),\n );\n }\n if (snapshot.hasData) {\n return Center(\n child: Text(\n snapshot.data.data['getLogs']\n ['message'], // This will change according to you needs.\n ),\n );\n }\n return Container();\n },\n );\n }\n}\n```\n\n```text\ngetLogs\n```\n\n```text\nstream.listen()\n```\n\n```text\nStreamSubscription<FetchResult>\n```\n\n```text\ncancel()\n```\n\n```text\ndispose()\n```\n\n```text\nDart\n```\n\n========================================\n\nComments:\n- what library are you using ? did you try something already ?\n- I don't have used a library, I created like my own one, I created my API calls to GraphQL\n- I was trying to use that library, but I don't know where I should initialize socketClient, could you give me any help?","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":241,"estimatedTokens":1413}}523{"id":"stack-63681836","source":"stackoverflow","questionId":63681836,"title":"Cannot determine GraphQL input type for argument named","tags":["typescript","graphql","typeorm","typegraphql"],"text":"Title: Cannot determine GraphQL input type for argument named\nTags: typescript, graphql, typeorm, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI have two relationed models:\n\n1.- RoleEntity\n\n```\nimport { Column, Entity, BaseEntity, OneToMany, PrimaryColumn } from \"typeorm\";\nimport { Field, ObjectType } from \"type-graphql\";\n\nimport { UserEntity } from \"./user.entity\";\n\n@ObjectType()\n@Entity({\n name: \"tb_roles\"\n})\nexport class RoleEntity extends BaseEntity {\n\n @Field()\n @PrimaryColumn({\n name: \"id\",\n type: \"character varying\",\n length: 5\n })\n id!: string;\n\n @Field()\n @Column({\n name: \"description\",\n type: \"character varying\",\n nullable: true\n })\n description!: string\n\n @Field(() => [UserEntity])\n @OneToMany(() => UserEntity, user => user.role)\n users!: UserEntity[];\n}\n```\n\n2.- UserEntity\n\n```\nimport {Field, ObjectType} from \"type-graphql\";\nimport { BaseEntity, Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from \"typeorm\";\n\nimport { RoleEntity } from \"./role.entity\";\n\n@ObjectType()\n@Entity({\n name: \"tb_users\"\n})\nexport class UserEntity extends BaseEntity {\n @Field()\n @PrimaryGeneratedColumn(\"uuid\", {\n name: \"id\"\n })\n id!: string;\n\n @Field()\n @Column({\n name: \"username\",\n type: \"character varying\",\n unique: true,\n nullable: false\n })\n username!: string;\n\n @Field()\n @Column({\n name: \"last_name\",\n type: \"character varying\",\n nullable: false\n })\n lastName!: string;\n\n @Field()\n @Column({\n name: \"mother_last_name\",\n type: \"character varying\",\n nullable: true\n })\n motherLastName!: string;\n\n @Field()\n @Column({\n name: \"first_name\",\n type: \"character varying\",\n nullable: false\n })\n firstName!: string;\n\n @Field()\n @Column({\n name: \"middle_name\",\n type: \"character varying\",\n nullable: true\n })\n middleName!: string;\n\n @Field()\n @Column({\n name: \"email\",\n type: \"character varying\",\n unique: true,\n nullable: false\n })\n email!: string;\n\n @Field()\n @Column({\n name: \"password\",\n type: \"character varying\",\n nullable: false\n })\n password!: string;\n\n @Field(() => RoleEntity)\n @ManyToOne(() => RoleEntity)\n @JoinColumn({name: \"role_id\"})\n role!: RoleEntity;\n\n @Field()\n @Column({\n name: \"is_active\",\n type: \"character varying\",\n nullable: true\n })\n isActive!: boolean;\n\n @Field()\n @CreateDateColumn({\n name: \"created_at\"\n })\n createdAt!: string;\n\n @Field()\n @UpdateDateColumn({\n name: \"updated_at\"\n })\n updatedAt!: string;\n}\n```\n\nAnd this is the resolver for user:\n\n```\nimport {Arg, Mutation, Query, Resolver} from \"type-graphql\";\nimport bcrypt from \"bcryptjs\";\n\nimport {UserEntity} from \"../../entity/user.entity\";\nimport {RoleEntity} from \"../../entity/role.entity\";\n\n@Resolver()\nexport class UserResolver {\n @Query(() => [UserEntity])\n async users() {\n return await UserEntity.find();\n }\n\n @Mutation(() => UserEntity)\n async createUser(\n @Arg('username') username: string,\n @Arg('lastName') lastName: string,\n @Arg('motherLastName') motherLastName: string,\n @Arg('firstName') firstName: string,\n @Arg('middleName') middleName: string,\n @Arg('email') email: string,\n @Arg('password') password: string,\n @Arg('role') role: RoleEntity,\n @Arg('isActive') isActive: boolean\n ): Promise {\n\n const hashedPassword = await bcrypt.hashSync(password, bcrypt.genSaltSync(10));\n\n const user = UserEntity.create({\n username,\n lastName,\n motherLastName,\n firstName,\n middleName,\n email,\n password: hashedPassword,\n role,\n isActive\n }).save();\n\n return user;\n }\n}\n```\n\nbut, i get this error:\n\n(node:14788) UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL input type for argument named 'role' of 'createUser' of 'UserResolver' class. Does the\nvalue used as its TS type or explicit type is decorated with a proper decorator or is it a proper input value?\n\nI need your help please.\n\n========================================\n\nTop Answer:\nThe error is because you can't use `ObjectType` arguments in mutationsΒΉ, just plain scalar types or `InputType`:\n\nhttps://typegraphql.com/docs/resolvers.html#input-types\n\nΒΉ: the `RoleEntity` ObjectType in your case.\n\n========================================\n\nCode:\n```js\nimport { Column, Entity, BaseEntity, OneToMany, PrimaryColumn } from \"typeorm\";\nimport { Field, ObjectType } from \"type-graphql\";\n\nimport { UserEntity } from \"./user.entity\";\n\n\n@ObjectType()\n@Entity({\n name: \"tb_roles\"\n})\nexport class RoleEntity extends BaseEntity {\n\n @Field()\n @PrimaryColumn({\n name: \"id\",\n type: \"character varying\",\n length: 5\n })\n id!: string;\n\n @Field()\n @Column({\n name: \"description\",\n type: \"character varying\",\n nullable: true\n })\n description!: string\n\n @Field(() => [UserEntity])\n @OneToMany(() => UserEntity, user => user.role)\n users!: UserEntity[];\n}\n```\n\n```js\nimport {Field, ObjectType} from \"type-graphql\";\nimport { BaseEntity, Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from \"typeorm\";\n\nimport { RoleEntity } from \"./role.entity\";\n\n\n@ObjectType()\n@Entity({\n name: \"tb_users\"\n})\nexport class UserEntity extends BaseEntity {\n @Field()\n @PrimaryGeneratedColumn(\"uuid\", {\n name: \"id\"\n })\n id!: string;\n\n @Field()\n @Column({\n name: \"username\",\n type: \"character varying\",\n unique: true,\n nullable: false\n })\n username!: string;\n\n @Field()\n @Column({\n name: \"last_name\",\n type: \"character varying\",\n nullable: false\n })\n lastName!: string;\n\n @Field()\n @Column({\n name: \"mother_last_name\",\n type: \"character varying\",\n nullable: true\n })\n motherLastName!: string;\n\n @Field()\n @Column({\n name: \"first_name\",\n type: \"character varying\",\n nullable: false\n })\n firstName!: string;\n\n @Field()\n @Column({\n name: \"middle_name\",\n type: \"character varying\",\n nullable: true\n })\n middleName!: string;\n\n @Field()\n @Column({\n name: \"email\",\n type: \"character varying\",\n unique: true,\n nullable: false\n })\n email!: string;\n\n @Field()\n @Column({\n name: \"password\",\n type: \"character varying\",\n nullable: false\n })\n password!: string;\n\n @Field(() => RoleEntity)\n @ManyToOne(() => RoleEntity)\n @JoinColumn({name: \"role_id\"})\n role!: RoleEntity;\n\n @Field()\n @Column({\n name: \"is_active\",\n type: \"character varying\",\n nullable: true\n })\n isActive!: boolean;\n\n @Field()\n @CreateDateColumn({\n name: \"created_at\"\n })\n createdAt!: string;\n\n @Field()\n @UpdateDateColumn({\n name: \"updated_at\"\n })\n updatedAt!: string;\n}\n```\n\n```js\nimport {Arg, Mutation, Query, Resolver} from \"type-graphql\";\nimport bcrypt from \"bcryptjs\";\n\nimport {UserEntity} from \"../../entity/user.entity\";\nimport {RoleEntity} from \"../../entity/role.entity\";\n\n\n@Resolver()\nexport class UserResolver {\n @Query(() => [UserEntity])\n async users() {\n return await UserEntity.find();\n }\n\n @Mutation(() => UserEntity)\n async createUser(\n @Arg('username') username: string,\n @Arg('lastName') lastName: string,\n @Arg('motherLastName') motherLastName: string,\n @Arg('firstName') firstName: string,\n @Arg('middleName') middleName: string,\n @Arg('email') email: string,\n @Arg('password') password: string,\n @Arg('role') role: RoleEntity,\n @Arg('isActive') isActive: boolean\n ): Promise<UserEntity> {\n\n const hashedPassword = await bcrypt.hashSync(password, bcrypt.genSaltSync(10));\n\n const user = UserEntity.create({\n username,\n lastName,\n motherLastName,\n firstName,\n middleName,\n email,\n password: hashedPassword,\n role,\n isActive\n }).save();\n\n return user;\n }\n}\n```\n\n```text\n@Field(() => RoleEntity)\n @ManyToOne(() => RoleEntity)\n @JoinColumn({name: \"role_id\"})\n role!: RoleEntity;\n```\n\n```text\n@Field()\n@Column({name: 'role_id'})\nroleId!: string;\n\n@Field(() => RoleEntity)\nrole!: RoleEntity;\n@ManyToOne(() => RoleEntity, role => role.userConnection)\n@JoinColumn({name: 'role_id'})\nroleConnection!: Promise<RoleEntity>\n```\n\n```text\n@OneToMany(() => UserEntity, user => user.roleConnection)\nuserConnection!: Promise<UserEntity[]>\n```\n\n```text\nquery users {\n users {\n firstName\n username\n roleId\n role {\n description\n }\n }\n}\n```\n\n```text\n@FieldResolver()\n async role(@Root() user: UserEntity): Promise<RoleEntity | undefined> {\n //const role: RoleEntity | undefined = await RoleEntity.findOne(user.roleId);\n //return role;\n return await RoleEntity.findOne(user.roleId);\n }\n```\n\n```text\nObjectType\n```\n\n```text\nInputType\n```\n\n```text\nRoleEntity\n```\n\n```text\nregisterEnumType\n```\n\n```text\n@nestjs/graphql\n```\n\n```text\nimport {registerEnumType} from '@nestjs/graphql'\n```\n\n```text\nregisterEnumType(OrderStatus, { name: 'OrderStatus' });\n```\n\n========================================\n\nComments:\n- Maybe related: github.com/MichalLytek/type-graphql/issues/371\n- Looking at the dates of the other answers, it looks like they've changed something and this is the way to do it now - though we're importing `registerEnumType` from the `'type-graphql'` lib.","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":478,"estimatedTokens":2337}}524{"id":"stack-47486785","source":"stackoverflow","questionId":47486785,"title":"How to avoid bundling mock modules on Webpack build?","tags":["javascript","reactjs","webpack","babeljs","graphql"],"text":"Title: How to avoid bundling mock modules on Webpack build?\nTags: javascript, reactjs, webpack, babeljs, graphql\nSource: Stack Overflow\n\nQuestion:\nWe are trying to make our React + GraphQL project independent of any other layers in the ecosystem to improve developers experience. In line with that, we have written a thin HOC that wraps Apollo own `graphql` HOC and uses an internal environment variable to switch between network fetching and mock data. On production builds, all that mock data is, obviously, not used, even if it *is* `import`ed.\n\nIs there any way to **avoid including modules** in Webpack's **production** bundle **that you know you are not going to need** while keeping everything else the same/not breaking the app?\n\nSomething like dynamic `import()` *could* do the trick, but that ends up chunking your build rather than omitting what you don't need/want.\n\n**UPDATE**: The app was created using create-react-app `1.0.17` and later ejected.\n\n========================================\n\nTop Answer:\nIn your webpack.config.dev.js:\n\n```\nresolve: {\n alias:{\n \"react-apollo\":\"./mock.js\"\n }\n}\n```\n\nNow all modules requesting react-apollo will get the mock when you compile for dev.\n\nI don't have apollo-client but here is an example of mocking jQuery:\n\nYour code:\n\n```\nimport $ from 'jquery';\nconsole.log($().message)\n```\n\nwebpack.dev.config.js:\n\n```\nalias:{\n \"jquery\":\"./mock.js\"\n}\n```\n\nmock.js:\n\n```\nconst org = require('../node_modules/jquery/src/jquery');\norg.fn.message = \"Hello from mock\";\nexport default org;\n```\n\n========================================\n\nCode:\n```text\ngraphql\n```\n\n```text\nimport\n```\n\n```text\nimport()\n```\n\n```text\n1.0.17\n```\n\n```text\napi\n index.js\n apimock.js\n apirest.js\n```\n\n```text\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./apirest');\n} else {\n module.exports = require('./apimock');\n}\n```\n\n```text\nnew webpack.DefinePlugin({\n 'process.env': {\n NODE_ENV: `\"${process.env.NODE_ENV || 'development'}\"`,\n ENABLE_DEVTOOLS: JSON.stringify(!!process.env.ENABLE_DEVTOOLS)\n }\n})\n```\n\n```text\nNODE_ENV=production webpack --config webpack.config.js\n```\n\n```text\nNODE_ENV=development webpack --config webpack.config.js\n```\n\n```text\nimport * as api from 'api';\n```\n\n```text\nresolve: {\n alias:{\n \"react-apollo\":\"./mock.js\"\n }\n}\n```\n\n```text\nimport $ from 'jquery';\nconsole.log($().message)\n```\n\n```text\nalias:{\n \"jquery\":\"./mock.js\"\n}\n```\n\n```text\nconst org = require('../node_modules/jquery/src/jquery');\norg.fn.message = \"Hello from mock\";\nexport default org;\n```\n\n========================================\n\nComments:\n- Would it be possible to resolve the mock data module to an empty module in production? github.com/facebookincubator/create-react-app/blob/master/…\n- mock apollo client to return the data you want to mock, locally resolve apollo to your mocked module using NODE_ENV env var in your webpack.conf file when NODE_ENV==='production' don't provide mocks for apollo, let it its course. That should work\n- @HMR I believe that would be one straight forward solution. Any ideas on how to approach that?\n- @DayanMorenoLeon I get your idea. It's similar to one of the answers given below. In this case, it's not as simple as swapping one module with another, I'm afraid.\n- it actually is. in your local you replace your apollo client on production you don't.\n- @NicolásFantone Maybe add an alias for the mock data module in the production config: github.com/facebookincubator/create-react-app/blob/master/… I assume the module doesn't export anything but modifies Apollo? So when that code is not loaded it doesn't change anything.\n- @HMR has the right thing, you might write the answer down to collect juicy bounty ;) you have to use `resolve.alias` webpack option\n- @whitep4nther Wanted to give the bounty to mauron85 but setting an alias seems to be a cleaner solution (one global switch instead of possibly many files having conditional import statements). I'll check tomorrow and see if anyone added an answer.\n- @HMR It doesn't modify Apollo (in a monkey-patching sense). It wraps its `graphql` HOC with a new one, that skips its functionality entirely given a particular env var was set. All others modules, import this wrapper instead of the Apollo one.\n- This would work. But unfortunately, it's not that simple in our scenario as the data layer is being accessed through Apollo's `graphql` HOC. You've given me something to think about, though.","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":146,"estimatedTokens":1116}}525{"id":"stack-62633904","source":"stackoverflow","questionId":62633904,"title":"React Apollo useQuery hook with TypeScript","tags":["reactjs","typescript","graphql","react-apollo","apollo-client"],"text":"Title: React Apollo useQuery hook with TypeScript\nTags: reactjs, typescript, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get `useQuery` hook to work with TypeScript.\n\nHere is my query\n\n```\nexport const FETCH_LINKS = gql`\n query FetchLinks {\n feed {\n links {\n id\n createdAt\n url\n description\n }\n }\n}\n`;\n```\n\nI generated the types from GraphQL schema with `graphql-codegen`\n\n```\nexport type Feed = {\n __typename?: 'Feed';\n links: Array;\n count: Scalars['Int'];\n};\n\nexport type Link = {\n __typename?: 'Link';\n id: Scalars['ID'];\n createdAt: Scalars['DateTime'];\n description: Scalars['String'];\n url: Scalars['String'];\n postedBy?: Maybe;\n votes: Array;\n};\n```\n\nIn my component, I apply the type to `useQuery` hook\n\n```\nconst { data, loading, error } = useQuery(FETCH_LINKS);\n```\n\nThe problem is that in the `data` variable I receive an object of the following shape:\n\n```\n{\nfeed: {\n __typename\n links\n count\n }\n}\n```\n\nSo, in order to loop through the array of links and render them on the page, I need to do `data.feed.links.map()` but the `Feed` type does not have a `feed` property on it and therefore, I get an error message `Property 'feed' does not exist on type 'Feed'`\nHow do I rectify this inconsistency\n\n========================================\n\nTop Answer:\nIf you check documentation you will see that you would need to create one more interface to represent data:\n\n```\ninterface FetchLinksData {\n feed: Feed[];\n}\n```\n\nIn component you could use that like this:\n\n```\nconst { data, loading, error } = useQuery(FETCH_LINKS);\nconst feeds = data.feed;\n```\n\n========================================\n\nCode:\n```text\nexport const FETCH_LINKS = gql`\n query FetchLinks {\n feed {\n links {\n id\n createdAt\n url\n description\n }\n }\n}\n`;\n```\n\n```text\nexport type Feed = {\n __typename?: 'Feed';\n links: Array<Link>;\n count: Scalars['Int'];\n};\n\nexport type Link = {\n __typename?: 'Link';\n id: Scalars['ID'];\n createdAt: Scalars['DateTime'];\n description: Scalars['String'];\n url: Scalars['String'];\n postedBy?: Maybe<User>;\n votes: Array<Vote>;\n};\n```\n\n```text\nconst { data, loading, error } = useQuery<Feed>(FETCH_LINKS);\n```\n\n```text\n{\nfeed: {\n __typename\n links\n count\n }\n}\n```\n\n```text\nuseQuery\n```\n\n```text\ngraphql-codegen\n```\n\n```text\nuseQuery\n```\n\n```text\ndata\n```\n\n```text\ndata.feed.links.map()\n```\n\n```text\nFeed\n```\n\n```text\nfeed\n```\n\n```text\nProperty 'feed' does not exist on type 'Feed'\n```\n\n```text\ninterface FetchLinksData {\n feed: Feed\n}\n```\n\n```text\ntypescript\n```\n\n```text\ninterface FetchLinksData {\n feed: Feed[];\n}\n```\n\n```text\nconst { data, loading, error } = useQuery<FetchLinksData>(FETCH_LINKS);\nconst feeds = data.feed;\n```\n\n```text\nreact-apollo\n```\n\n```text\napollo\n```\n\n========================================\n\nComments:\n- The obvious solution is to edit the Feed type generated by `graphql-codegen` but it does not feel like a correct way to go about it\n- try `useQuery`","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":199,"estimatedTokens":747}}526{"id":"stack-44839791","source":"stackoverflow","questionId":44839791,"title":"How data.refetch() function from react-apollo works","tags":["reactjs","graphql","apollo","react-apollo"],"text":"Title: How data.refetch() function from react-apollo works\nTags: reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nOn the frontend, I am using ReactJS and trying to build-in a filtering option to a list view. The list view correctly getting data from graphql endpoint by issuing this graphql query:\n\n```\nquery getVideos($filterByBook: ID, $limit: Int!, $after: ID) {\n videosQuery(filterByBook: $filterByBook, limit: $limit, after: $after) {\n totalCount\n edges {\n cursor\n node {\n id\n title\n ytDefaultThumbnail\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n}\n```\n\nOn the initial load `$filterByBook` variable is set to `null`, so the query correctly returns all pages for all nodes (query returns a paginated result). Then, by clicking on the filter (filter by book) another graphql query is issuing, but it always returns the same `data`. Here is a code snippet for filtering component\n\n```\nrenderFilters() {\n const { listOfBooksWithChapters, refetch } = this.props;\n\n return (\n \n {\n return refetch({\n variables: {\n limit: 3,\n after: 0,\n filterByBook: onBookTitleClickParam\n }\n })\n }}\n listOfBooksWithChapters={listOfBooksWithChapters}\n />\n \n )\n }\n```\n\nAnd, here is complete code without imports for the list view component \n\n```\nclass VideoList extends React.Component {\n constructor(props) {\n super(props);\n\n this.subscription = null;\n }\n\n componentWillUnmount() {\n if (this.subscription) {\n // unsubscribe\n this.subscription();\n }\n }\n\n renderVideos() {\n const { videosQuery } = this.props;\n\n return videosQuery.edges.map(({ node: { id, title, ytDefaultThumbnail } }) => {\n return (\n \n \n \n \n \n \n {title}\n \n \n \n \n \n );\n });\n }\n\n renderLoadMore() {\n const { videosQuery, loadMoreRows } = this.props;\n\n if (videosQuery.pageInfo.hasNextPage) {\n return (\n \n Load more ...\n \n );\n }\n }\n\n renderFilters() {\n const { listOfBooksWithChapters, refetch } = this.props;\n\n return (\n \n {\n return refetch({\n variables: {\n limit: 3,\n after: 0,\n filterByBook: onBookTitleClickParam\n }\n })\n }}\n listOfBooksWithChapters={listOfBooksWithChapters}\n />\n \n )\n }\n\n render() {\n const { loading, videosQuery } = this.props;\n\n if (loading && !videosQuery) {\n return (\n { /* loading... */}\n );\n } else {\n return (\n \n \n \n\n### Videos\n\n {this.renderFilters()}\n \n {this.renderVideos()}\n \n \n ({videosQuery.edges.length} / {videosQuery.totalCount})\n \n {this.renderLoadMore()}\n \n );\n }\n }\n}\n\nexport default compose(\n graphql(VIDEOS_QUERY, {\n options: () => {\n return {\n variables: {\n limit: 3,\n after: 0,\n filterByBook: null\n },\n };\n },\n props: ({ data }) => {\n const { loading, videosQuery, fetchMore, subscribeToMore, refetch } = data;\n const loadMoreRows = () => {\n return fetchMore({\n variables: {\n after: videosQuery.pageInfo.endCursor,\n },\n updateQuery: (previousResult, { fetchMoreResult }) => {\n const totalCount = fetchMoreResult.videosQuery.totalCount;\n const newEdges = fetchMoreResult.videosQuery.edges;\n const pageInfo = fetchMoreResult.videosQuery.pageInfo;\n\n return {\n videosQuery: {\n totalCount,\n edges: [...previousResult.videosQuery.edges, ...newEdges],\n pageInfo,\n __typename: \"VideosQuery\"\n }\n };\n }\n });\n };\n return { loading, videosQuery, subscribeToMore, loadMoreRows, refetch };\n }\n }),\n graphql(LIST_BOOKS_QUERY, {\n props: ({ data }) => {\n const { listOfBooksWithChapters } = data;\n return { listOfBooksWithChapters };\n }\n }),\n)(VideoList);\n```\n\n**Question:**\n\nWhy `refetch` function returns data without taking into account new variable `filterByBook`? How to check which `variables` object I supplied to the `refetch` function? Do I need to remap data that I receive from `refetch` function back to the component `props`?\n\n**EDIT:**\n\nI found the way to find what `variable` object I supplied to the query and found that `variable` object on filtering event returns this data\n\n```\nvariables:Object\n after:0\n limit:3\n variables:Object\n after:0\n filterByBook:\"2\"\n limit:3\n```\n\n========================================\n\nTop Answer:\nIt seem that `refetch` function is not meant to refetch data with different variables set (see this discussion).\n\nI finally and successfully solved my issue with the help from this article\n\n========================================\n\nCode:\n```text\nquery getVideos($filterByBook: ID, $limit: Int!, $after: ID) {\n videosQuery(filterByBook: $filterByBook, limit: $limit, after: $after) {\n totalCount\n edges {\n cursor\n node {\n id\n title\n ytDefaultThumbnail\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n}\n```\n\n```text\nrenderFilters() {\n const { listOfBooksWithChapters, refetch } = this.props;\n\n return (\n <Row>\n <FilterBooks\n onBookTitleClickParam={(onBookTitleClickParam) => {\n return refetch({\n variables: {\n limit: 3,\n after: 0,\n filterByBook: onBookTitleClickParam\n }\n })\n }}\n listOfBooksWithChapters={listOfBooksWithChapters}\n />\n </Row>\n )\n }\n```\n\n```text\nclass VideoList extends React.Component {\n constructor(props) {\n super(props);\n\n this.subscription = null;\n }\n\n componentWillUnmount() {\n if (this.subscription) {\n // unsubscribe\n this.subscription();\n }\n }\n\n renderVideos() {\n const { videosQuery } = this.props;\n\n return videosQuery.edges.map(({ node: { id, title, ytDefaultThumbnail } }) => {\n return (\n <Col sm=\"4\" key={id}>\n <Card>\n <CardImg top width=\"100%\" src={ytDefaultThumbnail} alt=\"video image\" />\n <CardBlock>\n <CardTitle>\n <Link\n className=\"post-link\"\n to={`/video/${id}`}>\n {title}\n </Link>\n </CardTitle>\n </CardBlock>\n </Card>\n </Col>\n );\n });\n }\n\n renderLoadMore() {\n const { videosQuery, loadMoreRows } = this.props;\n\n if (videosQuery.pageInfo.hasNextPage) {\n return (\n <Button id=\"load-more\" color=\"primary\" onClick={loadMoreRows}>\n Load more ...\n </Button>\n );\n }\n }\n\n renderFilters() {\n const { listOfBooksWithChapters, refetch } = this.props;\n\n return (\n <Row>\n <FilterBooks\n onBookTitleClickParam={(onBookTitleClickParam) => {\n return refetch({\n variables: {\n limit: 3,\n after: 0,\n filterByBook: onBookTitleClickParam\n }\n })\n }}\n listOfBooksWithChapters={listOfBooksWithChapters}\n />\n </Row>\n )\n }\n\n\n render() {\n const { loading, videosQuery } = this.props;\n\n if (loading && !videosQuery) {\n return (\n <div>{ /* loading... */}</div>\n );\n } else {\n return (\n <div>\n <Helmet\n title=\"Videos list\"\n meta={[{\n name: 'description',\n content: 'List of all videos'\n }]} />\n <h2>Videos</h2>\n {this.renderFilters()}\n <Row>\n {this.renderVideos()}\n </Row>\n <div>\n <small>({videosQuery.edges.length} / {videosQuery.totalCount})</small>\n </div>\n {this.renderLoadMore()}\n </div>\n );\n }\n }\n}\n\nexport default compose(\n graphql(VIDEOS_QUERY, {\n options: () => {\n return {\n variables: {\n limit: 3,\n after: 0,\n filterByBook: null\n },\n };\n },\n props: ({ data }) => {\n const { loading, videosQuery, fetchMore, subscribeToMore, refetch } = data;\n const loadMoreRows = () => {\n return fetchMore({\n variables: {\n after: videosQuery.pageInfo.endCursor,\n },\n updateQuery: (previousResult, { fetchMoreResult }) => {\n const totalCount = fetchMoreResult.videosQuery.totalCount;\n const newEdges = fetchMoreResult.videosQuery.edges;\n const pageInfo = fetchMoreResult.videosQuery.pageInfo;\n\n return {\n videosQuery: {\n totalCount,\n edges: [...previousResult.videosQuery.edges, ...newEdges],\n pageInfo,\n __typename: \"VideosQuery\"\n }\n };\n }\n });\n };\n return { loading, videosQuery, subscribeToMore, loadMoreRows, refetch };\n }\n }),\n graphql(LIST_BOOKS_QUERY, {\n props: ({ data }) => {\n const { listOfBooksWithChapters } = data;\n return { listOfBooksWithChapters };\n }\n }),\n)(VideoList);\n```\n\n```text\nvariables:Object\n after:0\n limit:3\n variables:Object\n after:0\n filterByBook:\"2\"\n limit:3\n```\n\n```text\n$filterByBook\n```\n\n```text\nnull\n```\n\n```text\ndata\n```\n\n```text\nrefetch\n```\n\n```text\nfilterByBook\n```\n\n```text\nvariables\n```\n\n```text\nrefetch\n```\n\n```text\nrefetch\n```\n\n```text\nprops\n```\n\n```text\nvariable\n```\n\n```text\nvariable\n```\n\n```text\nconst {loading, data, error,refetch} = useQuery(GET_ALL_PROJECTS,\n {\n variables: {id: JSON.parse(localStorage.getItem(\"user\")).id}\n });\n```\n\n```text\nconst saveChange = input => {\n refetch();\n\n };\n```\n\n```text\nconst saveChange = input => {\n setIsOpen(false);\n addProject({\n\n variables: {\n createBacklogInput: {\n backlogTitle: backlogInput,\n project:id\n }\n }\n }).then(refetch);\n```\n\n```text\nrefetch()\n```\n\n```text\nrefetch\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":505,"estimatedTokens":2404}}527{"id":"stack-59829676","source":"stackoverflow","questionId":59829676,"title":"Mocking ApolloClient's client.query method with Jest","tags":["unit-testing","mocking","graphql","jestjs","apollo-client"],"text":"Title: Mocking ApolloClient's client.query method with Jest\nTags: unit-testing, mocking, graphql, jestjs, apollo-client\nSource: Stack Overflow\n\nQuestion:\n### Update January 22nd 2020\n\nThe solution from @slideshowp2 is correct, but I could not get it to work at all, due to this TypeError:\n\n TypeError: Cannot read property 'query' of undefined\n\nWell it turned out to be my jest configuration that had `resetMocks: true` set. After I removed it, the test did pass. (I don't know why though)\n\n### Original question:\n\nI need to execute a graphql query in a helper function outside of a React component using Apollo Client and after a bit of trial and error I went for this approach which is working as it is supposed to:\n\nsetup.ts\n\n```\nexport const setupApi = (): ApolloClient => {\n setupServiceApi(API_CONFIG)\n return createServiceApolloClient({ uri: `${API_HOST}${API_PATH}` })\n}\n```\n\ngetAssetIdFromService.ts\n\n```\nimport { setupApi } from '../api/setup'\n\nconst client = setupApi()\n\nexport const GET_ASSET_ID = gql`\n query getAssetByExternalId($externalId: String!) {\n assetId: getAssetId(externalId: $externalId) {\n id\n }\n }\n`\n\nexport const getAssetIdFromService = async (externalId: string) => {\n return await client.query({\n query: GET_ASSET_ID,\n variables: { externalId },\n })\n\n return { data, errors, loading }\n}\n```\n\nNow I am trying to write test tests for the `getAssetIdFromService` function, but I have trouble figuring out how to get the `client.query` method to work in tests.\n\nI have tried the approach below including many others that did not work.\nFor this particular setup, jest throws \n\n TypeError: client.query is not a function\n\n```\nimport { setupApi } from '../../api/setup'\nimport { getAssetIdFromService } from '../getAssetIdFromService'\n\njest.mock('../../api/setup', () => ({\n setupApi: () => jest.fn(),\n}))\n\ndescribe('getAssetIdFromService', () => {\n it('returns an assetId when passed an externalId and the asset exists in the service', async () => {\n const { data, errors, loading } = await getAssetIdFromService('e1')\n\n // Do assertions \n })\n}\n```\n\nI assume I am missing something in relation to this part:\n\n```\njest.mock('../../api/setup', () => ({\n setupApi: () => jest.fn(),\n}))\n```\n\n...but I cannot see it.\n\n========================================\n\nTop Answer:\nUse blow mock class:\n\n```\nclass ApolloClient {\n constructor(uri: string, fetch: any, request: any) {}\n setupApi() {\n return {\n query: jest.fn(),\n };\n }\n query() {\n return jest.fn();\n }\n}\nmodule.exports = ApolloClient;\n```\n\nand add below line to jest.cofig.ts\n\n```\nmoduleNameMapper: {\n'apollo-boost': '/.jest/appolo-client.ts',\n```\n\n},\n\n========================================\n\nCode:\n```js\nexport const setupApi = (): ApolloClient<any> => {\n setupServiceApi(API_CONFIG)\n return createServiceApolloClient({ uri: `${API_HOST}${API_PATH}` })\n}\n```\n\n```js\nimport { setupApi } from '../api/setup'\n\nconst client = setupApi()\n\nexport const GET_ASSET_ID = gql`\n query getAssetByExternalId($externalId: String!) {\n assetId: getAssetId(externalId: $externalId) {\n id\n }\n }\n`\n\nexport const getAssetIdFromService = async (externalId: string) => {\n return await client.query({\n query: GET_ASSET_ID,\n variables: { externalId },\n })\n\n return { data, errors, loading }\n}\n```\n\n```js\nimport { setupApi } from '../../api/setup'\nimport { getAssetIdFromService } from '../getAssetIdFromService'\n\njest.mock('../../api/setup', () => ({\n setupApi: () => jest.fn(),\n}))\n\ndescribe('getAssetIdFromService', () => {\n it('returns an assetId when passed an externalId and the asset exists in the service', async () => {\n const { data, errors, loading } = await getAssetIdFromService('e1')\n\n // Do assertions \n })\n}\n```\n\n```text\njest.mock('../../api/setup', () => ({\n setupApi: () => jest.fn(),\n}))\n```\n\n```text\nresetMocks: true\n```\n\n```text\ngetAssetIdFromService\n```\n\n```text\nclient.query\n```\n\n```js\nimport { setupApi } from './setup';\nimport { gql } from 'apollo-server';\n\nconst client = setupApi();\n\nexport const GET_ASSET_ID = gql`\n query getAssetByExternalId($externalId: String!) {\n assetId: getAssetId(externalId: $externalId) {\n id\n }\n }\n`;\n\nexport const getAssetIdFromService = async (externalId: string) => {\n return await client.query({\n query: GET_ASSET_ID,\n variables: { externalId },\n });\n};\n```\n\n```js\nexport const setupApi = (): any => {};\n```\n\n```js\nimport { getAssetIdFromService, GET_ASSET_ID } from './getAssetIdFromService';\nimport { setupApi } from './setup';\n\njest.mock('./setup.ts', () => {\n const mApolloClient = { query: jest.fn() };\n return { setupApi: jest.fn(() => mApolloClient) };\n});\n\ndescribe('59829676', () => {\n it('should query and return data', async () => {\n const client = setupApi();\n const mGraphQLResponse = { data: {}, loading: false, errors: [] };\n client.query.mockResolvedValueOnce(mGraphQLResponse);\n const { data, loading, errors } = await getAssetIdFromService('e1');\n expect(client.query).toBeCalledWith({ query: GET_ASSET_ID, variables: { externalId: 'e1' } });\n expect(data).toEqual({});\n expect(loading).toBeFalsy();\n expect(errors).toEqual([]);\n });\n});\n```\n\n```sh\nPASS apollo-graphql-tutorial src/stackoverflow/59829676/getAssetIdFromService.test.ts (8.161s)\n 59829676\n β should query and return data (7ms)\n\n--------------------------|----------|----------|----------|----------|-------------------|\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |\n--------------------------|----------|----------|----------|----------|-------------------|\nAll files | 100 | 100 | 100 | 100 | |\n getAssetIdFromService.ts | 100 | 100 | 100 | 100 | |\n--------------------------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 8.479s\n```\n\n```text\ngetAssetIdFromService.ts\n```\n\n```text\nsetup.ts\n```\n\n```text\ngetAssetIdFromService.test.ts\n```\n\n```text\nclass ApolloClient {\n constructor(uri: string, fetch: any, request: any) {}\n setupApi() {\n return {\n query: jest.fn(),\n };\n }\n query() {\n return jest.fn();\n }\n}\nmodule.exports = ApolloClient;\n```\n\n```text\nmoduleNameMapper: {\n'apollo-boost': '<rootDir>/.jest/appolo-client.ts',\n```\n\n========================================\n\nComments:\n- Thanks for taking your time to write an answer @slideshowp2 . However, using the exact code you wrote I'm still seeing `TypeError: Cannot read property 'query' of undefined`\n- In the IDE when hovering the `.query` method in `client.query.mockResolvedValueOnce(mGraphQLResponse)` it says: `(method) ApolloClient.query(options: QueryOptions): Promise>` There is however an error on `.mockedResolvedValue(...)` instead: `Property 'mockResolvedValueOnce' does not exist on type '(options: QueryOptions) => Promise>'.ts(2339)`\n- @Anton You can ignore the type check of TypeScript and try again.\n- Still no luck. `client` somehow stays undefined after `const client = setupApi()`","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":287,"estimatedTokens":1779}}528{"id":"stack-59743243","source":"stackoverflow","questionId":59743243,"title":"AWS Appsync Javascript query example and input syntax","tags":["graphql","aws-amplify","aws-appsync"],"text":"Title: AWS Appsync Javascript query example and input syntax\nTags: graphql, aws-amplify, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI'm using Amplify and Appsync for a react app I'm building. Right now I'm trying to query a user and am using the appsync client: \n\n```\nconst client = new AWSAppSyncClient({\n url: awsconfig.aws_appsync_graphqlEndpoint,\n region: awsconfig.aws_appsync_region,\n auth: {\n type: awsconfig.aws_appsync_authenticationType,\n jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken()\n },\n complexObjectsCredentials: () => Auth.currentCredentials()\n});\n```\n\nI've been able to successfully run a mutation using the example provided on the amplify website\n\n```\nconst result = await client.mutate({\n mutation: gql(createTodo),\n variables: {\n input: {\n name: 'Use AppSync',\n description: 'Realtime and Offline',\n }\n }\n });\n```\n\nbut when it comes to running a query using the client, the only example they provide is with a list operation\n\n```\nconst result = await client.query({\n query: gql(listTodos)\n });\n```\n\nThey don't provide an example for how to query by a specific ID, so I'm wondering if anybody can shine some light on the syntax for this, provide an example, or point me in the direction of a good reference for this? Thank you in advance.\n\n========================================\n\nCode:\n```text\nconst client = new AWSAppSyncClient({\n url: awsconfig.aws_appsync_graphqlEndpoint,\n region: awsconfig.aws_appsync_region,\n auth: {\n type: awsconfig.aws_appsync_authenticationType,\n jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken()\n },\n complexObjectsCredentials: () => Auth.currentCredentials()\n});\n```\n\n```text\nconst result = await client.mutate({\n mutation: gql(createTodo),\n variables: {\n input: {\n name: 'Use AppSync',\n description: 'Realtime and Offline',\n }\n }\n });\n```\n\n```text\nconst result = await client.query({\n query: gql(listTodos)\n });\n```\n\n```text\nconst getBlog = `query GetBlog($id: ID!) {\n getBlog(id: $id) {\n id\n title\n content\n author\n }\n}\n`;\n```\n\n```text\nconst result = await client.query({\n query: gql(getBlog),\n variables: { id: '0002b432-157a-4b6a-ad67-6a8693e331d1' }\n });\n console.log(result.data.getBlog);\n```\n\n```text\nconst input = { id: '0002b432-157a-4b6a-ad67-6a8693e331d1' }\n const result = await client.query({\n query: gql(getBlog),\n variables: input\n });\n console.log(result.data.getBlog);\n```\n\n========================================\n\nComments:\n- Ah, thanks. I was unsure the format of the variables parameter.","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":109,"estimatedTokens":672}}529{"id":"stack-38934265","source":"stackoverflow","questionId":38934265,"title":"GraphQL implementation Java","tags":["java","rest","graphql"],"text":"Title: GraphQL implementation Java\nTags: java, rest, graphql\nSource: Stack Overflow\n\nQuestion:\nI am having 5 rest API's(java) with different endpoint URL,and each have different request,response format.So I have combined them as a single API with a common JSON complex request and response as a key value pair structure.\n\nNow T found recently about GraphQL and interested to fit it in my requirement,\nI have done analysis on that and want to know how well I Could implement some of my questions:\n\n1) Can we implement complex rest API service(post) in GRAPHQL?(while googling,got only for simple get method.Also is there only for node/javascript)\n\n 2) Is there any framework for java based graphQL implementation?\n\n========================================\n\nTop Answer:\nQuestion 1) is answered in the other answer.\n\nQuestion 2) Java Implementation:\n\n- graphql-java is a Java implementation for GraphQL.\n\n- graphql-java-annotations is a Java Library build on graphql-java.\n\nSample Code:\n\n```\npublic class HelloWorld {\n public static void main(String[] args) {\n GraphQLObjectType queryType = newObject()\n .name(\"helloWorldQuery\")\n .field(newFieldDefinition()\n .type(GraphQLString)\n .name(\"hello\")\n .staticValue(\"world\"))\n .build();\n\n GraphQLSchema schema = GraphQLSchema.newSchema()\n .query(queryType)\n .build();\n\n GraphQL graphQL = GraphQL.newGraphQL(schema).build();\n\n Map result = graphQL.execute(\"{hello}\").getData();\n System.out.println(result);\n // Prints: {hello=world}\n }\n}\n```\n\n========================================\n\nCode:\n```text\npublic class HelloWorld {\n public static void main(String[] args) {\n GraphQLObjectType queryType = newObject()\n .name(\"helloWorldQuery\")\n .field(newFieldDefinition()\n .type(GraphQLString)\n .name(\"hello\")\n .staticValue(\"world\"))\n .build();\n\n GraphQLSchema schema = GraphQLSchema.newSchema()\n .query(queryType)\n .build();\n\n GraphQL graphQL = GraphQL.newGraphQL(schema).build();\n\n Map<String, Object> result = graphQL.execute(\"{hello}\").getData();\n System.out.println(result);\n // Prints: {hello=world}\n }\n}\n```\n\n========================================\n\nComments:\n- Please don't just post a link to some library as an answer. At least demonstrate how the library solves the problem in the answer itself.\n- What's still wrong with my answer for getting more downvotes?\n- I upvoted you bro. The above comment is completely irrelevant.\n- This response presents client side usage. The question is about exposing server-side endpoint.","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":85,"estimatedTokens":654}}530{"id":"stack-59516375","source":"stackoverflow","questionId":59516375,"title":"Error: Invalid AST Node: {\"input\":\"** } on graphql mutation (Amplify client)","tags":["graphql","aws-amplify","amplifyjs"],"text":"Title: Error: Invalid AST Node: {\"input\":\"** } on graphql mutation (Amplify client)\nTags: graphql, aws-amplify, amplifyjs\nSource: Stack Overflow\n\nQuestion:\nI tried to use example schema on api doc(\"https://aws-amplify.github.io/docs/cli-toolchain/graphql?sdk=js\") like below on Many-To-Many Connections\n\n```\ntype Post @model {\n id: ID!\n title: String!\n editors: [PostEditor] @connection(keyName: \"byPost\", fields: [\"id\"])\n}\n\n# Create a join model and disable queries as you don't need them\n# and can query through Post.editors and User.posts\ntype PostEditor\n @model(queries: null)\n @key(name: \"byPost\", fields: [\"postID\", \"editorID\"])\n @key(name: \"byEditor\", fields: [\"editorID\", \"postID\"]) {\n id: ID!\n postID: ID!\n editorID: ID!\n post: Post! @connection(fields: [\"postID\"])\n editor: User! @connection(fields: [\"editorID\"])\n}\n\ntype User @model {\n id: ID!\n username: String!\n posts: [PostEditor] @connection(keyName: \"byEditor\", fields: [\"id\"])\n}\n```\n\nI created all items and then I tried to delete them but I failed especially on PostEditor.\n\nThere is a mutation to delete PostEditor so I called it like below\n\nAPI.graphql(graphqlOperation((deletePostEditor, {input: {id},})))\n\nIt fails with below error message.\n\nError: Invalid AST Node: {\"input\":\"b2f7064c-af32-49cd-8c87-*******\"}\n\nI think I provided right ID. I checked it on query.\n\n========================================\n\nCode:\n```text\ntype Post @model {\n id: ID!\n title: String!\n editors: [PostEditor] @connection(keyName: \"byPost\", fields: [\"id\"])\n}\n\n# Create a join model and disable queries as you don't need them\n# and can query through Post.editors and User.posts\ntype PostEditor\n @model(queries: null)\n @key(name: \"byPost\", fields: [\"postID\", \"editorID\"])\n @key(name: \"byEditor\", fields: [\"editorID\", \"postID\"]) {\n id: ID!\n postID: ID!\n editorID: ID!\n post: Post! @connection(fields: [\"postID\"])\n editor: User! @connection(fields: [\"editorID\"])\n}\n\ntype User @model {\n id: ID!\n username: String!\n posts: [PostEditor] @connection(keyName: \"byEditor\", fields: [\"id\"])\n}\n```\n\n```text\ngraphqlOperation\n```\n\n```text\nAPI.graphql(graphqlOperation((deletePostEditor, {input: {id},})))\n```\n\n```text\nAPI.graphql(graphqlOperation(deletePostEditor, { input: { id } }))\n```\n\n========================================\n\nComments:\n- is it possible to client side code,`deletePostEditor`\n- the code is generated by amplify codegen. the code is like below.\n- export const deletePostEditor = `mutation DeletePostEditor( $input: DeletePostEditorInput! $condition: ModelPostEditorConditionInput ) { deletePostEditor(input: $input, condition: $condition) { id postID editorID post { id title editors { nextToken } labels { nextToken } } editor { id username posts { nextToken } } } }`;\n- I am ashamed of my mistake... I should not turn off eslint or watch the code carefully....\n- it happened to all of us don't worry:-)","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":96,"estimatedTokens":719}}531{"id":"stack-64696988","source":"stackoverflow","questionId":64696988,"title":"How to conditionally include a filtering argument in a GraphQL query?","tags":["javascript","graphql","apollo"],"text":"Title: How to conditionally include a filtering argument in a GraphQL query?\nTags: javascript, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI have the following GraphQL query (using Apollo Client JS):\n\n```\nquery GetUsers($searchFilter: String) {\n users(\n first: 10,\n filter: { search: $searchFilter }\n ) {\n nodes {\n id\n name\n }\n }\n}\n```\n\nThis works well when I pass in the `$searchFilter` argument. However, I want this `$searchFilter` argument to be **optional**. So when it's `null` it doesn't apply the filter.\n\nThis seems simple enough, but the API requires the `search` to be non-nullable. So passing in `filter: { search: null }` is not allowed.\n\nI would like to achieve the following:\n\n```\nquery GetUsers($searchFilter: String) {\n users(\n first: 10,\n filter: $searchFilter = null ? null : { search: $searchFilter }\n ) {\n nodes {\n id\n name\n }\n }\n}\n```\n\nHow do I conditionally include the `filter` argument?\n\n========================================\n\nCode:\n```text\nquery GetUsers($searchFilter: String) {\n users(\n first: 10,\n filter: { search: $searchFilter }\n ) {\n nodes {\n id\n name\n }\n }\n}\n```\n\n```text\nquery GetUsers($searchFilter: String) {\n users(\n first: 10,\n filter: $searchFilter = null ? null : { search: $searchFilter }\n ) {\n nodes {\n id\n name\n }\n }\n}\n```\n\n```text\n$searchFilter\n```\n\n```text\n$searchFilter\n```\n\n```text\nnull\n```\n\n```text\nsearch\n```\n\n```text\nfilter: { search: null }\n```\n\n```text\nfilter\n```\n\n```text\nquery GetUsers($filter: SomeFilterInputType) {\n users(\n first: 10, \n filter: $filter ) {\n```\n\n```text\n{\n filter: { search: 'sth'}\n}\n```\n\n```text\nfilter\n```\n\n```text\nfilter\n```\n\n```text\nSomeFilterInputType\n```\n\n```text\nusers\n```\n\n```text\nvariables\n```\n\n```text\nSomeFilterInputType\n```\n\n```text\n!\n```\n\n```text\nfilter\n```\n\n========================================\n\nComments:\n- just pass (entire 'composed/prepared earlier') value or not (leave undefined) for `filter` variable ... no logic in graphql allowed (without directives, IMHO not suitable in this case)\n- @xadm What would be the syntax for that?\n- read `filter` arg type from server/api [this mutation] specs, pass object\n- `query GetUsers($filter: SomeFilterInputType) { users( first: 10, filter: $filter ) {...`, pass `filter: { search: 'sth'}`\n- @xadm That works, thanks! If you put that in an answer I'll accept it\n- This helped me out a lot, thanks. Had no idea the `!` turned it into a non-nullable value.\n- I didn't know I can pass the whole filter block as a variable so this is amazing! Thank you.","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":153,"estimatedTokens":656}}532{"id":"stack-65441260","source":"stackoverflow","questionId":65441260,"title":"NestJs GraphQL playground access","tags":["node.js","graphql","nestjs"],"text":"Title: NestJs GraphQL playground access\nTags: node.js, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI can't seem to access the GraphQL Playground using NestJS. I'm exploring the documentation and have followed this https://docs.nestjs.com/graphql/quick-start up to the Resolvers section to generate the `schema.gql`, but attempting to reach `localhost:3000/graphql` is not able to connect.\n\nAt first I thought my code was setup incorrectly, but I spent some time digging into Nest's examples and found that those also do not work when trying to access the `/graphql` endpoint. It does work if I setup a `get` endpoint to return a JSON body using the REST method.\n\n```\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { RecipesModule } from './recipes/recipes.module';\n\n@Module({\n imports: [\n RecipesModule,\n GraphQLModule.forRoot({\n installSubscriptionHandlers: true,\n autoSchemaFile: 'schema.gql',\n }),\n ],\n})\nexport class AppModule {}\n```\n\nThis is directly from the NestJS example. My understanding is that the GraphQLModule should be setting up the connection to the `/graphql` endpoint. Following the docs, `graphql, apollo-server-express, and graphql-tools` were all installed.\n\nAny idea why the graphql route is not connecting?\n\n[Edit]:\nThings I've tried so far:\n\n- setting `playground: true` explicitly with GraphQLModule.forRoot\n\n- verified `NODE_ENV` is not 'production'\n\n- confirmed server works when creating resolvers using REST\n\n- curl'd `localhost:3000/graphql` and receive a graphql validation error, so confirm that connects correctly\n\n========================================\n\nTop Answer:\nsometimes `helmet` causes this same issue. if you have helmet loaded as a middleware, it might probably also cause this.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { RecipesModule } from './recipes/recipes.module';\n\n@Module({\n imports: [\n RecipesModule,\n GraphQLModule.forRoot({\n installSubscriptionHandlers: true,\n autoSchemaFile: 'schema.gql',\n }),\n ],\n})\nexport class AppModule {}\n```\n\n```text\nschema.gql\n```\n\n```text\nlocalhost:3000/graphql\n```\n\n```text\n/graphql\n```\n\n```text\nget\n```\n\n```text\n/graphql\n```\n\n```text\ngraphql, apollo-server-express, and graphql-tools\n```\n\n```text\nplayground: true\n```\n\n```text\nNODE_ENV\n```\n\n```text\nlocalhost:3000/graphql\n```\n\n```text\nimports: [\n UsersModule,\n GraphQLModule.forRoot({\n // autoSchemaFile: true, did not work!\n autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n // schema.gql will automatically be created\n debug: true,\n playground: true,\n }),\n ],\n providers: [AppResolver], // all resolvers & service should be in providers\n```\n\n```text\nhelmet\n```\n\n```text\nprocess.env.CURRENT_ENV === 'dev' && app.use(helmet())\n```\n\n```text\nhelmet()\n```\n\n```text\nCURRENT_ENV\n```\n\n```text\nNODE_ENV\n```\n\n```text\nconst isGqlEnvProd = process.env.GQL_ENV === 'prod';\nif(isGqlEnvProd){\n app.use(helmet());\n}\n```\n\n========================================\n\nComments:\n- Check what your `process.env.NODE_ENV` is. If it is `PRODUCTION` then I think `apollo-server` disables the playground. If not, try adding `playground: true` explicitly\n- @JayMcDoniel I should've specified what I've tried already on the post, sorry. I've tried both and unfortunately, wasn't able to connect to the endpoint. I just curl'ed the endpoint to see if it is connecting to graphql and seems like it is since it returns GraphQL validation errors.\n- Are you able to provide a reproduction then? Can't see from what you've shared why that would be happening\n- So, I've tried with nest's example in their github repo (github.com/nestjs/nest/tree/master/sample/23-graphql-code-f‌​irst). It's about as basic as it can get and is essentially the same as the documentation's example. Nothing modified, just unable to connect to gql playground. Same result curling, able to see the gql validation errors, so it's connecting on the server though.\n- With that sample, the curl fails, but a browser requests to the same location succeeds. Probably looking at the user agent. It doesn't make much sense to send an interactive playground to the command line\n- Of course, for the command line I was just referring to sending a Post request to run a query, not trying to access the playground. But those requests worked and the queries in the schema were correctly being referenced. Odd that playground was accessible to you but not on my end, will dig a bit more and see if I figure it out. Thanks!\n- disabling helmet solves the issue in NestJs, but I'm wondering what causes it? And if that is the problem is that an option to disable helmet in the dev mode?\n- Helmet was a problem in my case too\n- does anybody know why helmet cause this issue ?","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":155,"estimatedTokens":1222}}533{"id":"stack-40541391","source":"stackoverflow","questionId":40541391,"title":"How do I specify polymorphic types with graphql-ruby?","tags":["ruby-on-rails","ruby","graphql"],"text":"Title: How do I specify polymorphic types with graphql-ruby?\nTags: ruby-on-rails, ruby, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a UserType and a userable that can be a Writer or Account.\n\nFor GraphQL I figured maybe I could use a UserableUnion like this:\n\n```\nUserableUnion = GraphQL::UnionType.define do\n name \"Userable\"\n description \"Account or Writer object\"\n possible_types [WriterType, AccountType]\nend\n```\n\nand then define my UserType like this: \n\n```\nUserType = GraphQL::ObjectType.define do\n name \"User\"\n description \"A user object\"\n field :id, !types.ID\n field :userable, UserableUnion\nend\n```\n\nBut I get `schema contains Interfaces or Unions, so you must define a 'resolve_type (obj, ctx) -> { ... }' function`\n\nI have tried putting a resolve_type in multiple places, but I can't seem to figure this out?\n\nDoes any one now how to implement this?\n\n========================================\n\nTop Answer:\nNow there is UnionType in GraphQL Ruby\n\nhttps://graphql-ruby.org/type_definitions/unions.html#defining-union-types\n\nIt has clear example how define UnionType that you can use.\n\n```\nclass Types::CommentSubject < Types::BaseUnion\n description \"Objects which may be commented on\"\n possible_types Types::Post, Types::Image\n\n # Optional: if this method is defined, it will override `Schema.resolve_type`\n def self.resolve_type(object, context)\n if object.is_a?(BlogPost)\n Types::Post\n else\n Types::Image\n end\n end\nend\n```\n\n========================================\n\nCode:\n```text\nUserableUnion = GraphQL::UnionType.define do\n name \"Userable\"\n description \"Account or Writer object\"\n possible_types [WriterType, AccountType]\nend\n```\n\n```text\nUserType = GraphQL::ObjectType.define do\n name \"User\"\n description \"A user object\"\n field :id, !types.ID\n field :userable, UserableUnion\nend\n```\n\n```text\nschema contains Interfaces or Unions, so you must define a 'resolve_type (obj, ctx) -> { ... }' function\n```\n\n```text\nAppSchema = GraphQL::Schema.define do\n resolve_type ->(record, ctx) do\n # figure out the GraphQL type from the record (activerecord)\n end\nend\n```\n\n```text\nclass ApplicationRecord < ActiveRecord::Base\n class << self\n attr_accessor :graph_ql_type\n end\nend\n\nclass Writer < ApplicationRecord\n self.graph_ql_type = WriterType\nend\n\nAppSchema = GraphQL::Schema.define do\n resolve_type ->(record, ctx) { record.class.graph_ql_type }\nend\n```\n\n```text\nresolve_type\n```\n\n```text\nclass Types::CommentSubject < Types::BaseUnion\n description \"Objects which may be commented on\"\n possible_types Types::Post, Types::Image\n\n # Optional: if this method is defined, it will override `Schema.resolve_type`\n def self.resolve_type(object, context)\n if object.is_a?(BlogPost)\n Types::Post\n else\n Types::Image\n end\n end\nend\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.064Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":126,"estimatedTokens":694}}534{"id":"stack-51877455","source":"stackoverflow","questionId":51877455,"title":"GraphQLError: Syntax Error: Expected :, found {","tags":["graphql","apollo"],"text":"Title: GraphQLError: Syntax Error: Expected :, found {\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nHere are my graphql queries / mutations.\n\nI'm getting the error:\nGraphQLError: Syntax Error: Expected :, found {\n\nI don't know which one of them is wrong.\n\n```\nimport gql from 'graphql-tag';\n\nexport const CategoriesQuery = gql`\n query categoriesQuery(\n $id: ID!,\n $country: String!,\n $name: String!\n ) {\n sections(\n id: $id,\n country: $country,\n name: $description\n ) {\n id,\n createdBy,\n createdDate,\n lastUpdate,\n name\n }\n }\n`;\n\nexport const ItemsQuery = gql`\n query itemsQuery(\n $id: ID!,\n $category: String!,\n $url: String!,\n $alias: String!,\n $name: String!\n ) {\n items(\n input {\n id: $id,\n category: $category,\n url: $url,\n alias: $alias,\n name: $name\n }\n ) {\n id,\n createdBy,\n createdDate,\n lastUpdate,\n name,\n category,\n url,\n alias,\n description\n }\n }\n`;\n\nexport const AddCategoryMutation = gql`\n mutation ($category: CategoryInput!) {\n addCategory(category: $category) {\n id\n }\n }\n`;\n\nexport const AddItemMutation = gql`\n mutation ($item: ItemInput!) {\n addItem(item: $item){\n id\n }\n }\n`;\n```\n\n========================================\n\nTop Answer:\nIn my case I realized that I forgot to add type to function\n\nfalse:\n\n```\ntype Mutation {\n ...\n\n createMentor(mentoremail: String, password: ID)\n }\n```\n\ntrue:\n\n```\ntype Mutation {\n... \n\ncreateMentor(mentoremail: String, password: ID): Mentor\n}\n```\n\n========================================\n\nCode:\n```text\nimport gql from 'graphql-tag';\n\nexport const CategoriesQuery = gql`\n query categoriesQuery(\n $id: ID!,\n $country: String!,\n $name: String!\n ) {\n sections(\n id: $id,\n country: $country,\n name: $description\n ) {\n id,\n createdBy,\n createdDate,\n lastUpdate,\n name\n }\n }\n`;\n\nexport const ItemsQuery = gql`\n query itemsQuery(\n $id: ID!,\n $category: String!,\n $url: String!,\n $alias: String!,\n $name: String!\n ) {\n items(\n input {\n id: $id,\n category: $category,\n url: $url,\n alias: $alias,\n name: $name\n }\n ) {\n id,\n createdBy,\n createdDate,\n lastUpdate,\n name,\n category,\n url,\n alias,\n description\n }\n }\n`;\n\nexport const AddCategoryMutation = gql`\n mutation ($category: CategoryInput!) {\n addCategory(category: $category) {\n id\n }\n }\n`;\n\nexport const AddItemMutation = gql`\n mutation ($item: ItemInput!) {\n addItem(item: $item){\n id\n }\n }\n`;\n```\n\n```text\nitems(\n input {\n id: $id,\n category: $category,\n url: $url,\n alias: $alias,\n name: $name\n }\n)\n```\n\n```text\nitems(\n input: {\n id: $id,\n category: $category,\n url: $url,\n alias: $alias,\n name: $name\n }\n)\n```\n\n```text\ninput\n```\n\n```text\ntype Mutation {\n ...\n\n createMentor(mentoremail: String, password: ID)\n }\n```\n\n```text\ntype Mutation {\n... \n\ncreateMentor(mentoremail: String, password: ID): Mentor\n}\n```\n\n========================================\n\nComments:\n- where is that file? on which file ?\n- these code snippets are the same or am i blind?\n- There is a colon after `input` on the second line","metadata":{"transformedAt":"2026-08-18T18:32:36.065Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":230,"estimatedTokens":862}}535{"id":"stack-43892343","source":"stackoverflow","questionId":43892343,"title":"how to set many-to-many relation in graphql mutation?","tags":["graphql","apollo","react-apollo"],"text":"Title: how to set many-to-many relation in graphql mutation?\nTags: graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI may be missing something, but can not find any information on Apollo docs about the way to set a many-to-many relation when creating a new entry.\n\nWhen the relation is one-to-many it is as simple as setting the ID of the one-side of the relationship in the many-side object.\n\nBut let's pretend I am working with Books and Authors, how would I write a graphql query that creates a Book for one (or many?) Authors?\n\n========================================\n\nTop Answer:\nIf u r using apollo graph server with one to many relations then connectors.js, resolvers.js and schema.js files as given formats\n\nschema.js\n\n```\nconst typeDefinitions = `\n\ntype Author {\n\n authorId: Int\n firstName: String\n lastName: String\n posts: [Post]\n\n}\n\ntype Post {\n\n postId: Int\n title: String \n text: String\n views: Int\n author: Author\n\n}\n\ninput postInput{\n title: String \n text: String\n views: Int\n}\n\ntype Query {\n\n author(firstName: String, lastName: String): [Author]\n posts(postId: Int, title: String, text: String, views: Int): [Post]\n\n}\n\ntype Mutation {\n\ncreateAuthor(firstName: String, lastName: String, posts:[postInput]): Author\n\nupdateAuthor(authorId: Int, firstName: String, lastName: String, posts:[postInput]): String\n\n}\n\nschema {\n query: Query\n mutation:Mutation\n}\n`;\n\nexport default [typeDefinitions];\n```\n\nresolvers.js\n\n```\nimport { Author } from './connectors';\nimport { Post } from './connectors';\n\nconst resolvers = {\n\n Query: {\n author(_, args) {\n return Author.findAll({ where: args });\n },\n posts(_, args) {\n return Post.findAll({ where: args });\n }\n },\n\n Mutation: {\n\n createAuthor(_, args) {\n console.log(args)\n return Author.create(args, {\n include: [{\n model: Post,\n }]\n });\n },\n\n updateAuthor(_, args) {\n\n var updateProfile = { title: \"name here\" };\n console.log(args.authorId)\n var filter = {\n where: {\n authorId: args.authorId\n },\n include: [\n { model: Post }\n ]\n };\n Author.findOne(filter).then(function (product) {\n Author.update(args, { where: { authorId: args.authorId } }).then(function (result) {\n product.posts[0].updateAttributes(args.posts[0]).then(function (result) {\n //return result;\n })\n });\n })\n return \"updated\";\n },\n\n },\n\n Author: {\n posts(author) {\n return author.getPosts();\n },\n },\n Post: {\n author(post) {\n return post.getAuthor();\n },\n },\n};\n\nexport default resolvers;\n```\n\nconnectors.js\n\n```\nimport rp from 'request-promise';\nvar Sequelize = require('sequelize');\nvar db = new Sequelize('test', 'postgres', 'postgres', {\n host: '192.168.1.168',\n dialect: 'postgres',\n\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n }\n\n});\n\nconst AuthorModel = db.define('author', {\n authorId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: \"author_id\" },\n firstName: { type: Sequelize.STRING, field: \"first_name\" },\n lastName: { type: Sequelize.STRING, field: \"last_name\" },\n},{\n freezeTableName: false,\n timestamps: false,\n underscored: false,\n tableName: \"author\"\n });\n\nconst PostModel = db.define('post', {\n postId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: \"post_id\" },\n text: { type: Sequelize.STRING },\n title: { type: Sequelize.STRING },\n views: { type: Sequelize.INTEGER },\n},{\n freezeTableName: false,\n timestamps: false,\n underscored: false,\n tableName: \"post\"\n });\n\nAuthorModel.hasMany(PostModel, {\n foreignKey: 'author_id'\n});\nPostModel.belongsTo(AuthorModel, {\n foreignKey: 'author_id'\n});\n\nconst Author = db.models.author;\nconst Post = db.models.post;\n\nexport { Author, Post };\n```\n\n========================================\n\nCode:\n```text\nBookAuthor\n```\n\n```text\nBook\n```\n\n```text\nAuthor\n```\n\n```text\nBookAuthor\n```\n\n```text\naddToBookAuthorConnection\n```\n\n```text\nupdateBookAuthorConnection\n```\n\n```text\nremoveFromBookAuthorConnection\n```\n\n```text\naddToBookAuthorConnection\n```\n\n```text\nconst typeDefinitions = `\n\n\n\ntype Author {\n\n authorId: Int\n firstName: String\n lastName: String\n posts: [Post]\n\n}\n\ntype Post {\n\n postId: Int\n title: String \n text: String\n views: Int\n author: Author\n\n}\n\ninput postInput{\n title: String \n text: String\n views: Int\n}\n\n\ntype Query {\n\n author(firstName: String, lastName: String): [Author]\n posts(postId: Int, title: String, text: String, views: Int): [Post]\n\n}\n\n\n\ntype Mutation {\n\ncreateAuthor(firstName: String, lastName: String, posts:[postInput]): Author\n\nupdateAuthor(authorId: Int, firstName: String, lastName: String, posts:[postInput]): String\n\n}\n\n\nschema {\n query: Query\n mutation:Mutation\n}\n`;\n\nexport default [typeDefinitions];\n```\n\n```text\nimport { Author } from './connectors';\nimport { Post } from './connectors';\n\n\nconst resolvers = {\n\n Query: {\n author(_, args) {\n return Author.findAll({ where: args });\n },\n posts(_, args) {\n return Post.findAll({ where: args });\n }\n },\n\n Mutation: {\n\n createAuthor(_, args) {\n console.log(args)\n return Author.create(args, {\n include: [{\n model: Post,\n }]\n });\n },\n\n updateAuthor(_, args) {\n\n var updateProfile = { title: \"name here\" };\n console.log(args.authorId)\n var filter = {\n where: {\n authorId: args.authorId\n },\n include: [\n { model: Post }\n ]\n };\n Author.findOne(filter).then(function (product) {\n Author.update(args, { where: { authorId: args.authorId } }).then(function (result) {\n product.posts[0].updateAttributes(args.posts[0]).then(function (result) {\n //return result;\n })\n });\n })\n return \"updated\";\n },\n\n },\n\n\n Author: {\n posts(author) {\n return author.getPosts();\n },\n },\n Post: {\n author(post) {\n return post.getAuthor();\n },\n },\n};\n\nexport default resolvers;\n```\n\n```text\nimport rp from 'request-promise';\nvar Sequelize = require('sequelize');\nvar db = new Sequelize('test', 'postgres', 'postgres', {\n host: '192.168.1.168',\n dialect: 'postgres',\n\n pool: {\n max: 5,\n min: 0,\n idle: 10000\n }\n\n});\n\n\nconst AuthorModel = db.define('author', {\n authorId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: \"author_id\" },\n firstName: { type: Sequelize.STRING, field: \"first_name\" },\n lastName: { type: Sequelize.STRING, field: \"last_name\" },\n},{\n freezeTableName: false,\n timestamps: false,\n underscored: false,\n tableName: \"author\"\n });\n\n\nconst PostModel = db.define('post', {\n postId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: \"post_id\" },\n text: { type: Sequelize.STRING },\n title: { type: Sequelize.STRING },\n views: { type: Sequelize.INTEGER },\n},{\n freezeTableName: false,\n timestamps: false,\n underscored: false,\n tableName: \"post\"\n });\n\n\nAuthorModel.hasMany(PostModel, {\n foreignKey: 'author_id'\n});\nPostModel.belongsTo(AuthorModel, {\n foreignKey: 'author_id'\n});\n\nconst Author = db.models.author;\nconst Post = db.models.post;\n\nexport { Author, Post };\n```\n\n========================================\n\nComments:\n- Thanks for the explanation!! I should have mentioned I am using graph.cool as a backend. Didn't dig their documentation at this point - dummy me. The docs seem short on this topic, but I contacted helpdesk. I'll update here.\n- I found the name of the relations with the help of the graphiQL auto-complete. Very useful since those names appear nowhere in my schema... in hope it helps others.\n- Gotcha! GraphiQL is a great tool to dig into your API and see what exists. Hopefully the relations are more clear now. If you have some time, you should check out Scaphold as well!\n- What's the difference between explicitly defining the fields and doing it this way? AuthorModel.hasMany(PostModel, { through: 'AuthorPosts' });\n- I think this code is for one (Author) to many (Post) and not a many to many.","metadata":{"transformedAt":"2026-08-18T18:32:36.065Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":412,"estimatedTokens":1979}}536{"id":"stack-48817281","source":"stackoverflow","questionId":48817281,"title":"Implementing pagination in vanilla GraphQL","tags":["mongodb","mongoose","graphql","ecmascript-5","graphql-js"],"text":"Title: Implementing pagination in vanilla GraphQL\nTags: mongodb, mongoose, graphql, ecmascript-5, graphql-js\nSource: Stack Overflow\n\nQuestion:\nEvery tutorial I have found thus far has achieved pagination in GraphQL via Apollo, Relay, or some other magic framework. I was hoping to find answers in similar asked questions here but they don't exist. I understand how to setup the *queries* but I'm unclear as to how I would implement the resolvers.\n\nCould someone point me in the right direction? I am using mongoose/MongoDB and ES5, if that helps.\n\nEDIT: It's worth noting that the official site for learning GraphQL doesn't have an entry on pagination if you choose to use `graphql.js`.\n\nEDIT 2: I love that there are *some* people who vote to close questions before doing their research whereas others use their knowledge to help others. You can't stop progress, no matter how hard you try. (:\n\n========================================\n\nTop Answer:\nThere's a number of ways you could implement pagination, but here's two simple example resolvers that use Mongoose to get you started:\n\n**Simple pagination using limit and skip**:\n\n```\n(obj, { pageSize = 10, page = 0 }) => {\n return Foo.find()\n .skip(page*pageSize)\n .limit(pageSize)\n .exec()\n}\n```\n\n**Using _id as a cursor**:\n\n```\n(obj, { pageSize = 10, cursor }) => {\n const params = cursor ? {'_id': {'$gt': cursor}} : undefined\n return Foo.find(params).limit(pageSize).exec()\n}\n```\n\n========================================\n\nCode:\n```text\ngraphql.js\n```\n\n```text\n// Pagination argument type to represent offset and limit arguments\nconst PaginationArgType = new GraphQLInputObjectType({\n name: 'PaginationArg',\n fields: {\n offset: {\n type: GraphQLInt,\n description: \"Skip n rows.\"\n },\n first: {\n type: GraphQLInt,\n description: \"First n rows after the offset.\"\n },\n }\n})\n\n// Function to generate paginated list type for a GraphQLObjectType (for representing paginated response)\n// Accepts a GraphQLObjectType as an argument and gives a paginated list type to represent paginated response.\nconst PaginatedListType = (ItemType) => new GraphQLObjectType({\n name: 'Paginated' + ItemType, // So that a new type name is generated for each item type, when we want paginated types for different types (eg. for Person, Book, etc.). Otherwise, GraphQL would complain saying that duplicate type is created when there are multiple paginated types.\n fields: {\n count: { type: GraphQLInt },\n items: { type: new GraphQLList(ItemType) }\n }\n})\n\n// Type for representing a single item. eg. Person\nconst PersonType = new GraphQLObjectType({\n name: 'Person',\n fields: {\n id: { type: new GraphQLNonNull(GraphQLID) },\n name: { type: GraphQLString },\n }\n})\n\n// Query type which accepts pagination arguments with resolve function\nconst PersonQueryTypes = {\n people: {\n type: PaginatedListType(PersonType),\n args: { \n pagination: { \n type: PaginationArgType, \n defaultValue: { offset: 0, first: 10 } \n },\n },\n resolve: (_, args) => {\n const { offset, first } = args.pagination\n // Call MongoDB/Mongoose functions to fetch data and count from database here.\n return {\n items: People.find().skip(offset).limit(first).exec()\n count: People.count()\n }\n },\n }\n}\n\n// Root query type\nconst QueryType = new GraphQLObjectType({\n name: 'QueryType',\n fields: {\n ...PersonQueryTypes,\n },\n});\n\n// GraphQL Schema\nconst Schema = new GraphQLSchema({\n query: QueryType\n});\n```\n\n```text\n{\n people(pagination: {offset: 0, first: 10}) {\n items {\n id\n name\n }\n count\n }\n}\n```\n\n```text\n(obj, { pageSize = 10, page = 0 }) => {\n return Foo.find()\n .skip(page*pageSize)\n .limit(pageSize)\n .exec()\n}\n```\n\n```text\n(obj, { pageSize = 10, cursor }) => {\n const params = cursor ? {'_id': {'$gt': cursor}} : undefined\n return Foo.find(params).limit(pageSize).exec()\n}\n```\n\n========================================\n\nComments:\n- Can you tell what you have tried and didn't work? Where did you get stuck?\n- I've tried pretty much any tutorial you can readily find online. I get stuck around the parts where the resolvers and/or edges come into play.\n- Can you give a more concrete example of something you are trying to achieve?\n- @TalZ I'm not sure how much more concrete I can be. How should I improve my question? I updated it with a link to howtographql.com. There, you will find tutorials on how to setup a GraphQL server. Not all of them have tutorials on implementing pagination.\n- Maybe you can post some code of a mongodb/mongoose query that uses pagination and a related resolver that you want to be able to use with that pagination.\n- Thank you for providing code snippets but I'm not sure how I would integrate this.\n- Username checks out, bless you!\n- Glad to have helped ;)","metadata":{"transformedAt":"2026-08-18T18:32:36.065Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":154,"estimatedTokens":1213}}537{"id":"stack-65720312","source":"stackoverflow","questionId":65720312,"title":"type-graphql: How to know which fields are returned by Resolver","tags":["typescript","graphql","typegraphql"],"text":"Title: type-graphql: How to know which fields are returned by Resolver\nTags: typescript, graphql, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI am writing a backend application that uses type-graphql. The GraphQL schema includes a `Folder` type that looks like this:\n\n```\ntype Folder {\n id: ID!\n name: String!\n rules: [Rule!]!\n parent: Group\n}\n```\n\n`Rule` and `Group` are other types.\n\nMy Resolver defines a Query called `folders` that returns all Folders:\n\n```\nimport {Query, Resolver} from 'type-graphql'\n\n@Resolver(() => Folder)\nexport default class FolderResolver {\n\n @Query(() => [Folder])\n folders(): Promise {\n // query db and return results\n }\n}\n```\n\nTo query the folders, their rules, and their parent group from the database, I have to join the database tables and return the joined result, which works without problems. However: If the `rules` field and / or the `parent` field was not requested in the GraphQL query, I could omit the joins and make the database query much more efficient. So the fields that were requested in the GraphQL query have a definite effect on the logic that I need to execute, but I don't see a way of finding out which fields were requested inside the `folders` function.\n\nWhen a Query in a type-graphql Resolver is executed, is there a way to determine which fields were requested in the GraphQL query?\n\n========================================\n\nCode:\n```text\ntype Folder {\n id: ID!\n name: String!\n rules: [Rule!]!\n parent: Group\n}\n```\n\n```text\nimport {Query, Resolver} from 'type-graphql'\n\n@Resolver(() => Folder)\nexport default class FolderResolver {\n\n @Query(() => [Folder])\n folders(): Promise<Folder[]> {\n // query db and return results\n }\n}\n```\n\n```text\nFolder\n```\n\n```text\nRule\n```\n\n```text\nGroup\n```\n\n```text\nfolders\n```\n\n```text\nrules\n```\n\n```text\nparent\n```\n\n```text\nfolders\n```\n\n```ts\nimport {Query, Resolver, FieldResolver} from 'type-graphql'\n\n@Resolver(() => Folder)\nexport default class FolderResolver {\n\n @FieldResolver()\n rules(@Root() folder: Folder) {\n // ...\n }\n\n\n @FieldResolver()\n parent(@Root() folder: Folder) {\n // ...\n }\n\n @Query(() => [Folder])\n folders(): Promise<Folder[]> {\n // query db and return results\n }\n}\n```\n\n```ts\nimport graphqlFields from 'graphql-fields';\n\n @Query(() => [Folder])\n folders(@Info() info: GraphQLResolveInfo): Promise<Folder[]> {\n // get fields\n const topLevelFields = Object.keys(graphqlFields(info));\n // query db and return results\n }\n```\n\n```text\nrules\n```\n\n```text\nparent\n```\n\n```text\ninfo\n```\n\n========================================\n\nComments:\n- I don't think the Field Resolver helps here unfortunately. If neither `parent` nor `rules` is requested, I want `folders` to execute a database query that queries only the folder table. If `parent` and / or `rules` is requested, I want `folders` to execute a database query that queries the folder table and joins on the parent and / or rule table (which I currently do no matter what fields are requested from the GraphQL query). In either case, I want to perform a single database query. I'm hoping that I can execute that query inside `folders` and shape it based on the requested fields.\n- @MatthiasFischer I have updayed the answer as per your comment. Have a look.\n- Awesome! The `@Info` decorator is exactly what I was missing. The graphqlFields library seems really useful, too, I will check it out. Thanks a lot!","metadata":{"transformedAt":"2026-08-18T18:32:36.065Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":143,"estimatedTokens":854}}538{"id":"stack-59527847","source":"stackoverflow","questionId":59527847,"title":"Input Object type `TypeName` must define one or more fields","tags":["graphql","nestjs","typegraphql"],"text":"Title: Input Object type `TypeName` must define one or more fields\nTags: graphql, nestjs, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI am experimenting with `NestJS` and `TypeGraphQL`. And I have an example model of a cat.\n\n```\nimport { Document } from 'mongoose';\nimport { ObjectType, InputType, Field, ID } from 'type-graphql';\n\nexport interface Cat extends Document {\n readonly name: string;\n readonly age?: number;\n}\n\nclass CatBase {\n @Field()\n name: string;\n\n @Field({ nullable: true })\n age?: number;\n}\n\n@ObjectType()\nexport class CatObjectType extends CatBase implements Cat {\n @Field(type => ID)\n id: string;\n}\n\n@InputType()\nexport class CatInputType extends CatBase implements Cat {\n}\n```\n\nHere I am trying to reuse `BaseCat` in `CatObjectType` and `CatInputType`. But I getting this error:\n\n```\n[ { GraphQLError: Input Object type CatInputType must define one or more fields.\n at SchemaValidationContext.reportError (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:90:19)\n at validateInputFields (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:432:13)\n at validateTypes (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:240:7)\n at validateSchema (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:54:3)\n at graphqlImpl (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:79:62)\n at /Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:28:59\n at new Promise ()\n at Object.graphql (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:26:10)\n at Function. (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:18:52)\n at Generator.next ()\n at /Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:110:75\n at new Promise ()\n at Object.__awaiter (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:106:16)\n at Function.generateFromMetadata (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:15:24)\n at /Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/utils/buildSchema.js:11:65\n at Generator.next ()\n message:\n 'Input Object type CatInputType must define one or more fields.' } ]\n(node:72485) UnhandledPromiseRejectionWarning: Error: Generating schema error\n at Function. (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:20:27)\n at Generator.next ()\n at fulfilled (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:107:62)\n at processTicksAndRejections (internal/process/next_tick.js:81:5)\n(node:72485) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:72485) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\nWhen in `CatInputType` are described all fields from `BaseCat` all work as expected. What I am doing wrong?\n\n========================================\n\nCode:\n```text\nimport { Document } from 'mongoose';\nimport { ObjectType, InputType, Field, ID } from 'type-graphql';\n\nexport interface Cat extends Document {\n readonly name: string;\n readonly age?: number;\n}\n\nclass CatBase {\n @Field()\n name: string;\n\n @Field({ nullable: true })\n age?: number;\n}\n\n@ObjectType()\nexport class CatObjectType extends CatBase implements Cat {\n @Field(type => ID)\n id: string;\n}\n\n@InputType()\nexport class CatInputType extends CatBase implements Cat {\n}\n```\n\n```text\n[ { GraphQLError: Input Object type CatInputType must define one or more fields.\n at SchemaValidationContext.reportError (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:90:19)\n at validateInputFields (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:432:13)\n at validateTypes (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:240:7)\n at validateSchema (/Users/pavel/Dev/exampleproject/node_modules/graphql/type/validate.js:54:3)\n at graphqlImpl (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:79:62)\n at /Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:28:59\n at new Promise (<anonymous>)\n at Object.graphql (/Users/pavel/Dev/exampleproject/node_modules/graphql/graphql.js:26:10)\n at Function.<anonymous> (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:18:52)\n at Generator.next (<anonymous>)\n at /Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:110:75\n at new Promise (<anonymous>)\n at Object.__awaiter (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:106:16)\n at Function.generateFromMetadata (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:15:24)\n at /Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/utils/buildSchema.js:11:65\n at Generator.next (<anonymous>)\n message:\n 'Input Object type CatInputType must define one or more fields.' } ]\n(node:72485) UnhandledPromiseRejectionWarning: Error: Generating schema error\n at Function.<anonymous> (/Users/pavel/Dev/exampleproject/node_modules/type-graphql/dist/schema/schema-generator.js:20:27)\n at Generator.next (<anonymous>)\n at fulfilled (/Users/pavel/Dev/exampleproject/node_modules/tslib/tslib.js:107:62)\n at processTicksAndRejections (internal/process/next_tick.js:81:5)\n(node:72485) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:72485) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\nNestJS\n```\n\n```text\nTypeGraphQL\n```\n\n```text\nBaseCat\n```\n\n```text\nCatObjectType\n```\n\n```text\nCatInputType\n```\n\n```text\nCatInputType\n```\n\n```text\nBaseCat\n```\n\n```text\n@ObjectType({ isAbstract: true })\n@InputType({ isAbstract: true })\nclass CatBase {\n @Field()\n name: string;\n\n @Field({ nullable: true })\n age?: number;\n}\n```\n\n```text\n@Field\n```\n\n```text\n@InputType\n```\n\n```text\n@ObjectType\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.065Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":179,"estimatedTokens":1625}}539{"id":"stack-52725737","source":"stackoverflow","questionId":52725737,"title":"How to return directly from the request mapper?","tags":["amazon-web-services","graphql","aws-appsync","vtl"],"text":"Title: How to return directly from the request mapper?\nTags: amazon-web-services, graphql, aws-appsync, vtl\nSource: Stack Overflow\n\nQuestion:\nConsider the following GraphQL template:\n\n```\ntype Foo {\n id: ID!\n bars: Bars\n}\n\ntype Bar {\n id: ID!\n name: String!\n}\n\ntype Bars {\n items: [Bar]!\n nextToken: String\n}\n```\n\nThe mapping template for the `bars` field in the Foo type looks like this:\n\n```\n#set($ids = [])\n#foreach($id in $context.source.bars)\n #set($map = {})\n $util.qr($map.put(\"id\", $util.dynamodb.toString($id)))\n $util.qr($ids.add($map))\n#end\n{\n \"version\" : \"2018-05-29\",\n \"operation\" : \"BatchGetItem\",\n \"tables\" : {\n \"barsTable\" : {\n \"keys\": $util.toJson($ids),\n \"consistentRead\": true\n }\n }\n}\n```\n\nThis works well. But if the `bars` field contains and empty array `[]`, the template will obviously crash with the following error:\n\n```\n\"errors\": [\n {\n \"path\": [\n \"getFoo\",\n \"bars\"\n ],\n \"data\": null,\n \"errorType\": \"MappingTemplate\",\n \"errorInfo\": null,\n \"locations\": [\n {\n \"line\": 59,\n \"column\": 7,\n \"sourceName\": null\n }\n ],\n \"message\": \"RequestItem keys '$[tables][barsTable]' can't be empty\"\n }\n ]\n```\n\nSo my question is:\n\n**How do I prevent the query to be executed and just return an empty array to the response template when `$context.source.bars` is empty ?**\n\n========================================\n\nTop Answer:\nYou can use \n\n```\n#if(!$array.isEmpty())\n //do something\n#else\n //do something else\n#end\n```\n\nFor more information you can refer the resolver mapping template reference guide here\n\n========================================\n\nCode:\n```text\ntype Foo {\n id: ID!\n bars: Bars\n}\n\ntype Bar {\n id: ID!\n name: String!\n}\n\ntype Bars {\n items: [Bar]!\n nextToken: String\n}\n```\n\n```text\n#set($ids = [])\n#foreach($id in $context.source.bars)\n #set($map = {})\n $util.qr($map.put(\"id\", $util.dynamodb.toString($id)))\n $util.qr($ids.add($map))\n#end\n{\n \"version\" : \"2018-05-29\",\n \"operation\" : \"BatchGetItem\",\n \"tables\" : {\n \"barsTable\" : {\n \"keys\": $util.toJson($ids),\n \"consistentRead\": true\n }\n }\n}\n```\n\n```text\n\"errors\": [\n {\n \"path\": [\n \"getFoo\",\n \"bars\"\n ],\n \"data\": null,\n \"errorType\": \"MappingTemplate\",\n \"errorInfo\": null,\n \"locations\": [\n {\n \"line\": 59,\n \"column\": 7,\n \"sourceName\": null\n }\n ],\n \"message\": \"RequestItem keys '$[tables][barsTable]' can't be empty\"\n }\n ]\n```\n\n```text\nbars\n```\n\n```text\nbars\n```\n\n```text\n[]\n```\n\n```text\n$context.source.bars\n```\n\n```text\n#if ($context.source.bars.size() <= 0) \n #return([])\n#end\n\n#set($ids = [])\n#foreach($id in $context.source.bars)\n #set($map = {})\n $util.qr($map.put(\"id\", $util.dynamodb.toString($id)))\n $util.qr($ids.add($map))\n#end\n{\n \"version\" : \"2018-05-29\",\n \"operation\" : \"BatchGetItem\",\n \"tables\" : {\n \"barsTable\" : {\n \"keys\": $util.toJson($ids),\n \"consistentRead\": true\n }\n }\n}\n```\n\n```text\n#return(data)\n```\n\n```text\n#if(!$array.isEmpty())\n //do something\n#else\n //do something else\n#end\n```\n\n```text\ntype Query {\n getTests(ids: [ID!]): [Test]\n}\ntype Test {\n id: ID!\n title: String!\n}\nschema {\n query: Query\n}\n```\n\n```text\n## REQUEST MAPPING\n#set($ids = [])\n## CREATE A FAKE-ID TO RETURN NULL ONLY IF ids IS NULL OR EMPTY\n#if( $ctx.args.ids.isEmpty() || $util.isNull($ctx.args.ids) )\n #set($map = {})\n $util.qr($map.put(\"id\", $util.dynamodb.toString(\"fake-id-to-return-null\")))\n $util.qr($ids.add($map))\n#else\n #foreach($id in $ctx.args.ids)\n #set($map = {})\n $util.qr($map.put(\"id\", $util.dynamodb.toString($id)))\n $util.qr($ids.add($map))\n #end\n#end\n\n{\n \"version\" : \"2018-05-29\",\n \"operation\" : \"BatchGetItem\",\n \"tables\" : {\n \"TestTable\": {\n \"keys\": $util.toJson($ids),\n \"consistentRead\": true\n }\n }\n}\n\n## RESPONSE MAPPING\n$utils.toJson($ctx.result.data.TestTable)\n```\n\n```text\n#if( !($util.isNull($ctx.args.ids) || $ctx.args.ids.isEmpty()) ) \n #set($ids = [])\n #foreach($id in $ctx.args.ids)\n #set($map = {})\n $util.qr($map.put(\"id\", $util.dynamodb.toString($id)))\n $util.qr($ids.add($map))\n #end\n {\n \"version\" : \"2018-05-29\",\n \"operation\" : \"BatchGetItem\",\n \"tables\" : {\n \"TestTable\": {\n \"keys\": $util.toJson($ids),\n \"consistentRead\": true\n }\n }\n }\n#else\n {\n \"version\": \"2017-02-28\",\n \"operation\": \"GetItem\",\n \"key\": {\n \"id\": $util.dynamodb.toDynamoDBJson(\".\"),\n }\n }\n#end\n```\n\n========================================\n\nComments:\n- Yes but what do I put in the else statement that will return an empty array without executing any Dynamodb request ?\n- This would return ALL items if `$context.source.bars` is empty, while I want nothing to be returned :/\n- Yes, I found out days later! Thanks for digging this up though, I forgot to post the answer. Accepting yours ;)\n- Definitely a hero.\n- It took me 2 hours of debugging and searching to find this post, but I'm glad I eventually got here. Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.065Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":281,"estimatedTokens":1291}}540{"id":"stack-54203423","source":"stackoverflow","questionId":54203423,"title":"Connecting two gatsby nodes","tags":["javascript","graphql","gatsby","graphql-js"],"text":"Title: Connecting two gatsby nodes\nTags: javascript, graphql, gatsby, graphql-js\nSource: Stack Overflow\n\nQuestion:\nSo, I'm using the gatsby-mdx plugin to create a site from MDX files. I want to create an association between the SitePage object and the Mdx object so that I can do one graphQL query of the SitePage edges in order to construct a site navigation.\n\nMuch of my code is in TypeScript, so ignore any type annotations if you're wondering WTF those are.\n\n### Things I've tried\n\n### Using Fields\n\nMy first thought was to use the `onCreateNode` API, grab the MDX node, and add it to the SitePage using the `createNodeField` action. That all works great, B-U-T the gatsby-mdx plugin adds a bunch of other info to their node later using the `setFieldsOnGraphQLNodeType` API (which occurs *after* the `onCreateNode` API). I want those fields (such as frontmatter and tableOfContents) to be available in later graphql queries, but they aren't using this method.\n\n### Implementing my own `setFieldsOnGraphQLNodeType`\n\nI figured I could just extend the SitePage object the same way gatsby-mdx was extending the Mdx node.\n\nThe key problem I ran into here was that I couldn't figure out how to create the Mdx GraphQL node type.\n\n```\nexport const setFieldsOnGraphQLNodeType = ({type, actions, getNodes}: any, pluginOptions: any) => {\n if (type.name === \"SitePage\") {\n const {createParentChildLink} = actions\n return new Promise((resolve) => {\n return resolve({\n \"childMdx\": {\n type: new GraphQLObjectType({\n name: 'Mdx'\n }),\n async resolve(sitePageNode: any) {\n const allNodes = getNodes()\n if (sitePageNode.component &&\n (sitePageNode.component.endsWith(\".mdx\") || sitePageNode.component === DefaultLayout)\n ) {\n const associatedMdx = allNodes.find((mdxNode: any) =>\n mdxNode.internal.type === 'Mdx' && mdxNode.fileAbsolutePath === sitePageNode.component\n )\n if (associatedMdx) {\n console.log(\"Found associated MDX node\", associatedMdx.id)\n console.log(\"Adding it to the sitepage node\", sitePageNode.id)\n return associatedMdx\n }\n }\n }\n }\n })\n })\n }\n return {}\n}\n```\n\nI also tried simply passing the type as a String ('Mdx'), but that failed too.\n\n### Using Parent-Child Links\n\nThat plugin creates a parent-child link between the File node and the parsed MDX node in the `onCreateNode` API, using the createParentChildLink action (source).\n\nI tried implementing that...\n\n```\nexport const onCreateNode = ({node, actions, getNodes}: OnCreateNodeArgument) => {\n const {createParentChildLink} = actions\n const allNodes = getNodes()\n if (node.internal && node.internal.type === 'SitePage' && node.component &&\n (node.component.endsWith(\".mdx\") || node.component === DefaultLayout)\n ) {\n const associatedMdx = allNodes.find((mdxNode: any) =>\n mdxNode && mdxNode.internal && mdxNode.internal.type === 'Mdx' &&\n (mdxNode.fileAbsolutePath === node.component || mdxNode.fileAbsolutePath === node.context.fileAbsolutePath)\n )\n if (associatedMdx) {\n console.log(\"Found associated MDX node\", associatedMdx.id)\n console.log(\"Adding it to the sitepage node as a child\", node.id)\n createParentChildLink({parent: node, child: associatedMdx})\n }\n }\n}\n```\n\nAt first, that appears to succeed, but the `tableOfContents` property that gatsby-mdx adds to the Mdx node still isn't available in a graphQL query like:\n\n```\n{\n allSitePage(filter: {fields: {childMdx: {id: {ne: null}}}}) {\n edges {\n node {\n path\n fields{\n childMdx {\n tableOfContents\n fileAbsolutePath\n frontmatter {\n title\n }\n }\n }\n context {\n roughFilePath\n id\n }\n }\n }\n }\n}\n```\n\n### Other (possibly irrelevant) info\n\nI'm creating some pages programmatically in gatsby-node.js.\n\nI've seen a suggestion for similar use cases to use node type mappings, but I since my mapping between the SitePage & the MDX object requires a bit of finesse (specifically, reading some things from siteMetadata and doing a string comparison), I don't think that will work for my use case.\n\n========================================\n\nCode:\n```text\nexport const setFieldsOnGraphQLNodeType = ({type, actions, getNodes}: any, pluginOptions: any) => {\n if (type.name === \"SitePage\") {\n const {createParentChildLink} = actions\n return new Promise((resolve) => {\n return resolve({\n \"childMdx\": {\n type: new GraphQLObjectType({\n name: 'Mdx'\n }),\n async resolve(sitePageNode: any) {\n const allNodes = getNodes()\n if (sitePageNode.component &&\n (sitePageNode.component.endsWith(\".mdx\") || sitePageNode.component === DefaultLayout)\n ) {\n const associatedMdx = allNodes.find((mdxNode: any) =>\n mdxNode.internal.type === 'Mdx' && mdxNode.fileAbsolutePath === sitePageNode.component\n )\n if (associatedMdx) {\n console.log(\"Found associated MDX node\", associatedMdx.id)\n console.log(\"Adding it to the sitepage node\", sitePageNode.id)\n return associatedMdx\n }\n }\n }\n }\n })\n })\n }\n return {}\n}\n```\n\n```text\nexport const onCreateNode = ({node, actions, getNodes}: OnCreateNodeArgument) => {\n const {createParentChildLink} = actions\n const allNodes = getNodes()\n if (node.internal && node.internal.type === 'SitePage' && node.component &&\n (node.component.endsWith(\".mdx\") || node.component === DefaultLayout)\n ) {\n const associatedMdx = allNodes.find((mdxNode: any) =>\n mdxNode && mdxNode.internal && mdxNode.internal.type === 'Mdx' &&\n (mdxNode.fileAbsolutePath === node.component || mdxNode.fileAbsolutePath === node.context.fileAbsolutePath)\n )\n if (associatedMdx) {\n console.log(\"Found associated MDX node\", associatedMdx.id)\n console.log(\"Adding it to the sitepage node as a child\", node.id)\n createParentChildLink({parent: node, child: associatedMdx})\n }\n }\n}\n```\n\n```text\n{\n allSitePage(filter: {fields: {childMdx: {id: {ne: null}}}}) {\n edges {\n node {\n path\n fields{\n childMdx {\n tableOfContents\n fileAbsolutePath\n frontmatter {\n title\n }\n }\n }\n context {\n roughFilePath\n id\n }\n }\n }\n }\n}\n```\n\n```text\nonCreateNode\n```\n\n```text\ncreateNodeField\n```\n\n```text\nsetFieldsOnGraphQLNodeType\n```\n\n```text\nonCreateNode\n```\n\n```text\nsetFieldsOnGraphQLNodeType\n```\n\n```text\nonCreateNode\n```\n\n```text\ntableOfContents\n```\n\n```text\nconst path = require(\"path\")\nconst { createFilePath } = require(\"gatsby-source-filesystem\")\n\nexports.onCreateNode = ({ node, actions, getNode }) => {\n const { createNodeField } = actions\n\n if (node.internal.type === \"SitePage\" && node.context && node.context.id) {\n\n createNodeField({\n name: \"Mdx___NODE\",\n value: node.context.id,\n node,\n })\n }\n\n if (node.internal.type === \"Mdx\") {\n const value = createFilePath({ node, getNode })\n createNodeField({\n // 1) this is the name of the field you are adding,\n name: \"slug\",\n // 2) this node refers to each individual MDX\n node,\n value: `/blog${value}`\n })\n }\n}\n\n\nexports.createPages = async ({ graphql, actions }) => {\n const { createPage } = actions;\n const { data, errors } = await graphql(`\n {\n allMdx {\n edges {\n node {\n id\n fields {\n slug\n }\n }\n }\n }\n }\n `)\n\n if (errors) throw errors\n data.allMdx.edges.forEach(({ node }) => {\n createPage({\n path: node.fields.slug,\n component: path.resolve(`./src/components/posts-page-layout.js`),\n context: { id: node.id }\n });\n });\n};\n```\n\n```text\ncontext\n```\n\n```text\ncreatePage\n```\n\n```text\nid\n```\n\n```text\nonCreateNode\n```\n\n```text\nSitePage\n```\n\n```text\ncreateNodeField\n```\n\n```text\nMdx___NODE\n```\n\n```text\ngatsby-node.js\n```\n\n========================================\n\nComments:\n- Maybe I'm missing something, but shouldn't all mdx files already be a part of sitePage nodes? if your purpose is to construct a site navigation, won't you be able to find all the generated pages there?\n- So, the SitePage nodes don't directly link to their associated Mdx node in graphql queries without some intervention. There's some specific information on the Mdx nodes that I want for the navigation: frontmatter and tableOfContents. Those aren't on the SitePage node itself. While I can do one big query of both `allSitePage` and `allMdx`, then finagle them together using JavaScript, that... well, kind of sucks! By all appearances, I should be able manipulate the SitePage nodes to include the information I want, but the timing of the various phases complicates matters.\n- The `createParentChildLink` action seems like the most appropriate solution. I may just need to make a deep debugger dive on that `TypeError: Cannot read property 'internal' of undefined` message.\n- Updated question, as that cryptic error went away after I cleared the .cache folder and restarted.\n- Thanks for providing additional context, I've never dealt with this but it's probably good to know how. I've just shared my findings as an answer below\n- It definitely does! Thanks.","metadata":{"transformedAt":"2026-08-18T18:32:36.065Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":322,"estimatedTokens":2424}}541{"id":"stack-53277983","source":"stackoverflow","questionId":53277983,"title":"AWS AppSync Lambda resolver fields","tags":["amazon-web-services","aws-lambda","graphql","aws-appsync"],"text":"Title: AWS AppSync Lambda resolver fields\nTags: amazon-web-services, aws-lambda, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI have the following query:\n\n```\nquery xxx {\n getSomething(id: \"id\") {\n field1\n field2\n }\n}\n```\n\nIs there any way for me to get `field1` and `field2` in lambda? For example, to query only those fields in mysql, not get all of them just to be discarded by AppSync later.\n\nI tried logging all the `$context` in the request mapper VTL file but they are not there. Any ideas? Seems quite stupid to not be able to do that. The only thing I get in lambda is the `id` argument.\n\nThanks,\nMihai\n\n========================================\n\nTop Answer:\nAppSync now supports getting the GraphQL Info object. You can get the list of requested columns from the selectionSetList variable.\n\nThe layout of the Info object:\n\n```\n{\n \"fieldName\": \"string\",\n \"parentTypeName\": \"string\",\n \"variables\": { ... },\n \"selectionSetList\": [\"string\"],\n \"selectionSetGraphQL\": \"string\"\n}\n```\n\nAn example passing the selectionSetList property to a lambda resolver:\n\n```\n{\n \"version\" : \"2017-02-28\",\n \"operation\": \"Invoke\",\n \"payload\": {\n \"arguments\": $utils.toJson($ctx.args),\n \"selectionSetList\": $utils.toJson($ctx.info.selectionSetList),\n \"selectionSetGraphQL\": $utils.toJson($ctx.info.selectionSetGraphQL)\n }\n}\n```\n\n**Note:** If you are trying to pass the selectionSetList then you need to specifically reference it (like in the example above). The list will not be available if the info object is passed in directly with something like `$utils.toJson($ctx.info)`.\n\n========================================\n\nCode:\n```text\nquery xxx {\n getSomething(id: \"id\") {\n field1\n field2\n }\n}\n```\n\n```text\nfield1\n```\n\n```text\nfield2\n```\n\n```text\n$context\n```\n\n```text\nid\n```\n\n```text\ngetThingFromTableA\n```\n\n```text\ngetThingFromTableB\n```\n\n```text\ngetThing\n```\n\n```text\n{ cheapA, cheapB, expensiveA { expensiveTableAThingA, expensiveTableAThingB }, expensiveB }\n```\n\n```text\n$context.source\n```\n\n```text\n$context\n```\n\n```text\nevent.source\n```\n\n```text\n{\n \"fieldName\": \"string\",\n \"parentTypeName\": \"string\",\n \"variables\": { ... },\n \"selectionSetList\": [\"string\"],\n \"selectionSetGraphQL\": \"string\"\n}\n```\n\n```text\n{\n \"version\" : \"2017-02-28\",\n \"operation\": \"Invoke\",\n \"payload\": {\n \"arguments\": $utils.toJson($ctx.args),\n \"selectionSetList\": $utils.toJson($ctx.info.selectionSetList),\n \"selectionSetGraphQL\": $utils.toJson($ctx.info.selectionSetGraphQL)\n }\n}\n```\n\n```text\n$utils.toJson($ctx.info)\n```\n\n========================================\n\nComments:\n- how your response mapping template looks like. Also have you seen this tutorial? docs.aws.amazon.com/appsync/latest/devguide/…\n- I'm talking about request, not response. Response template is for modifying the response, I'm interested in getting the fields in the request.\n- Yeah, I get it. Thought about using a field resolver but that means another lambda, even if it's the same one, it's another lambda fired up. I wanted to get this done with only one function. Thanks\n- It does sound like a useful feature- although I guess that because fields can be nested, have arguments, and such it's quite a complex custom object to express.\n- This oversight on Appsyncβs part is quite frustrating. I can imagine scalar fields, for example, that are computed that Iβd want to avoid computing if they werenβt asked for. Using field-level resolvers for those fields means an additional round trips to the data source (e.g. database) along with the serialization of the source/parent result and subsequent deserialization in the sub-query resolvers. Itβd be nice to have access to the entire query tree below a given query or field resolver so the lambda has the option of optimizing DB access / result computation. E.g., lacinia does\n- Tried that, they are not. Only the arguments are there","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":147,"estimatedTokens":975}}542{"id":"stack-57393078","source":"stackoverflow","questionId":57393078,"title":"How to implement auto jwt token refresh before every graphql request with Apollo and React Native?","tags":["node.js","react-native","jwt","graphql","apollo-client"],"text":"Title: How to implement auto jwt token refresh before every graphql request with Apollo and React Native?\nTags: node.js, react-native, jwt, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI would like to implement auto refresh jwt token before every request to **GraphQL** with **Apollo** middleware in **React Native** app. After every user login he gets two tokens: access and refresh. Access token it is the short one for 30-60 min for using in authorization header. And refresh token it is the long one for 60 days for confirm of refresh token graphql mutation. \nMy flow:\n\n- User login and gets 2 tokens -> put access token to authorization header with **Appollo** setContext.\nUser make request to **GraphQL** -> check expireTime of accessToken on a client side:\n-> if it is not expired -> confirm request\n-> if it is has expired -> call **GraphQL** refreshToken mutation -> get new tokens -> confirm request.\nFor keeping tokens on the client side i use **KeyChain** storage. Can you tell me please should i use **Apollo** cache for keeping tokens too? Should i write **Apollo** state for tokens? And how i can implement my flow?\n\nGraphQL mutation\n\n```\nmutation UpdateTokens($refreshToken: String!, $refreshTokenId: String!) \n {\n updateTokens(refreshToken: $refreshToken, refreshTokenId: $refreshTokenId) {\n user {\n name\n phone\n }\n accessToken\n refreshToken\n }\n }\n```\n\nApp.js\n\n```\nimport React from 'react'\nimport { ApolloClient } from 'apollo-client'\nimport { ApolloLink } from 'apollo-link'\nimport { ApolloProvider } from 'react-apollo'\nimport { ApolloProvider as ApolloHooksProvider } from 'react-apollo-hooks'\nimport { createHttpLink } from 'apollo-link-http'\nimport { InMemoryCache } from 'apollo-cache-inmemory'\nimport { setContext } from 'apollo-link-context'\nimport * as Keychain from 'react-native-keychain'\nimport AppNavigator from './AppNavigator'\n\nconst httpLink = createHttpLink({\n uri: 'http://localhost:4000'\n})\n\nconst cache = new InMemoryCache()\n\nconst authLink = setContext(async (req, { headers, ...context }) => {\n const tokens = await Keychain.getGenericPassword()\n const accessToken = tokens.username\n return {\n headers: {\n ...headers,\n authorization: accessToken ? `Bearer ${accessToken}` : ''\n },\n ...context\n }\n})\n\nconst client = new ApolloClient({\n link: ApolloLink.from([authLink, httpLink]),\n cache,\n connectToDevTools: true\n})\n\nconst App = () => {\n return (\n \n \n \n \n \n )\n}\n\nexport default App\n```\n\n========================================\n\nCode:\n```text\nmutation UpdateTokens($refreshToken: String!, $refreshTokenId: String!) \n {\n updateTokens(refreshToken: $refreshToken, refreshTokenId: $refreshTokenId) {\n user {\n name\n phone\n }\n accessToken\n refreshToken\n }\n }\n```\n\n```text\nimport React from 'react'\nimport { ApolloClient } from 'apollo-client'\nimport { ApolloLink } from 'apollo-link'\nimport { ApolloProvider } from 'react-apollo'\nimport { ApolloProvider as ApolloHooksProvider } from 'react-apollo-hooks'\nimport { createHttpLink } from 'apollo-link-http'\nimport { InMemoryCache } from 'apollo-cache-inmemory'\nimport { setContext } from 'apollo-link-context'\nimport * as Keychain from 'react-native-keychain'\nimport AppNavigator from './AppNavigator'\n\nconst httpLink = createHttpLink({\n uri: 'http://localhost:4000'\n})\n\nconst cache = new InMemoryCache()\n\nconst authLink = setContext(async (req, { headers, ...context }) => {\n const tokens = await Keychain.getGenericPassword()\n const accessToken = tokens.username\n return {\n headers: {\n ...headers,\n authorization: accessToken ? `Bearer ${accessToken}` : ''\n },\n ...context\n }\n})\n\nconst client = new ApolloClient({\n link: ApolloLink.from([authLink, httpLink]),\n cache,\n connectToDevTools: true\n})\n\nconst App = () => {\n return (\n <ApolloProvider client={client}>\n <ApolloHooksProvider client={client}>\n <AppNavigator />\n </ApolloHooksProvider>\n </ApolloProvider>\n )\n}\n\nexport default App\n```\n\n```text\napollo-link-context\n```\n\n```text\nsetContext\n```\n\n========================================\n\nComments:\n- Can you provide inputs on how to access request headers in grapQL - React native? stackoverflow.com/questions/64617612/…\n- Link is no longer active\n- Certainly, @jocoders, accepting the answer and upvotes always welcome for great answers ;)","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":161,"estimatedTokens":1085}}543{"id":"stack-54546009","source":"stackoverflow","questionId":54546009,"title":"Fetch API cannot load webpack://... error","tags":["reactjs","graphql","react-apollo","apollo-client","next.js"],"text":"Title: Fetch API cannot load webpack://... error\nTags: reactjs, graphql, react-apollo, apollo-client, next.js\nSource: Stack Overflow\n\nQuestion:\nI am trying to learn some new tricks with Apollo Client and GraphQL but I have run into an error that I can't figure out what is causing it. The stack I am using is GraphQL and ApolloClient. The error is \n\n`Fetch API cannot load webpack://%5Bname%5D_%5Bchunkhash%5D/./node_modules/react-dom/cjs/react-dom.development.js?. URL scheme must be \"http\" or \"https\" for CORS request.`\n\nI checked my CORS setup and I can make other queries with no problem. The error appears with this specific query:\n\n```\nquery SINGLE_STORE_QUERY($id: ID!) {\n store(where: { id: $id }) {\n id\n name\n description\n image\n address\n lat\n lng\n reviews {\n user {\n name\n }\n text\n rating\n }\n }\n }\n```\n\nMy Apollo Query in the NextJS component is: \n\n```\n\n {({ data: { store }, error, loading }) => {\n if (error) return ;\n if (loading) return Loading...\n\n;\n\n console.log(store);\n return (\n \n \n {store.name}\n \n\n \n {store.address}\n\n {store.description}\n\n {store.reviews.map((review, ind) => (\n \n ))}\n \n \n \n );\n }}\n \n```\n\nThe interesting thing is that when I remove the `reviews` from the query I don't get the error. However, in the GraphQL playground it works fine, so I know the data is there. Also, if I refresh the page, it loads properly. It is only on the first load of the page that it errors out.\n\nCan anyone point me in the right direction for how to better structure this query? I know I am close, but I am missing something minor. Thanks!\n\n========================================\n\nCode:\n```text\nquery SINGLE_STORE_QUERY($id: ID!) {\n store(where: { id: $id }) {\n id\n name\n description\n image\n address\n lat\n lng\n reviews {\n user {\n name\n }\n text\n rating\n }\n }\n }\n```\n\n```text\n<Query\n query={SINGLE_STORE_QUERY}\n variables={{ id: this.props.id }}\n errorPolicy=\"all\"\n >\n {({ data: { store }, error, loading }) => {\n if (error) return <Error error={error} />;\n if (loading) return <p>Loading...</p>;\n\n console.log(store);\n return (\n <div>\n <StoreHero>\n <SingleTitle>{store.name}</SingleTitle>\n </StoreHero>\n\n <Container>\n <p className=\"location\">{store.address}</p>\n <p className=\"description\">{store.description}</p>\n {store.reviews.map((review, ind) => (\n <Review review={review} key={ind} />\n ))}\n <ReviewForm id={this.props.id} />\n </Container>\n </div>\n );\n }}\n </Query>\n```\n\n```text\nFetch API cannot load webpack://%5Bname%5D_%5Bchunkhash%5D/./node_modules/react-dom/cjs/react-dom.development.js?. URL scheme must be \"http\" or \"https\" for CORS request.\n```\n\n```text\nreviews\n```\n\n```text\nreact-error-overlay\n```\n\n```text\nReview\n```\n\n========================================\n\nComments:\n- This was exactly right. I should have come back and given an answer to this, but I forgot in the waves of relief after solving my mistakes. I had to go back into how I had setup the Reviews.","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":144,"estimatedTokens":814}}544{"id":"stack-59384531","source":"stackoverflow","questionId":59384531,"title":"GraphQL: How to pass Query Variables via playground?","tags":["graphql"],"text":"Title: GraphQL: How to pass Query Variables via playground?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI am following Andrew Mead's tutorial on Gatsby and for some reason I am having trouble with passing query variables to the query via GraphQL playground. As far as I can tell, the query works on node, as the contents of the 'blog' are being populated.\n\nHere is my code for the Query Variables (bottom left in GQL playground).\n\n```\n{\n \"slug\": \"example\"\n}\n```\n\nAnd the query I am making:\n\n```\nquery ($slug: String!) {\n markdownRemark (\n fields: {\n slug: {\n eq: $slug\n }\n }\n ) {\n frontmatter {\n title\n date\n }\n html\n }\n}\n```\n\nHowever, this results in error: `\"message\": \"Variable \\\"$slug\\\" of required type \\\"String!\\\" was not provided.\",`\n\nAfter playing around with making the variable required and not required, I am pretty sure it is because the query variable is not being passed, but I cannot figure out why as every other resource seems to do what Andrew Mead is doing. eg. Here\n\nThe strange thing is, the query seems to work when I run it on VS Code, but not on the playground. Is there a setting I am missing?\n\nEDIT 2019-12-18: It was a dumb mistake of mine. I had clicked on `HTTP HEADERS` on the bottom left, NOT `QUERY VARIABLES`, as Daniel Reardon kindly pointed out.\n\n========================================\n\nCode:\n```text\n{\n \"slug\": \"example\"\n}\n```\n\n```text\nquery ($slug: String!) {\n markdownRemark (\n fields: {\n slug: {\n eq: $slug\n }\n }\n ) {\n frontmatter {\n title\n date\n }\n html\n }\n}\n```\n\n```text\n\"message\": \"Variable \\\"$slug\\\" of required type \\\"String!\\\" was not provided.\",\n```\n\n```text\nHTTP HEADERS\n```\n\n```text\nQUERY VARIABLES\n```\n\n========================================\n\nComments:\n- Are you sure you're entering the variables into the variables input and not the headers input? The UI is a bit ambiguous.\n- @DanielRearden Ahh omg you're right. It was HTTP Headers that was highlighted. Stupid mistake of mine. Thank you so much!\n- holy crap, thanks! I wasted at least a couple of hours trying to find the formatting error in my query before finding your answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":88,"estimatedTokens":534}}545{"id":"stack-61709707","source":"stackoverflow","questionId":61709707,"title":"Apollo client's codegen adds unwanted \"or null\" in my types","tags":["graphql","apollo","typescript-typings","apollo-client"],"text":"Title: Apollo client's codegen adds unwanted \"or null\" in my types\nTags: graphql, apollo, typescript-typings, apollo-client\nSource: Stack Overflow\n\nQuestion:\nApollo client's codegen adds `| null` in the generated types, and I don't understand why they are there and how to get rid of them.\n\nI see no reason why the API would return an array of null, so I don't want to check in my code weather the oject is null or not everytime.\n\nOffending generated types from apollo codegen:\n\n```\nexport interface MusicGenres_musicGenres {\n name: string;\n}\n\nexport interface MusicGenres {\n musicGenres: (MusicGenres_musicGenres | null)[];\n ^^^^^^\n WHY ?\n}\n```\n\nMy Graphql Schema:\n\n```\ntype Query {\n musicGenres: [MusicGenre]!\n}\n\ntype MusicGenre {\n id: ID!\n name: String!\n}\n```\n\nQuery in my TypeScript code from which are generated the types:\n\n```\ngql`\n query MusicGenres {\n musicGenres { name }\n }\n`\n```\n\n========================================\n\nCode:\n```js\nexport interface MusicGenres_musicGenres {\n name: string;\n}\n\nexport interface MusicGenres {\n musicGenres: (MusicGenres_musicGenres | null)[];\n ^^^^^^\n WHY ?\n}\n```\n\n```text\ntype Query {\n musicGenres: [MusicGenre]!\n}\n\ntype MusicGenre {\n id: ID!\n name: String!\n}\n```\n\n```text\ngql`\n query MusicGenres {\n musicGenres { name }\n }\n`\n```\n\n```text\n| null\n```\n\n```text\nmusicGenres: [MusicGenre]!\n```\n\n```text\nmusicGenres: [MusicGenre!]!\n```\n\n```text\nmusicGenres\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":95,"estimatedTokens":373}}546{"id":"stack-58904569","source":"stackoverflow","questionId":58904569,"title":"Managing multiple calls to the same Apollo mutation","tags":["javascript","reactjs","graphql","apollo"],"text":"Title: Managing multiple calls to the same Apollo mutation\nTags: javascript, reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nSo taking a look at the Apollo useMutation example in the docs https://www.apollographql.com/docs/react/data/mutations/#tracking-loading-and-error-states\n\n```\nfunction Todos() {\n...\n const [\n updateTodo,\n { loading: mutationLoading, error: mutationError },\n ] = useMutation(UPDATE_TODO);\n...\n\n return data.todos.map(({ id, type }) => {\n let input;\n\n return (\n \n {type}\n\n {\n e.preventDefault();\n updateTodo({ variables: { id, type: input.value } });\n\n input.value = '';\n }}\n >\n {\n input = node;\n }}\n />\n Update Todo\n \n {mutationLoading && Loading...\n\n}\n {mutationError && Error :( Please try again\n\n}\n \n );\n });\n}\n```\n\nThis seems to have a major flaw (imo), updating any of the todos will show the loading state for every single todo, not just the one that has the pending mutation. \n\nhttps://i.sstatic.net/mUf2I.gif\n\nAnd this seems to stem from a larger problem: there's no way to track the state of multiple calls to the same mutation. So even if I did want to only show the loading state for the todos that were actually loading, there's no way to do that since we only have the concept of \"is loading\" not \"is loading for todo X\". \n\nBesides manually tracking loading state outside of Apollo, the only decent solution I can see is splitting out a separate component, use that to render each Todo instead of having that code directly in the Todos component, and having those components each initialize their own mutation. I'm not sure if I think that's a good or bad design, but in either case it doesn't feel like I should have to change the structure of my components to accomplish this.\n\nAnd this also extends to error handling. What if I update one todo, and then update another while the first update is in progress. If the first call errors, will that be visible at all in the `data` returned from `useMutation`? What about the second call? \n\nIs there a native Apollo way to fix this? And if not, are there options for handling this that may be better than the ones I've mentioned? \n\nCode Sandbox: https://codesandbox.io/s/v3mn68xxvy\n\n========================================\n\nCode:\n```text\nfunction Todos() {\n...\n const [\n updateTodo,\n { loading: mutationLoading, error: mutationError },\n ] = useMutation(UPDATE_TODO);\n...\n\n return data.todos.map(({ id, type }) => {\n let input;\n\n return (\n <div key={id}>\n <p>{type}</p>\n <form\n onSubmit={e => {\n e.preventDefault();\n updateTodo({ variables: { id, type: input.value } });\n\n input.value = '';\n }}\n >\n <input\n ref={node => {\n input = node;\n }}\n />\n <button type=\"submit\">Update Todo</button>\n </form>\n {mutationLoading && <p>Loading...</p>}\n {mutationError && <p>Error :( Please try again</p>}\n </div>\n );\n });\n}\n```\n\n```text\ndata\n```\n\n```text\nuseMutation\n```\n\n```text\nconst [updateA, { loading: loadingA, error: errorA }] = useMutation(YOUR_MUTATION)\nconst [updateB, { loading: loadingB, error: errorB }] = useMutation(YOUR_MUTATION)\nconst [updateC, { loading: loadingC, error: errorC }] = useMutation(YOUR_MUTATION)\n```\n\n```text\nconst ToDo = ({ id, type }) => {\n const [value, setValue] = useState('')\n const options = { variables = { id, type: value } }\n const [updateTodo, { loading, error }] = useMutation(UPDATE_TODO, options)\n const handleChange = event => setValue(event.target.value)\n\n return (\n <div>\n <p>{type}</p>\n <form onSubmit={updateTodo}>\n <input\n value={value}\n onChange={handleChange}\n />\n <button type=\"submit\">Update Todo</button>\n </form>\n </div>\n )\n}\n\n// back in our original component...\n\nreturn data.todos.map(({ id, type }) => (\n <Todo key={id} id={id} type={type] />\n))\n```\n\n```text\nuseQuery\n```\n\n```text\nuseMutation\n```\n\n```text\nfetchMore\n```\n\n========================================\n\nComments:\n- I'm kind of confused by your question. It's not that apollo doesn't have unique / multiple loading states, its your code that only has one `mutationLoading`. state that you pass to your todos. the same state gets passed to all of them, so even if apollo had something you want, your code still wouldn't be making use of it. it would have to be something like `loadingId === id` at the very least. Anyways your problem is completely solved by calling `useMutation` at the item level, not the list level. that's not a workaround, it's perfectly sane solution\n- on another note, apollo does keep track of which query is running. so you could combine your `isLoading` with the knowledge of which variable was being passed to the mutation, though I would consider that to be a much worse solution\n- I know that the current code wouldn't take advantage of any per-item state returned from useMutation. I know you'd wanna do something like `loadingId === id`, but `loadingId` isn't available.\n- As for \"you could combine your isLoading with the knowledge of which variable was being passed to the mutation\", how would that work if multiple mutations were in progress at the same time? `loading` would mean nothing if I don't know exactly which mutations are the ones actually `loading`.\n- And as for pushing the mutation down to the item level, I don't disagree that that's a sane solution, but it does have drawbacks. Namely, the parent component loses any insight into the loading state of its items. Say I wanted to surface loading state for the todo items in the `Todos` component (for some reason) I would either lose that ability, or need to add some sort of `onLoading` callback to the `Todo` components, and still manually keep track of loading state in `Todos`.\n- that's a fair point. You should be able to get the variables used in the mutation `const [mutation, { loading, error, variables } = useMutation(..)` though for some in the docs it only shows that for `useQuery`. Hmm there is an issue there though as you mention. I'm trying to think of what apollo would need to implement here to satisfy this.. it would have to return a list of pending queries. it might do that actually somewhere\n- Sounds like you want something like a list of all in flight queries, here's a recent possibly relevant questions stackoverflow.com/a/58029443/3225108","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":167,"estimatedTokens":1605}}547{"id":"stack-61314336","source":"stackoverflow","questionId":61314336,"title":"When to use vs page query in Gatsby?","tags":["reactjs","graphql","gatsby"],"text":"Title: When to use vs page query in Gatsby?\nTags: reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nAs I understand in Gatsby, a page query would be made at the parent level and would be passed down as props to the children components. And a `` or the `useStaticQuery` hook when you are inside a component and want to obtain some data to pass into it. What is the best practice and when should I use one over another?\n\nI'm guessing this comes down to React itself and if for example, we have components that need data at a deep level we would use `Context` and pass that down so you do not have to pass down props at deeper levels. Is it the same as this? Also if anyone has any patterns they use.\n\n========================================\n\nCode:\n```text\n<StatiQuery />\n```\n\n```text\nuseStaticQuery\n```\n\n```text\nContext\n```\n\n========================================\n\nComments:\n- Thank you I will look into these resources as you mentioned!","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":28,"estimatedTokens":237}}548{"id":"stack-56795531","source":"stackoverflow","questionId":56795531,"title":"Bootstraping Strapi Role Permissions","tags":["javascript","node.js","graphql","strapi"],"text":"Title: Bootstraping Strapi Role Permissions\nTags: javascript, node.js, graphql, strapi\nSource: Stack Overflow\n\nQuestion:\nI am a developer that is doing front end work, strapi and javascript for the first time. I hope someone could take pity on me and provide an example of how to set the Public role permissions via a bootstrap.js script.\nnode.js v10.16.0\n\nStrapi v3.0.0-next.11\n\nGraphql 14.3.1\n\nMongoDB: 3.6\n\nAll on Windows 10\n\nIn the Strapi UI, it is the Roles and Permissions for the Public Role\nhttps://i.sstatic.net/oCUq1.jpg\n\n(source: strapi.io)\n\nI want to set these boxes to CHECKED\nhttps://i.sstatic.net/QwcMP.jpg\n\n(source: strapi.io)\n\nAnother developer has used the bootstrap.js file to add items to the services we created (menu). I don't know how to return even the most basic information on the role permissions.\nMy function is called test() I searched for examples and the best I found was this on stackoverflow:\nStrapi Plugin Route Default Permission :\n\n```\nstrapi.plugins['users-permissions'].models.role.find\n```\n\nbut I cannot figure out how to use it:\n\n```\nWORKING\nfunction add_widgets_from_sheet(sheet_name, model_object){\n console.log(`adding ${sheet_name}`)\n let xlsxSheet = Sheets[sheet_name]\n const widgets = XLSX.utils.sheet_to_json(xlsxSheet)\n\n widgets.forEach(function (widget) {\n //See if the object is already in the db before adding it\n model_object.count(widget)\n .then(result => {\n if (result == 0) {\n console.log('Adding '+sheet_name+': ' + JSON.stringify(widget))\n return model_object.add(widget)\n }\n })\n })\n}\n\nNOT WORKING\nfunction test(){\n console.log(`Testing ${strapi.plugins['users-permissions'].models.role.find}`)\n}\n\nmodule.exports = next => {\n\n console.log('Starting Strapi bootstrap')\n add_widgets_from_sheet('Menus', strapi.services.menu) //adding menus\n test() // Returning nothing\n console.log('Ending Strapi bootstrap')\n next()\n}\n```\n\nI would like to toggle those checkboxes to TRUE, CHECKED or whatever its called. so that we don't have to manually do it through the UI everytime we dump the database.\n\nI learn best from examples...I hope you can help. Thank you!\n\n========================================\n\nTop Answer:\nBuilding on both of the previous answers, it seems you can get away with a single loop and in that you can set permissions for both `public` and `authenticated` users.\n\nThis was written against strapi `3.2.4` and I'm using NodeJS 12 so things like the spread operator `...` are available.\n\n```\nconst permOrm = strapi.query('permission', 'users-permissions')\n const perms = await permOrm.find({ type: 'application' })\n for (const curr of perms) {\n if (curr.role.type === 'authenticated') {\n strapi.log.info(\n `Allowing authenticated to call ${curr.controller}.${curr.action}`,\n )\n permOrm.update({ id: curr.id }, { ...curr, enabled: true })\n continue\n }\n // permission is for public\n const isReadEndpoint = ['find', 'findone', 'count'].includes(curr.action)\n if (isReadEndpoint) {\n strapi.log.info(\n `Allowing public to call ${curr.controller}.${curr.action}`,\n )\n permOrm.update({ id: curr.id }, { ...curr, enabled: true })\n continue\n }\n // TODO add custom logic for any non-standard actions here\n strapi.log.info(\n `Disallowing public from calling ${curr.controller}.${curr.action}`,\n )\n permOrm.update({ id: curr.id }, { ...curr, enabled: false })\n }\n```\n\n========================================\n\nCode:\n```js\nstrapi.plugins['users-permissions'].models.role.find\n```\n\n```js\nWORKING\nfunction add_widgets_from_sheet(sheet_name, model_object){\n console.log(`adding ${sheet_name}`)\n let xlsxSheet = Sheets[sheet_name]\n const widgets = XLSX.utils.sheet_to_json(xlsxSheet)\n\n widgets.forEach(function (widget) {\n //See if the object is already in the db before adding it\n model_object.count(widget)\n .then(result => {\n if (result == 0) {\n console.log('Adding '+sheet_name+': ' + JSON.stringify(widget))\n return model_object.add(widget)\n }\n })\n })\n}\n\nNOT WORKING\nfunction test(){\n console.log(`Testing ${strapi.plugins['users-permissions'].models.role.find}`)\n}\n\nmodule.exports = next => {\n\n console.log('Starting Strapi bootstrap')\n add_widgets_from_sheet('Menus', strapi.services.menu) //adding menus\n test() // Returning nothing\n console.log('Ending Strapi bootstrap')\n next()\n}\n```\n\n```text\n'use strict'\n```\n\n```text\nrequire('dotenv').config({ path:'../.env' })\n```\n\n```text\nconst XLSX = require('xlsx')\nconst BOOTSTRAP_DATA = XLSX.readFile(process.env.BOOTSTRAP_DATA).Sheets\n```\n\n```text\nconst ADMIN_USERNAME = process.env.ADMIN_USERNAME\nconst ADMIN_PASSWORD = process.env.ADMIN_PASSWORD\nconst ADMIN_EMAIL = process.env.ADMIN_EMAIL\n```\n\n```text\nasync function bootstrap_resource(resource_type, resource_service) {\n strapi.log.info(`Bootstrapping ${resource_type}`)\n\n const resources = XLSX.utils.sheet_to_json(BOOTSTRAP_DATA[resource_type])\n\n for (let resource of resources) {\n\n if (await resource_service.count(resource) === 0) {\n strapi.log.warn(`Bootstrapping ${resource_type}: ${JSON.stringify(resource)}`)\n\n await resource_service.create(resource)\n }\n }\n}\n```\n\n```text\nasync function bootstrap_admin() {\n strapi.log.info(`Bootstrapping Admin`)\n\n const admin_orm = strapi.admin.queries('administrator', 'admin')\n\n const admins = await admin_orm.find({username: ADMIN_USERNAME})\n\n if ( admins.length === 0) {\n const blocked = false\n const username = ADMIN_USERNAME\n const password = await strapi.admin.services.auth.hashPassword(ADMIN_PASSWORD)\n const email = ADMIN_EMAIL\n const user = { blocked, username, password, email }\n\n const data = await admin_orm.create(user)\n\n strapi.log.warn(`Bootstrapped Admin User: ${JSON.stringify(user)}`)\n }\n}\n```\n\n```text\nasync function get_roles() {\n const role_orm = strapi.plugins['users-permissions'].queries('role', 'users-permissions')\n\n const role_list = await role_orm.find({}, [])\n\n const roles = {}\n\n for (let role of role_list) {\n roles[ role._id ] = role\n roles[ role.name ] = role\n }\n\n return roles\n}\n\nasync function get_permissions( selected_role, selected_type, selected_controller ) {\n const roles = await get_roles()\n const permission_orm = strapi.plugins['users-permissions'].queries('permission', 'users-permissions')\n\n let permission_list = await permission_orm.find({_limit: 999}, [])\n\n if ( selected_role ) permission_list = permission_list.filter( ({ role }) => `${role}` === `${roles[selected_role]._id}` )\n if ( selected_type ) permission_list = permission_list.filter( ({ type }) => `${type}` === `${selected_type}` )\n if ( selected_controller ) permission_list = permission_list.filter( ({ controller }) => `${controller}` === `${selected_controller}` )\n\n return permission_list\n}\n\nasync function enable_permissions(role, type, controller) {\n strapi.log.info(`Setting '${controller}' permissions for '${role}'`)\n\n const permission_orm = strapi.plugins['users-permissions'].queries('permission', 'users-permissions')\n\n const permissions = await get_permissions(role, type, controller)\n\n for (let { _id } of permissions) {\n permission_orm.update({ _id }, { enabled: true })\n }\n}\n```\n\n```text\nmodule.exports = async next => {\n\n await bootstrap_admin()\n\n await bootstrap_resource( 'Clients', strapi.services.client )\n await bootstrap_resource( 'Menus', strapi.services.menu )\n\n enable_permissions('Public', 'application', 'client' )\n enable_permissions('Public', 'application', 'github' )\n enable_permissions('Public', 'application', 'menu' )\n enable_permissions('Public', 'application', 'confluence' )\n\n next()\n}\n```\n\n```js\n// In your bootstrap.js file\n'use strict';\nmodule.exports = async () => {\n\n const authenticated = await strapi.query('role', 'users-permissions').findOne({ type: 'authenticated' });\n authenticated.permissions.forEach(permission => {\n\n if (permission.type === 'application'){ // Whatever permissions you want to change\n let newPermission = permission;\n newPermission.enabled = true; // Editing permission as needed\n\n strapi.query('permission', 'users-permissions').update( { id: newPermission.id }, newPermission ); // Updating Strapi with the permission\n }\n });\n return;\n};\n```\n\n```js\nconst permOrm = strapi.query('permission', 'users-permissions')\n const perms = await permOrm.find({ type: 'application' })\n for (const curr of perms) {\n if (curr.role.type === 'authenticated') {\n strapi.log.info(\n `Allowing authenticated to call ${curr.controller}.${curr.action}`,\n )\n permOrm.update({ id: curr.id }, { ...curr, enabled: true })\n continue\n }\n // permission is for public\n const isReadEndpoint = ['find', 'findone', 'count'].includes(curr.action)\n if (isReadEndpoint) {\n strapi.log.info(\n `Allowing public to call ${curr.controller}.${curr.action}`,\n )\n permOrm.update({ id: curr.id }, { ...curr, enabled: true })\n continue\n }\n // TODO add custom logic for any non-standard actions here\n strapi.log.info(\n `Disallowing public from calling ${curr.controller}.${curr.action}`,\n )\n permOrm.update({ id: curr.id }, { ...curr, enabled: false })\n }\n```\n\n```text\npublic\n```\n\n```text\nauthenticated\n```\n\n```text\n3.2.4\n```\n\n```text\n...\n```\n\n```js\n'use strict';\n\nmodule.exports = async () => {\n const publicRole = await getRoleByName('Public')\n await grantPermissions(publicRole, 'application', 'images', ['upload', 'remove']) // upload, remove in 'images' controller\n await grantPermissions(publicRole, 'application', 'project') // any action in 'project' controller \n};\n\nasync function getRoleByName(name) {\n return strapi.query('role', 'users-permissions').findOne({ name }, [])\n}\n\nasync function getPermissions(role, permissionType, controller, actions = null) {\n const permissionQuery = strapi.query('permission', 'users-permissions')\n const permissionRequest = {\n _limit: 1000,\n role: role.id,\n type: permissionType,\n controller: controller\n }\n\n if (actions) {\n permissionRequest.action_in = Array.isArray(actions) ? actions : [actions]\n }\n\n return permissionQuery.find(permissionRequest, [])\n}\n\nasync function grantPermissions(role, permissionType, controller, actions) {\n if (actions && !Array.isArray(actions)) {\n actions = [ actions ]\n }\n strapi.log.info(`Setting '${controller}' [${actions ? actions.join(', ') : '*'}] permissions for '${role.name}'`)\n\n const permissionQuery = strapi.query('permission', 'users-permissions')\n const permissions = await getPermissions(role, permissionType, controller, actions)\n if (permissions.length === 0) {\n throw new Error(`Error enabling permissions: ${role.name}, ${permissionType}, ${controller}, ${actions}`)\n }\n\n for (const { id } of permissions) {\n await permissionQuery.update({ id }, { enabled: true })\n }\n}\n```\n\n```text\n3.3.x\n```\n\n========================================\n\nComments:\n- strapi.plugins.users-permissions.models.permission.update is not a function?\n- You already figured it out in your answer but for anyone else, you need to do `strapi.query('permission', 'users-permissions')` now. Taken from here\n- With Strapi 3.2.4, I get: `Error: The model administrator can't be found.` as part of the admin bootstrap routine.","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":387,"estimatedTokens":2844}}549{"id":"stack-37606819","source":"stackoverflow","questionId":37606819,"title":"Get data from parent node on field resolver","tags":["graphql"],"text":"Title: Get data from parent node on field resolver\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nSo what I'm trying to do its to make a `GraphQL` like this if possible:\n\n```\n{\n people {\n _id\n name\n acted {\n _id\n title\n coactors {\n name\n }\n }\n }\n}\n```\n\nSo what I'm doing, it's getting actors (people), then get the movies they acted, that works fine. So then I'm trying to get the co-actors in that movie. I'm thinking to pass the current actor's id to the co-actors field as an argument like this: \n\n```\n{\n people {\n _id\n name\n acted {\n _id\n title\n coactors(actor: people._id) {\n name\n }\n }\n }\n}\n```\n\nObviously, I'm getting an error and don't know if that could be made internally.\n\nSo here are my Types:\n\nconst MovieType = new GraphQLObjectType({\n name: 'movie',\n fields: () => ({\n _id: {\n type: GraphQLInt\n },\n title: {\n type: GraphQLString\n },\n tagline: {\n type: GraphQLString\n },\n released: {\n type: GraphQLInt\n },\n actors: {\n type: new GraphQLList(PersonType),\n resolve: (movie) => {\n return [];\n }\n },\n coactors: {\n type: new GraphQLList(PersonType),\n args: {\n actor: {\n type: GraphQLInt\n }\n },\n resolve: (movie, args) => {\n getCoActorsFor(movie, args.actor) // How can I do something like this\n .then((actors) => {\n return actors;\n })\n }\n }\n })\n});\n\nconst PersonType = new GraphQLObjectType({\n name: 'person',\n fields: ()=> ({\n _id: {\n type: GraphQLInt\n },\n name: {\n type: GraphQLString\n },\n born: {\n type: GraphQLInt\n },\n acted: {\n type: new GraphQLList(MovieType),\n resolve: (person) => {\n\n return [];\n\n }\n }\n })\n});\n\n========================================\n\nCode:\n```text\n{\n people {\n _id\n name\n acted {\n _id\n title\n coactors {\n name\n }\n }\n }\n}\n```\n\n```text\n{\n people {\n _id\n name\n acted {\n _id\n title\n coactors(actor: people._id) {\n name\n }\n }\n }\n}\n```\n\n```text\nconst MovieType = new GraphQLObjectType({\n name: 'movie',\n fields: () => ({\n _id: {\n type: GraphQLInt\n },\n title: {\n type: GraphQLString\n },\n tagline: {\n type: GraphQLString\n },\n released: {\n type: GraphQLInt\n },\n actors: {\n type: new GraphQLList(PersonType),\n resolve: (movie) => {\n return [];\n }\n },\n coactors: {\n type: new GraphQLList(PersonType),\n args: {\n actor: {\n type: GraphQLInt\n }\n },\n resolve: (movie, args) => {\n getCoActorsFor(movie, args.actor) // How can I do something like this\n .then((actors) => {\n return actors;\n })\n }\n }\n })\n});\n\nconst PersonType = new GraphQLObjectType({\n name: 'person',\n fields: ()=> ({\n _id: {\n type: GraphQLInt\n },\n name: {\n type: GraphQLString\n },\n born: {\n type: GraphQLInt\n },\n acted: {\n type: new GraphQLList(MovieType),\n resolve: (person) => {\n\n return [];\n\n }\n }\n })\n});\n```\n\n```text\nGraphQL\n```\n\n========================================\n\nComments:\n- Yeah I can handle it into the client, I wanted to know if there is maybe a way to access to the parent node, I was thinking maybe when we define de QueryType (?)\n- what are you talking about anti-pattern. From where are you drawing this conclusion that this is an antiparttern? From who? The whole point of resolvers is to be able to pass data from parent to child nodes just for this reason so that you can actually make meaningful and useful nodes. You have to have some data like Ids to get related data!","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":213,"estimatedTokens":944}}550{"id":"stack-37376631","source":"stackoverflow","questionId":37376631,"title":"How to use Relay/GraphQL with Loopback?","tags":["strongloop","graphql","loopback","relay"],"text":"Title: How to use Relay/GraphQL with Loopback?\nTags: strongloop, graphql, loopback, relay\nSource: Stack Overflow\n\nQuestion:\nAny working solutions of using Relay/GraphQL with Loopback? I guess a few things I'm considering are how to access the database (since I'm assuming going through the ORM wouldn't be possible) and how to leverage the api generators when using Relay/GraphQL...\n\n========================================\n\nTop Answer:\nI have created this npm library to generate GraphQL schema from loopback models: https://github.com/Tallyb/loopback-graphql\n\n========================================\n\nCode:\n```text\napp.use('/graphql', bodyParser.json(), graphqlExpress({schema}));\napp.use('graphiql', graphiqlExpress({\n endpointURL: \"/graphql\"\n}))\n```\n\n```text\napp\n```\n\n========================================\n\nComments:\n- You should create a middle layer(GraphQL), which `resolve` data from Loopback, and provide data to front-end(Relay)\n- Any examples for this by chance? Thank you!\n- Please elaborate. Link only answers are not enough, because they will become useless if the linked content goes down.","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":32,"estimatedTokens":278}}551{"id":"stack-48394636","source":"stackoverflow","questionId":48394636,"title":"Can you use fragments in graphql server schema file","tags":["graphql","graphql-java"],"text":"Title: Can you use fragments in graphql server schema file\nTags: graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nCan you use fragments in graphql server schema file? Could you please point me to an example","metadata":{"transformedAt":"2026-08-18T18:32:36.066Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":6,"estimatedTokens":54}}552{"id":"stack-61943014","source":"stackoverflow","questionId":61943014,"title":"GraphQL server with Deno","tags":["javascript","node.js","express","graphql","deno"],"text":"Title: GraphQL server with Deno\nTags: javascript, node.js, express, graphql, deno\nSource: Stack Overflow\n\nQuestion:\nIt works just once for the below code\n\n```\nimport {\n graphql,\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLString,\n buildSchema,\n} from \"https://cdn.pika.dev/graphql/^15.0.0\";\nimport { serve } from \"https://deno.land/std@0.50.0/http/server.ts\";\n\nvar schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: \"RootQueryType\",\n fields: {\n hello: {\n type: GraphQLString,\n resolve() {\n return \"world\";\n },\n },\n },\n }),\n});\n\nvar query = \"{ hello }\";\n\ngraphql(schema, query).then((result) => {\n console.log(result);\n});\n```\n\nHow to keep it listening, just like `express`\nSomething like this\n\n```\nvar express = require('express');\nvar graphqlHTTP = require('express-graphql');\nvar { buildSchema } = require('graphql');\n\n// Construct a schema, using GraphQL schema language\nvar schema = buildSchema(`\n type Query {\n hello: String\n }\n`);\n\n// The root provides a resolver function for each API endpoint\nvar root = {\n hello: () => {\n return 'Hello world!';\n },\n};\n\nvar app = express();\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n rootValue: root,\n graphiql: true,\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at http://localhost:4000/graphql');\n```\n\n========================================\n\nTop Answer:\nYou can now use https://deno.land/x/deno_graphql to achieve this goal.\n\nIt provides everything needed out-of-the-box and works with multiple Deno frameworks (oak, abc, attain, etc).\n\nThis is how you code looks like (with oak for example):\n\n```\nimport { Application, Context, Router } from \"https://deno.land/x/oak/mod.ts\";\nimport {\n gql,\n graphqlHttp,\n makeExecutableSchema,\n} from \"https://deno.land/x/deno_graphql/oak.ts\";\n\nconst typeDefs = gql`\n type Query {\n hello: String\n }\n`;\n\nconst resolvers = {\n Query: {\n hello: () => \"Hello world!\",\n },\n};\n\nconst context = (context: Context) => ({\n request: context.request,\n});\n\nconst schema = makeExecutableSchema({ typeDefs, resolvers });\n\nconst app = new Application();\nconst router = new Router();\n\nrouter.post(\"/graphql\", graphqlHttp({ schema, context }));\n\napp.use(router.routes());\n\nawait app.listen({ port: 4000 });\n```\n\nPS : i'm the author of the package, so you can ask me anything.\n\nHope this helps!\n\n========================================\n\nCode:\n```text\nimport {\n graphql,\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLString,\n buildSchema,\n} from \"https://cdn.pika.dev/graphql/^15.0.0\";\nimport { serve } from \"https://deno.land/std@0.50.0/http/server.ts\";\n\nvar schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: \"RootQueryType\",\n fields: {\n hello: {\n type: GraphQLString,\n resolve() {\n return \"world\";\n },\n },\n },\n }),\n});\n\nvar query = \"{ hello }\";\n\ngraphql(schema, query).then((result) => {\n console.log(result);\n});\n```\n\n```text\nvar express = require('express');\nvar graphqlHTTP = require('express-graphql');\nvar { buildSchema } = require('graphql');\n\n// Construct a schema, using GraphQL schema language\nvar schema = buildSchema(`\n type Query {\n hello: String\n }\n`);\n\n// The root provides a resolver function for each API endpoint\nvar root = {\n hello: () => {\n return 'Hello world!';\n },\n};\n\nvar app = express();\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n rootValue: root,\n graphiql: true,\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at http://localhost:4000/graphql');\n```\n\n```text\nexpress\n```\n\n```text\nimport {\n graphql,\n buildSchema,\n} from \"https://cdn.pika.dev/graphql/^15.0.0\";\nimport {Application, Router} from \"https://deno.land/x/oak/mod.ts\";\n\nvar schema = buildSchema(`\n type Query {\n hello: String\n }\n`);\n\nvar resolver = {hello: () => 'Hello world!'}\n\nconst executeSchema = async (query:any) => {\n const result = await graphql(schema, query, resolver); \n return result;\n}\n\nvar router = new Router();\n\nrouter.post(\"/graph\", async ({request, response}) => {\n if(request.hasBody) {\n const body = await request.body();\n const result = await executeSchema(body.value);\n response.body = result;\n } else {\n response.body = \"Query Unknown\";\n }\n})\n\n\nlet app = new Application();\napp.use(router.routes());\napp.use(router.allowedMethods());\nconsole.log(\"Server running\");\napp.listen({port: 5000})\n```\n\n```js\nimport {\n graphql,\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLString\n} from \"https://cdn.pika.dev/graphql/^15.0.0\";\n\nvar schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: \"RootQueryType\",\n fields: {\n hello: {\n type: GraphQLString,\n resolve() {\n return \"world\";\n },\n },\n },\n }),\n});\n\nexport async function querySchema(query: any) {\n return await graphql(schema, query)\n .then(async (result) => {\n return result;\n });\n}\n```\n\n```js\nimport { Application, Router } from \"https://deno.land/x/oak/mod.ts\";\nimport { querySchema } from \"./graphRepository.ts\";\n\nconst router = new Router();\n\nrouter\n .get(\"/graph/query/:value\", async (context) => {\n const queryValue: any = context.params.value;\n const query = `{ ${queryValue}}`\n const result = await querySchema(query);\n console.log(result)\n context.response.body = result;\n })\n\nconst app = new Application();\napp.use(router.routes());\napp.use(router.allowedMethods());\n\nawait app.listen({ port: 8000 });\n```\n\n```text\ngraphRepository.ts\n```\n\n```text\napp.ts\n```\n\n```text\nimport { Application } from \"https://deno.land/x/oak/mod.ts\";\nimport { applyGraphQL, gql } from \"https://deno.land/x/oak_graphql/mod.ts\";\n\nconst app = new Application();\n\napp.use(async (ctx, next) => {\n await next();\n const rt = ctx.response.headers.get(\"X-Response-Time\");\n console.log(`${ctx.request.method} ${ctx.request.url} - ${rt}`);\n});\n\napp.use(async (ctx, next) => {\n const start = Date.now();\n await next();\n const ms = Date.now() - start;\n ctx.response.headers.set(\"X-Response-Time\", `${ms}ms`);\n});\n\nconst types = gql`\ntype User {\n firstName: String\n lastName: String\n}\n\ninput UserInput {\n firstName: String\n lastName: String\n}\n\ntype ResolveType {\n done: Boolean\n}\n\ntype Query {\n getUser(id: String): User \n}\n\ntype Mutation {\n setUser(input: UserInput!): ResolveType!\n}\n`;\n\nconst resolvers = {\n Query: {\n getUser: (parent: any, {id}: any, context: any, info: any) => {\n console.log(\"id\", id, context);\n return {\n firstName: \"wooseok\",\n lastName: \"lee\",\n };\n },\n },\n Mutation: {\n setUser: (parent: any, {firstName, lastName}: any, context: any, info: any) => {\n console.log(\"input:\", firstName, lastName);\n return {\n done: true,\n };\n },\n },\n};\n\nconst GraphQLService = applyGraphQL({\n typeDefs: types,\n resolvers: resolvers\n})\n\napp.use(GraphQLService.routes(), GraphQLService.allowedMethods());\n\nconsole.log(\"Server start at http://localhost:8080\");\nawait app.listen({ port: 8080 });\n```\n\n```js\nimport { Application, Context, Router } from \"https://deno.land/x/oak/mod.ts\";\nimport {\n gql,\n graphqlHttp,\n makeExecutableSchema,\n} from \"https://deno.land/x/deno_graphql/oak.ts\";\n\nconst typeDefs = gql`\n type Query {\n hello: String\n }\n`;\n\nconst resolvers = {\n Query: {\n hello: () => \"Hello world!\",\n },\n};\n\nconst context = (context: Context) => ({\n request: context.request,\n});\n\nconst schema = makeExecutableSchema({ typeDefs, resolvers });\n\nconst app = new Application();\nconst router = new Router();\n\nrouter.post(\"/graphql\", graphqlHttp({ schema, context }));\n\napp.use(router.routes());\n\nawait app.listen({ port: 4000 });\n```\n\n```text\nimport { serve } from 'https://deno.land/std@0.90.0/http/server.ts'\nimport { GraphQLHTTP } from 'https://deno.land/x/gql/mod.ts'\nimport { makeExecutableSchema } from 'https://deno.land/x/graphql_tools/mod.ts'\nimport { gql } from 'https://deno.land/x/graphql_tag/mod.ts'\n\nconst typeDefs = gql`\n type Query {\n hello: String\n }\n`\n\nconst resolvers = {\n Query: {\n hello: () => `Hello World!`\n }\n}\n\nconst schema = makeExecutableSchema({ resolvers, typeDefs })\n\nconst s = serve({ port: 3000 })\n\nfor await (const req of s) {\n req.url.startsWith('/graphql')\n ? await GraphQLHTTP({\n schema,\n graphiql: true\n })(req)\n : req.respond({\n status: 404\n })\n}\n```\n\n```text\nstd/http\n```\n\n========================================\n\nComments:\n- @HemantMetallia I rewrote my answer see if that solves your problem","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":438,"estimatedTokens":2149}}553{"id":"stack-54265160","source":"stackoverflow","questionId":54265160,"title":"GET query missing: Implementing GraphQL Using Apollo On an Express Server","tags":["node.js","express","graphql","apollo","apollo-server"],"text":"Title: GET query missing: Implementing GraphQL Using Apollo On an Express Server\nTags: node.js, express, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm following the tutorial here: Implementing GraphQL Using Apollo On an Express Server and I'm getting the error **GET query missing** in the browser at http://localhost:7700/graphql.\n\nFirst I typed all the code myself. When I encountered the error, I downloaded the code from GitHub: kimobrian/GraphQL-Express: An Express Server implemented using GraphQL to eliminate the possibility that I had made a mistake. However, I'm still getting the same error.\n\nI presume it is better to provide the link to the repo rather than paste the code here because I'm using the same code from the repo. Also, I am not sure which file might contain the problem.\n\n```\n$ npm start\n\n> tutorial-server@1.0.0 start kimobrian/GraphQL-Express.git\n> nodemon ./server.js --exec babel-node -e js\n\n[nodemon] 1.18.9\n[nodemon] to restart at any time, enter `rs`\n[nodemon] watching: *.*\n[nodemon] starting `babel-node ./server.js`\nGraphQL Server is now running on http://localhost:7700\n```\n\nThe error is **GET query missing** in the browser at http://localhost:7700/graphql. It's the same in Firefox and Chromium.\n\nUpdate: The only question I find with relevant information is here: nodejs with Graphql. The suggested solution is \n\n```\nserver.use('/graphiql', graphiqlExpress({\n endpointURL: '/graphql',\n}));\n```\n\nHowever, that's exactly the code I have already (from the tutorial). Here is my entire `server.js`:\n\n```\nimport express from 'express';\nimport cors from 'cors';\n\nimport {\n graphqlExpress,\n graphiqlExpress,\n} from 'graphql-server-express';\n\nimport bodyParser from 'body-parser';\n\nimport { schema } from './src/schema';\n\nconst PORT = 7700;\nconst server = express();\nserver.use('*', cors({ origin: 'http://localhost:7800' }));\n\nserver.use('/graphql', bodyParser.json(), graphqlExpress({\n schema\n}));\n\nserver.use('/graphiql', graphiqlExpress({\n endpointURL: '/graphql'\n}));\n\nserver.listen(PORT, () =>\n console.log(`GraphQL Server is now running on http://localhost:${PORT}`)\n);\n```\n\n========================================\n\nTop Answer:\nI fixed it by addding two fields into Apollo Server constructor: `playground: true` and `introspection: true`:\n\n```\nconst apolloServer = new ApolloServer({\n schema,\n context: (ctx: Context) => ctx,\n playground: true,\n introspection: true,\n});\n```\n\n**Note:** Beware that cors should be set up properly for your graphql server to be able to answer requests.\n\nFound here.\n\n========================================\n\nCode:\n```text\n$ npm start\n\n> tutorial-server@1.0.0 start kimobrian/GraphQL-Express.git\n> nodemon ./server.js --exec babel-node -e js\n\n[nodemon] 1.18.9\n[nodemon] to restart at any time, enter `rs`\n[nodemon] watching: *.*\n[nodemon] starting `babel-node ./server.js`\nGraphQL Server is now running on http://localhost:7700\n```\n\n```text\nserver.use('/graphiql', graphiqlExpress({\n endpointURL: '/graphql',\n}));\n```\n\n```text\nimport express from 'express';\nimport cors from 'cors';\n\nimport {\n graphqlExpress,\n graphiqlExpress,\n} from 'graphql-server-express';\n\nimport bodyParser from 'body-parser';\n\nimport { schema } from './src/schema';\n\nconst PORT = 7700;\nconst server = express();\nserver.use('*', cors({ origin: 'http://localhost:7800' }));\n\nserver.use('/graphql', bodyParser.json(), graphqlExpress({\n schema\n}));\n\nserver.use('/graphiql', graphiqlExpress({\n endpointURL: '/graphql'\n}));\n\nserver.listen(PORT, () =>\n console.log(`GraphQL Server is now running on http://localhost:${PORT}`)\n);\n```\n\n```text\nserver.js\n```\n\n```text\nconst server = new ApolloServer({ typeDefs, resolvers });\n\nconst port = 7700;\n\nserver.listen({ port });\n```\n\n```text\nconst server = new ApolloServer({ typeDefs, resolvers });\n\nconst app = express();\nserver.applyMiddleware({ app });\n\nconst port = 7700;\n\napp.listen({ port });\n```\n\n```text\napollo-server-express\n```\n\n```text\ncors\n```\n\n```text\nbody-parser\n```\n\n```text\napollo-server-express\n```\n\n```text\nconst apolloServer = new ApolloServer({\n schema,\n context: (ctx: Context) => ctx,\n playground: true,\n introspection: true,\n});\n```\n\n```text\nplayground: true\n```\n\n```text\nintrospection: true\n```\n\n========================================\n\nComments:\n- Check your package version. Its seems your package name changed to require('apollo-server-express') npmjs.com/package/graphql-server-express. Use this one to integrate GraphQL on Express graphql.org/graphql-js/running-an-express-graphql-server\n- I am getting same issue with fastify. I have followed the steps from - npmjs.com/package/apollo-server-fastify. On hitting localhost:3000/graphql it is giving me 'Get Query missing'. Please help\n- @khushboo29 Please open a new question with all relevant code.\n- Yeah, I opened one - stackoverflow.com/questions/63072227/…\n- I searched everywhere, but only the `playground: true` parameter helped","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":200,"estimatedTokens":1236}}554{"id":"stack-50502781","source":"stackoverflow","questionId":50502781,"title":"Limiting SQL query to defined fields/columns in Graphene-SQLAlchemy","tags":["python","sql","sqlalchemy","graphql","graphene-python"],"text":"Title: Limiting SQL query to defined fields/columns in Graphene-SQLAlchemy\nTags: python, sql, sqlalchemy, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nThis question has been posted as a GH issues under https://github.com/graphql-python/graphene-sqlalchemy/issues/134 but I thought I'd post it here too to tap into the SO crowd.\n\nA full working demo can be found under https://github.com/somada141/demo-graphql-sqlalchemy-falcon.\n\nConsider the following SQLAlchemy ORM class:\n\n```\nclass Author(Base, OrmBaseMixin):\n __tablename__ = \"authors\"\n\n author_id = sqlalchemy.Column(\n sqlalchemy.types.Integer(),\n primary_key=True,\n )\n\n name_first = sqlalchemy.Column(\n sqlalchemy.types.Unicode(length=80),\n nullable=False,\n )\n\n name_last = sqlalchemy.Column(\n sqlalchemy.types.Unicode(length=80),\n nullable=False,\n )\n```\n\nSimply wrapped in an `SQLAlchemyObjectType` as such:\n\n```\nclass TypeAuthor(SQLAlchemyObjectType):\n class Meta:\n model = Author\n```\n\nand exposed through:\n\n```\nauthor = graphene.Field(\n TypeAuthor,\n author_id=graphene.Argument(type=graphene.Int, required=False),\n name_first=graphene.Argument(type=graphene.String, required=False),\n name_last=graphene.Argument(type=graphene.String, required=False),\n)\n\n@staticmethod\ndef resolve_author(\n args,\n info,\n author_id: Union[int, None] = None,\n name_first: Union[str, None] = None,\n name_last: Union[str, None] = None,\n):\n query = TypeAuthor.get_query(info=info)\n\n if author_id:\n query = query.filter(Author.author_id == author_id)\n\n if name_first:\n query = query.filter(Author.name_first == name_first)\n\n if name_last:\n query = query.filter(Author.name_last == name_last)\n\n author = query.first()\n\n return author\n```\n\nA GraphQL query such as:\n\n```\nquery GetAuthor{\n author(authorId: 1) {\n nameFirst\n }\n}\n```\n\nwill cause the following raw SQL to be emitted (taken from the echo logs of the SQLA engine):\n\n```\nSELECT authors.author_id AS authors_author_id, authors.name_first AS authors_name_first, authors.name_last AS authors_name_last\nFROM authors\nWHERE authors.author_id = ?\n LIMIT ? OFFSET ?\n2018-05-24 16:23:03,669 INFO sqlalchemy.engine.base.Engine (1, 1, 0)\n```\n\nAs one can see we may only want the `nameFirst` field, i.e., the `name_first` column but the entire row is fetched. Of course the GraphQL response only contains the requested fields, i.e.,\n\n```\n{\n \"data\": {\n \"author\": {\n \"nameFirst\": \"Robert\"\n }\n }\n}\n```\n\nbut we have still fetched the entire row, which becomes a major issue when dealing with wide tables.\n\nIs there a way to automagically communicate which columns are needed to SQLAlchemy so as preclude this form of over-fetching?\n\n========================================\n\nCode:\n```text\nclass Author(Base, OrmBaseMixin):\n __tablename__ = \"authors\"\n\n author_id = sqlalchemy.Column(\n sqlalchemy.types.Integer(),\n primary_key=True,\n )\n\n name_first = sqlalchemy.Column(\n sqlalchemy.types.Unicode(length=80),\n nullable=False,\n )\n\n name_last = sqlalchemy.Column(\n sqlalchemy.types.Unicode(length=80),\n nullable=False,\n )\n```\n\n```text\nclass TypeAuthor(SQLAlchemyObjectType):\n class Meta:\n model = Author\n```\n\n```text\nauthor = graphene.Field(\n TypeAuthor,\n author_id=graphene.Argument(type=graphene.Int, required=False),\n name_first=graphene.Argument(type=graphene.String, required=False),\n name_last=graphene.Argument(type=graphene.String, required=False),\n)\n\n@staticmethod\ndef resolve_author(\n args,\n info,\n author_id: Union[int, None] = None,\n name_first: Union[str, None] = None,\n name_last: Union[str, None] = None,\n):\n query = TypeAuthor.get_query(info=info)\n\n if author_id:\n query = query.filter(Author.author_id == author_id)\n\n if name_first:\n query = query.filter(Author.name_first == name_first)\n\n if name_last:\n query = query.filter(Author.name_last == name_last)\n\n author = query.first()\n\n return author\n```\n\n```text\nquery GetAuthor{\n author(authorId: 1) {\n nameFirst\n }\n}\n```\n\n```text\nSELECT authors.author_id AS authors_author_id, authors.name_first AS authors_name_first, authors.name_last AS authors_name_last\nFROM authors\nWHERE authors.author_id = ?\n LIMIT ? OFFSET ?\n2018-05-24 16:23:03,669 INFO sqlalchemy.engine.base.Engine (1, 1, 0)\n```\n\n```text\n{\n \"data\": {\n \"author\": {\n \"nameFirst\": \"Robert\"\n }\n }\n}\n```\n\n```text\nSQLAlchemyObjectType\n```\n\n```text\nnameFirst\n```\n\n```text\nname_first\n```\n\n```text\ndef get_field_names(info):\n \"\"\"\n Parses a query info into a list of composite field names.\n For example the following query:\n {\n carts {\n edges {\n node {\n id\n name\n ...cartInfo\n }\n }\n }\n }\n fragment cartInfo on CartType { whatever }\n\n Will result in an array:\n [\n 'carts',\n 'carts.edges',\n 'carts.edges.node',\n 'carts.edges.node.id',\n 'carts.edges.node.name',\n 'carts.edges.node.whatever'\n ]\n \"\"\"\n\n fragments = info.fragments\n\n def iterate_field_names(prefix, field):\n name = field.name.value\n\n if isinstance(field, FragmentSpread):\n _results = []\n new_prefix = prefix\n sub_selection = fragments[field.name.value].selection_set.selections\n else:\n _results = [prefix + name]\n new_prefix = prefix + name + \".\"\n if field.selection_set:\n sub_selection = field.selection_set.selections\n else:\n sub_selection = []\n\n for sub_field in sub_selection:\n _results += iterate_field_names(new_prefix, sub_field)\n\n return _results\n\n results = iterate_field_names('', info.field_asts[0])\n\n return results\n```\n\n```text\nfields = get_field_names(info=info)\nquery = TypeAuthor.get_query(info=info).options(load_only(*relation_fields))\n```\n\n```text\nquery GetAuthor{\n author(authorId: 1) {\n nameFirst\n }\n}\n```\n\n```text\nINFO:sqlalchemy.engine.base.Engine:SELECT authors.author_id AS authors_author_id, authors.name_first AS authors_name_first\nFROM authors\nWHERE authors.author_id = ?\n LIMIT ? OFFSET ?\n2018-06-09 13:22:16,396 INFO sqlalchemy.engine.base.Engine (1, 1, 0)\n```\n\n```text\nfrom typing import List, Dict, Union, Type\n\nimport graphql\nfrom graphql.language.ast import FragmentSpread\nfrom graphql.language.ast import Field\nfrom graphene.utils.str_converters import to_snake_case\nimport sqlalchemy.orm\n\nfrom demo.orm_base import OrmBaseMixin\n\ndef extract_requested_fields(\n info: graphql.execution.base.ResolveInfo,\n fields: List[Union[Field, FragmentSpread]],\n do_convert_to_snake_case: bool = True,\n) -> Dict:\n \"\"\"Extracts the fields requested in a GraphQL query by processing the AST\n and returns a nested dictionary representing the requested fields.\n\n Note:\n This function should support arbitrarily nested field structures\n including fragments.\n\n Example:\n Consider the following query passed to a resolver and running this\n function with the `ResolveInfo` object passed to the resolver.\n\n >>> query = \"query getAuthor{author(authorId: 1){nameFirst, nameLast}}\"\n >>> extract_requested_fields(info, info.field_asts, True)\n {'author': {'name_first': None, 'name_last': None}}\n\n Args:\n info (graphql.execution.base.ResolveInfo): The GraphQL query info passed\n to the resolver function.\n fields (List[Union[Field, FragmentSpread]]): The list of `Field` or\n `FragmentSpread` objects parsed out of the GraphQL query and stored\n in the AST.\n do_convert_to_snake_case (bool): Whether to convert the fields as they\n appear in the GraphQL query (typically in camel-case) back to\n snake-case (which is how they typically appear in ORM classes).\n\n Returns:\n Dict: The nested dictionary containing all the requested fields.\n \"\"\"\n\n result = {}\n for field in fields:\n\n # Set the `key` as the field name.\n key = field.name.value\n\n # Convert the key from camel-case to snake-case (if required).\n if do_convert_to_snake_case:\n key = to_snake_case(name=key)\n\n # Initialize `val` to `None`. Fields without nested-fields under them\n # will have a dictionary value of `None`.\n val = None\n\n # If the field is of type `Field` then extract the nested fields under\n # the `selection_set` (if defined). These nested fields will be\n # extracted recursively and placed in a dictionary under the field\n # name in the `result` dictionary.\n if isinstance(field, Field):\n if (\n hasattr(field, \"selection_set\") and\n field.selection_set is not None\n ):\n # Extract field names out of the field selections.\n val = extract_requested_fields(\n info=info,\n fields=field.selection_set.selections,\n )\n result[key] = val\n # If the field is of type `FragmentSpread` then retrieve the fragment\n # from `info.fragments` and recursively extract the nested fields but\n # as we don't want the name of the fragment appearing in the result\n # dictionary (since it does not match anything in the ORM classes) the\n # result will simply be result of the extraction.\n elif isinstance(field, FragmentSpread):\n # Retrieve referened fragment.\n fragment = info.fragments[field.name.value]\n # Extract field names out of the fragment selections.\n val = extract_requested_fields(\n info=info,\n fields=fragment.selection_set.selections,\n )\n result = val\n\n return result\n```\n\n```text\nquery getAuthor{\n author(authorId: 1) {\n nameFirst,\n nameLast\n }\n}\n```\n\n```text\n{'author': {'name_first': None, 'name_last': None}}\n```\n\n```text\nquery getAuthor{\n author(nameFirst: \"Brandon\") {\n ...authorFields\n books {\n ...bookFields\n }\n }\n}\n\nfragment authorFields on TypeAuthor {\n nameFirst,\n nameLast\n}\n\nfragment bookFields on TypeBook {\n title,\n year\n}\n```\n\n```text\n{'author': {'books': {'title': None, 'year': None},\n 'name_first': None,\n 'name_last': None}}\n```\n\n```py\ndef apply_requested_fields(\n info: graphql.execution.base.ResolveInfo,\n query: sqlalchemy.orm.Query,\n orm_class: Type[OrmBaseMixin]\n) -> sqlalchemy.orm.Query:\n \"\"\"Updates the SQLAlchemy Query object by limiting the loaded fields of the\n table and its relationship to the ones explicitly requested in the GraphQL\n query.\n\n Note:\n This function is fairly simplistic in that it assumes that (1) the\n SQLAlchemy query only selects a single ORM class/table and that (2)\n relationship fields are only one level deep, i.e., that requestd fields\n are either table fields or fields of the table relationship, e.g., it\n does not support fields of relationship relationships.\n\n Args:\n info (graphql.execution.base.ResolveInfo): The GraphQL query info passed\n to the resolver function.\n query (sqlalchemy.orm.Query): The SQLAlchemy Query object to be updated.\n orm_class (Type[OrmBaseMixin]): The ORM class of the selected table.\n\n Returns:\n sqlalchemy.orm.Query: The updated SQLAlchemy Query object.\n \"\"\"\n\n # Extract the fields requested in the GraphQL query.\n fields = extract_requested_fields(\n info=info,\n fields=info.field_asts,\n do_convert_to_snake_case=True,\n )\n\n # We assume that the top level of the `fields` dictionary only contains a\n # single key referring to the GraphQL resource being resolved.\n tl_key = list(fields.keys())[0]\n # We assume that any keys that have a value of `None` (as opposed to\n # dictionaries) are fields of the primary table.\n table_fields = [\n key for key, val in fields[tl_key].items()\n if val is None\n ]\n\n # We assume that any keys that have a value being a dictionary are\n # relationship attributes on the primary table with the keys in the\n # dictionary being fields on that relationship. Thus we create a list of\n # `[relatioship_name, relationship_fields]` lists to be used in the\n # `joinedload` definitions.\n relationship_fieldsets = [\n [key, val.keys()]\n for key, val in fields[tl_key].items()\n if isinstance(val, dict)\n ]\n\n # Assemble a list of `joinedload` definitions on the defined relationship\n # attribute name and the requested fields on that relationship.\n options_joinedloads = []\n for relationship_fieldset in relationship_fieldsets:\n relationship = relationship_fieldset[0]\n rel_fields = relationship_fieldset[1]\n options_joinedloads.append(\n sqlalchemy.orm.joinedload(\n getattr(orm_class, relationship)\n ).load_only(*rel_fields)\n )\n\n # Update the SQLAlchemy query by limiting the loaded fields on the primary\n # table as well as by including the `joinedload` definitions.\n query = query.options(\n sqlalchemy.orm.load_only(*table_fields),\n *options_joinedloads\n )\n\n return query\n```\n\n```text\ninfo\n```\n\n```text\ngraphql.execution.base.ResolveInfo\n```\n\n```text\nget_field_names\n```\n\n```text\nget_field_names\n```\n\n```text\n['author', 'author.nameFirst']\n```\n\n```text\nget_field_names\n```\n\n```text\nauthor\n```\n\n```text\ngraphene.utils.str_converters.to_snake_case\n```\n\n```text\nget_query_fields\n```\n\n```text\ndict\n```\n\n```text\ninfo\n```\n\n```text\nAuthor\n```\n\n```text\nNone\n```\n\n```text\nname_first\n```\n\n```text\ntitle\n```\n\n```text\nbooks\n```\n\n========================================\n\nComments:\n- This is exactly what I was looking for, and thank you for posting it!! My only question is - why isn't this output natively available in the info object, rather than needing such a complex custom solution? That's a genuine question- it seems like something you'd often want to make sure you're fetching the right data (preventing unnecessary / wasteful queries down the line) from the DB for further processing- but I'm new to Graphene/GraphQL so I'm wondering if I'm just missing something about how Graphene/GraphQL are \"meant\" to work?\n- @Ascendant I think the issue isn't with Graphene/GraphQL. Those solutions don't care about how you fetch the data or how performant the fetching is. The issue is in the Graphene-SQLAlchemy package for which the primary concern is mapping the SQLAlchemy schema to a GraphQL one. Producing such queries while covering all edge-cases would be far too complex (if not impossible) so the actual fetching falls to the developer. My solution above is not a one-size-fits-all but falls flat at many cases given how insanely complex SQLAlchemy is π.\n- Isn't it a more general question in GraphQL of when you're querying many-to-many in a database, regardless of what ORM you're using, if any? If you have a many-to-many relationship of `a` and `b`, and your query is `{ a { b } }`, it seems like you'd want to do a join of `a` and `b` (grouping by `a`) in the resolver of `a`... otherwise, the resolver of `b` within `a` would hit the database for every single row in `a`. But there's no way for the resolver of `a` to *know* it needs to join against `b` without a solution like what you posted.\n- how would you use the `apply_requested_fields` function? Can you provide an example applying it on a standard query with other clauses like `.filter_by(...)` or `.one()` or `.all()` please?","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":35,"totalLines":565,"estimatedTokens":3920}}555{"id":"stack-46921190","source":"stackoverflow","questionId":46921190,"title":"GraphQL Client for C++ and .NET","tags":["graphql","apollo","apollo-client"],"text":"Title: GraphQL Client for C++ and .NET\nTags: graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nIs there an GraphQL client library available for C++ (Windows and Linux) and .NET?\n\nFrom Apollo website I can only see clients for React, Vue.js, Angular, Android, iOS, Ember and Meteor.\n\nIf there is an Apollo client for C++ and .NET, where is it located ? \n\nIf not, what should be used ?\n\n========================================\n\nTop Answer:\nApollo Client has a good set of caching features, but if you don't need those features, you can just use your favorite http library (libcurl, or Boost.Beast, or Casanova maybe) to send a POST with the text of your graphql query or mutation. The response will be the same sort or response that you would see in the GraphiQL console.\n\nCurrently, there's not an Apollo Client implementation for C++ or C#. However, I see the benefit of having such a library around. Is anybody interested in translating Apollo Client 2 for C++ and C#? If so, please start a bounty, and link it in a comment!","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":19,"estimatedTokens":261}}556{"id":"stack-47266238","source":"stackoverflow","questionId":47266238,"title":"Graphql with mutation spring boot","tags":["spring-boot","graphql"],"text":"Title: Graphql with mutation spring boot\nTags: spring-boot, graphql\nSource: Stack Overflow\n\nQuestion:\nMy schema file is\n\n```\ntype Mutation {\ncreateCustomer(name: String!, email: String!, product: [Product]): Customer\n}\n\ninput Product {\n id: ID!\n name: String!\n price: Int\n}\n\ninterface Person {\n id: ID!\n name: String!\n email: String!\n}\n\ntype Customer implements Person {\n id: ID!\n name: String!\n email: String!\n product: [Product] \n}\n```\n\nI want to insert customer detail here which has product list as input. My query is\n\n```\nmutation {\n createCustomer(\n name: \"kitte\", \n email: \"kitte@gmail.com\",\n product: [\n {\n name: \"soap\", \n price: 435,\n }\n ]\n ) \n {\n id\n name\n email\n product{name}\n\n }\n}\n```\n\nBut I am getting exception\n\n```\n{\n \"data\": null,\n \"errors\": [\n {\n \"validationErrorType\": \"WrongType\",\n \"message\": \"Validation error of type WrongType: argument value ArrayValue{values=[ObjectValue{objectFields=[ObjectField{name='name', value=StringValue{value='dars76788hi'}}, ObjectField{name='price', value=IntValue{value=123}}]}, ObjectValue{objectFields=[ObjectField{name='name', value=StringValue{value='darr'}}, ObjectField{name='price', value=IntValue{value=145}}]}]} has wrong type\",\n \"locations\": [\n {\n \"line\": 5,\n \"column\": 5\n }\n ],\n \"errorType\": \"ValidationError\"\n }\n ]\n}\n```\n\nI don't understand what is the error. And how to pass list to mutation. I have referred some examples but not able to insert product as list.\n\n========================================\n\nCode:\n```text\ntype Mutation {\ncreateCustomer(name: String!, email: String!, product: [Product]): Customer\n}\n\ninput Product {\n id: ID!\n name: String!\n price: Int\n}\n\ninterface Person {\n id: ID!\n name: String!\n email: String!\n}\n\ntype Customer implements Person {\n id: ID!\n name: String!\n email: String!\n product: [Product] \n}\n```\n\n```text\nmutation {\n createCustomer(\n name: \"kitte\", \n email: \"kitte@gmail.com\",\n product: [\n {\n name: \"soap\", \n price: 435,\n }\n ]\n ) \n {\n id\n name\n email\n product{name}\n\n }\n}\n```\n\n```text\n{\n \"data\": null,\n \"errors\": [\n {\n \"validationErrorType\": \"WrongType\",\n \"message\": \"Validation error of type WrongType: argument value ArrayValue{values=[ObjectValue{objectFields=[ObjectField{name='name', value=StringValue{value='dars76788hi'}}, ObjectField{name='price', value=IntValue{value=123}}]}, ObjectValue{objectFields=[ObjectField{name='name', value=StringValue{value='darr'}}, ObjectField{name='price', value=IntValue{value=145}}]}]} has wrong type\",\n \"locations\": [\n {\n \"line\": 5,\n \"column\": 5\n }\n ],\n \"errorType\": \"ValidationError\"\n }\n ]\n}\n```\n\n```text\ntype Product {\n id: ID!\n name: String!\n price: Int\n}\n\ninput ProductInput {\n name: String!\n price: Int\n}\n\ninput CustomerInput {\n ...\n products: [ProductInput]\n}\n```\n\n========================================\n\nComments:\n- Have you tried to get some product fields in your mutation, like `mutation { createCustomer(...) { id, name, email, product {name} } }`?\n- It solved this error. But getting new error\n- It is storing customer to db. but not able to return product by\tproducts { name }\n- mutation Customer { createCustomer(name: \"trrth\", email: \"night\", product: [{id:\"1\", name: \"thrh\", price: 123}]) { id name email products { id name } } }\n- It should be `product {id, name}` based on your schema. Watch for single product vs products and add a coma between id and name.\n- Never mind the comas :) I see that you were just writing quickly. You are getting Wrong type error so try to add `type Product {...}` in addition to your input type.\n- Thanks for your answer. I have resolved this by taking input type for mutation and returning type instread of input type. So i am not getting type cast error now.","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":176,"estimatedTokens":958}}557{"id":"stack-61940478","source":"stackoverflow","questionId":61940478,"title":"[GraphQL error]: Message: Unknown fragment","tags":["javascript","graphql","apollo-client","webpack-encore"],"text":"Title: [GraphQL error]: Message: Unknown fragment\nTags: javascript, graphql, apollo-client, webpack-encore\nSource: Stack Overflow\n\nQuestion:\nI want to use some fragment: \n\n```\nimport {gql} from \"apollo-boost\";\nimport \"../fragments/cardFragments.graphql\"\n\nexport const ADD_CARD = gql`\n mutation AddCard {\n createCard(input: {\n private: true,\n section: \"school\",\n createdBy: \"api/users/1\"\n }) {\n card {\n ...CardFields\n }\n }\n }\n`;\n\nexport default {ADD_CARD}\n```\n\ncardFragments.graphql: \n\n```\nfragment CardFields on card {\n id\n private\n section\n createdBy {\n id\n }\n}\n```\n\nInside the console I get the error :\n\n [GraphQL error]: Message: Unknown fragment \"CardFields\"., Location: [object Object], Path: undefined\n\nDid I forgot something? \n\n**EDIT:**\n\nFor the graphql fragmets to work I need to load it with webpack: Apollo docs\n\nI did this with `Webpack Encore`: \n\n```\n.addLoader({\n test: /\\.(graphql|gql)$/,\n exclude: /node_modules/,\n loader: 'graphql-tag/loader',\n});\n\nmodule.exports = Encore.getWebpackConfig();\n```\n\nBefore I did this - I got an error for the not loadable .graphql extention inside of `Webpack Encore`. \n\nIs there something I do not see about creating cutsom loader with `Webpack Encore`?\n\n========================================\n\nCode:\n```text\nimport {gql} from \"apollo-boost\";\nimport \"../fragments/cardFragments.graphql\"\n\nexport const ADD_CARD = gql`\n mutation AddCard {\n createCard(input: {\n private: true,\n section: \"school\",\n createdBy: \"api/users/1\"\n }) {\n card {\n ...CardFields\n }\n }\n }\n`;\n\nexport default {ADD_CARD}\n```\n\n```text\nfragment CardFields on card {\n id\n private\n section\n createdBy {\n id\n }\n}\n```\n\n```text\n.addLoader({\n test: /\\.(graphql|gql)$/,\n exclude: /node_modules/,\n loader: 'graphql-tag/loader',\n});\n\nmodule.exports = Encore.getWebpackConfig();\n```\n\n```text\nWebpack Encore\n```\n\n```text\nWebpack Encore\n```\n\n```text\nWebpack Encore\n```\n\n```js\nimport {gql} from \"apollo-boost\";\nimport { CARD_FEILDS } from \"../fragments/cardFragments.js\"\n\nexport const ADD_CARD = gql`\n mutation AddCard {\n createCard(input: {\n private: true,\n section: \"school\",\n createdBy: \"api/users/1\"\n }) {\n card {\n ...CardFields\n }\n }\n }\n ${CARD_FEILDS}\n`;\n\nexport default {ADD_CARD}\n```\n\n```js\nimport {gql} from \"apollo-boost\"\nexport const CARD_FEILDS = gql `\n fragment CardFields on card {\n id\n private\n section\n createdBy {\n id\n }\n }\n`\n```\n\n```text\nimport { CardFields } from \"../fragments/cardFragments.js\"\n```\n\n========================================\n\nComments:\n- It's really unclear what you expect `import \"../fragments/cardFragments.graphql\"` to do. A graphql file is not even valid JS code, so you must be relying on some build tool as well?\n- @Bergi, most likely graphql-tag/loader for webpack\n- @JosephD. Is that implied by the `apollo-client` tag?\n- @Bergi yes. Apollo is a graphql client.\n- Ok, I use webpack encore with symfony and created a custom loader: with the description form the docs - before I did this I got an error that this file format can not be loaded. So now it gets loaded. Should I register that somewere in the new ApolloClient() function?\n- Thank u for this suggestion. Nice to know tat its possible to solve it this way when the webpack loading configuration does not work at all. Do u solve it this way? Its not the recommended way isn't it ?\n- @MichaelBrauner I think you should use .js file as much as possible rather than using .graphql file in React app. So you just need babel-loader to compile your file. I think it's better than use .graphql file\n- Ok, I will do it this way. Thank you.\n- Just so you know you do not need `gql` on your `fragment`","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":176,"estimatedTokens":965}}558{"id":"stack-34847285","source":"stackoverflow","questionId":34847285,"title":"Graphql Multiple enums in query","tags":["graphql","graphql-js"],"text":"Title: Graphql Multiple enums in query\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'd like to set up a query that has multiple enums sent over for the same parameter. \n\n```\ntest_query(enum:FIRST,SECOND){\n stuffs\n}\n```\n\nIt appears that this is not possible in graphql-JS, but I'm not sure.\n\n========================================\n\nCode:\n```text\ntest_query(enum:FIRST,SECOND){\n stuffs\n}\n```\n\n```text\ntest_query(enum:[FIRST,SECOND]){\n stuffs\n}\n```\n\n```text\n[]\n```\n\n========================================\n\nComments:\n- Note you must also modify your schema to accept a GraphQLList of GraphQLEnumType\n- No, you actually don't. ENUMs are sets of named values.\n- Interesting! Will retest, perhaps I was running into another issue.\n- how is this accomplished using the javascript notation?\n- Actually, I was wrong. You need to wrap it in `GraphQLList`, but once you've done it's not mandatory to send the enum as a list. You can do simply `enum: FIRST` even though it expects a set.\n- in ruby you do: `argument :myfieldname, types[Types::MyFieldENUM], \"description\"`","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":43,"estimatedTokens":270}}559{"id":"stack-57054236","source":"stackoverflow","questionId":57054236,"title":"How do I implement subscriptions in GraphQL HotChocolate?","tags":["c#","graphql","hotchocolate"],"text":"Title: How do I implement subscriptions in GraphQL HotChocolate?\nTags: c#, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI am implementing HotChocolate as part of my ASP.NET API. I'm trying to add subscriptions to the chat portion on my app, however, the documentation on the HotChocolate site is not implemented yet. From what I can tell from other sites/frameworks, I can use the C# `IObservable` as the return type for the subscription method. \n\nCan anyone give me an example of a query method or point me towards another resource? \n\n```\npublic async Task> GetMessages(Guid chatId) {\n var messages = ..Get chats;\n\n return messages;\n}\n```\n\nHowever, how does this work from a query standpoint? How do we trigger an event to update this?\n\nThanks.\n\n========================================\n\nCode:\n```text\npublic async Task<IObservable<Message>> GetMessages(Guid chatId) {\n var messages = ..Get chats;\n\n return messages;\n}\n```\n\n```text\nIObservable<Chat>\n```\n\n========================================\n\nComments:\n- Thanks Michael, that documentation is perfect! Thanks for the speedy response as well!\n- github.com/ChilliCream/graphql-workshop/blob/master/docs/…","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":41,"estimatedTokens":295}}560{"id":"stack-35811116","source":"stackoverflow","questionId":35811116,"title":"querying graphql with node","tags":["node.js","graphql","graphql-js"],"text":"Title: querying graphql with node\nTags: node.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am trying to query a graphQL endpoint but I can't figure out what I am doing wrong. How am I supposed to set up the graphQL object to pass over. If I am trying to pass \n\n```\n{\n name {\n age\n }\n}\n```\n\nHow should I be wrapping this to get the correct response from the server? The full code I am currently working with is below\n\n```\nvar http = require('http')\nvar qs = require('querystring')\n\nvar options = {\n hostname: 'url',\n method: 'POST',\n path: '/query'\n}\n\nvar req = http.request(options, function(res){\n console.log('STATUS: ' + res.statusCode);\n console.log('HEADERS: ' + JSON.stringify(res.headers));\n res.on('data', function (chunk) {\n console.log('BODY: ' + chunk);\n });\n res.on('end', function() {\n console.log('No more data in response.')\n })\n})\n\nvar query = qs.stringify({data: {classes:{}}})\n\nreq.on('error', function(e) {\n console.log('problem with request: ' + e.message);\n});\n\nreq.write(query)\nreq.end()\n```\n\n========================================\n\nTop Answer:\nHere is the example using fetch.\nI think you don't need apollo client unless you really need it.\n\n```\nrequire('isomorphic-fetch');\n\nfetch('https://api.example.com/graphql', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'authorization': `Bearer ${token}`,\n },\n body: JSON.stringify({ query: '{ name { age } }' }),\n})\n```\n\n========================================\n\nCode:\n```text\n{\n name {\n age\n }\n}\n```\n\n```text\nvar http = require('http')\nvar qs = require('querystring')\n\nvar options = {\n hostname: 'url',\n method: 'POST',\n path: '/query'\n}\n\nvar req = http.request(options, function(res){\n console.log('STATUS: ' + res.statusCode);\n console.log('HEADERS: ' + JSON.stringify(res.headers));\n res.on('data', function (chunk) {\n console.log('BODY: ' + chunk);\n });\n res.on('end', function() {\n console.log('No more data in response.')\n })\n})\n\nvar query = qs.stringify({data: {classes:{}}})\n\n\nreq.on('error', function(e) {\n console.log('problem with request: ' + e.message);\n});\n\nreq.write(query)\nreq.end()\n```\n\n```text\npayload = {\n \"query\": `{\n name {\n age\n }\n }`\n}\nJSON.stringify(payload)\n```\n\n```text\nrequire('isomorphic-fetch');\n\nfetch('https://api.example.com/graphql', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'authorization': `Bearer ${token}`,\n },\n body: JSON.stringify({ query: '{ name { age } }' }),\n})\n```\n\n```js\nimport {\n ApolloClient,\n InMemoryCache,\n HttpLink\n} from \"@apollo/client/core\"\n// Use cross-fetch for Node versions lower than 18.\nimport fetch from 'cross-fetch'\n\nconst client = new ApolloClient({\n link: new HttpLink({ uri, fetch }),\n cache: new InMemoryCache(),\n name: \"my client\",\n version: \"1.0.0\",\n assumeImmutableResults: true\n})\n\nconst query = gql`\n query Query {\n hello\n }\n`\nconst response = await client.query({ query })\n```\n\n```text\n@apollo/client\n```\n\n```text\ncore\n```\n\n```text\n@apollo/client/core\n```\n\n```text\n\"@apollo/client\": \"^3.6.5\"\n```\n\n========================================\n\nComments:\n- Now I found a good solution - \"graphql-request\". Here is the link. npmjs.com/package/graphql-request Hope it helps others save time.\n- Note that unlike running javascript in the browser, node does not have a native fetch() function, hence the need to `require('isomorphic-fetch');` in this example. There are other packages you can install to get a simple fetch() in node, eg `const fetch = require('node-fetch');` You need to run `npm install iosmorphic-fetch` (or `npm install your-chosen-fetch-package` to gain access to the fetch() function in node.\n- fetch() was added as default in node v18 blog.logrocket.com/fetch-api-node-js","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":181,"estimatedTokens":961}}561{"id":"stack-50196885","source":"stackoverflow","questionId":50196885,"title":"DynamoDB: Best hash/sort keys for my use case [confusion with AppSync/GraphQL]","tags":["amazon-web-services","amazon-dynamodb","graphql","amazon-cognito","aws-appsync"],"text":"Title: DynamoDB: Best hash/sort keys for my use case [confusion with AppSync/GraphQL]\nTags: amazon-web-services, amazon-dynamodb, graphql, amazon-cognito, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI plan on using AWS Cognito for user auth, DynamoDB for persistence and AppSync (and a lot of Mobile Hub) to power the API - *a Book Review site*.\n\nI'm having a hard time determining which field should be my hash key and which should be my sort key, and which LSI/GSI I should create.\n\nI have a list of Books with details like so:\n\n```\ntype Book {\n isbn: Int!\n year: Int!\n title: String!\n description: String\n front_cover_photo_url: String\n genre_ids: [Int]\n count_thumbs: Int\n us_release_date: String\n upcoming_release: Boolean\n currently_featured_in_book_stores: Boolean\n best_seller: Boolean\n reviews: [Review]\n}\n```\n\nI also have a review record each time a user writes a review about a book.\n\n```\ntype Review {\n isbn: Int!\n id: ID!\n created_at: String!\n\n # The user that submitted the review\n user_id: String!\n\n # The number of thumbs out of 5\n thumbs: Int!\n\n # Comments on the review\n comments: String!\n}\n```\n\nBooks, in my case, can have multiple genres - e.g.\"Fantasy\" and \"Drama\". Books also have reviews by Users, whose data is stored in Cognito. We will display the reviews in reverse chronological order next to every book.\n\n**QUESTION 1: If I denormalize and use `Drama` as a genre instead of Genre ID `2`, then what if I need to rename the genre later to `Dramatic`... wouldn't I need to update every item?**\n\nI need to be able to answer, at a minimum:\n\n- Get all books currently featured in book stores [`currently_featured_in_book_stores` == True]\n\n- Get all books that are \"upcoming\" [`upcoming_release` == True]\n\n- Get all books sorted by most thumbs [sort by `count_thumbs` DESC]\n\n- Get all books that are in genre \"Comedy\" [`genre_ids` contains `123` or \"Comedy\" depending on answer to **Q1**]\n\n- Query for book(s) named \"Harry Potter\" [`title` LIKE '%Harry Potter%']\n\n- Get all books with ISBN 1, 2, 3, 4, or 9 [ `isbn` IN [1,2,3,4,9] ]\n\n**QUESTION 2: What's the best way to structure the book data in DynamoDB, and which hash/sort/LSI/GSI would you use?**\n\nSince I'm using Cognito, the user profile data is stored outside of DynamoDB. \n\n**QUESTION 3: Should I have a `User` table in DynamoDB and dual write new registrations, so I can use AppSync to populate the review's details when showing their review? If not, how would I get the user's username/first name/last name when populating the book review details?**\n\n**QUESTION 4: Since we've gone this far, any suggestions for the graphql schema?**\n\n========================================\n\nCode:\n```text\ntype Book {\n isbn: Int!\n year: Int!\n title: String!\n description: String\n front_cover_photo_url: String\n genre_ids: [Int]\n count_thumbs: Int\n us_release_date: String\n upcoming_release: Boolean\n currently_featured_in_book_stores: Boolean\n best_seller: Boolean\n reviews: [Review]\n}\n```\n\n```text\ntype Review {\n isbn: Int!\n id: ID!\n created_at: String!\n\n # The user that submitted the review\n user_id: String!\n\n # The number of thumbs out of 5\n thumbs: Int!\n\n # Comments on the review\n comments: String!\n}\n```\n\n```text\nDrama\n```\n\n```text\n2\n```\n\n```text\nDramatic\n```\n\n```text\ncurrently_featured_in_book_stores\n```\n\n```text\nupcoming_release\n```\n\n```text\ncount_thumbs\n```\n\n```text\ngenre_ids\n```\n\n```text\n123\n```\n\n```text\ntitle\n```\n\n```text\nisbn\n```\n\n```text\nUser\n```\n\n```text\nTable: Books\nPartition Key: ISBN\n\nTable: BookReviews\nPartition Key: ISBN\nSort Key: BookReview-id\n```\n\n```text\nvar params = {\n TableName: \"Books\",\n ExpressionAttributeValues: {\n \":a\": {\n BOOL: true\n }\n }, \n FilterExpression: \"currently_featured_in_book_stores = :a\"\n };\n dynamodb.scan(params, function(err, data) {\n if (err) console.log(err, err.stack); // an error occurred\n else console.log(data); // successful response\n });\n```\n\n```text\nvar params = {\n TableName: \"Books\",\n IndexName: \"Index_Books_In_Stores\",\n ExpressionAttributeValues: {\n \":v1\": {\n BOOL: true\n }\n }, \n KeyConditionExpression: \"currently_featured_in_book_stores = :v1\"\n };\n dynamodb.query(params, function(err, data) {\n if (err) console.log(err, err.stack); // an error occurred\n else console.log(data); // successful response\n });\n```\n\n```text\nvar params = {\n TableName: \"Books\",\n ExpressionAttributeValues: {\n \":a\": {\n BOOL: true\n }\n }, \n FilterExpression: \"upcoming_release = :a\"\n };\n dynamodb.scan(params, function(err, data) {\n if (err) console.log(err, err.stack); // an error occurred\n else console.log(data); // successful response\n });\n```\n\n```text\nvar params = {\n TableName: \"Books\"\n };\n dynamodb.scan(params, function(err, data) {\n if (err) console.log(err, err.stack); // an error occurred\n else console.log(data); // successful response\n });\n```\n\n```text\nvar params = {\n TableName: \"Books\",\n ExpressionAttributeValues: {\n \":a\": {\n S: \"Harry Potter\"\n }\n }, \n FilterExpression: \"title CONTAINS :a\"\n };\n dynamodb.scan(params, function(err, data) {\n if (err) console.log(err, err.stack); // an error occurred\n else console.log(data); // successful response\n });\n```\n\n```text\nvar params = {\n Key: {\n \"ISBN\": {\n S: \"1\"\n }\n }, \n TableName: \"Books\"\n };\n dynamodb.getItem(params, function(err, data) {\n if (err) console.log(err, err.stack); // an error occurred\n else console.log(data); // successful response\n });\n```\n\n========================================\n\nComments:\n- What is your preferred programming language? I will include examples in an answer.\n- javascript in this case, please, @Stu\n- thanks for this, but how does AppSync play nice with scans and/or a cache? It doesnβt seem as though AppSync would benefit from the cache and scans will be slow, right?\n- I would think of the cache as sitting alongside your DynamoDB 'big tables'. For queries where answers can be pre-built, you would want to use the cache only, for others you need to go to DynamoDB. The cache could be implemented any way you like, including in DynamoDB itself (i.e. by creating separate tables to answer certain queries, like the top books).\n- Scans are not slow or fast, that's a misconception. They evaluate every item in a table, sometimes that's what you need, sometimes its not. When you are returning large parts of a table, its a fair assumption that a scan is fine to use.\n- I would suggest my answer is agnostic to AppSync, or whatever client side technology you are using. I think the answer was mainly around how to structure your database. AppSync lets you sync data to a client side store. The main thing there is to work out what data you need to sync to allow the app to work offline to a reasonable degree.","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":262,"estimatedTokens":1706}}562{"id":"stack-71525821","source":"stackoverflow","questionId":71525821,"title":"Apollo Graphql fetchMore, updateQuery does not update state","tags":["reactjs","graphql","apollo","react-apollo"],"text":"Title: Apollo Graphql fetchMore, updateQuery does not update state\nTags: reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm currently trying to implement pagination on my `posts`.\nUsing Apollo graphql here is my useQuery\n\n```\nconst { data: postsData, fetchMore } = useQuery(POSTS_BY_USER_DRAFT, {\nfetchPolicy: 'network-only',\nvariables: {\n user: user.id,\n start: 0,\n limit: limit\n},\nonCompleted: () => {\n setTotal(postsData[model].meta.pagination.total)\n}})\n```\n\nand here is my onClick handler for fetching more `posts`\n\n```\nconst loadMorePosts = async () => {\nconst nextStart = start + limit\nsetStart(nextStart);\nawait fetchMore({\n variables: {\n user: user.id,\n offset: nextStart,\n limit: limit,\n },\n updateQuery: (prevResult, { fetchMoreResult }) => {\n if (!fetchMoreResult) {\n return prevResult\n }\n const prevData = prevResult[model].data\n const moreData = fetchMoreResult[model].data\n\n fetchMoreResult[model].data = [...prevData, ...moreData]\n // fetchMoreResult[model].data = [...moreData]\n return fetchMoreResult\n },\n})}\n```\n\nMy queries are successful as I do get correctly the data, however `postsData` does not get updated\n\n[NOTICED]: If I switch `fetchMoreResult[model].data = [...prevData, ...moreData]` for\n`fetchMoreResult[model].data = [...moreData]` my `postsData` does get updated.\n\nI have tried `return { ...fetchMoreResult }` and multiple ways of returning data fearing an immutability/comparaison issue but it does not seem to do the job.\n\n========================================\n\nCode:\n```text\nconst { data: postsData, fetchMore } = useQuery(POSTS_BY_USER_DRAFT, {\nfetchPolicy: 'network-only',\nvariables: {\n user: user.id,\n start: 0,\n limit: limit\n},\nonCompleted: () => {\n setTotal(postsData[model].meta.pagination.total)\n}})\n```\n\n```text\nconst loadMorePosts = async () => {\nconst nextStart = start + limit\nsetStart(nextStart);\nawait fetchMore({\n variables: {\n user: user.id,\n offset: nextStart,\n limit: limit,\n },\n updateQuery: (prevResult, { fetchMoreResult }) => {\n if (!fetchMoreResult) {\n return prevResult\n }\n const prevData = prevResult[model].data\n const moreData = fetchMoreResult[model].data\n\n fetchMoreResult[model].data = [...prevData, ...moreData]\n // fetchMoreResult[model].data = [...moreData]\n return fetchMoreResult\n },\n})}\n```\n\n```text\nposts\n```\n\n```text\nposts\n```\n\n```text\npostsData\n```\n\n```text\nfetchMoreResult[model].data = [...prevData, ...moreData]\n```\n\n```text\nfetchMoreResult[model].data = [...moreData]\n```\n\n```text\npostsData\n```\n\n```text\nreturn { ...fetchMoreResult }\n```\n\n```text\nconst client = new ApolloClient({\n\n\nlink: authLink.concat(httpLink),\n cache: new InMemoryCache({\n typePolicies: {\n Publication: {\n merge: true,\n },\n Post: {\n merge: true,\n },\n },\n }),\n defaultOptions: defaultOptions,\n})\n```\n\n========================================\n\nComments:\n- I had the same issue using MongoDB Realm and your answer helped me realize that I needed a typePolicy for each custom resolver that made use of fetchMore or refetch.\n- This is a requirement of Apollo's InMemoryCache: apollographql.com/docs/react/caching/cache-configuration/… Just wanted to the why :)","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":146,"estimatedTokens":807}}563{"id":"stack-60365959","source":"stackoverflow","questionId":60365959,"title":"GraphQL: Use input type and one of its fields in the same query","tags":["javascript","node.js","graphql"],"text":"Title: GraphQL: Use input type and one of its fields in the same query\nTags: javascript, node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm wondering how to use both an input type and one of its fields as arguments in the same GraphQL query. I think there are a few valid solutions, but I'm wondering which (if any) are best practice.\n\nConsider the following hypothetical query. We get players by location and status, and team members who are in the same location, but the `member` field only has a `location` argument:\n\n```\ninput PlayerInput {\n location: String!\n status: Int!\n}\n\nquery getPlayers($playerInput: PlayerInput) {\n players(playerInput: $playerInput) {\n name\n team {\n name\n members(location: ???) { // I can think of a few ways to solve this:\n\n**1. Change the query to take individual arguments**\n\n```\nquery getPlayers($location: String!, $status: Int!) {\n players(playerInput: { location: $location, status: $status }) {\n name\n team {\n name\n members(location: $location) {\n name\n }\n }\n }\n}\n```\n\n**2. Update the schema so `members` takes the right input type**\n\n```\nquery getPlayers($playerInput: PlayerInput) {\n players(playerInput: $playerInput) {\n name\n team {\n name\n members(playerInput: $playerInput) { // This doesn't seem great for a few reasons, and would only work if you have the ability to update the schema.\n\n**3. Pass `location` in as a redundant individual argument**\n\n```\nquery getPlayers($playerInput: PlayerInput, $location: String!) {\n players(playerInput: $playerInput) {\n name\n team {\n name\n members(location: $location) {\n name\n }\n }\n }\n}\n```\n\nThis seems fine, just that there's some duplication when creating the query:\n\n```\nconst location = 'US';\nconst status = 1;\n\nfetch({\n query: getPlayersQuery,\n variables: {\n location,\n playerInput: {\n location,\n status,\n }\n }\n})...\n```\n\nAre any of these the preferred way of doing something like this? Are there other ways I haven't considered?\n\n========================================\n\nCode:\n```text\ninput PlayerInput {\n location: String!\n status: Int!\n}\n\nquery getPlayers($playerInput: PlayerInput) {\n players(playerInput: $playerInput) {\n name\n team {\n name\n members(location: ???) { // <-- How to access playerInput.location?\n name\n }\n }\n }\n}\n```\n\n```js\nquery getPlayers($location: String!, $status: Int!) {\n players(playerInput: { location: $location, status: $status }) {\n name\n team {\n name\n members(location: $location) {\n name\n }\n }\n }\n}\n```\n\n```js\nquery getPlayers($playerInput: PlayerInput) {\n players(playerInput: $playerInput) {\n name\n team {\n name\n members(playerInput: $playerInput) { // <-- Requires changing schema\n name\n }\n }\n }\n}\n```\n\n```js\nquery getPlayers($playerInput: PlayerInput, $location: String!) {\n players(playerInput: $playerInput) {\n name\n team {\n name\n members(location: $location) {\n name\n }\n }\n }\n}\n```\n\n```js\nconst location = 'US';\nconst status = 1;\n\nfetch({\n query: getPlayersQuery,\n variables: {\n location,\n playerInput: {\n location,\n status,\n }\n }\n})...\n```\n\n```text\nmember\n```\n\n```text\nlocation\n```\n\n```text\nmembers\n```\n\n```text\nlocation\n```\n\n```text\nquery getPlayers($status: Int!, $location: String!) {\n players(playerInput: { status: $status, location: $location }) {\n name\n team {\n name\n members(location: $location) {\n name\n }\n }\n }\n}\n```\n\n```text\nplayers\n```\n\n```text\nteam\n```\n\n```text\nmembers\n```\n\n```text\nmembers\n```\n\n```text\nplayers\n```\n\n```text\nmembers\n```\n\n```text\nmembers\n```\n\n```text\nlocation\n```\n\n========================================\n\nComments:\n- I would definitely prefer #1 or #3 over #2 - changing the schema only to support one special query is a no-go. Unless you *really* plan to make the `members` of a team filterable by `isActive`, and your query really wants to get only active teammates of active players and inactive mates of inactive players.\n- That makes sense - #2 seemed like a no-go to me too, just wanted to confirm. #1 seems the cleanest to me, just looking for a second opinion. Thanks!\n- This is a great explanation, thank you! Giving flexibility to the frontend dev is what I like about options 1 and 3 too. One thing - isn't your example the same as option 1? Thanks for your explanation in terms of hierarchy/constraints, that's helpful!\n- No, look at two examples again. In my snippet, `players` still takes a single argument named `playerInput` -- the difference is instead of providing a single variable, we're constructing the object and providing multiple variables for its fields. I'm not saying this is necessarily better, but if you're determined to only provide the location once this is one way to do it *without changing the field to accept multiple arguments as in your first snippet*.\n- I've looked at them again, they are the same - in example 1, the *query* takes multiple arguments, but `players` takes a single `playerInput` argument, constructed out of the arguments passed into the query. (I edited the example because previously it was using an `isActive` argument, but didn't make any other changes). Again, thank you for your explanation!","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":234,"estimatedTokens":1303}}564{"id":"stack-52372233","source":"stackoverflow","questionId":52372233,"title":"Nextjs-Graphql webpack loader: How to integrate Nextjs with Graphql loader","tags":["javascript","webpack","graphql","next.js","graphql-tag"],"text":"Title: Nextjs-Graphql webpack loader: How to integrate Nextjs with Graphql loader\nTags: javascript, webpack, graphql, next.js, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nI am trying to integrate Nextjs with graphql-tag/loader, This is my `next.config.js` file:\n\n```\nconst withSass = require('@zeit/next-sass')\nconst graphqlLoader = require('graphql-tag/loader')\n\nmodule.exports = withSass({\n webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {\n config.module.rules.push({\n test: /\\.(graphql|gql)$/,\n loader: graphqlLoader,\n exclude: /node_modules/\n })\n\n return config\n }\n})\n```\n\nI am unable to build, I get the error below:\n\n```\n/HOME/node_modules/graphql-tag/loader.js:43\n this.cacheable();\n ^\nTypeError: Cannot read property 'cacheable' of undefined\n```\n\nPlease help.\n\n========================================\n\nCode:\n```text\nconst withSass = require('@zeit/next-sass')\nconst graphqlLoader = require('graphql-tag/loader')\n\nmodule.exports = withSass({\n webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {\n config.module.rules.push({\n test: /\\.(graphql|gql)$/,\n loader: graphqlLoader,\n exclude: /node_modules/\n })\n\n return config\n }\n})\n```\n\n```text\n/HOME/node_modules/graphql-tag/loader.js:43\n this.cacheable();\n ^\nTypeError: Cannot read property 'cacheable' of undefined\n```\n\n```text\nnext.config.js\n```\n\n```text\nconst withSass = require(\"@zeit/next-sass\");\nconst webpack = require(\"webpack\");\nconst withGraphQL = require(\"next-plugin-graphql\");\nconst withOptimizedImages = require(\"next-optimized-images\");\n\nmodule.exports = withOptimizedImages(\n withGraphQL(\n withSass({\n cssModules: true,\n cssLoaderOptions: {\n importLoaders: 1,\n localIdentName: \"[local]___[hash:base64:5]\"\n },\n webpack: config => {\n\n config.plugins.push(\n new webpack.ContextReplacementPlugin(\n /graphql-language-service-interface[\\\\/]dist$/,\n new RegExp(`^\\\\./.*\\\\.js$`)\n )\n );\n\n return config;\n }\n })\n )\n);\n```\n\n```text\nconfig.module.rules.push({\n test: /\\.(graphql|gql)$/,\n include: [dir],\n exclude: /node_modules/,\n use: [\n {\n loader: 'graphql-tag/loader'\n }\n ]\n })\n```\n\n========================================\n\nComments:\n- I have tried to add the rule when `isServer === true`, and when `isServer === false`, stil unable to build, with the same error.\n- Thanks, I will look at the plugin next-graphql-plugin in more details.\n- So once one does this, how does one then use graphql files in their project? Can you just import a graphql file into a .ts file?\n- @tettoffensive you'll need to define a type for .graphql files in a `@types` folder within your source directory. the type being: `declare module '*.graphql' { import { DocumentNode } from 'graphql'; const value: DocumentNode; export = value; }` and add @types to your tsconfig if not already present, e.g. assuming a src folder: `\"compilerOptions\": { ... \"typeRoots\": [\"src/@types\", ...], },`","metadata":{"transformedAt":"2026-08-18T18:32:36.067Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":116,"estimatedTokens":768}}565{"id":"stack-49036910","source":"stackoverflow","questionId":49036910,"title":"GraphQl and passport session: access req.user when querying GraphQl","tags":["node.js","reactjs","passport.js","graphql","express-session"],"text":"Title: GraphQl and passport session: access req.user when querying GraphQl\nTags: node.js, reactjs, passport.js, graphql, express-session\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQl server and a react frontend. I use passport and LocalStrategy to authenticate the user which works well, I can successfully login an existing user. I also want to use passport session to create a user session, so that I can access the logged in user later in my GraphQl resolvers for authentication. I expected passport to set the user in the session after successfully authenticating one. But after sending correct credentials from the client to the server, GraphQl queries do not have access to `req.user`.\n\nThe GraphQL server code looks like this:\n\n```\nimport express from 'express';\nimport passport from 'passport';\nimport {Strategy as LocalStrategy} from 'passport-local';\nimport session from 'express-session';\nimport cors from 'cors';\nimport bodyParser from 'body-parser';\nimport models from './models';\nimport typeDefs from './schema';\nimport resolvers from './resolvers';\nimport { graphqlExpress, graphiqlExpress } from 'apollo-server-express';\nimport { makeExecutableSchema } from 'graphql-tools';\n\nexport const schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n});\n\nconst app = express();\n\napp.use('*', cors({ origin: 'http://localhost:3000' }));\n\napp.set('port', (process.env.PORT || 3001));\n\n//--- Passport ----\napp.use(session({ \n saveUninitialized: true, \n resave: false,\n secret: 'verysecretsecret'\n}));\napp.use(passport.initialize());\napp.use(passport.session());\n\npassport.serializeUser((user, done) => {\n done(null, user);\n });\n\npassport.deserializeUser((user, done) => {\n done(null, user);\n});\n\npassport.use(new LocalStrategy(\n {\n usernameField: 'email',\n passwordField: 'password',\n },\n function(email, password, done) {\n models.User.findOne({\n where: {\n email: email\n }\n }).then(function(user) {\n if (user) {\n if (user.validPassword(password)) {\n return done(null, user);\n } else {\n return done(null, false);\n }\n } \n return done(null, false); \n }); \n }\n));\n\n//--- Routes ----\napp.use('/graphiql', graphiqlExpress({ \n endpointURL: '/graphql' \n}));\n\napp.use(\n '/graphql',\n bodyParser.json(),\n graphqlExpress( (req) => {\n console.log('/graphql User: ' + req.user); // prints undefined after sending correct login credentials to /login\n return ({\n schema,\n context: {\n user: req.user,\n },\n });}),\n);\n\napp.use(bodyParser.urlencoded({ extended: true }) );\napp.post('/login', passport.authenticate('local'), (req, res) => {\n console.log('/login: User', req.user); // prints the logged in user's data\n return res.sendStatus(200);\n});\n\nexport default app;\n```\n\nAnd this is the login fetch request from the client:\n\n```\nonSubmit = () => {\n\n var details = {\n 'email': this.state.email,\n 'password': this.state.password,\n };\n\n var formBody = [];\n for (var property in details) {\n var encodedKey = encodeURIComponent(property);\n var encodedValue = encodeURIComponent(details[property]);\n formBody.push(encodedKey + \"=\" + encodedValue);\n }\n formBody = formBody.join(\"&\");\n\n fetch('http://localhost:3001/login', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'\n },\n credentials: 'include',\n body: formBody\n }).then(function(response) {\n console.log(response);\n }).catch(function(err) {\n // Error\n });\n };\n```\n\nDo I have to change something on the client side for the server to receive the session cookie? Or is something going wrong in the backend?\n\nI also uploaded a minimal example to this repo: https://github.com/schmitzl/passport-graphql-minimal-example\n\n========================================\n\nCode:\n```text\nimport express from 'express';\nimport passport from 'passport';\nimport {Strategy as LocalStrategy} from 'passport-local';\nimport session from 'express-session';\nimport cors from 'cors';\nimport bodyParser from 'body-parser';\nimport models from './models';\nimport typeDefs from './schema';\nimport resolvers from './resolvers';\nimport { graphqlExpress, graphiqlExpress } from 'apollo-server-express';\nimport { makeExecutableSchema } from 'graphql-tools';\n\nexport const schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n});\n\nconst app = express();\n\napp.use('*', cors({ origin: 'http://localhost:3000' }));\n\napp.set('port', (process.env.PORT || 3001));\n\n//--- Passport ----\napp.use(session({ \n saveUninitialized: true, \n resave: false,\n secret: 'verysecretsecret'\n}));\napp.use(passport.initialize());\napp.use(passport.session());\n\npassport.serializeUser((user, done) => {\n done(null, user);\n });\n\npassport.deserializeUser((user, done) => {\n done(null, user);\n});\n\npassport.use(new LocalStrategy(\n {\n usernameField: 'email',\n passwordField: 'password',\n },\n function(email, password, done) {\n models.User.findOne({\n where: {\n email: email\n }\n }).then(function(user) {\n if (user) {\n if (user.validPassword(password)) {\n return done(null, user);\n } else {\n return done(null, false);\n }\n } \n return done(null, false); \n }); \n }\n));\n\n//--- Routes ----\napp.use('/graphiql', graphiqlExpress({ \n endpointURL: '/graphql' \n}));\n\napp.use(\n '/graphql',\n bodyParser.json(),\n graphqlExpress( (req) => {\n console.log('/graphql User: ' + req.user); // prints undefined after sending correct login credentials to /login\n return ({\n schema,\n context: {\n user: req.user,\n },\n });}),\n);\n\napp.use(bodyParser.urlencoded({ extended: true }) );\napp.post('/login', passport.authenticate('local'), (req, res) => {\n console.log('/login: User', req.user); // prints the logged in user's data\n return res.sendStatus(200);\n});\n\nexport default app;\n```\n\n```text\nonSubmit = () => {\n\n var details = {\n 'email': this.state.email,\n 'password': this.state.password,\n };\n\n var formBody = [];\n for (var property in details) {\n var encodedKey = encodeURIComponent(property);\n var encodedValue = encodeURIComponent(details[property]);\n formBody.push(encodedKey + \"=\" + encodedValue);\n }\n formBody = formBody.join(\"&\");\n\n fetch('http://localhost:3001/login', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'\n },\n credentials: 'include',\n body: formBody\n }).then(function(response) {\n console.log(response);\n }).catch(function(err) {\n // Error\n });\n };\n```\n\n```text\nreq.user\n```\n\n```text\napp.use('*', cors({ origin: 'http://localhost:3000', credentials: true }));\n```\n\n```text\nimport ApolloClient from 'apollo-client'\nimport { HttpLink, InMemoryCache } from 'apollo-client-preset'\n\nconst client = new ApolloClient({\n link: new HttpLink({ uri: apolloUri, credentials: 'include' }),\n cache: new InMemoryCache()\n})\n```\n\n```text\nAccess-Control-Allow-Credentials\n```\n\n```text\ncredentials\n```\n\n```text\ninclude\n```\n\n```text\napollo-boost\n```\n\n```text\ncredentials\n```\n\n```text\napollo-boost\n```\n\n```text\napollo-client-preset\n```\n\n```text\ncredentials\n```\n\n```text\nHttpLink\n```\n\n========================================\n\nComments:\n- Thank you, that solved the problem! The cookie is now correctly set in the graphql query and I can access the user object.","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":320,"estimatedTokens":1813}}566{"id":"stack-53950885","source":"stackoverflow","questionId":53950885,"title":"GraphQL: How nested to make schema?","tags":["node.js","graphql","apollo","graphql-subscriptions"],"text":"Title: GraphQL: How nested to make schema?\nTags: node.js, graphql, apollo, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nThis past year I converted an application to use Graphql. Its been great so far, during the conversion I essentially ported all my services that backed my REST endpoints to back grapqhl queries and mutations. The app is working well but would like to continue to evolve my object graph. \n\nLets consider I have the following relationships.\n\nUser -> Team -> Boards -> Lists -> Cards -> Comments\n\nI currently have two different nested schema: User -> team: \n\n```\ntype User {\n id: ID!\n email: String!\n role: String!\n name: String!\n resetPasswordToken: String\n team: Team!\n lastActiveAt: Date\n}\n\ntype Team {\n id: ID!\n inviteToken: String!\n owner: String!\n name: String!\n archived: Boolean!\n members: [String]\n}\n```\n\nThen I have Boards -> Lists -> Cards -> Comments\n\n```\ntype Board {\n id: ID!\n name: String!\n teamId: String!\n lists: [List]\n createdAt: Date\n updatedAt: Date\n}\n\ntype List {\n id: ID!\n name: String!\n order: Int!\n description: String\n backgroundColor: String\n cardColor: String\n archived: Boolean\n boardId: String!\n ownerId: String!\n teamId: String!\n cards: [Card]\n}\n\ntype Card {\n id: ID!\n text: String!\n order: Int\n groupCards: [Card]\n type: String\n backgroundColor: String\n votes: [String]\n boardId: String\n listId: String\n ownerId: String\n teamId: String!\n comments: [Comment]\n createdAt: Date\n updatedAt: Date\n}\n\ntype Comment {\n id: ID!\n text: String!\n archived: Boolean\n boardId: String!\n ownerId: String\n teamId: String!\n cardId: String!\n createdAt: Date\n updatedAt: Date\n}\n```\n\nWhich works great. But I'm curious how nested I can truly make my schema. If I added the rest to make the graph complete:\n\n```\ntype Team {\n id: ID!\n inviteToken: String!\n owner: String!\n name: String!\n archived: Boolean!\n members: [String]\n **boards: [Board]**\n }\n```\n\nThis would achieve a much much deeper graph. However I worried how much complicated mutations would be. Specifically for the board schema downwards I need to publish subscription updates for all actions. Which if I add a comment, publish the entire board update is incredibly inefficient. While built a subscription logic for each create/update of every nested schema seems like a ton of code to achieve something simple. \n\nAny thoughts on what the right depth is in object graphs? With keeping in mind the every object beside a user needs to be broadcast to multiple users. \n\nThanks\n\n========================================\n\nTop Answer:\nYou can use nesting in `GraphQL` like\n\n```\ntype NestedObject {\n title: String\n content: String\n}\n\ntype MainObject {\n id: ID!\n myObject: [NestedObject]\n}\n```\n\nIn the above code, the type definition of `NestObject` gets injected into the `myObject` array. To understand better you can see it as:\n\n```\ntype MainObject {\n id: ID!\n myobject: [\n {\n title: String\n content: String\n }\n ]\n}\n```\n\nI Hope this solves your problem!\n\n========================================\n\nCode:\n```text\ntype User {\n id: ID!\n email: String!\n role: String!\n name: String!\n resetPasswordToken: String\n team: Team!\n lastActiveAt: Date\n}\n\ntype Team {\n id: ID!\n inviteToken: String!\n owner: String!\n name: String!\n archived: Boolean!\n members: [String]\n}\n```\n\n```text\ntype Board {\n id: ID!\n name: String!\n teamId: String!\n lists: [List]\n createdAt: Date\n updatedAt: Date\n}\n\ntype List {\n id: ID!\n name: String!\n order: Int!\n description: String\n backgroundColor: String\n cardColor: String\n archived: Boolean\n boardId: String!\n ownerId: String!\n teamId: String!\n cards: [Card]\n}\n\ntype Card {\n id: ID!\n text: String!\n order: Int\n groupCards: [Card]\n type: String\n backgroundColor: String\n votes: [String]\n boardId: String\n listId: String\n ownerId: String\n teamId: String!\n comments: [Comment]\n createdAt: Date\n updatedAt: Date\n}\n\ntype Comment {\n id: ID!\n text: String!\n archived: Boolean\n boardId: String!\n ownerId: String\n teamId: String!\n cardId: String!\n createdAt: Date\n updatedAt: Date\n}\n```\n\n```text\ntype Team {\n id: ID!\n inviteToken: String!\n owner: String!\n name: String!\n archived: Boolean!\n members: [String]\n **boards: [Board]**\n }\n```\n\n```text\ntype NestedObject {\n title: String\n content: String\n}\n\ntype MainObject {\n id: ID!\n myObject: [NestedObject]\n}\n```\n\n```text\ntype MainObject {\n id: ID!\n myobject: [\n {\n title: String\n content: String\n }\n ]\n}\n```\n\n```text\nGraphQL\n```\n\n```text\nNestObject\n```\n\n```text\nmyObject\n```\n\n========================================\n\nComments:\n- Who is consuming your API? It sounds like it's a single client that you are also developing. If you know what client or clients are using your API, do those clients need the functionality provided by adding, for example, a `boards` field on the `Team` type?\n- \"Which if I add a comment, publish the entire board update is incredibly inefficient.\" Can you clarify why you're publishing the entire board when adding a comment? I would imagine adding a comment should only result in publishing to some kind of `commentAdded` subscription. If `card` has a `comments` field, the client should take care of updating that field using `writeQuery` rather than relying on the `card` being published. Am I missing something?\n- Not entirely sure why this didn't update me, sorry for the delayed response. The article you posted about Modeling GraphQL Mutations was a really good read. Makes a lot of sense... I was actually just sending a JSON type for updates because I didn't want to write a mutation per field. I guess to conclude though, the biggest thing that feels like boiler plate to me is the subscriptions part, I can have this amazing queryable object graph, but needing to make essentially 2 subscription handlers per object feels odd. Maybe some frameworks help, wish could pass an option on a mutation or something","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":275,"estimatedTokens":1479}}567{"id":"stack-70751118","source":"stackoverflow","questionId":70751118,"title":"How to use graphql subscription query with react-query?","tags":["react-native","graphql","react-query"],"text":"Title: How to use graphql subscription query with react-query?\nTags: react-native, graphql, react-query\nSource: Stack Overflow\n\nQuestion:\nI am using react-query for api calls in my react native app. And backend is based on graphql. For query and mutation requests there is no problem. I simply use useMutation and useQuery to fetch data. My problem is that I should notify user of new notifications that comes from graphql subscription. And I don't know how to use it with react-query. I couldn't find any documentation in react-query docs. thanks for any help.\n\n========================================\n\nCode:\n```text\nqueryClient.setQueryData\n```\n\n========================================\n\nComments:\n- I study the link you provided but I really don't know where to add my subscription query?\n- > \"Additionally, you can setup an app-wide useEffect that connects you to your WebSocket endpoint.\" So I would do it in a useEffect in your App component ?","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":19,"estimatedTokens":238}}568{"id":"stack-56402841","source":"stackoverflow","questionId":56402841,"title":"What's the best way to call another resolver in Apollo Server?","tags":["graphql","apollo","apollo-server"],"text":"Title: What's the best way to call another resolver in Apollo Server?\nTags: graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nSay you wanted to call the `createdAt` resolver from the `updatedAt` resolver. For example this doesn't work:\n\n```\n{\n Review: {\n createdAt: review => review._id.getTimestamp(),\n updatedAt: review => review.updatedAt || this.createdAt(review)\n },\n}\n```\n\nI realize I could make a `reviewCreatedAt()` function that is called from both, but I'm looking for a way to call the `createdAt` resolver.\n\n========================================\n\nCode:\n```js\n{\n Review: {\n createdAt: review => review._id.getTimestamp(),\n updatedAt: review => review.updatedAt || this.createdAt(review)\n },\n}\n```\n\n```text\ncreatedAt\n```\n\n```text\nupdatedAt\n```\n\n```text\nreviewCreatedAt()\n```\n\n```text\ncreatedAt\n```\n\n```text\nconst resolvers = {\n Review: {\n createdAt: review => review._id.getTimestamp(),\n updatedAt: review => review.updatedAt || resolvers.Review.createdAt(review)\n },\n}\n```\n\n```text\nthis\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":58,"estimatedTokens":259}}569{"id":"stack-53493889","source":"stackoverflow","questionId":53493889,"title":"How to send custom error in AppSync with $util.error","tags":["error-handling","graphql","graphql-js","aws-appsync","vtl"],"text":"Title: How to send custom error in AppSync with $util.error\nTags: error-handling, graphql, graphql-js, aws-appsync, vtl\nSource: Stack Overflow\n\nQuestion:\nI have a question about AppSync error handling. I would like to send `errorInfo` object along with the error response and I tried with `$util.error`. Per the document:\n\nhttps://docs.aws.amazon.com/appsync/latest/devguide/resolver-util-reference.html\n\n`$util.error(String, String, Object, Object)`\n\nThrows a custom error. This can be used in request or response mapping\ntemplates if the template detects an error with the request or with\nthe invocation result. Additionally, an errorType field, a data field,\nand a errorInfo field can be specified. The data value will be added\nto the corresponding error block inside errors in the GraphQL\nresponse. Note: data will be filtered based on the query selection\nset. The errorInfo value will be added to the corresponding error\nblock inside errors in the GraphQL response. Note: errorInfo will NOT\nbe filtered based on the query selection set.\n\nAnd here is what my ResponseMappingTemplate look like:\n\n```\n#if( $context.result && $context.result.errorMessage )\n $utils.error($context.result.errorMessage, $context.result.errorType, $context.result.data), $context.result.errorInfo)\n#else\n $utils.toJson($context.result.data)\n#end\n```\n\nHere is what I did on the resolver:\n\n```\nvar result = {\n data: null,\n errorMessage: 'I made this error',\n errorType: 'ALWAYS_ERROR',\n errorInfo: {\n errorCode: 500,\n validations: [\n {\n fieldName: '_',\n result: false,\n reasons: [\n 'Failed! Yay!'\n ]\n }\n ],\n }\n};\ncallback(null, result);\n```\n\nAnd here is what I see in CloudWatch log:\n\n```\n{\n \"errors\": [\n \"CustomTemplateException(message=I made this error, errorType=ALWAYS_ERROR, data=null, errorInfo={errorCode=500, validations=[{fieldName=_, result=false, reasons=[Failed! Yay!]}]})\"\n ],\n \"mappingTemplateType\": \"Response Mapping\",\n \"path\": \"[getError]\",\n \"resolverArn\": \"arn:aws:appsync:ap-southeast-1:....\",\n \"context\": {\n \"arguments\": {},\n \"result\": {\n \"errorMessage\": \"I made this error\",\n \"errorType\": \"ALWAYS_ERROR\",\n \"errorInfo\": {\n \"errorCode\": 500,\n \"validations\": [\n {\n \"fieldName\": \"_\",\n \"result\": false,\n \"reasons\": [\n \"Failed! Yay!\"\n ]\n }\n ]\n }\n },\n \"stash\": {},\n \"outErrors\": []\n },\n \"fieldInError\": true\n}\n```\n\nAnd here is what I got in the response:\n\n```\n{\n \"data\": {\n \"getError\": null\n },\n \"errors\": [\n {\n \"path\": [\n \"getError\"\n ],\n \"data\": null,\n \"errorType\": \"ALWAYS_ERROR\",\n \"errorInfo\": null,\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3,\n \"sourceName\": null\n }\n ],\n \"message\": \"I made this error\"\n }\n ]\n}\n```\n\nNotice that `errorInfo` is null and I some how got CustomTemplateException. I suspect that is because of the 4th parameter to `$utils.error`. But I donβt know why. Could anyone help to point out the error or tell me whether sending custom `errorInfo` is possible\n\n========================================\n\nCode:\n```vtl\n#if( $context.result && $context.result.errorMessage )\n $utils.error($context.result.errorMessage, $context.result.errorType, $context.result.data), $context.result.errorInfo)\n#else\n $utils.toJson($context.result.data)\n#end\n```\n\n```js\nvar result = {\n data: null,\n errorMessage: 'I made this error',\n errorType: 'ALWAYS_ERROR',\n errorInfo: {\n errorCode: 500,\n validations: [\n {\n fieldName: '_',\n result: false,\n reasons: [\n 'Failed! Yay!'\n ]\n }\n ],\n }\n};\ncallback(null, result);\n```\n\n```json\n{\n \"errors\": [\n \"CustomTemplateException(message=I made this error, errorType=ALWAYS_ERROR, data=null, errorInfo={errorCode=500, validations=[{fieldName=_, result=false, reasons=[Failed! Yay!]}]})\"\n ],\n \"mappingTemplateType\": \"Response Mapping\",\n \"path\": \"[getError]\",\n \"resolverArn\": \"arn:aws:appsync:ap-southeast-1:....\",\n \"context\": {\n \"arguments\": {},\n \"result\": {\n \"errorMessage\": \"I made this error\",\n \"errorType\": \"ALWAYS_ERROR\",\n \"errorInfo\": {\n \"errorCode\": 500,\n \"validations\": [\n {\n \"fieldName\": \"_\",\n \"result\": false,\n \"reasons\": [\n \"Failed! Yay!\"\n ]\n }\n ]\n }\n },\n \"stash\": {},\n \"outErrors\": []\n },\n \"fieldInError\": true\n}\n```\n\n```json\n{\n \"data\": {\n \"getError\": null\n },\n \"errors\": [\n {\n \"path\": [\n \"getError\"\n ],\n \"data\": null,\n \"errorType\": \"ALWAYS_ERROR\",\n \"errorInfo\": null,\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3,\n \"sourceName\": null\n }\n ],\n \"message\": \"I made this error\"\n }\n ]\n}\n```\n\n```text\nerrorInfo\n```\n\n```text\n$util.error\n```\n\n```text\n$util.error(String, String, Object, Object)\n```\n\n```text\nerrorInfo\n```\n\n```text\n$utils.error\n```\n\n```text\nerrorInfo\n```\n\n```yaml\nRequestMappingTemplate: |\n {\n \"version\": \"2018-05-29\",\n \"operation\": \"Invoke\",\n \"payload\": {\n \"field\": \"getError\",\n \"arguments\": $utils.toJson($context.arguments)\n }\n }\n```\n\n```text\n2018-05-29\n```\n\n```text\n2017-02-28\n```\n\n```text\n2018-05-29\n```\n\n========================================\n\nComments:\n- Similar question for errorData: stackoverflow.com/questions/51733996/… But that doesn't answer this question for errorInfo.\n- This is for request mapping. Lambda functions are executing after request mapping. The error throw are captured by the response mapping.\n- @ShadabFaiz AWS response mapping templates are not versioned, instead they take their version from the request mapping template (I can't find any explicit mention of this AWS docs, but this is implied via: 1. \"Given the following response mapping template....Previously with 2017-02-28...\" with an example without a version field [docs.aws.amazon.com/appsync/latest/devguide/…, 2. \"Common to all request mapping templates, the version field defines\"[docs.aws.amazon.com/appsync/latest/devguide/…","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":264,"estimatedTokens":1525}}570{"id":"stack-56171092","source":"stackoverflow","questionId":56171092,"title":"Can GraphQL optionally resolve a field given result of a query in resolver?","tags":["javascript","ecmascript-6","graphql"],"text":"Title: Can GraphQL optionally resolve a field given result of a query in resolver?\nTags: javascript, ecmascript-6, graphql\nSource: Stack Overflow\n\nQuestion:\nI have the following REST endpoints:\n\n /orders/{id}\n\n```\nreturns {\n orderId,\n orderItem,\n customerId\n}\n```\n\n /customers/{id}\n\n```\nreturns {\n customerId,\n firstName,\n lastName\n}\n```\n\nI am limited by these two endpoints, which are going to be wrapped in my graphql schema.\n\nI would like the following Schema:\n\n```\ntype Order {\n orderId: ID!,\n orderItem: String,\n customer: Customer\n}\n\ntype Customer{\n customerId: ID!\n firstName: String!\n lastName: String!\n}\n\ntype Query {\n getOrder(id: String!): Order,\n getCustomer(id: String!): Customer\n}\n```\n\nI'm wondering if it is possible to have GraphQL resolve the Customer object in the Order type? I understand that you cannot pass the result of a query into the parameter of another.\n\nI have considered the resolver of `getOrder` be:\n\n```\nconst getOrderResolver = axios.get(`/orders/${id}`)\n .then((ordersRes) => {\n let customerId;\n if(ordersRes.data.customerId !== null) {\n customerId = ordersRes.data.customerId \n axios.get(`/customers/${customerId}`)\n .then((customerRes) => ({\n return {\n orderId: ordersRes.data.orderId\n orderItem: ordersRes.data.orderItem\n customer: {\n customerId: customerRes.data.customerId\n firstName: customerRes.data.firstName\n lastName: customerRes.data.lastName \n }\n }\n })\n } else {\n return {\n orderId: ordersRes.data.orderId\n orderItem: ordersRes.data.orderItem\n customer: null\n }\n }\n })\n })\n```\n\n`getCustomer` resolver\n\n```\nconst getCustomerResolver = axios.get(`/customers/${customerId}`)\n .then((customerRes) => ({\n return {\n customerId: customerRes.data.customerId\n firstName: customerRes.data.firstName\n lastName: customerRes.data.lastName \n }\n })\n```\n\nIt seems with my solution, there will be the additional cost of always fetching the `Customer` type whether or not it is queried within the `getOrder` query. Is it possible to rewrite my GraphQL schema in a way that GraphQL would be able to resolve the `Customer` type only when queried?\n\nThe limitation of my given my `ORDERS` REST API only returns the `CustomerId` makes it difficult to resolve in `getOrder`, since the `Customer` API requires a `customerId`\n\n========================================\n\nCode:\n```text\nreturns {\n orderId,\n orderItem,\n customerId\n}\n```\n\n```text\nreturns {\n customerId,\n firstName,\n lastName\n}\n```\n\n```text\ntype Order {\n orderId: ID!,\n orderItem: String,\n customer: Customer\n}\n\ntype Customer{\n customerId: ID!\n firstName: String!\n lastName: String!\n}\n\ntype Query {\n getOrder(id: String!): Order,\n getCustomer(id: String!): Customer\n}\n```\n\n```text\nconst getOrderResolver = axios.get(`/orders/${id}`)\n .then((ordersRes) => {\n let customerId;\n if(ordersRes.data.customerId !== null) {\n customerId = ordersRes.data.customerId \n axios.get(`/customers/${customerId}`)\n .then((customerRes) => ({\n return {\n orderId: ordersRes.data.orderId\n orderItem: ordersRes.data.orderItem\n customer: {\n customerId: customerRes.data.customerId\n firstName: customerRes.data.firstName\n lastName: customerRes.data.lastName \n }\n }\n })\n } else {\n return {\n orderId: ordersRes.data.orderId\n orderItem: ordersRes.data.orderItem\n customer: null\n }\n }\n })\n })\n```\n\n```text\nconst getCustomerResolver = axios.get(`/customers/${customerId}`)\n .then((customerRes) => ({\n return {\n customerId: customerRes.data.customerId\n firstName: customerRes.data.firstName\n lastName: customerRes.data.lastName \n }\n })\n```\n\n```text\ngetOrder\n```\n\n```text\ngetCustomer\n```\n\n```text\nCustomer\n```\n\n```text\ngetOrder\n```\n\n```text\nCustomer\n```\n\n```text\nORDERS\n```\n\n```text\nCustomerId\n```\n\n```text\ngetOrder\n```\n\n```text\nCustomer\n```\n\n```text\ncustomerId\n```\n\n```text\nconst resolvers = {\n Query: {\n getOrder: (parent, args, context, info) => {\n const response = await axios.get(`/orders/${args.id}`)\n return response.data\n },\n ...\n },\n ...\n}\n```\n\n```text\nconst resolvers = {\n Query: { ... },\n Order: {\n customer: (parent, args, context, info) => {\n if (!parent.customerId) {\n return null\n }\n const response = await axios.get('/customers/${parent.customerId}')\n return response.data\n },\n },\n ...\n}\n```\n\n```text\ngetOrder\n```\n\n```text\nresponse.data\n```\n\n```text\ncustomer\n```\n\n```text\ngetOrder\n```\n\n```text\nOrder\n```\n\n```text\nparent\n```\n\n```text\nparent.customerId\n```\n\n```text\n/customers\n```\n\n```text\ncustomer\n```\n\n========================================\n\nComments:\n- How are you building your schema? Are you calling the GraphQLSchema constructor directly or using a utility function like `buildSchema` or `makeExecutableSchema`? Or is the schema creation coupled with some other library you're using, like Apollo Server?\n- I am using `makeExecutableSchema` via `graphql-tools` and serving it via Apollo Server.\n- Thanks so much! Works like a charm and is now saving me multiple API round trips after refactoring the backend!\n- Is it possible to define resolvers for childen of children? For example, how would you add another child resolver to `customer` when it is already a child of `Order`?\n- @Jim Every field has a type. If that type is an object type, you can define resolvers for any field on that type. So if `customer` has the type `Customer` and `Customer` is an object type, you can define resolvers for any field on `Customer`. The fact that `customer` is a field on `Order` is irrelevant.","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":291,"estimatedTokens":1421}}571{"id":"stack-73326579","source":"stackoverflow","questionId":73326579,"title":"GraphQLTester with SpringBoot Failed to instantiate xxx specified class is an interface","tags":["java","spring-boot","unit-testing","junit","graphql"],"text":"Title: GraphQLTester with SpringBoot Failed to instantiate xxx specified class is an interface\nTags: java, spring-boot, unit-testing, junit, graphql\nSource: Stack Overflow\n\nQuestion:\n**PlayerController.java:**\n\n```\n@Controller\npublic class PlayerController {\n\n private final int MAXIMUM_CAPACITY = 12;\n @Autowired\n private final PlayerRepository playerRepository;\n\n public PlayerController(PlayerRepository repository){\n this.playerRepository = repository;\n\n }\n\n @QueryMapping\n List getAllPlayers(){\n List ps = new ArrayList<>();\n playerRepository.findAll().forEach(ps::add);\n return ps;\n }\n\n @QueryMapping\n Optional playerById(@Argument Long id){\n return playerRepository.findById(id);\n\n }\n\n @MutationMapping\n Object AddPlayer(@Argument PlayerInput player){\n\n if(playerRepository.count() >= MAXIMUM_CAPACITY)\n return new PlayerFailedPayload(\"maximum number of players reached (\" + MAXIMUM_CAPACITY + \")! Please delete players before adding more.\" );\n\n if(!PlayerPosition.isValidPosition(player.position()))\n return new PlayerFailedPayload(\"Invalid Player Position, The valid positions are: {'PG','SG','SF','PF','C'}\");\n\n if(player.name().isEmpty() || player.surname().isEmpty())\n return new PlayerFailedPayload(\"Name or surname cannot be empty\");\n\n Player p = new Player(player.name(),player.surname(),player.position());\n return new PlayerSuccessPayload(\"A new player was added successfully.\" , playerRepository.save(p));\n }\n\n @MutationMapping\n Object DeletePlayer(@Argument Long id) {\n Optional player = playerRepository.findById(id);\n\n if(player.isEmpty())\n return new PlayerFailedPayload(\"player with id \" + id + \" does not exist!\");\n playerRepository.deleteById(id);\n return new PlayerSuccessPayload(\"Player with id \" + id + \" was deleted successfully\",player.get());\n\n }\n\n record PlayerInput(String name, String surname, String position){}\n record PlayerSuccessPayload(String message,Player player){}\n record PlayerFailedPayload(String error){}\n}\n```\n\n**PlayerRepository.java**\n\n```\n@Repository\npublic interface PlayerRepository extends CrudRepository {\n\n}\n```\n\n**schema.graphqls:**\n\n```\nunion PlayerPayload = PlayerSuccessPayload | PlayerFailedPayload\n\ntype PlayerFailedPayload {\n error: String!\n}\n\ntype PlayerSuccessPayload {\n message: String!\n player : Player!\n}\n\ntype Query {\n getAllPlayers: [Player]\n playerById(id: ID!): Player!\n}\n\ntype Mutation{\n AddPlayer(player: PlayerInput): PlayerPayload!\n DeletePlayer(id : ID!): PlayerPayload!\n}\n\ninput PlayerInput {\n name: String!\n surname: String!\n position: String!\n}\n\ntype Player {\n id: ID!\n name: String!\n surname: String!\n position: String!\n}\n```\n\n**PlayerControllerIntTest.java**\n\n```\n@GraphQlTest(PlayerController.class)\n@Import(PlayerRepository.class)\nclass PlayerControllerIntTest {\n\n @Autowired\n GraphQlTester graphQlTester;\n\n @Test\n void testGetAllPlayersShouldReturnAllPlayers() {\n // language=GraphQL\n String document = \"\"\"\n query {\n getAllPlayers {\n id\n name\n surname\n position \n }\n } \n \"\"\";\n\n graphQlTester.document(document)\n .execute()\n .path(\"getAllPlayers\")\n .entityList(Player.class)\n .hasSize(3);\n }\n}\n```\n\nI am trying to write simple Unit test to get all of the players.\nHowever no matter how much I researched I haven't been able to find a solution\nI am getting this error:\n\n```\nCaused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'playerController' defined in file [E:\\Documents\\Github\\Java\\basketball\\basketball\\target\\classes\\com\\example\\basketball\\controller\\PlayerController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.example.basketball.repository.PlayerRepository': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.basketball.repository.PlayerRepository]: Specified class is an interface\n```\n\n**Things I have tried:**\n\n```\n@EnableAutoConfiguration\n@ContextConfiguration(classes = {PlayerRepository.class})\n```\n\nI added these annotations at the top of the `PlayerControllerIntTest`\nThen I get a different error saying:\n\n```\njava.lang.IllegalArgumentException: Unrecognized Type: org.springframework.core.ResolvableType$EmptyType@5333f08f\n```\n\nThis is how my project structure looks like:\nstructure\n\nAny help?\n\n========================================\n\nCode:\n```text\n@Controller\npublic class PlayerController {\n\n\n private final int MAXIMUM_CAPACITY = 12;\n @Autowired\n private final PlayerRepository playerRepository;\n\n\n public PlayerController(PlayerRepository repository){\n this.playerRepository = repository;\n\n }\n\n @QueryMapping\n List<Player> getAllPlayers(){\n List<Player> ps = new ArrayList<>();\n playerRepository.findAll().forEach(ps::add);\n return ps;\n }\n\n @QueryMapping\n Optional<Player> playerById(@Argument Long id){\n return playerRepository.findById(id);\n\n }\n\n @MutationMapping\n Object AddPlayer(@Argument PlayerInput player){\n\n if(playerRepository.count() >= MAXIMUM_CAPACITY)\n return new PlayerFailedPayload(\"maximum number of players reached (\" + MAXIMUM_CAPACITY + \")! Please delete players before adding more.\" );\n\n if(!PlayerPosition.isValidPosition(player.position()))\n return new PlayerFailedPayload(\"Invalid Player Position, The valid positions are: {'PG','SG','SF','PF','C'}\");\n\n if(player.name().isEmpty() || player.surname().isEmpty())\n return new PlayerFailedPayload(\"Name or surname cannot be empty\");\n\n\n Player p = new Player(player.name(),player.surname(),player.position());\n return new PlayerSuccessPayload(\"A new player was added successfully.\" , playerRepository.save(p));\n }\n\n @MutationMapping\n Object DeletePlayer(@Argument Long id) {\n Optional<Player> player = playerRepository.findById(id);\n\n if(player.isEmpty())\n return new PlayerFailedPayload(\"player with id \" + id + \" does not exist!\");\n playerRepository.deleteById(id);\n return new PlayerSuccessPayload(\"Player with id \" + id + \" was deleted successfully\",player.get());\n\n\n }\n\n record PlayerInput(String name, String surname, String position){}\n record PlayerSuccessPayload(String message,Player player){}\n record PlayerFailedPayload(String error){}\n}\n```\n\n```text\n@Repository\npublic interface PlayerRepository extends CrudRepository<Player,Long> {\n\n\n}\n```\n\n```text\nunion PlayerPayload = PlayerSuccessPayload | PlayerFailedPayload\n\ntype PlayerFailedPayload {\n error: String!\n}\n\ntype PlayerSuccessPayload {\n message: String!\n player : Player!\n}\n\ntype Query {\n getAllPlayers: [Player]\n playerById(id: ID!): Player!\n}\n\ntype Mutation{\n AddPlayer(player: PlayerInput): PlayerPayload!\n DeletePlayer(id : ID!): PlayerPayload!\n}\n\ninput PlayerInput {\n name: String!\n surname: String!\n position: String!\n}\n\ntype Player {\n id: ID!\n name: String!\n surname: String!\n position: String!\n}\n```\n\n```text\n@GraphQlTest(PlayerController.class)\n@Import(PlayerRepository.class)\nclass PlayerControllerIntTest {\n\n\n @Autowired\n GraphQlTester graphQlTester;\n\n @Test\n void testGetAllPlayersShouldReturnAllPlayers() {\n // language=GraphQL\n String document = \"\"\"\n query {\n getAllPlayers {\n id\n name\n surname\n position \n }\n } \n \"\"\";\n\n graphQlTester.document(document)\n .execute()\n .path(\"getAllPlayers\")\n .entityList(Player.class)\n .hasSize(3);\n }\n}\n```\n\n```text\nCaused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'playerController' defined in file [E:\\Documents\\Github\\Java\\basketball\\basketball\\target\\classes\\com\\example\\basketball\\controller\\PlayerController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.example.basketball.repository.PlayerRepository': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.basketball.repository.PlayerRepository]: Specified class is an interface\n```\n\n```text\n@EnableAutoConfiguration\n@ContextConfiguration(classes = {PlayerRepository.class})\n```\n\n```text\njava.lang.IllegalArgumentException: Unrecognized Type: org.springframework.core.ResolvableType$EmptyType@5333f08f\n```\n\n```text\nPlayerControllerIntTest\n```\n\n```text\n@GraphQlTest(PlayerController.class)\n@Import(PlayerRepository.class)\nclass PlayerControllerIntTest {\n```\n\n```text\n@SpringBootTest\n@AutoConfigureGraphQlTester\npublic class PlayerControllerIntTest {\n```\n\n```text\nspring-graphql\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":347,"estimatedTokens":2238}}572{"id":"stack-57517793","source":"stackoverflow","questionId":57517793,"title":"graphql server side validation","tags":["validation","graphql","sequelize.js","apollo-server"],"text":"Title: graphql server side validation\nTags: validation, graphql, sequelize.js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI just want to get a gauge of what people think is the best practice for doing validation of user input fileds (such as url or email address) on the server with a graphql / orm setup.\n\nMy application is using apollo server / gql and sequelize as the orm.\n\nI've seen some who do validation on the model in sequelize and other examples of validation in the graphql resolver with with a validation library or using custom scalars.\n\nIs any one way preferable? Thanks.\n\n========================================\n\nCode:\n```text\nif (validationPass) {...} else {..}\n```\n\n```text\ninfo\n```\n\n========================================\n\nComments:\n- thanks for the overview. i ended up doing it in the model layer since it was already supported by Sequelize.","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":28,"estimatedTokens":218}}573{"id":"stack-49577677","source":"stackoverflow","questionId":49577677,"title":"Difference between axios({method: \"post\"}) and axios.post()","tags":["javascript","shopify","graphql","axios"],"text":"Title: Difference between axios({method: \"post\"}) and axios.post()\nTags: javascript, shopify, graphql, axios\nSource: Stack Overflow\n\nQuestion:\nI'm using Shopify Storefront API and Axios to develop locally a e-shop.\n\nShopify give me a response when I use `axios()`, but it returns `403 Forbidden` when I do the same thing with `axios.post()`.\n\nWhat's the difference between those two?\n\n```\naxios.post(\n SHOPIFY_DOMAIN,\n {\n headers: {\n \"Content-Type\": \"application/graphql\",\n \"X-Shopify-Storefront-Access-Token\": SHOPIFY_TOKEN\n },\n data: `{ shop }`\n})\n```\n\n```\naxios({\n method: \"post\",\n url: SHOPIFY_DOMAIN,\n headers: {\n \"Content-Type\": \"application/graphql\",\n \"X-Shopify-Storefront-Access-Token\": SHOPIFY_TOKEN\n },\n data: `{ shop }`\n})\n```\n\n========================================\n\nCode:\n```js\naxios.post(\n SHOPIFY_DOMAIN,\n {\n headers: {\n \"Content-Type\": \"application/graphql\",\n \"X-Shopify-Storefront-Access-Token\": SHOPIFY_TOKEN\n },\n data: `{ shop }`\n})\n```\n\n```js\naxios({\n method: \"post\",\n url: SHOPIFY_DOMAIN,\n headers: {\n \"Content-Type\": \"application/graphql\",\n \"X-Shopify-Storefront-Access-Token\": SHOPIFY_TOKEN\n },\n data: `{ shop }`\n})\n```\n\n```text\naxios()\n```\n\n```text\n403 Forbidden\n```\n\n```text\naxios.post()\n```\n\n```text\naxios.post(\n SHOPIFY_DOMAIN,\n `{ shop }`,\n {\n headers: {\n \"Content-Type\": \"application/graphql\",\n \"X-Shopify-Storefront-Access-Token\": SHOPIFY_TOKEN\n }\n }\n);\n```\n\n```text\naxios.post\n```\n\n```text\naxios.post(url[, data[, config]])\n```\n\n========================================\n\nComments:\n- it just a short hand\n- Your answer is way clearer than that documentation bit. Thanks mate.","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":100,"estimatedTokens":424}}574{"id":"stack-68055994","source":"stackoverflow","questionId":68055994,"title":"Apollo React Why Can't Query inside UseEffect hook","tags":["javascript","reactjs","graphql","apollo"],"text":"Title: Apollo React Why Can't Query inside UseEffect hook\nTags: javascript, reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI am just learning about Apollo-React but I couldn't make graphql request\n\nThis is how I do without Apollo\n\n```\nconst Search = () => {\n const [searchedText, setSearchedText] = React.useState('')\n const [suggestions, setSuggestions] = React.useState([])\n const [selected, setSelected] = React.useState(null)\n\n const debounceHandler = (searchedText) => debounce(() => {\n sendQuery(`{search(str:\"${searchedText}\") {name}}`).then(({search}) => {\n if (!search) return\n setSuggestions(search)\n })\n }, 500)\n\n const handleInputChange = async (e) => {\n if(e.key === 'Enter') {\n const name = e.target.value\n sendQuery(`{getPokemon(str:\"${name}\"){name, image}}`).then(({getPokemon}) => {\n setSelected(getPokemon)\n })\n }\n debounceHandler(searchedText)()\n }\n\n return (\n \n \n\n### Pokemon Search\n\n setSearchedText(e.target.value)} onKeyUp={(e) => handleInputChange(e)} style={{width:'100%'}} />\n \n \n {selected ? : suggestions.map(({name}) => (\n \n )) }\n \n \n )\n}\n```\n\nNow without my own sendQuery function, I want to use Apollo's useQuery hook.\n\n```\nconst GET_POKEMON = gql`\n query getPokemon ($str: String!) {\n getPokemon(str: $str) {\n name\n image\n }\n }\n`;\n\nconst SEARCH = gql `\nquery search($str: String!) {\n search(str:$str) {\n name\n } \n }\n`;\n```\n\nThese are my queries and results correctly on the playground. Now I write Search function again. I say whenever searchedText changes (WHen user types in), query Search and set the returning data as suggestions. Whenever user hits enter, I want to query the Pokemon from backend and set it as selected.\n\n```\nconst Search = () => {\n const [searchedText, setSearchedText] = React.useState(null)\n const [suggestions, setSuggestions] = React.useState([])\n const [selected, setSelected] = React.useState(null)\n \n React.useEffect(() => {\n const { data } = useQuery(SEARCH, {\n variables: { \"str\": searchedText },\n pollInterval: 500,\n });\n\n if (data) {\n setSuggestions(data)\n }\n\n }, [searchedText])\n\n const fetchAndSelect = name => {\n setSearchedText('')\n const { pokemon } = useQuery(GET_POKEMON, {\n variables: {\n \"str\": name\n }\n })\n\n setSelected(pokemon)\n }\n\n const handleInputChange = (e) => {\n const name = e.target.value\n if(e.key === 'Enter') {\n return fetchAndSelect(name)\n }\n setSearchedText(name)\n }\n\n return (\n \n \n\n### Pokemon Search\n\n handleInputChange(e)} style={{width:'100%'}} />\n \n \n {selected ? : suggestions.map(({name}) => (\n \n ))}\n \n \n )\n}\n```\n\nBut this gives `Invalid hook` call error. If I don't make the query inside useEffect ( I am not sure what is wrong with this?) this time I get `Rendered more hooks than during the previous render.` error. I am not sure what I am doing wrong?\n\n**EDIT**\n\nBased on answer I edit the code like following\n\n```\nconst Search = () => {\n const [searchedText, setSearchedText] = React.useState(null)\n const [suggestions, setSuggestions] = React.useState([])\n const [selected, setSelected] = React.useState(null)\n const debouncedSearch = debounce(searchedText, 1000) // Trying to debounce the searched text\n const [searchPokemons, { data }] = useLazyQuery(SEARCH);\n const [getPokemon, { pokemon }] = useLazyQuery(GET_POKEMON)\n\n React.useEffect(() => {\n if (!searchedText) return\n\n setSelected(null)\n searchPokemons({ variables: { str: searchedText }})\n\n if (data) {\n console.log(data)\n setSuggestions(data)\n }\n\n }, [debouncedSearch])\n\n const fetchAndSelect = name => {\n setSearchedText('')\n getPokemon({variables: {str: name}})\n if (pokemon) {\n setSelected(pokemon)\n }\n }\n\n const handleInputChange = (e) => {\n const name = e.target.value\n if(e.key === 'Enter') {\n return fetchAndSelect(name)\n }\n setSearchedText(name)\n }\n\n return (\n \n \n\n### Pokemon Search\n\n handleInputChange(e)} style={{width:'100%'}} />\n \n \n {selected ? : suggestions.map(({name}) => (\n \n ))}\n \n \n )\n}\n```\n\nI am unable to type anything on the input. It is fetching like crazy. Please help\n\n========================================\n\nCode:\n```text\nconst Search = () => {\n const [searchedText, setSearchedText] = React.useState('')\n const [suggestions, setSuggestions] = React.useState([])\n const [selected, setSelected] = React.useState(null)\n\n const debounceHandler = (searchedText) => debounce(() => {\n sendQuery(`{search(str:\"${searchedText}\") {name}}`).then(({search}) => {\n if (!search) return\n setSuggestions(search)\n })\n }, 500)\n\n const handleInputChange = async (e) => {\n if(e.key === 'Enter') {\n const name = e.target.value\n sendQuery(`{getPokemon(str:\"${name}\"){name, image}}`).then(({getPokemon}) => {\n setSelected(getPokemon)\n })\n }\n debounceHandler(searchedText)()\n }\n\n return (\n <div>\n <h1>Pokemon Search</h1>\n <input type=\"text\" value={searchedText} onChange={(e) => setSearchedText(e.target.value)} onKeyUp={(e) => handleInputChange(e)} style={{width:'100%'}} />\n <hr />\n <div>\n {selected ? <PokemonProfile selected={selected} /> : suggestions.map(({name}) => (\n <ShowSuggestion name={name} searchedText={searchedText} setSelected={setSelected}/>\n )) }\n </div>\n </div>\n )\n}\n```\n\n```text\nconst GET_POKEMON = gql`\n query getPokemon ($str: String!) {\n getPokemon(str: $str) {\n name\n image\n }\n }\n`;\n\nconst SEARCH = gql `\nquery search($str: String!) {\n search(str:$str) {\n name\n } \n }\n`;\n```\n\n```text\nconst Search = () => {\n const [searchedText, setSearchedText] = React.useState(null)\n const [suggestions, setSuggestions] = React.useState([])\n const [selected, setSelected] = React.useState(null)\n \n React.useEffect(() => {\n const { data } = useQuery(SEARCH, {\n variables: { \"str\": searchedText },\n pollInterval: 500,\n });\n\n if (data) {\n setSuggestions(data)\n }\n\n }, [searchedText])\n\n\n const fetchAndSelect = name => {\n setSearchedText('')\n const { pokemon } = useQuery(GET_POKEMON, {\n variables: {\n \"str\": name\n }\n })\n\n setSelected(pokemon)\n }\n\n\n\n const handleInputChange = (e) => {\n const name = e.target.value\n if(e.key === 'Enter') {\n return fetchAndSelect(name)\n }\n setSearchedText(name)\n }\n\n\n return (\n <div>\n <h1>Pokemon Search</h1>\n <input type=\"text\" value={searchedText} onKeyUp={(e) => handleInputChange(e)} style={{width:'100%'}} />\n <hr />\n <div>\n {selected ? <PokemonProfile selected={selected} /> : suggestions.map(({name}) => (\n <ShowSuggestion name={name} searchedText={searchedText} setSelected={setSelected}/>\n ))}\n </div>\n </div>\n )\n}\n```\n\n```text\nconst Search = () => {\n const [searchedText, setSearchedText] = React.useState(null)\n const [suggestions, setSuggestions] = React.useState([])\n const [selected, setSelected] = React.useState(null)\n const debouncedSearch = debounce(searchedText, 1000) // Trying to debounce the searched text\n const [searchPokemons, { data }] = useLazyQuery(SEARCH);\n const [getPokemon, { pokemon }] = useLazyQuery(GET_POKEMON)\n\n React.useEffect(() => {\n if (!searchedText) return\n\n setSelected(null)\n searchPokemons({ variables: { str: searchedText }})\n\n if (data) {\n console.log(data)\n setSuggestions(data)\n }\n\n }, [debouncedSearch])\n\n\n const fetchAndSelect = name => {\n setSearchedText('')\n getPokemon({variables: {str: name}})\n if (pokemon) {\n setSelected(pokemon)\n }\n }\n\n const handleInputChange = (e) => {\n const name = e.target.value\n if(e.key === 'Enter') {\n return fetchAndSelect(name)\n }\n setSearchedText(name)\n }\n\n return (\n <div>\n <h1>Pokemon Search</h1>\n <input type=\"text\" value={searchedText} onKeyUp={(e) => handleInputChange(e)} style={{width:'100%'}} />\n <hr />\n <div>\n {selected ? <PokemonProfile selected={selected} /> : suggestions.map(({name}) => (\n <ShowSuggestion name={name} searchedText={searchedText} setSelected={setSelected}/>\n ))}\n </div>\n </div>\n )\n}\n```\n\n```text\nInvalid hook\n```\n\n```text\nRendered more hooks than during the previous render.\n```\n\n```text\nconst [search, { data }] = useLazyQuery(SEARCH, {\n variables: { \"str\": searchedText },\n pollInterval: 500,\n });\n\nReact.useEffect(() => {\n if (searchedText) \n search() // Function for executing the query\n\n if (data) \n setSuggestions(data)\n\n }, [searchedText])\n```\n\n========================================\n\nComments:\n- hook rule broken (the same number and order) - `useLazyQuery` is for 'manual'/on event querying\n- usehooks.com/useDebounce\n- this effect won't catch the `data` (different time, use `onCompleted` option) ... data duplication into state is unnecessary\n- I am not sue how to achieve that. Do you mind editing the answer?\n- ah, OP [bad] idea ... just `const [search, { data : suggestions }] = useLazyQuery(` ... `suggestions && suggestions.map(`","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":394,"estimatedTokens":2344}}575{"id":"stack-55084490","source":"stackoverflow","questionId":55084490,"title":"How do I create a mutation on a nested object with GraphQL?","tags":["node.js","mongodb","graphql"],"text":"Title: How do I create a mutation on a nested object with GraphQL?\nTags: node.js, mongodb, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a graphql mutation to update an object field with an array of other objects. Here is my schema: \n\n```\ntype Guide {\n _id: ID!\n first_name: String!\n last_name: String\n email: String!\n phone: String!\n creator: User!\n }\n\n input GuideInput {\n _id: ID!\n first_name: String!\n last_name: String\n email: String!\n phone: String!\n }\n\n type Trip {\n _id: ID!\n name: String!\n description: String\n location: String\n start_date: String\n start_time: String\n duration: Int\n creator: User!\n guides: [Guide!]\n guests: [Guest!]\n }\n\n input TripInput {\n name: String\n description: String\n location: String\n start_date: String\n start_time: String\n duration: Int\n guides: [GuideInput]\n }\n\n type RootQuery {\n trips: [Trip!]\n guides: [Guide!]\n }\n\n type RootMutation {\n updateTrip(tripId: ID!, tripInput: TripInput): Trip\n deleteTrip(tripId: ID!): Trip\n createGuide(guideInput: GuideInput): Guide\n deleteGuide(guideId: ID!): Guide\n }\n\n schema {\n query: RootQuery\n mutation: RootMutation\n }\n```\n\nAnd my query looks like this: \n\n```\nconst requestBody = {\n query: `\n mutation {\n updateTrip(\n tripId: \"${tripId}\",\n tripInput: {\n guides: ${guides}\n }\n ) {\n guides {\n first_name\n last_name\n }\n }\n }\n `\n }\n```\n\nThe error I'm getting when I execute this request is:\n\n```\nExpected type GuideInput, found object.\nExpected type GuideInput, found Object.\n```\n\nI am passing an array of objects into the mutation that is the same shape as the GuideInput object so I'm stumped. Thank you in advance!\n\n========================================\n\nCode:\n```text\ntype Guide {\n _id: ID!\n first_name: String!\n last_name: String\n email: String!\n phone: String!\n creator: User!\n }\n\n input GuideInput {\n _id: ID!\n first_name: String!\n last_name: String\n email: String!\n phone: String!\n }\n\n type Trip {\n _id: ID!\n name: String!\n description: String\n location: String\n start_date: String\n start_time: String\n duration: Int\n creator: User!\n guides: [Guide!]\n guests: [Guest!]\n }\n\n input TripInput {\n name: String\n description: String\n location: String\n start_date: String\n start_time: String\n duration: Int\n guides: [GuideInput]\n }\n\n type RootQuery {\n trips: [Trip!]\n guides: [Guide!]\n }\n\n type RootMutation {\n updateTrip(tripId: ID!, tripInput: TripInput): Trip\n deleteTrip(tripId: ID!): Trip\n createGuide(guideInput: GuideInput): Guide\n deleteGuide(guideId: ID!): Guide\n }\n\n schema {\n query: RootQuery\n mutation: RootMutation\n }\n```\n\n```text\nconst requestBody = {\n query: `\n mutation {\n updateTrip(\n tripId: \"${tripId}\",\n tripInput: {\n guides: ${guides}\n }\n ) {\n guides {\n first_name\n last_name\n }\n }\n }\n `\n }\n```\n\n```text\nExpected type GuideInput, found object.\nExpected type GuideInput, found Object.\n```\n\n```text\ntripInput: {\n guides: [object Object]\n}\n```\n\n```js\nconst requestBody = {\n query: `\n mutation SomeMutationName($tripId: ID!, $guides: [GuideInput]) {\n updateTrip(\n tripId: $tripId\n tripInput: {\n guides: $guides\n }\n ) {\n guides {\n first_name\n last_name\n }\n }\n }\n `,\n variables: {\n tripId,\n guides,\n },\n}\n```\n\n```text\n${guides}\n```\n\n```text\nguides\n```\n\n```text\ntoString()\n```\n\n```text\n[object Object]\n```\n\n```text\nrequestBody\n```\n\n========================================\n\nComments:\n- I would also highly recommend using a client like Apollo instead of putting the requests together yourself.\n- Awesome - worked like a charm. I am trying to get a firm understanding of how GraphQL works before using something like Apollo. Thanks for your help Daniel!","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":239,"estimatedTokens":1006}}576{"id":"stack-43818401","source":"stackoverflow","questionId":43818401,"title":"Error compiling Typescript with graphql files","tags":["node.js","typescript","graphql","tsc","serverless-framework"],"text":"Title: Error compiling Typescript with graphql files\nTags: node.js, typescript, graphql, tsc, serverless-framework\nSource: Stack Overflow\n\nQuestion:\nSo I'm new in this area, the thing is that I'm trying to compile a Typescript project with graphql files on it (with `.graphql`extension).\nIt' based on the serverless framework, so to compile it I launch `npm start`which launches a `cd src/app && tsc`in the command line.\n\nThe `.ts`file references the `.graphql`file like this:\n\n`import SchemaDefinition from './schemaDefinition.graphql';`\n\nAnd the error is\n\ndata/schema/index.ts(2,30): error TS2307: Cannot find module './schemaDefinition.graphql'.\n\nI think the issue here is in the `tsc`compilation, as it creates the output directory (../../built) but it is not copying the `.graphql`files. Here is my `tsconfig.json` file:\n\n```\n{\n \"compilerOptions\": {\n \"declaration\": false,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es5\",\n \"lib\": [\"dom\", \"es6\"],\n \"module\": \"commonjs\",\n \"allowJs\": true,\n \"moduleResolution\": \"node\",\n \"noImplicitAny\": false,\n \"removeComments\": true,\n \"preserveConstEnums\": true,\n \"rootDir\": \"./\",\n \"outDir\": \"../../built\",\n \"sourceMap\": true,\n \"pretty\": true,\n \"typeRoots\": [\n \"node_modules/@types\"\n ],\n \"types\": [\n \"@types/node\",\n \"@types/graphql\"\n ],\n \"allowSyntheticDefaultImports\": true\n },\n \"include\": [\n \"./*\"\n ],\n \"exclude\": [\n \"node_modules\"\n ]\n}\n```\n\nI'm not sure if I have to do some trick to copy these files or put a precompiler step to convert the `.graphql`files in `.ts`files, using something like this: GraphQL Code Generator\n\nAny ideas out there? I'm stuck :S\n\n========================================\n\nTop Answer:\nAssuming the graphql files have a JS extension so are processed if they do not export anything or nothing imports them you could try the not recommended\n\nimport \"./my-module.js\";\n\n========================================\n\nCode:\n```text\n{\n \"compilerOptions\": {\n \"declaration\": false,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"target\": \"es5\",\n \"lib\": [\"dom\", \"es6\"],\n \"module\": \"commonjs\",\n \"allowJs\": true,\n \"moduleResolution\": \"node\",\n \"noImplicitAny\": false,\n \"removeComments\": true,\n \"preserveConstEnums\": true,\n \"rootDir\": \"./\",\n \"outDir\": \"../../built\",\n \"sourceMap\": true,\n \"pretty\": true,\n \"typeRoots\": [\n \"node_modules/@types\"\n ],\n \"types\": [\n \"@types/node\",\n \"@types/graphql\"\n ],\n \"allowSyntheticDefaultImports\": true\n },\n \"include\": [\n \"./*\"\n ],\n \"exclude\": [\n \"node_modules\"\n ]\n}\n```\n\n```text\n.graphql\n```\n\n```text\nnpm start\n```\n\n```text\ncd src/app && tsc\n```\n\n```text\n.ts\n```\n\n```text\n.graphql\n```\n\n```text\nimport SchemaDefinition from './schemaDefinition.graphql';\n```\n\n```text\ntsc\n```\n\n```text\n.graphql\n```\n\n```text\ntsconfig.json\n```\n\n```text\n.graphql\n```\n\n```text\n.ts\n```\n\n```text\ndeclare module \"*.graphql\" {\n const value: any;\n export default value;\n}\n```\n\n```text\nimport * as query from query.graphql\n```\n\n```text\nmodule: {\n rules: [\n { test: /\\.json$/, loader: 'json-loader' },\n { test: /\\.html$/, loader: 'raw-loader' },\n { test: /\\.graphql$/, loader: 'raw-loader' },\n ]\n```\n\n```text\nwebpack.config.js\n```\n\n```text\ntypings.d.ts\n```\n\n```text\ntypings.d.ts\n```\n\n```text\n.graphql\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":183,"estimatedTokens":860}}577{"id":"stack-61841777","source":"stackoverflow","questionId":61841777,"title":"In a GraphQL schema documentation comment, how do you link to a type?","tags":["graphql","markdown","documentation"],"text":"Title: In a GraphQL schema documentation comment, how do you link to a type?\nTags: graphql, markdown, documentation\nSource: Stack Overflow\n\nQuestion:\nComments in GraphQL schema are in Markdown, so you can put links in them. I'd like a link in the comment for a type to point to another type, so readers of the documentation can browse from one type to the other.\n\nFor instance, I've tried this:\n\n```\n\"\"\"\nA written or printed work consisting of pages glued or sewn together along one side and bound in covers.\nA book has an [Author](Author).\n\"\"\"\ntype Book {\n id: ID\n name: String\n author: Author\n}\n```\n\nIn GraphiQL, this was correctly translated to a link but the destination was wrong.\n\nI'm afraid this is not really possible, but I figured I'd ask anyway! :)\n\n========================================\n\nCode:\n```text\n\"\"\"\nA written or printed work consisting of pages glued or sewn together along one side and bound in covers.\nA book has an [Author](Author).\n\"\"\"\ntype Book {\n id: ID\n name: String\n author: Author\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.068Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":39,"estimatedTokens":257}}578{"id":"stack-54003825","source":"stackoverflow","questionId":54003825,"title":"AppSync - query for all items created within a date range?","tags":["elasticsearch","graphql","aws-appsync","aws-amplify","amplifyjs"],"text":"Title: AppSync - query for all items created within a date range?\nTags: elasticsearch, graphql, aws-appsync, aws-amplify, amplifyjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to query my items (which have fields of AWS DateTime of CreatedAt and UpdatedAt) for all within a certain date range. For example, the past 48 hours.\n\nFor example, using this schema:\n\n```\ntype Note @model @searchable @auth(rules: [{ allow: owner }]) {\n id: ID!\n note: String\n createdAt: AWSDateTime\n```\n\nI'm able to search for dates using, for example:\n\n```\nquery {\n searchNotes(filter:{createdAt: { matchPhrasePrefix: \"2018-12-27\"}}) {\n items{\n id\n title\n createdAt\n }\n }\n}\n```\n\nWhich returns all notes that match the UTC time with that string prefix. \n\nFrom which, I have to sort myself using moment.diff(), or some other method.\n\nI'm not sure there is a better/more efficient way of doing searching/filtering by dates and time using AppSync and GraphQl?\n\nThank you.\n\n========================================\n\nTop Answer:\nYou can use this query to filter 2 `AWSDateTime`:\n\n```\nquery {\n searchNotes(filter:{createdAt: { between: [\"2018-12-27T00:00:00\", \"2019-01-27T00:00:00\"]}}) {\n items{\n id\n title\n createdAt\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\ntype Note @model @searchable @auth(rules: [{ allow: owner }]) {\n id: ID!\n note: String\n createdAt: AWSDateTime\n```\n\n```text\nquery {\n searchNotes(filter:{createdAt: { matchPhrasePrefix: \"2018-12-27\"}}) {\n items{\n id\n title\n createdAt\n }\n }\n}\n```\n\n```text\ntype Query {\n searchNotesByCreatedAt(start: String!, end: String!): NotesConnection\n}\n```\n\n```text\n{\n \"version\": \"2017-02-28\",\n \"operation\": \"GET\",\n \"path\": \"/note-<your-api-id>/doc/_search\", // created by amplify\n \"params\": {\n \"body\": {\n \"sort\": [{ \"createdAt\" : {\"order\" : \"desc\"}}],\n \"query\": {\n \"range\" : {\n \"createdAt\" : {\n \"gte\": $ctx.args.start, \n \"lte\": $ctx.args.end\n }\n }\n }\n }\n }\n}\n```\n\n```text\ngt, lt, gte, ...\n```\n\n```text\nquery {\n searchNotes(filter:{createdAt: { between: [\"2018-12-27T00:00:00\", \"2019-01-27T00:00:00\"]}}) {\n items{\n id\n title\n createdAt\n }\n }\n}\n```\n\n```text\nAWSDateTime\n```\n\n========================================\n\nComments:\n- This is a thorough, and very beneficial answer. Thank you! I actually did end up doing the first method you recommended, by storing the date in Unix Epoch time, which is an integer and sorting that way.\n- Custom resolvers are now supported, here's how: aws-amplify.github.io/docs/cli/…\n- Thanks. Is this a new feature/ability?\n- @stephenlizcano I don't think so, AWSDateTime are serialized in sort-able string so you can use same operations than strings operations\n- This is the correct way and should be the top answer. Can also be used on `AWSDate` fields.\n- This is no longer possible using ElasticSearch, as the between predicate has been removed. However, it can be done using a list query.\n- to access createdAt from graphQL you have to add it to your model schema. Keep in mind, this might allow these sections to be updated where they were originally protected.\n- Hi @aguafrommars i know this answer is last year, but i have 1 question which related with your answer. Can we just filter \"date\" only without seconds at the back? I tried `between: [\"2018-12-27\", \"2019-01-27\"]` but it doesn't work. Thanks\n- @FaiZalDong actually I don't know. Did you try to use an AWSDate instead of AWSDateTime ?","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":136,"estimatedTokens":883}}579{"id":"stack-53648169","source":"stackoverflow","questionId":53648169,"title":"How to combine two dependent GraphQL queries with 'compose'?","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: How to combine two dependent GraphQL queries with 'compose'?\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\n### Solved!\n\nI'm trying to combine two dependent GraphQL queries. \n\nThe first one should get an ID and the second one should take that ID. I read that compose behaves like flowRight(), but no matter in what order I put the queries, if queryId is below queryDetails, queryDetail's is always skipped (as expected). No matter how I put my code together the variable is undefined.\n\n```\nimport { graphql, compose } from 'react-apollo'\nimport gql from 'graphql-tag'\n\nclass Home extends Component {\n constructor(props) {\n super(props)\n console.log(\"Where's my data?\")\n console.log(props)\n }\n\n render() {\n return(\n \n )\n }\n}\n\nexport const queryIdConst = gql`\n query IdQuery {\n account(name:\"SuperAccount\") \n {\n lists {\n edges {\n id\n }\n }\n } \n }\n`\n\nexport const queryDataConst = gql`\n query DataQuery($id: ID!) {\n account(name:\"SuperAccount\") \n {\n list(id: $id) {\n displayTitle\n }\n } \n }\n`\n\nexport default compose(\n graphql(queryIdConst, {\n name: 'listId',\n }),\n graphql(queryDataConst, { \n name: 'data',\n skip: ({ listId }) => !listId.data,\n options: ({ listId }) => ({\n variables: {\n id: list.data.account.lists.edges[0].id\n }\n })\n })\n)(Home)\n```\n\nI have already tried to change the compose functions order, but anyway this is not working, as I expected it to work.\n\nThanks for any help!\n\nEdit: Switched the two graphql() in compose() to be inline with AbsoluteSith's comment link\n\n### Solution\n\nWith hints and help from Daniel Rearden and AbsoluteSith I implemented the following solution:\n\nChanged the compose():\n\n```\nexport default compose(\n graphql(queryIdConst, {\n name: 'listId',\n }),\n graphql(queryDataConst, { \n name: 'dataHome', // changed to 'dataHome' to avoid confusion\n skip: ({ listId }) => !listId.account,\n options: ({ listId }) => ({\n variables: {\n id: listId.account.lists.edges[0].id\n }\n })\n })\n)(Home)\n```\n\nAnd my render():\n\n```\nreturn(\n \n { dataHome && !dataHome.loading && \n {dataHome.account.list.displayTitle} \n }\n \n)\n```\n\n========================================\n\nCode:\n```text\nimport { graphql, compose } from 'react-apollo'\nimport gql from 'graphql-tag'\n\nclass Home extends Component {\n constructor(props) {\n super(props)\n console.log(\"Where's my data?\")\n console.log(props)\n }\n\n render() {\n return(\n <div />\n )\n }\n}\n\nexport const queryIdConst = gql`\n query IdQuery {\n account(name:\"SuperAccount\") \n {\n lists {\n edges {\n id\n }\n }\n } \n }\n`\n\nexport const queryDataConst = gql`\n query DataQuery($id: ID!) {\n account(name:\"SuperAccount\") \n {\n list(id: $id) {\n displayTitle\n }\n } \n }\n`\n\nexport default compose(\n graphql(queryIdConst, {\n name: 'listId',\n }),\n graphql(queryDataConst, { \n name: 'data',\n skip: ({ listId }) => !listId.data,\n options: ({ listId }) => ({\n variables: {\n id: list.data.account.lists.edges[0].id\n }\n })\n })\n)(Home)\n```\n\n```text\nexport default compose(\n graphql(queryIdConst, {\n name: 'listId',\n }),\n graphql(queryDataConst, { \n name: 'dataHome', // changed to 'dataHome' to avoid confusion\n skip: ({ listId }) => !listId.account,\n options: ({ listId }) => ({\n variables: {\n id: listId.account.lists.edges[0].id\n }\n })\n })\n)(Home)\n```\n\n```text\nreturn(\n <div>\n { dataHome && !dataHome.loading && \n <div>{dataHome.account.list.displayTitle}</div> \n }\n </div>\n)\n```\n\n```text\nquery IdQuery {\n account(name:\"SuperAccount\") {\n lists {\n edges {\n id\n }\n }\n } \n}\n```\n\n```text\nthis.props.listId.account\n```\n\n```text\ngraphql(queryDataConst, { \n skip: ({ listId }) => !listId.account, // <--\n options: ({ listId }) => ({\n variables: {\n id: listId.account.lists.edges[0].id // <--\n }\n })\n})\n```\n\n```text\ngraphql\n```\n\n```text\ndata\n```\n\n```text\nmutate\n```\n\n```text\nthis.props.data.account\n```\n\n```text\nname\n```\n\n```text\ndata\n```\n\n```text\nlistId\n```\n\n========================================\n\nComments:\n- Have you tried this solution\n- Thanks for your reply! Yes, that's where I came from. But my variables in the second Query are always undefined. I get the query object with all the functions, but data is undefined. In your link the variable is defined with 'firstQuery.data.someQuery.someValue', should I 'call' a query or is 'list.data.account.lists.edges[0].id' the right to access data?\n- Yeah try passing the right data ie; list.data.account.lists.edges[0].id. See the network calls made check if both the queries are executed and their order. But a better solution is to create a separate component for the second query\n- Also this might help too. Effectively you might not be accessing the data in the correct format/ hierarchy.\n- Sorry saw your schema so you should be accessing the data as listId.account.lists.edges[0].id && check for listId value only\n- Thanks for your help! Yes, I was a little bit confused by renaming and accessing and the lifecycle of the query and components.\n- Perfect! Thanks for your help! I think I was confused with renaming and accessing afterwards. The second caveat was, that I thought the 2nd query should be listed as the 1st within my compose function, because the Doc states that it's called as flowRight(), but the 1st query must be above the 2nd, otherwise the 2nd doesn't know the 'listId'. confusion... Anyway, that's great and it is working now!","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":263,"estimatedTokens":1375}}580{"id":"stack-44070485","source":"stackoverflow","questionId":44070485,"title":"Mutations - batch creation of objects","tags":["graphql","graphene-python"],"text":"Title: Mutations - batch creation of objects\nTags: graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI want to use graphene to create many people in one go.\nThe document only mention the way to create one person like this:\n\n```\nclass CreatePerson(graphene.Mutation):\nclass Input:\n name = graphene.String()\n age = graphene.Int()\n\nok = graphene.Boolean()\nperson = graphene.Field(lambda: Person)\n\n@staticmethod\ndef mutate(root, args, context, info):\n person = Person(name=args.get('name'), age=args.get('age'), mobile=args.get('mobile'))\n ok = True\n return CreatePerson(person=person, ok=ok)\n```\n\nare there any ways to get it done?\n\n========================================\n\nTop Answer:\nInstead of using a mutation that creates a list of objects, you can also call a mutation that creates one objects *multiple times in one GraphQL request*. This is accomplished using *GraphQL Aliases*:\n\n```\nmutation {\n c001: createPerson(\n name: \"Donald Duck\"\n age: 42\n ) {\n id\n }\n\n c002: createPerson(\n name: \"Daisy Duck\"\n age: 43\n ) {\n id\n }\n\n c003: createPerson(\n name: \"Mickey Mouse\"\n age: 44\n ) {\n id\n }\n}\n```\n\n========================================\n\nCode:\n```text\nclass CreatePerson(graphene.Mutation):\nclass Input:\n name = graphene.String()\n age = graphene.Int()\n\nok = graphene.Boolean()\nperson = graphene.Field(lambda: Person)\n\n@staticmethod\ndef mutate(root, args, context, info):\n person = Person(name=args.get('name'), age=args.get('age'), mobile=args.get('mobile'))\n ok = True\n return CreatePerson(person=person, ok=ok)\n```\n\n```text\nclass PersonInput(InputObjectType):\n name = graphene.String()\n age = graphene.Int()\n\nclass CreatePeople(graphene.Mutation):\n class Input:\n people = graphene.List(PersonInput)\n\n people = graphene.List(lambda: Person)\n\n @staticmethod\n def mutate(root, args, context, info):\n people = [Person.objects.create(name=person.name, age=person.age) for person in args.get('people')]\n return CreatePeople(people=people)\n```\n\n```text\ngraphene.InputObjectType\n```\n\n```text\nclass CreatePerson(graphene.Mutation):\n class Input:\n name = graphene.List(graphene.String)\n\n ok = graphene.Boolean()\n people = graphene.List(Person)\n\n @staticmethod\n def mutate(root, args, context, info):\n people = [Person(name=name) for name in args.get('name)]\n ok = True\n return CreatePerson(people=people, ok=ok)\n```\n\n```text\nmutation {\n c001: createPerson(\n name: \"Donald Duck\"\n age: 42\n ) {\n id\n }\n\n c002: createPerson(\n name: \"Daisy Duck\"\n age: 43\n ) {\n id\n }\n\n c003: createPerson(\n name: \"Mickey Mouse\"\n age: 44\n ) {\n id\n }\n}\n```\n\n```text\nclass UserType(DjangoObjectType):\n\n class Meta:\n model = User\n interfaces = (CustomGrapheneNode, )\n filter_fields = {}\n only_fields = (\n 'name',\n 'email'\n )\n```\n\n```text\nclass UserInput(graphene.InputObjectType):\n name = graphene.String(required=True)\n password = graphene.String(required=True)\n```\n\n```text\nclass CreateUser(graphene.Mutation):\n users = graphene.List(UserType)\n\n class Input:\n data = graphene.List(UserInput)\n\n Output = graphene.List(UserType)\n\n def mutate(self, info, data):\n users = []\n for item in data:\n user = User.objects.create(name=data['name'], \n password=data['password'])\n users.append(user)\n return users\n```\n\n```text\nclass Mutation():\n create_user = CreateUser.Field()\n```\n\n```text\nmutation{\n createUser(data:[{name:\"john\", password:\"1234\"},\n {name:\"john\", password:\"1234\"}]) {\n user{\n name\n }\n } \n}\n```\n\n========================================\n\nComments:\n- FYI you can post your solution as an answer and accept it so people coming after you can easily see the final solution.\n- great! but how can I deal with more than one field. E.g. name, address and age for the person?\n- You can have complex input types, see the docs: docs.graphene-python.org/en/latest/types/mutations\n- Hi Jan, I use the InputObject and it worked but the data was not saved to the db. Would you mind helping on this. Thank you very much!\n- the link to the FAQ is dead.\n- which one is better, the batch of list or batch of alias?\n- good solution. Just to add you could use the bulk_create() method there in the mutate() function as described in the docs: docs.djangoproject.com/en/3.2/ref/models/querysets\n- in case someone else tries this answer and you run into error, in the mutate function just change for item in data: user = User.objects.create(name=data['name'], password=data['password']) to instead: for item in data: user = User.objects.create(name=item['name'], password=item['password'])\n- I created a mutation this way but I can't find a way how to write a graphql query for this. How do you do that?\n- @KarinaKlinkeviΔiΕ«tΔ you can find the answer here - docs.graphene-python.org/projects/django/en/latest/queries","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":202,"estimatedTokens":1258}}581{"id":"stack-57104238","source":"stackoverflow","questionId":57104238,"title":"How to use GraphQL subscription correctly?","tags":["javascript","graphql","graphql-js","koa","graphql-subscriptions"],"text":"Title: How to use GraphQL subscription correctly?\nTags: javascript, graphql, graphql-js, koa, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQL powered app. The query and mutation parts work well. I try to add GraphQL subscription.\n\nThe server GraphQL subscription part code is inspired by the demo in the readme of apollographql/subscriptions-transport-ws.\n\nPlease also check the comments in the code for more details.\n\n```\nimport Koa from 'koa';\nimport Router from 'koa-router';\nimport graphqlHTTP from 'koa-graphql';\nimport asyncify from 'callback-to-async-iterator';\nimport { SubscriptionServer } from 'subscriptions-transport-ws';\nimport firebase from 'firebase-admin';\nimport { execute, subscribe } from 'graphql';\nimport { GraphQLObjectType, GraphQLString } from 'graphql';\n\nconst MeType = new GraphQLObjectType({\n name: 'Me',\n fields: () => ({\n name: { type: GraphQLString },\n // ...\n }),\n});\n\nconst listenMe = async (callback) => {\n // Below the firebase API returns real-time data\n return firebase\n .database()\n .ref('/users/123')\n .on('value', (snapshot) => {\n // snapshot.val() returns an Object including name field.\n // Here I tested is correct, it always returns { name: 'Rose', ... }\n // when some other fields inside got updated in database.\n return callback(snapshot.val());\n });\n};\n\nconst Subscription = new GraphQLObjectType({\n name: 'Subscription',\n fields: () => ({\n meChanged: {\n type: MeType,\n subscribe: () => asyncify(listenMe),\n },\n }),\n});\n\nconst schema = new GraphQLSchema({\n query: Query,\n mutation: Mutation,\n subscription: Subscription,\n});\n\nconst app = new Koa();\napp\n .use(new Router()\n .post('/graphql', async (ctx) => {\n // ...\n\n await graphqlHTTP({\n schema,\n graphiql: true,\n })(ctx);\n })\n .routes());\n\nconst server = app.listen(3009);\n\nSubscriptionServer.create(\n {\n schema,\n execute,\n subscribe,\n },\n {\n server,\n path: '/subscriptions',\n },\n);\n```\n\nI am using Altair GraphQL Client to test since it supports GraphQL subscription.\n\nhttps://i.sstatic.net/RUHDs.png\n\nAs the screenshot shows, it does get new data every time when the data changes in database.\n\nHowever, `meChanged` is `null` and it does not throw any error. Any idea? Thanks\n\n========================================\n\nCode:\n```text\nimport Koa from 'koa';\nimport Router from 'koa-router';\nimport graphqlHTTP from 'koa-graphql';\nimport asyncify from 'callback-to-async-iterator';\nimport { SubscriptionServer } from 'subscriptions-transport-ws';\nimport firebase from 'firebase-admin';\nimport { execute, subscribe } from 'graphql';\nimport { GraphQLObjectType, GraphQLString } from 'graphql';\n\nconst MeType = new GraphQLObjectType({\n name: 'Me',\n fields: () => ({\n name: { type: GraphQLString },\n // ...\n }),\n});\n\nconst listenMe = async (callback) => {\n // Below the firebase API returns real-time data\n return firebase\n .database()\n .ref('/users/123')\n .on('value', (snapshot) => {\n // snapshot.val() returns an Object including name field.\n // Here I tested is correct, it always returns { name: 'Rose', ... }\n // when some other fields inside got updated in database.\n return callback(snapshot.val());\n });\n};\n\nconst Subscription = new GraphQLObjectType({\n name: 'Subscription',\n fields: () => ({\n meChanged: {\n type: MeType,\n subscribe: () => asyncify(listenMe),\n },\n }),\n});\n\nconst schema = new GraphQLSchema({\n query: Query,\n mutation: Mutation,\n subscription: Subscription,\n});\n\nconst app = new Koa();\napp\n .use(new Router()\n .post('/graphql', async (ctx) => {\n // ...\n\n await graphqlHTTP({\n schema,\n graphiql: true,\n })(ctx);\n })\n .routes());\n\nconst server = app.listen(3009);\n\nSubscriptionServer.create(\n {\n schema,\n execute,\n subscribe,\n },\n {\n server,\n path: '/subscriptions',\n },\n);\n```\n\n```text\nmeChanged\n```\n\n```text\nnull\n```\n\n```text\nimport { useServer } from 'graphql-ws/lib/use/ws';\nimport WebSocket from 'ws';\nimport { buildSchema } from 'graphql';\n\nconst schema = buildSchema(`\n type Subscription {\n greeting: String\n }\n`);\n\nconst roots = {\n subscription: {\n greeting: async function* sayHiIn5Languages() {\n for (const hi of ['Hi', 'Bonjour', 'Hola', 'Ciao', 'Zdravo']) {\n yield { greeting: hi };\n }\n },\n },\n};\n\nconst wsServer = new ws.Server({\n server, // Your HTTP server\n path: '/graphql',\n});\nuseServer(\n {\n schema,\n execute,\n subscribe,\n roots,\n },\n wsServer\n);\n```\n\n```text\nimport { execute, subscribe, GraphQLObjectType, GraphQLSchema, GraphQLString } from 'graphql';\nimport { useServer } from 'graphql-ws/lib/use/ws';\nimport WebSocket from 'ws';\nimport { PubSub } from 'graphql-subscriptions';\n\nconst pubsub = new PubSub();\n\nconst subscription = new GraphQLObjectType({\n name: 'Subscription',\n fields: {\n greeting: {\n type: GraphQLString,\n resolve: (source) => {\n if (source instanceof Error) {\n throw source;\n }\n return source.greeting;\n },\n subscribe: () => {\n return pubsub.asyncIterator('greeting');\n },\n },\n },\n});\n\nconst schema = new GraphQLSchema({\n query,\n mutation,\n subscription,\n});\n\nsetInterval(() => {\n pubsub.publish('greeting', {\n greeting: 'Bonjour',\n });\n}, 1000);\n\nconst wsServer = new ws.Server({\n server, // Your HTTP server\n path: '/graphql',\n});\nuseServer(\n {\n schema,\n execute,\n subscribe,\n roots,\n },\n wsServer\n);\n```\n\n```text\nimport { createClient } from 'graphql-ws';\n\nconst client = createClient({\n url: 'wss://localhost:5000/graphql',\n});\n\nclient.subscribe(\n {\n query: 'subscription { greeting }',\n },\n {\n next: (data) => {\n console.log('data', data);\n },\n error: (error) => {\n console.error('error', error);\n },\n complete: () => {\n console.log('no more greetings');\n },\n }\n);\n```\n\n========================================\n\nComments:\n- I don't know what alway means and you don't include the error message from the Network panel in Chrome Dev Tools so diagnosing your problem is difficult. However, have you looked at this: stackoverflow.com/questions/56319137/…\n- @Preston Thanks! Just updated the title. I hope I could post Chrome console error message, but I havenβt started to build subscription part for client yet, since it is lack of document of using GraphQL subscription without any framework like Apollo. That is why I use Altair GraphQL Client as a start point to help me understand how GraphQL subscription works.\n- I tried the first server ie,(Server (GraphQL Schema Definition Language)) and client code as it is to do one POC but i got following error :- \"Subscription field must return Async Iterable. Received: {}.\". Can you please let me know what i might be doing wrong as i'm a noob in graphql subscriptions\n- @sagg1295 check github.com/Hongbo-Miao/hongbomiao.com/blob/main/api/src/grap‌​hQL/… which might help you. It is a full working demo.\n- thanks for this. I want to clarify one thing in the above link you have used graphql-subscriptions module. Is it necessary to do subscrption using this? Can't we just use graphql-ws, ws and graphql to do graphql susbcriptions? As i was following code given on github page of graphql-ws. That was not working. If you want i can my github repo also if you can go through that it having just two files with logic\n- @sagg1295 the GraphQL Schema Definition Language way in the answer is also using `graphql-subscriptions` with `graphql-ws`, which is same.\n- but when i searched on google to do subscriptions in graphql i also this graphql-subscriptions is separate thing than `graphql-ws`. Might i'be wrong. I thought both these are different approaches to do **susbcription in graphql**\n- @sagg1295 graphql-ws is same level with subscriptions-transport-ws. And graphql-subscriptions is different level thing.\n- how to handle variables in graphql subscription query passed by client at server here, can you give any example? tried seeing the documentation but not able to get this through\n- Your first example has `import WebSocket from 'ws';` but then you're doing `ws.Server`, which is correct?","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":307,"estimatedTokens":2041}}582{"id":"stack-60643685","source":"stackoverflow","questionId":60643685,"title":"There is a way to syntax highlight GraphQl TypeDef inside ` ` (grave accent) in vscode?","tags":["visual-studio-code","graphql"],"text":"Title: There is a way to syntax highlight GraphQl TypeDef inside ` ` (grave accent) in vscode?\nTags: visual-studio-code, graphql\nSource: Stack Overflow\n\nQuestion:\nI Want to syntax highlight the code inside typeDef. It is possible?\n\nThere is a extension for this? Or I have to code the typeDef other way?\n\n```\nexport const typeDef = `\n type User {\n _id: ID!\n email: String!\n password: String\n createdEvents: [Event!]\n }\n\n type AuthData {\n userId: ID!\n token: String!\n tokenExpiration: Int!\n }\n\n input UserInput {\n email: String!\n password: String!\n }\n`;\n```\n\n========================================\n\nTop Answer:\nUse String.raw to trick VSCode into Syntax Highlighting GraphQL. It works for other languages as well.\n\n```\nexport const gql = String.raw\n\nexport const typeDef = gql`\n type User {\n _id: ID!\n email: String!\n password: String\n createdEvents: [Event!]\n }\n\n type AuthData {\n userId: ID!\n token: String!\n tokenExpiration: Int!\n }\n\n input UserInput {\n email: String!\n password: String!\n }\n`\n```\n\n========================================\n\nCode:\n```text\nexport const typeDef = `\n type User {\n _id: ID!\n email: String!\n password: String\n createdEvents: [Event!]\n }\n\n type AuthData {\n userId: ID!\n token: String!\n tokenExpiration: Int!\n }\n\n input UserInput {\n email: String!\n password: String!\n }\n`;\n```\n\n```text\nconst gql = require('graphql-tag')\n\nconst typeDefs = gql`\n type User { ... }\n`\n```\n\n```text\ngql\n```\n\n```text\ngraphql-tag\n```\n\n```text\nDocumentNode\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nApolloServer\n```\n\n```text\nDocumentNode\n```\n\n```text\nexport const gql = String.raw\n\nexport const typeDef = gql`\n type User {\n _id: ID!\n email: String!\n password: String\n createdEvents: [Event!]\n }\n\n type AuthData {\n userId: ID!\n token: String!\n tokenExpiration: Int!\n }\n\n input UserInput {\n email: String!\n password: String!\n }\n`\n```\n\n========================================\n\nComments:\n- Thanks! That is exactly what I need. I have this extension, but I not reconfigured correctly .\n- @DaniloCunha You can also use a hack `const gql = String.raw` to get syntax highlighting without needing to download `graphql-tag` or similar packages β stackoverflow.com/a/67135985/6141587\n- export const gql = String.raw didn't work for me when I tried to run my server. But when I turned off the \"export\" it did. require(\"graphql-tag\") also works too.\n- This is just awesome.","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":148,"estimatedTokens":604}}583{"id":"stack-48242062","source":"stackoverflow","questionId":48242062,"title":"How to update a paginated list after a mutation?","tags":["javascript","graphql","apollo","react-apollo","apollo-client"],"text":"Title: How to update a paginated list after a mutation?\nTags: javascript, graphql, apollo, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have a thread with a list of messages, which is fetched with a `GET_THREAD_MESSAGES` query. That query is paginated, and depending on if a user has seen the thread before or not might load the first page, last page or only the new messages. (i.e. any of `first/after/before/last` could be passed with any values)\n\n```\nthread(id: \"asdf\") {\n messageConnection(after: $after, first: $first, before: $before, last: $last) {\n edges {\n cursor\n node { ...messageInfo }\n }\n }\n}\n```\n\nNow I have a `sendMessage` mutation, which I call and then in the `update` method of that mutation I want to optimistically add that sent message to the threads messages for a nicer UX. Without pagination, I know I would do that something like:\n\n```\nconst data = store.readQuery({\n query: GET_THREAD_MESSAGES,\n variables: { id: message.threadId }\n})\n\ndata.messageConnection.edges.push(newMessageEdge);\n\nstore.writeQuery({\n query: GET_THREAD_MESSAGES,\n variables: { id: message.threadId },\n data,\n})\n```\n\nUnfortunately, since I know have pagination the `store.readQuery` call throws an error saying βIt canβt find the field `messageConnection` of that threadβ because the field is now something like `messageConnection({ after: 'jfds1223asdhfl', first: 50, before: null, last: null })`. The Apollo docs say that one should use the `@connection` directive in the query to work around that. I've tried to update the query to look something like this:\n\n```\nthread(id: \"asdf\") {\n messageConnection(...) @connection(key: \"messageConnection\") {\n edges {\n cursor\n node { ...messageInfo }\n }\n }\n}\n```\n\nUnfortunately, when I use that the optimistic update is returned and shown correctly, but as soon as the server returns the actual message that was stored I get an error saying `\"Missing field cursor in { node: { id: '...', timestamp: '...'\"`, because obviously the message that the server returns is not a `MessageConnectionEdge`, it's just the node, and thusly doesn't have a cursor field.\n\nHow can I tell Apollo to only replace the node of the optimistic response, not the entire edge? Is there another way to work around the original issue maybe?\n\n========================================\n\nTop Answer:\nI'll have a crack at this.\n\nWithout seeing the mutation I'll presume that it looks something like the following.\n\n```\nmutation NewMessage($message: String!, $threadId: ID!) {\n sendMessage(message: $message, threadId: $threadId) {\n ...messageInfo\n }\n}\n```\n\nIf that is the case, it's potentially unreliable to infer where in the connection the message should go. Since cursors are opaque strings we can't be certain that this message should indeed come after the latest message.\n\nInstead I'd try something like the following.\n\n```\nmutation NewMessage(message: String!, threadId: ID!, $after: Cursor, first: Int) {\n\n sendMessage(message: $message, threadId: $threadId) {\n messageConnection(\n after: $after,\n first: $first,\n before: null,\n last: null\n ) @connection(key: \"messageConnection\") {\n edges {\n cursor\n node { ...messageInfo }\n }\n }\n }\n}\n```\n\nThis connection should include the new message and any others that have been added since.\n\nHere is the official documentation on the `@connection` directive: https://www.apollographql.com/docs/react/advanced/caching/#the-connection-directive\n\n========================================\n\nCode:\n```text\nthread(id: \"asdf\") {\n messageConnection(after: $after, first: $first, before: $before, last: $last) {\n edges {\n cursor\n node { ...messageInfo }\n }\n }\n}\n```\n\n```text\nconst data = store.readQuery({\n query: GET_THREAD_MESSAGES,\n variables: { id: message.threadId }\n})\n\ndata.messageConnection.edges.push(newMessageEdge);\n\nstore.writeQuery({\n query: GET_THREAD_MESSAGES,\n variables: { id: message.threadId },\n data,\n})\n```\n\n```text\nthread(id: \"asdf\") {\n messageConnection(...) @connection(key: \"messageConnection\") {\n edges {\n cursor\n node { ...messageInfo }\n }\n }\n}\n```\n\n```text\nGET_THREAD_MESSAGES\n```\n\n```text\nfirst/after/before/last\n```\n\n```text\nsendMessage\n```\n\n```text\nupdate\n```\n\n```text\nstore.readQuery\n```\n\n```text\nmessageConnection\n```\n\n```text\nmessageConnection({ after: 'jfds1223asdhfl', first: 50, before: null, last: null })\n```\n\n```text\n@connection\n```\n\n```text\n\"Missing field cursor in { node: { id: '...', timestamp: '...'\"\n```\n\n```text\nMessageConnectionEdge\n```\n\n```text\nsubscribeToNewMessages: () => {\n return props.data.subscribeToMore({\n document: subscribeToNewMessages,\n variables: {\n thread: props.ownProps.id,\n },\n updateQuery: (prev, { subscriptionData }) => {\n const newMessage = subscriptionData.data.messageAdded;\n return Object.assign({}, prev, {\n ...prev,\n thread: {\n ...prev.thread,\n messageConnection: {\n ...prev.thread.messageConnection,\n edges: [\n ...prev.thread.messageConnection.edges,\n { node: newMessage, __typename: 'ThreadMessageEdge' },\n ],\n },\n },\n });\n },\n });\n},\n```\n\n```text\n{ node: newMessage, cursor: newMessage.id, __typename: 'ThreadMessageEdge' }\n```\n\n```text\nupdate\n```\n\n```text\nmutation NewMessage($message: String!, $threadId: ID!) {\n sendMessage(message: $message, threadId: $threadId) {\n ...messageInfo\n }\n}\n```\n\n```text\nmutation NewMessage(message: String!, threadId: ID!, $after: Cursor, first: Int) {\n\n sendMessage(message: $message, threadId: $threadId) {\n messageConnection(\n after: $after,\n first: $first,\n before: null,\n last: null\n ) @connection(key: \"messageConnection\") {\n edges {\n cursor\n node { ...messageInfo }\n }\n }\n }\n}\n```\n\n```text\n@connection\n```\n\n========================================\n\nComments:\n- Can we see the mutation too?\n- Thank you for so much for taking the time to take a stab at this. The issue turned out to be in the subscription rather than the mutation, I've posted an explanation in full as a separate answer: stackoverflow.com/a/48279184/2115623\n- this is exactly what i was looking for - it makes it so that the 'after', 'first', 'before', and 'last' variables are not considered as part of the cached query identifier. thank you!\n- I appreciate the perfect answer with proper explanation.","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":247,"estimatedTokens":1600}}584{"id":"stack-46719337","source":"stackoverflow","questionId":46719337,"title":"Node server on docker not accessible on localhost even after port binding","tags":["node.js","docker","localhost","graphql"],"text":"Title: Node server on docker not accessible on localhost even after port binding\nTags: node.js, docker, localhost, graphql\nSource: Stack Overflow\n\nQuestion:\nI have graphql node server. I am able to run it locally without docker. But after creating a docker container of the server and binding the container port with the host port this doesn't work.\n\nHere's my Dockerfile code:\n\n```\nFROM node:boron-alpine\n WORKDIR /app\n COPY package.json /app\n RUN npm install\n COPY . /app\n ENV SERVER_PORT 8080 \n EXPOSE 8080\n CMD npm run build && npm start\n```\n\nMy node server code is as such :\n\n```\napp.listen(process.env.SERVER_PORT,'0.0.0.0')\n console.log(`listening at ${port}`)\n```\n\nI run docker with the following command:\n\n```\ndocker run -it -p 8080:8080 nodeapi\n```\n\nThis works perfectly nodejs can see the env SERVER_PORT cause it shows\n\n```\n\"listening at 8080\"\n```\n\nin the console.\n\nBut when i open localhost:8080 this doesn't work (The site cannot be reached).\n\nI have also tried running docker command\n\n```\ndocker run -it -p 127.0.0.1:8080:8080 nodeapi\n```\n\nThis doesn't work\n\nI am using docker toolbox on windows 10 latest build\n\nThank you\n\n========================================\n\nTop Answer:\nIf you avoid specifying the IP 0.0.0.0\n\n```\napp.listen(process.env.SERVER_PORT, function () {\n console.log('Listening on port '+ process.env.SERVER_PORT);\n});\n```\n\nand\n\n```\ndocker run -it -p 8080:8080 nodeapi\n```\n\nit will let you load the site as\n\n```\nhttp://localhost:8080\n```\n\n========================================\n\nCode:\n```text\nFROM node:boron-alpine\n WORKDIR /app\n COPY package.json /app\n RUN npm install\n COPY . /app\n ENV SERVER_PORT 8080 \n EXPOSE 8080\n CMD npm run build && npm start\n```\n\n```text\napp.listen(process.env.SERVER_PORT,'0.0.0.0')\n console.log(`listening at ${port}`)\n```\n\n```text\ndocker run -it -p 8080:8080 nodeapi\n```\n\n```text\n\"listening at 8080\"\n```\n\n```text\ndocker run -it -p 127.0.0.1:8080:8080 nodeapi\n```\n\n```text\ndocker-machine ip\n```\n\n```text\nhttp://<IP>:8080\n```\n\n```text\napp.listen(process.env.SERVER_PORT, function () {\n console.log('Listening on port '+ process.env.SERVER_PORT);\n});\n```\n\n```text\ndocker run -it -p 8080:8080 nodeapi\n```\n\n```text\nhttp://localhost:8080\n```\n\n========================================\n\nComments:\n- This works perfectly thanks. But is there a way to map it to localhost instead?.\n- docker-machine ip gives No machine name(s) specified and no \"default\" machine exist to me\n- @scroobius, you can map it to localhost by doing port forwarding in the VM settings\n- @StepanYakovenko, you are using docker for windows or docker toolbox? You can manually launch virtualbox and see the machine name. If there is none then that means you haven't initialised the default machine as well","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":138,"estimatedTokens":685}}585{"id":"stack-45522750","source":"stackoverflow","questionId":45522750,"title":"spring boot starter graphql not working","tags":["java","spring","spring-boot","graphql","graphql-java"],"text":"Title: spring boot starter graphql not working\nTags: java, spring, spring-boot, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI recently started working with `graphql` and found it very intriguing. Since most of my `rest` apps were in `java`, I decided to do a quick setup using the provided spring boot starter project by the `graphql-java` team. It comes with `graph-iql` autoconf spring setup, which makes it easier to query `/graphql` endpoint. \n\nAfter spending a few good hours on the project setup in IDEA, I was able to run the graphql-sample-app. But I think my servlet is still not enabled, and only the `graphiql` endpoint is running, as the default query is returning `404`. \n\nThis is `application.yml`:\n\n```\nspring:\n application:\n name: graphql-todo-app\nserver:\n port: 9000\n\ngraphql:\n spring-graphql-common:\n clientMutationIdName: clientMutationId\n injectClientMutationId: true\n allowEmptyClientMutationId: false\n mutationInputArgumentName: input\n outputObjectNamePrefix: Payload\n inputObjectNamePrefix: Input\n schemaMutationObjectName: Mutation\n servlet:\n mapping: /graphql\n enabled: true\n corsEnabled: true\n\ngraphiql:\n mapping: /graphiql\n enabled: true\n```\n\nThis is what my `build.gradle` file looks like:\n\n```\nbuildscript {\n repositories {\n maven { url \"https://plugins.gradle.org/m2/\" }\n maven { url 'http://repo.spring.io/plugins-release' }\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE\")\n classpath \"com.jfrog.bintray.gradle:gradle-bintray-plugin:1.6\"\n }\n}\n\napply plugin: 'java'\napply plugin: 'org.springframework.boot'\n\nrepositories {\n jcenter()\n mavenCentral()\n}\n\ndependencies{\n// compile(project(\":graphql-spring-boot-starter\"))\n// compile(project(\":graphiql-spring-boot-starter\"))\n compile 'com.graphql-java:graphql-spring-boot-starter:3.6.0'\n\n // to embed GraphiQL tool\n compile 'com.graphql-java:graphiql-spring-boot-starter:3.6.0'\n\n compile \"com.embedler.moon.graphql:spring-graphql-common:$LIB_SPRING_GRAPHQL_COMMON_VER\"\n\n compile(\"org.springframework.boot:spring-boot-starter-web\")\n compile(\"org.springframework.boot:spring-boot-starter-actuator\")\n\n testCompile(\"org.springframework.boot:spring-boot-starter-test\")\n}\n\njar.enabled = true\nuploadArchives.enabled = false\nbintrayUpload.enabled = false\n```\n\nAfter running `gradle build`, I run the generated `jar` file from the terminal. This is what I get on localhost:\n\nhttps://i.sstatic.net/2qGRf.png\n\n========================================\n\nTop Answer:\nChange to version 1.5.9.RELEASE of the spring-boot-starter-stop and it worked for me\n\n========================================\n\nCode:\n```text\nspring:\n application:\n name: graphql-todo-app\nserver:\n port: 9000\n\ngraphql:\n spring-graphql-common:\n clientMutationIdName: clientMutationId\n injectClientMutationId: true\n allowEmptyClientMutationId: false\n mutationInputArgumentName: input\n outputObjectNamePrefix: Payload\n inputObjectNamePrefix: Input\n schemaMutationObjectName: Mutation\n servlet:\n mapping: /graphql\n enabled: true\n corsEnabled: true\n\ngraphiql:\n mapping: /graphiql\n enabled: true\n```\n\n```text\nbuildscript {\n repositories {\n maven { url \"https://plugins.gradle.org/m2/\" }\n maven { url 'http://repo.spring.io/plugins-release' }\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE\")\n classpath \"com.jfrog.bintray.gradle:gradle-bintray-plugin:1.6\"\n }\n}\n\napply plugin: 'java'\napply plugin: 'org.springframework.boot'\n\nrepositories {\n jcenter()\n mavenCentral()\n}\n\ndependencies{\n// compile(project(\":graphql-spring-boot-starter\"))\n// compile(project(\":graphiql-spring-boot-starter\"))\n compile 'com.graphql-java:graphql-spring-boot-starter:3.6.0'\n\n // to embed GraphiQL tool\n compile 'com.graphql-java:graphiql-spring-boot-starter:3.6.0'\n\n compile \"com.embedler.moon.graphql:spring-graphql-common:$LIB_SPRING_GRAPHQL_COMMON_VER\"\n\n compile(\"org.springframework.boot:spring-boot-starter-web\")\n compile(\"org.springframework.boot:spring-boot-starter-actuator\")\n\n testCompile(\"org.springframework.boot:spring-boot-starter-test\")\n}\n\njar.enabled = true\nuploadArchives.enabled = false\nbintrayUpload.enabled = false\n```\n\n```text\ngraphql\n```\n\n```text\nrest\n```\n\n```text\njava\n```\n\n```text\ngraphql-java\n```\n\n```text\ngraph-iql\n```\n\n```text\n/graphql\n```\n\n```text\ngraphiql\n```\n\n```text\n404\n```\n\n```text\napplication.yml\n```\n\n```text\nbuild.gradle\n```\n\n```text\ngradle build\n```\n\n```text\njar\n```\n\n========================================\n\nComments:\n- It's a little hard to tell what's going on without the full code, would you mind creating a sample project and throwing it up on github?","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":211,"estimatedTokens":1213}}586{"id":"stack-68690827","source":"stackoverflow","questionId":68690827,"title":"Can't import IResolvers from graphql-tools","tags":["typescript","graphql","apollo","apollo-server","graphql-tools"],"text":"Title: Can't import IResolvers from graphql-tools\nTags: typescript, graphql, apollo, apollo-server, graphql-tools\nSource: Stack Overflow\n\nQuestion:\n`import { IResolvers } from \"graphql-tools\";`\nI was trying to import IResolvers from graphql-tools and got the message Module: *'\"../node_modules/graphql-tools\"' has no exported member 'IResolvers'*.\n\nMy dependencies are:\"apollo-server-express\": \"^3.1.2\",\"graphql\": \"^15.5.1\", \"graphql-tools\": \"^8.1.0\"\n\nIs this because I am on apollo 3 instead of apollo 2 which has IResolver?\n\n========================================\n\nCode:\n```text\nimport { IResolvers } from \"graphql-tools\";\n```\n\n```text\nIResolvers\n```\n\n```text\nnpm install graphql-tools@4.x\n```\n\n```text\ngraphql-tools\n```\n\n```text\nnpm install @graphql-tools/utils\n```\n\n```text\nIResolvers\n```\n\n```text\n@graphql-tools/utils\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":42,"estimatedTokens":207}}587{"id":"stack-74669446","source":"stackoverflow","questionId":74669446,"title":"How to get Apollo gql codgen to work with frontend nextJS","tags":["reactjs","typescript","next.js","graphql","react-apollo"],"text":"Title: How to get Apollo gql codgen to work with frontend nextJS\nTags: reactjs, typescript, next.js, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI am using nextJS, I want my front end react queries with apollo to be typed out, but no configuration is working. I get an unknown error on my query when I use `import {gql} from src/__generated__/gql` and the following message when I hover over gql():\n\n`The query argument is unknown! Please regenerate the types`\n\nMy question is do I need to do something different because I am using nextJS? I want to be able to use TypeScript with Apollo Client code gendocs so my gql queries will be typed\n\n**My entire pothos schema is in my `pages/api/index.ts` file (*I do not yet know how to spread this code out into multiple files*)**\n\nExample Query:\n\n```\nconst CREATED_EVENT_QUERY = gql(`\n query EventById($id: mongoId!) {\n eventById(id: $id) {\n _id\n name\n description\n location{\n coordinates\n }\n date\n eventApplicants{\n name\n userId\n weight\n }\n link\n weights{\n weight\n spotsAvailable{\n name\n userId\n }\n }\n }\n }\n `);\n\n// Apollo Query\n\n const { loading, error, data } = useQuery(CREATED_EVENT_QUERY, {\n variables: {\n id: params.id\n }\n });\n```\n\n### I have tried the following configurations:\n\n### Apollos recommendation\n\n*Link Above*\n\n```\nimport { CodegenConfig } from '@graphql-codegen/cli';\n\nconst config: CodegenConfig = {\n schema: 'http://localhost:3000/api',\n documents: ['*.ts'],\n generates: {\n './src/__generated__/': {\n preset: 'client',\n plugins: [],\n presetConfig: {\n gqlTagName: 'gql',\n }\n }\n },\n ignoreNoDocuments: true,\n};\n\nexport default config;\n```\n\n### the guilds nextJS recomendation\n\n```\nimport type { CodegenConfig } from '@graphql-codegen/cli'\n\nconst config: CodegenConfig = {\n // ...\n generates: {\n 'path/to/file.ts': {\n plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],\n config: {\n reactApolloVersion: 3\n }\n }\n }\n}\nexport default config\n```\n\n### combination of the two\n\n```\nimport { CodegenConfig } from '@graphql-codegen/cli';\n\nconst config: CodegenConfig = {\n schema: 'http://localhost:3000/api',\n documents: ['*.ts'],\n generates: {\n 'pages/api/index.ts': {\n plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],\n config: {\n reactApolloVersion: 3\n }\n }\n },\n ignoreNoDocuments: true,\n};\n\nexport default config;\n```\n\n========================================\n\nTop Answer:\nI found out the reason why I was facing the problem. This was my previous configuration object.\n\n```\nconst config: CodegenConfig = {\n schema: 'http://localhost:3000/bff/graphql',\n documents: ['src/**/*.tsx'],\n generates: {\n './src/__generated__/': {\n preset: 'client',\n plugins: [],\n presetConfig: {\n gqlTagName: 'gql',\n },\n },\n },\n ignoreNoDocuments: true,\n};\n```\n\nThis is the configuration object that works. The reason for that is I was writing custom React hooks and I included the code in `*.ts` files. However, I wasn't including `*.ts` files in the config file. That's why it's not working even if I tried recompiling.\n\n```\nconst config: CodegenConfig = {\n schema: 'http://localhost:3000/bff/graphql',\n documents: ['src/**/*.ts', 'src/**/*.tsx'],\n generates: {\n './src/__generated__/': {\n preset: 'client',\n plugins: [],\n presetConfig: {\n gqlTagName: 'gql',\n },\n },\n },\n ignoreNoDocuments: true,\n};\n```\n\n========================================\n\nCode:\n```js\nconst CREATED_EVENT_QUERY = gql(`\n query EventById($id: mongoId!) {\n eventById(id: $id) {\n _id\n name\n description\n location{\n coordinates\n }\n date\n eventApplicants{\n name\n userId\n weight\n }\n link\n weights{\n weight\n spotsAvailable{\n name\n userId\n }\n }\n }\n }\n `);\n\n// Apollo Query\n\n const { loading, error, data } = useQuery(CREATED_EVENT_QUERY, {\n variables: {\n id: params.id\n }\n });\n```\n\n```js\nimport { CodegenConfig } from '@graphql-codegen/cli';\n\nconst config: CodegenConfig = {\n schema: 'http://localhost:3000/api',\n documents: ['*.ts'],\n generates: {\n './src/__generated__/': {\n preset: 'client',\n plugins: [],\n presetConfig: {\n gqlTagName: 'gql',\n }\n }\n },\n ignoreNoDocuments: true,\n};\n\nexport default config;\n```\n\n```js\nimport type { CodegenConfig } from '@graphql-codegen/cli'\n\nconst config: CodegenConfig = {\n // ...\n generates: {\n 'path/to/file.ts': {\n plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],\n config: {\n reactApolloVersion: 3\n }\n }\n }\n}\nexport default config\n```\n\n```js\nimport { CodegenConfig } from '@graphql-codegen/cli';\n\nconst config: CodegenConfig = {\n schema: 'http://localhost:3000/api',\n documents: ['*.ts'],\n generates: {\n 'pages/api/index.ts': {\n plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],\n config: {\n reactApolloVersion: 3\n }\n }\n },\n ignoreNoDocuments: true,\n};\n\nexport default config;\n```\n\n```text\nimport {gql} from src/__generated__/gql\n```\n\n```text\nThe query argument is unknown! Please regenerate the types\n```\n\n```text\npages/api/index.ts\n```\n\n```text\n// in the root of your project\n\nimport { CodegenConfig } from \"@graphql-codegen/cli\";\n\nconst config: CodegenConfig = {\n schema: \"http://localhost:3000/api\",\n documents: [\"app/**/*.tsx\", \"!pages/api/index.ts\"],\n generates: {\n \"./src/__generated__/\": {\n preset: \"client\",\n plugins: [],\n presetConfig: {\n gqlTagName: \"gql\",\n },\n },\n },\n ignoreNoDocuments: true,\n};\n\nexport default config;\n```\n\n```text\n\"scripts\": {\n \"compile\": \"graphql-codegen\",\n \"watch\": \"graphql-codegen --w\"\n },\n```\n\n```text\nimport {gql} from \"src/__generated__\"\n```\n\n```text\nconst config: CodegenConfig = {\n schema: 'http://localhost:3000/bff/graphql',\n documents: ['src/**/*.tsx'],\n generates: {\n './src/__generated__/': {\n preset: 'client',\n plugins: [],\n presetConfig: {\n gqlTagName: 'gql',\n },\n },\n },\n ignoreNoDocuments: true,\n};\n```\n\n```text\nconst config: CodegenConfig = {\n schema: 'http://localhost:3000/bff/graphql',\n documents: ['src/**/*.ts', 'src/**/*.tsx'],\n generates: {\n './src/__generated__/': {\n preset: 'client',\n plugins: [],\n presetConfig: {\n gqlTagName: 'gql',\n },\n },\n },\n ignoreNoDocuments: true,\n};\n```\n\n```text\n*.ts\n```\n\n```text\n*.ts\n```\n\n========================================\n\nComments:\n- Have u found any solution for this problem yet?\n- I think so. I will post a solution later today.\n- Sorry @StephenFong forgot to post the solution sooner. I posted answer below please lmk if that works for you","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":353,"estimatedTokens":1714}}588{"id":"stack-55002303","source":"stackoverflow","questionId":55002303,"title":"Why use Prisma in a backend environment?","tags":["graphql","prisma"],"text":"Title: Why use Prisma in a backend environment?\nTags: graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nAfter learning about GraphQL and using it in a few projects, I finally wanted to give Prisma a go. It promises to eliminate the need for a database and it generates a GraphQL client and a working database from the GraphQL Schema. So far so good.\n\nBut my question is: A GraphQL client to me really only seems useful for a client (prevent overfetching, speed up pages, React integrations, ...). Prisma however does not eliminate the need for business logic, and so one would end up using the generated client library in Node.js, just to reexport a lot of the functionality in yet another GraphQL server to the actual client.\n\nWhy should I prefer Prisma over a custom database solution? Is there a thought behind having to re-expose a lot of endpoints to the actual client?\n\n========================================\n\nTop Answer:\nEven I had similar questions when I started learning graphql. This is what I learned and realised after using it.\n\nPrisma acts as a proxy for your database providing you with a ready\nto use GraphQL API that allows you to filter and sort data along with\nsome custom types like `DateTime` which are not a part of graphql and\nyou'd have to otherwise implement yourself. It's not a GraphQL server. Just a \nlayer between your database and backend server like an ORM.\n\nIt covers almost all the possible usecases that you might have from a\ndata model with all the **CRUD** operations pre-defined in a schema\nalong with **subscriptions**, so you don't have to do all that stuff\nand focus more on your business logic side of things.\n\nAlso it removes the dependency of you writing different queries for\ndifferent databases like Sql or MongoDb acting as a layer to\ntransform it's query language to actual database queries.\n\nYou can use the API(graphql) server to expose only the desired schema\nto the client rather than everything. Since graphql queries can get\nhighly nested, it may be difficult and tricky to implement that which\nmay also lead to performance issues which is not the case in Prisma as it handles everything itself.\n\nYou can check out this article for more info.\n\n========================================\n\nCode:\n```text\nDateTime\n```\n\n========================================\n\nComments:\n- I've just sent you an email to the address I've found on your website and shared a preview of the blog post that I mentioned in my answer. I hope this addresses all your questions! Please let me know if you have any further questions. @NikxDa\n- @nburk Thanks for helping out with this! I'll be checking out the blog post tonight and I'll get back to you via mail about it. I appreciate the help! :)\n- @nburk I've dropped you a mail. Thanks for the insight! I'll edit the blog post into your answer once it is released.\n- Awesome, thanks so much for the feedback! Great to hear the article resonates with you :) Happy to help with any further questions.","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":52,"estimatedTokens":744}}589{"id":"stack-40324512","source":"stackoverflow","questionId":40324512,"title":"Apollo GraphQL: Multiple Queries in One Component?","tags":["graphql","apollo","apollo-server"],"text":"Title: Apollo GraphQL: Multiple Queries in One Component?\nTags: graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI have a component that needs to query two entirely separate tables. What do the schema, query and resolver need to look like in this case? I've googled but haven't found examples yet. Thanks in advance for any info.\n\n**UPDATE:**\nOn Slack I see there may be a way to use `compose` for this purpose, e.g.:\n\n```\nexport default compose(\n graphql(query1, \n ....),\n graphql(query2, \n ....),\n graphql(query3, \n ....),\n withApollo\n)(PrintListEditPage)\n```\n\nIs there a way to have multiple declarations like this:\n\n```\nconst withMutations = graphql(updateName, {\n props({ mutate }) {\n return {\n updatePrintListName({ printListId, name }) {\n return mutate({\n variables: { printListId, name },\n });\n },\n };\n },\n});\n```\n\n...that come before the call to `export default compose`?\n\n========================================\n\nCode:\n```js\nexport default compose(\n graphql(query1, \n ....),\n graphql(query2, \n ....),\n graphql(query3, \n ....),\n withApollo\n)(PrintListEditPage)\n```\n\n```js\nconst withMutations = graphql(updateName, {\n props({ mutate }) {\n return {\n updatePrintListName({ printListId, name }) {\n return mutate({\n variables: { printListId, name },\n });\n },\n };\n },\n});\n```\n\n```text\ncompose\n```\n\n```text\nexport default compose\n```\n\n```js\nimport { graphql, compose } from 'react-apollo'\n\nexport default compose(\n graphql(mutation1, { name: 'createSomething' }),\n graphql(mutation2, { name: 'deleteSomething' }),\n)(Component)\n```\n\n```text\ngraphql\n```\n\n```text\nname\n```\n\n```text\nmutate\n```\n\n========================================\n\nComments:\n- This is outdated. `react-apollo` no longer exports `compose`.","metadata":{"transformedAt":"2026-08-18T18:32:36.069Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":102,"estimatedTokens":444}}590{"id":"stack-41092127","source":"stackoverflow","questionId":41092127,"title":"ES6 Fat Arrow and Parentheses `(...) => ({...})`","tags":["javascript","reactjs","ecmascript-6","graphql","relay"],"text":"Title: ES6 Fat Arrow and Parentheses `(...) => ({...})`\nTags: javascript, reactjs, ecmascript-6, graphql, relay\nSource: Stack Overflow\n\nQuestion:\nI've been working through some Graph QL/React/Relay examples and I ran into some strange syntax.\n\nWhen defining the fields in Graph QL Objects the following syntax is used:\n\n```\nconst xType = new GraphQLObjectType({\n name: 'X',\n description: 'A made up type for example.',\n fields: () => ({\n field: {/*etc.*/}\n })\n});\n```\n\nFrom what I gather this is just defining an anonymous function and assigning it to xType.fields. That anonymous function returns the object containing the field definitions. \n\nI'm assuming with however the Graph QL schema mechanism works this has to be defined as a function returning an object rather than simply an object. But the part that has me confused is the parenthesis around the curly braces.\n\nIs this to differentiate an object definition from a function definition? Is it for clarity's sake for the reader?\n\nThe only similar syntax a google search has found is in the airbnb style guide where it seems to be a readability/clarity thing.\n\nJust looking for confirmation or an explanation beyond my assumptions as I start to play around with Graph QL a little more.\n\n========================================\n\nTop Answer:\nIt's for clarity's sake for the compiler as well as for the reader. The `field:` syntax in your example appears to be an unambiguous giveaway that this is an object literal, but take this code for instance:\n\n\r\n\r\n\n```\nlet f = () => {\r\n field: 'value'\r\n}\r\n\r\nconsole.log(f()) //=> undefined\n```\n\n\r\n\r\n\r\n\nYou would expect this to log an object with `field` set to `'value'`, but it logs `undefined`. Why?\n\nEssentially, what you see as an object literal with a single property, the compiler sees as a function body (denoted by opening and closing curly braces, like a typical function) and a single label statement, which uses the syntax `label:`. Since the expression following is it just a literal string, and it is never returned (or even assigned to a variable), the function `f()` effectively does nothing, and its result is `undefined`.\n\nHowever, by placing parentheses around your \"object literal,\" you tell the compiler to treat the same characters as an expression rather than a bunch of statements, and so the object you desire is returned. (See this article on the Mozilla Development Network, from the comments section.)\n\n\r\n\r\n\n```\nlet g = () => ({\r\n field: 'value'\r\n})\r\n\r\nconsole.log(g()) //=> { field: 'value' }\n```\n\n========================================\n\nCode:\n```text\nconst xType = new GraphQLObjectType({\n name: 'X',\n description: 'A made up type for example.',\n fields: () => ({\n field: {/*etc.*/}\n })\n});\n```\n\n```text\nfields: () => ({\n field: {/*etc.*/}\n})\n```\n\n```text\nfields: () => { // start of the function body\n // now we have to define an object \n // and explicitly use the return keyword\n return { field: {/*etc.*/} }\n}\n```\n\n```text\n()\n```\n\n```text\n{}\n```\n\n```text\n()\n```\n\n```text\nfield: ...\n```\n\n```text\nlabel\n```\n\n```text\nundefined\n```\n\n```js\nlet f = () => {\n field: 'value'\n}\n\nconsole.log(f()) //=> undefined\n```\n\n```js\nlet g = () => ({\n field: 'value'\n})\n\nconsole.log(g()) //=> { field: 'value' }\n```\n\n```text\nfield:\n```\n\n```text\nfield\n```\n\n```text\n'value'\n```\n\n```text\nundefined\n```\n\n```text\nlabel:\n```\n\n```text\nf()\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- \"Is this to differentiate an object definition from a function definition? Is it for clarity's sake for the reader?\" Yes, it is just that.\n- You can get more info at the duplicated question, or in this MDN article.","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":166,"estimatedTokens":914}}591{"id":"stack-68601402","source":"stackoverflow","questionId":68601402,"title":"Issue with refetchQueries in the Apollo Client useMutation hook","tags":["reactjs","graphql","apollo-client","react-apollo","graphql-mutation"],"text":"Title: Issue with refetchQueries in the Apollo Client useMutation hook\nTags: reactjs, graphql, apollo-client, react-apollo, graphql-mutation\nSource: Stack Overflow\n\nQuestion:\nI'm running into the following error while trying to define `refetchQueries` in my `useMutation` hook.\n\n```\nType 'DocumentNode' is not assignable to type 'string | PureQueryOptions'. \nProperty 'query' is missing in type 'DocumentNode' but required in type 'PureQueryOptions'.\n```\n\nI'm not sure what I'm doing wrong as the official Apollo documentation is a bit unclear on it and I can't find any precedence when Googling.\n\nAs I understand the error, the property `query` is missing from my GraphQL query. Am I passing the right value to the `refetchQueries`? I think I'm doing it correctly, but then I don't know why it's complaining about `query` not being part of it.\n\n**Code**\n\n```\nimport { useMutation, useQuery } from '@apollo/client';\nimport { GET_CUSTOMERS, MARK_AS_VIP } from './queries';\n\nexport default function Customers() {\n const [ markAsVIP, { data: vips, loading: vipLoading, error: vipError } ] = useMutation( MARK_AS_VIP );\n const { loading, error, data: getCustomerResp } = useQuery( GET_CUSTOMERS );\n\n const handleMarkAsVIP = ( customerId: string ) => {\n markAsVIP( {\n variables: { id: customerId, tags: [ 'VIP' ] },\n refetchQueries: [\n GET_CUSTOMERS, // error shows here\n 'getCustomers'\n ]\n } )\n }\n}\n```\n\n**Queries**\n\n```\nimport { gql } from '@apollo/client';\n\nexport const GET_CUSTOMERS = gql`\n query getCustomers {\n customers( first: 50 ) {\n edges {\n cursor\n node {\n id\n displayName\n tags\n }\n }\n }\n }\n `;\n\nexport const MARK_AS_VIP = gql`\n mutation markAsVIP( $id: ID!, $tags: [String!]! ) {\n tagsAdd( id: $id, tags: $tags ) {\n node {\n id\n }\n userErrors {\n field\n message\n }\n }\n }\n`;\n```\n\n========================================\n\nCode:\n```text\nType 'DocumentNode' is not assignable to type 'string | PureQueryOptions'. \nProperty 'query' is missing in type 'DocumentNode' but required in type 'PureQueryOptions'.\n```\n\n```text\nimport { useMutation, useQuery } from '@apollo/client';\nimport { GET_CUSTOMERS, MARK_AS_VIP } from './queries';\n\nexport default function Customers() {\n const [ markAsVIP, { data: vips, loading: vipLoading, error: vipError } ] = useMutation( MARK_AS_VIP );\n const { loading, error, data: getCustomerResp } = useQuery( GET_CUSTOMERS );\n\n const handleMarkAsVIP = ( customerId: string ) => {\n markAsVIP( {\n variables: { id: customerId, tags: [ 'VIP' ] },\n refetchQueries: [\n GET_CUSTOMERS, // error shows here\n 'getCustomers'\n ]\n } )\n }\n}\n```\n\n```text\nimport { gql } from '@apollo/client';\n\nexport const GET_CUSTOMERS = gql`\n query getCustomers {\n customers( first: 50 ) {\n edges {\n cursor\n node {\n id\n displayName\n tags\n }\n }\n }\n }\n `;\n\nexport const MARK_AS_VIP = gql`\n mutation markAsVIP( $id: ID!, $tags: [String!]! ) {\n tagsAdd( id: $id, tags: $tags ) {\n node {\n id\n }\n userErrors {\n field\n message\n }\n }\n }\n`;\n```\n\n```text\nrefetchQueries\n```\n\n```text\nuseMutation\n```\n\n```text\nquery\n```\n\n```text\nrefetchQueries\n```\n\n```text\nquery\n```\n\n```js\nconst handleMarkAsVIP = ( customerId: string ) => {\n markAsVIP({\n variables: { id: customerId, tags: [ 'VIP' ] },\n refetchQueries: [\n { query: GET_CUSTOMERS },\n 'getCustomers'\n ]\n })\n}\n```\n\n```text\nquery\n```\n\n```text\nquery\n```\n\n========================================\n\nComments:\n- Thanks! I had exactly the same issue, but couldn't figure it out :D\n- There is an issue that your GET_CUSTOMERS query will work without most recently provided set of variables.\n- Thanks... I am surprised not to see this in the official docs.","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":180,"estimatedTokens":970}}592{"id":"stack-49442317","source":"stackoverflow","questionId":49442317,"title":"Github GraphQL Repository Query, commits totalCount","tags":["search","github","repository","graphql","github-graphql"],"text":"Title: Github GraphQL Repository Query, commits totalCount\nTags: search, github, repository, graphql, github-graphql\nSource: Stack Overflow\n\nQuestion:\nHow to search for Github Repositories using GraphQL, and get its *total commits count* as well in return? \n\nIt looks strange to me that all fields available describing Repositories contains total count of commit *comments* but not total count of *commits*.\n\n========================================\n\nTop Answer:\nbswinnerton's answer works well, but not for repositories without a `master` branch.\nIn this case you can use `defaultBranchRef`\n\nHere's an example of how to get the total number of commits for the **default** branch in the rails/rails repository\n\n```\nquery {\n repository(owner:\"rails\", name:\"rails\") {\n defaultBranchRef {\n target {\n ... on Commit {\n history {\n totalCount\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n repository(owner:\"rails\", name:\"rails\") {\n object(expression:\"master\") {\n ... on Commit {\n history {\n totalCount\n }\n }\n }\n }\n}\n```\n\n```text\nmaster\n```\n\n```text\nquery {\n repository(owner:\"rails\", name:\"rails\") {\n defaultBranchRef {\n target {\n ... on Commit {\n history {\n totalCount\n }\n }\n }\n }\n }\n}\n```\n\n```text\nmaster\n```\n\n```text\ndefaultBranchRef\n```\n\n========================================\n\nComments:\n- This Q/A helped me find a better Github search approach, FYI.\n- OMG bswinnerton, you are better than the Github insiders that support GraphQL -- they said that it is impossible now and hard to do in future. Amazing!\n- I may *be* a GitHub insider π\n- @bswinnerton Please can tell me how I'll make request using C# to call API v4 query for getting commit count, folks count, watch count & Created Date for a repository?? I've list of some repository\n- what does ... on Commit mean?\n- @jjxtra It is an inline fragment\n- This actually helped with GitLab's GraphQL API! Thanks!!","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":88,"estimatedTokens":502}}593{"id":"stack-63584205","source":"stackoverflow","questionId":63584205,"title":"How to set custom message for regex in joi","tags":["error-handling","graphql","joi"],"text":"Title: How to set custom message for regex in joi\nTags: error-handling, graphql, joi\nSource: Stack Overflow\n\nQuestion:\nWhen I validate my graphql arguments, I'm getting error message like this for the password field.\n\n```\n\"password\" with value \"\" fails to match the required pattern: /^(?=\\\\S*[a-z])(?=\\\\S*[A-Z])(?=\\\\S*\\\\d)(?=\\\\S*[^\\\\w\\\\s])\\\\S{8,30}$/\"\n```\n\nI don't want to show regex pattern in the error message. So I tried to set the custom error message for the password field but still it's showing the regex pattern.\n\n```\nimport Joi from \"joi\";\n\nexport default Joi.object().keys({\n email: Joi.string().email().required().label(\"Email\"),\n username: Joi.string().alphanum().min(4).max(20).required().label(\"Username\"),\n name: Joi.string().min(4).max(256).required().label(\"Name\"),\n password: Joi.string()\n .min(8)\n .regex(/^(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*\\d)(?=\\S*[^\\w\\s])\\S{8,30}$/)\n .required()\n .label(\"Password\")\n .messages({\n \"string.min\": \"Must have at least 8 characters\",\n \"object.regex\": \"Must have at least 8 characters\",\n }),\n});\n```\n\nI think it's not selecting the regex by `object.regex`. Please help.\n\n========================================\n\nCode:\n```text\n\"password\" with value \"\" fails to match the required pattern: /^(?=\\\\S*[a-z])(?=\\\\S*[A-Z])(?=\\\\S*\\\\d)(?=\\\\S*[^\\\\w\\\\s])\\\\S{8,30}$/\"\n```\n\n```js\nimport Joi from \"joi\";\n\nexport default Joi.object().keys({\n email: Joi.string().email().required().label(\"Email\"),\n username: Joi.string().alphanum().min(4).max(20).required().label(\"Username\"),\n name: Joi.string().min(4).max(256).required().label(\"Name\"),\n password: Joi.string()\n .min(8)\n .regex(/^(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*\\d)(?=\\S*[^\\w\\s])\\S{8,30}$/)\n .required()\n .label(\"Password\")\n .messages({\n \"string.min\": \"Must have at least 8 characters\",\n \"object.regex\": \"Must have at least 8 characters\",\n }),\n});\n```\n\n```text\nobject.regex\n```\n\n```text\nconst Joi = require('@hapi/joi');\n\nconst joiSchema = Joi.object().keys({\n password: Joi.string()\n .min(8)\n .regex(/^(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*\\d)(?=\\S*[^\\w\\s])\\S{8,30}$/)\n .required()\n .label(\"Password\")\n .messages({\n \"string.min\": \"Must have at least 8 characters\",\n \"object.regex\": \"Must have at least 8 characters\",\n \"string.pattern.base\": \"enter your custom error here...\"\n })\n});\n\nconst validationResult = joiSchema.validate({ password: \"2\" }, { abortEarly: false });\nconsole.log(validationResult.error.details.map(errDetail => errDetail.type), validationResult.error);\n```\n\n```text\ntype\n```\n\n```text\n[\"string.min\", \"string.pattern.base\"]\n```\n\n```text\ndetails\n```\n\n```text\nabortEarly\n```\n\n========================================\n\nComments:\n- this always display the string.pattern.base even the data is already valid.","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":104,"estimatedTokens":692}}594{"id":"stack-46080411","source":"stackoverflow","questionId":46080411,"title":"React Apollo MockProvider always loading, never giving data","tags":["reactjs","mocking","graphql","enzyme","react-apollo"],"text":"Title: React Apollo MockProvider always loading, never giving data\nTags: reactjs, mocking, graphql, enzyme, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm trying to test a component that uses graphql, but when using Apollo's MockProvider I never get the data, it just says loading = true every time.\n\nA complete, minimalist example is here\n\nThings I've tried: \n\n \n- Looking online (found this similar question, but since it had no answer I thought I'd make a new one with more information)\n\n- Tried exporting components without the graphql when testing (`export function Component`), but that doesn't work when testing nested components\n\n- Tried simplifying as much as possible (the results of which is in the example)\n\n========================================\n\nTop Answer:\nI'm not a fan of the `await wait(0)` approach. Looking at the apollo docs: \n\n`For more complex UI with heavy calculations, or delays added into its render logic, the wait(0) will not be long enough.`\n\nThis means that your tests can potentially be flaky. To solve this issue I use the `wait-for-expect` package (also covered in the docs: https://www.apollographql.com/docs/guides/testing-react-components.html#Testing-mutation-components):\n\n```\nit('should render the HeroDiv if there is guide data', async () => {\n const wrapper = mount(\n \n \n \n );\n\n await waitForExpect(() => {\n wrapper.update();\n expect(wrapper.find('HeroDiv').exists()).toBeTruthy();\n });\n})\n```\n\n`waitForExpect` will essentially poll until the condition is complete and it times out after 5 seconds. This guarantees that your test will complete, as long as your query completes before 5 seconds, which it absolutely should if you're using MockedProvider.\n\nThe docs point out one caveat: `The risk of using a package like this everywhere by default is that every test could take up to five seconds to execute (or longer if the default timeout has been increased).` But in my experience this won't ever happen with MockedProvider. Also aside, `await wait(0)` would not handle this case consistently anyway.\n\n========================================\n\nCode:\n```text\nexport function Component\n```\n\n```js\nit('should render the HeroDiv if there is guide data', async () => {\n const wrapper = mount(\n <MockedProvider mocks={mocksWithGuideData} addTypename={false}>\n <Hero {...props} />\n </MockedProvider>\n );\n\n await wait(0);\n wrapper.update();\n\n expect(wrapper.find('HeroDiv').exists()).toBeTruthy();\n})\n```\n\n```text\nwrapper\n```\n\n```text\nwrapper.update()\n```\n\n```text\nit('should render the HeroDiv if there is guide data', async () => {\n const wrapper = mount(\n <MockedProvider mocks={mocksWithGuideData} addTypename={false}>\n <Hero {...props} />\n </MockedProvider>\n );\n\n await waitForExpect(() => {\n wrapper.update();\n expect(wrapper.find('HeroDiv').exists()).toBeTruthy();\n });\n})\n```\n\n```text\nawait wait(0)\n```\n\n```text\nFor more complex UI with heavy calculations, or delays added into its render logic, the wait(0) will not be long enough.\n```\n\n```text\nwait-for-expect\n```\n\n```text\nwaitForExpect\n```\n\n```text\nThe risk of using a package like this everywhere by default is that every test could take up to five seconds to execute (or longer if the default timeout has been increased).\n```\n\n```text\nawait wait(0)\n```\n\n```text\nimport { CURRENT_USER_QUERY } from '../lib/queries';\n```\n\n```text\nimport { CURRENT_USER_QUERY } from './User';\n```\n\n========================================\n\nComments:\n- what are you using? Enzyme?\n- @arcom yes. Added the tag\n- Yeah, that's weird but it worked. For anyone else reading this, substitute the `wait` for wrapping the `expect` in setTimeout with 0 time\n- amazing, i've been stuck on this for days...Thanks a lot","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":130,"estimatedTokens":933}}595{"id":"stack-38970764","source":"stackoverflow","questionId":38970764,"title":"How I can use graphql with angular 1.5?","tags":["angularjs","graphql"],"text":"Title: How I can use graphql with angular 1.5?\nTags: angularjs, graphql\nSource: Stack Overflow\n\nQuestion:\nI have standart factories in my angular app for rest api. I need to configure my angular app for api with **GraphQl**. How i can do this? I now about\nangular2-apollo but I have **angular 1.5**.\n\n========================================\n\nTop Answer:\nYou can use `angular1-apollo` package.\n\nhttp://github.com/apollostack/angular1-apollo\n\n========================================\n\nCode:\n```text\nangular1-apollo\n```\n\n========================================\n\nComments:\n- @kamil's answer is more updated, I can't delete mine until it get's to be the accepted answer...\n- is it possible to use in AngularJS app which is written in Javascript. I saw your repository in GitHub, it's in typescript. As far as I know for a AngularJS app, a javascript file needs to be added to the app, I didn't find a javascript file for angualr1-apollo.\n- When trying to do `npm run build` on this example and running it I encounter an error: `Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:unpr] Unknown provider: e` Do you know how to fix this?\n- My guess: js-minification. It only runs on build and angular 1's DI breaks during minification. If it was me I'd run eject and then add the angularjs injection babel plugin or modify the webpack config to remove minification.","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":29,"estimatedTokens":351}}596{"id":"stack-55446867","source":"stackoverflow","questionId":55446867,"title":"How to set Auth token cookie from GraphQL Mutation with Apollo","tags":["reactjs","cookies","graphql","apollo","prisma"],"text":"Title: How to set Auth token cookie from GraphQL Mutation with Apollo\nTags: reactjs, cookies, graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm using GraphQLServer from graphql-yoga to handle requests. My back-end is able to communicate with my React front-end at this point and I can make graphql queries and get the response just fine.\n\nI was recently informed that I should be setting a cookie with the token, rather than returning it in the mutation response. So I'm trying to switch over but the cookie isn't being set by the mutation.\n\n***server.js*** (node)\n\n```\nimport { GraphQLServer, PubSub } from 'graphql-yoga';\nimport {resolvers, fragmentReplacements} from './resolvers/index'\nimport prisma from './prisma'\n\nconst pubsub = new PubSub()\n\nexport default new GraphQLServer({\n typeDefs: './src/schema.graphql',\n resolvers,\n context(request) {\n return {\n pubsub,\n prisma,\n request, //fragmentReplacements[], request, response\n }\n },\n fragmentReplacements\n});\n```\n\n***Mutation.js*** (node)\n\n```\nexport default {\n async createUser(parent, args, {prisma, request}, info) {\n const lastActive = new Date().toISOString()\n const user = await prisma.mutation.createUser({ data: {...args.data, lastActive }})\n const token = generateToken(user.id)\n const options = {\n maxAge: 1000 * 60 * 60 * 24, //expires in a day\n // httpOnly: true, // cookie is only accessible by the server\n // secure: process.env.NODE_ENV === 'prod', // only transferred over https\n // sameSite: true, // only sent for requests to the same FQDN as the domain in the cookie\n }\n const cookie = request.response.cookie('token', token, options)\n console.log(cookie)\n return {user}\n },\n // more mutations...\n```\n\nhttps://i.sstatic.net/USsiz.png\n\nconsole.log(cookie) outputs with the cookie attached\n\n***index.js*** (react)\n\n```\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './components/App';\nimport ApolloClient, { InMemoryCache, create } from 'apollo-boost';\nimport {ApolloProvider} from 'react-apollo'\n\nconst client = new ApolloClient({\n uri: 'http://localhost:4000',\n cache: new InMemoryCache(),\n credentials: 'include',\n request: async operation => {\n operation.setContext({\n fetchOptions: {\n credentials: 'same-origin'\n }\n })\n },\n})\n\nReactDOM.render(\n \n \n , \n document.getElementById('root'));\n```\n\nSo my questions are:\n\n- **Is there a better way to do authentication with GraphQL**, or is setting the token with a cookie in the auth mutation suitable?\n\n- Assuming it's a decent approach, **how can I set the cookie from the mutation**?\n\nThanks for your time!\n\n========================================\n\nCode:\n```text\nimport { GraphQLServer, PubSub } from 'graphql-yoga';\nimport {resolvers, fragmentReplacements} from './resolvers/index'\nimport prisma from './prisma'\n\nconst pubsub = new PubSub()\n\nexport default new GraphQLServer({\n typeDefs: './src/schema.graphql',\n resolvers,\n context(request) {\n return {\n pubsub,\n prisma,\n request, //fragmentReplacements[], request, response\n }\n },\n fragmentReplacements\n});\n```\n\n```text\nexport default {\n async createUser(parent, args, {prisma, request}, info) {\n const lastActive = new Date().toISOString()\n const user = await prisma.mutation.createUser({ data: {...args.data, lastActive }})\n const token = generateToken(user.id)\n const options = {\n maxAge: 1000 * 60 * 60 * 24, //expires in a day\n // httpOnly: true, // cookie is only accessible by the server\n // secure: process.env.NODE_ENV === 'prod', // only transferred over https\n // sameSite: true, // only sent for requests to the same FQDN as the domain in the cookie\n }\n const cookie = request.response.cookie('token', token, options)\n console.log(cookie)\n return {user}\n },\n // more mutations...\n```\n\n```text\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './components/App';\nimport ApolloClient, { InMemoryCache, create } from 'apollo-boost';\nimport {ApolloProvider} from 'react-apollo'\n\nconst client = new ApolloClient({\n uri: 'http://localhost:4000',\n cache: new InMemoryCache(),\n credentials: 'include',\n request: async operation => {\n operation.setContext({\n fetchOptions: {\n credentials: 'same-origin'\n }\n })\n },\n})\n\nReactDOM.render(\n <ApolloProvider client={client}>\n <App />\n </ApolloProvider>, \n document.getElementById('root'));\n```\n\n```text\nfetchOptions: {\n credentials: 'include'\n }\n```\n\n========================================\n\nComments:\n- The way that you set the cookie is correct, I have successfully set cookies this way from an Express app. When you say that it is \"not set\", what do you mean exactly? Is it not visible in the developer console in the UI? Regarding the first question - you can use JWT and return the token as part of the response rather than a cookie. It appears to be the standard authentication/authorisation mechanism in GraphQL, I have managed to implement this successfully in the past.\n- Returning the token and using it directly in subsequent requests is not advisable in a browser-based client as it can be stolen by an attacker using JS, whereas cookies set with HTTPOnly and Secure flags cannot be accessed by JS.\n- @Jaryl Thanks, went with using the secure same-domain cookie.","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":178,"estimatedTokens":1332}}597{"id":"stack-49102797","source":"stackoverflow","questionId":49102797,"title":"Apollo graphql: writeQuery after mutation does not trigger re-render of flatlist","tags":["react-native","graphql","apollo","apollo-client"],"text":"Title: Apollo graphql: writeQuery after mutation does not trigger re-render of flatlist\nTags: react-native, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have the following button in a flatlist that triggers a graphql mutation and after the mutation I do a writeQuery to update the local cache (store). In the update functionf of the mutation I am updating two fields within the cache. essentially when the user touches the like button I chang the boolean value of the like to true and update the like count for that post by +1 (similiar to twitter). However the components in the flatlist do not get updated. I even printed out the apollo store/cache and I see the values getting updated. why is the flatlist not re-rendering after the cache write?\n\n```\nrender() {\n\n const { posts, isFetching, lastUpdated, location, navigation, data, likeMutation, username, distancePointLatitude, distancePointLongitude, searchPointLatitude, searchPointLongitude } = this.props\n\n }\n showsVerticalScrollIndicator={false}\n onRefresh={this._onRefresh.bind(this)}\n refreshing={this.state.refreshing}\n keyExtractor={this._keyExtractor}\n renderItem={({item, index}) => item.posts.length != 0 && \n\n{item.posts[0].userInteraction.userLike ? \n : likeMutation({ variables: { elementId: item.posts[0].postId, userId: username },\n\n update: (store, { data: { addLike } }) => {\n // Read the data from our cache for this query.\n\n var thisLocationRadius = {searchPointLongitude: searchPointLongitude,\n searchPointLatitude: searchPointLatitude,\n radius: fiftyMilesInMeters, distancePointLongitude: distancePointLongitude,\n distancePointLatitude: distancePointLatitude };\n\n var data = store.readQuery({ query: getLocalPosts,\n variables: {\n locationRadius: thisLocationRadius,\n userId: username\n }, });\n\n data.near[index].posts[0].userInteraction.userLike = true\n\n data.near[index].posts[0].interactionStats.totalLikes + 1\n\n // Write our data back to the cache.\n store.writeQuery({ query: getLocalPosts, data });\n\n },\n }).catch((error) => {\n console.log('there was an error sending the query', error);\n })} /> }\n}\n\n const HomeWithData = graphql(getLocalPosts, {\n options: ({ searchPointLongitude, searchPointLatitude, distancePointLongitude, distancePointLatitude, username }) => ({ variables: { locationRadius: {searchPointLongitude: searchPointLongitude,\n searchPointLatitude: searchPointLatitude,\n radius: fiftyMilesInMeters, distancePointLongitude: distancePointLongitude,\n distancePointLatitude: distancePointLatitude }, userId: username } }),\n\n });\n\nexport default compose( connect(mapStateToProps),\nHomeWithData,\ngraphql(like, { name: 'likeMutation' }))(Home);\n```\n\ngetLocalPosts Query:\n\n```\nexport const getLocalPosts = gql`query getLocalPosts($locationRadius: locationRadius!, , $userId: String!) {\n near(locationRadius: $locationRadius){\n name,\n address,\n phonenumber,\n email,\n website,\n about,\n location {\n longitude,\n latitude\n },\n distance(unit: MILE),\n businessId,\n hours {\n weekDay,\n startTime,\n endTime\n },\n posts(isActive: true) {\n postText,\n postId,\n userInteraction(userId: $userId){\n userLike\n },\n interactionStats{\n totalLikes\n }\n },\n }\n }`;\n```\n\n========================================\n\nCode:\n```text\nrender() {\n\n\n const { posts, isFetching, lastUpdated, location, navigation, data, likeMutation, username, distancePointLatitude, distancePointLongitude, searchPointLatitude, searchPointLongitude } = this.props\n\n\n <FlatList\n data={data.near}\n style={styles.scrollViewContent}\n extraData={this.props.store}\n //renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}\n showsVerticalScrollIndicator={false}\n onRefresh={this._onRefresh.bind(this)}\n refreshing={this.state.refreshing}\n keyExtractor={this._keyExtractor}\n renderItem={({item, index}) => item.posts.length != 0 && <ListItem>\n\n{item.posts[0].userInteraction.userLike ? <Icon name='md-heart' style={{ color: 'crimson',fontSize: 28}} /> \n : <Icon name='heart' style={{ fontSize: 26}} \n\n onPress={() => likeMutation({ variables: { elementId: item.posts[0].postId, userId: username },\n\n update: (store, { data: { addLike } }) => {\n // Read the data from our cache for this query.\n\n var thisLocationRadius = {searchPointLongitude: searchPointLongitude,\n searchPointLatitude: searchPointLatitude,\n radius: fiftyMilesInMeters, distancePointLongitude: distancePointLongitude,\n distancePointLatitude: distancePointLatitude };\n\n\n var data = store.readQuery({ query: getLocalPosts,\n variables: {\n locationRadius: thisLocationRadius,\n userId: username\n }, });\n\n\n data.near[index].posts[0].userInteraction.userLike = true\n\n data.near[index].posts[0].interactionStats.totalLikes + 1\n\n\n // Write our data back to the cache.\n store.writeQuery({ query: getLocalPosts, data });\n\n\n\n },\n }).catch((error) => {\n console.log('there was an error sending the query', error);\n })} /> }\n}\n\n const HomeWithData = graphql(getLocalPosts, {\n options: ({ searchPointLongitude, searchPointLatitude, distancePointLongitude, distancePointLatitude, username }) => ({ variables: { locationRadius: {searchPointLongitude: searchPointLongitude,\n searchPointLatitude: searchPointLatitude,\n radius: fiftyMilesInMeters, distancePointLongitude: distancePointLongitude,\n distancePointLatitude: distancePointLatitude }, userId: username } }),\n\n });\n\n\nexport default compose( connect(mapStateToProps),\nHomeWithData,\ngraphql(like, { name: 'likeMutation' }))(Home);\n```\n\n```text\nexport const getLocalPosts = gql`query getLocalPosts($locationRadius: locationRadius!, , $userId: String!) {\n near(locationRadius: $locationRadius){\n name,\n address,\n phonenumber,\n email,\n website,\n about,\n location {\n longitude,\n latitude\n },\n distance(unit: MILE),\n businessId,\n hours {\n weekDay,\n startTime,\n endTime\n },\n posts(isActive: true) {\n postText,\n postId,\n userInteraction(userId: $userId){\n userLike\n },\n interactionStats{\n totalLikes\n }\n },\n }\n }`;\n```\n\n```text\nstore.writeQuery({ \n query: getLocalPosts, \n data, \n variables: {\n locationRadius: thisLocationRadius,\n userId: username\n }\n });\n```\n\n```text\nvariables\n```\n\n```text\nwriteQuery\n```\n\n```text\nvariables\n```\n\n```text\nwriteQuery\n```\n\n```text\nstore.writeQuery\n```\n\n========================================\n\nComments:\n- Can you post the code where you defined your query operation and connected it to the flat list?\n- @TalZ I have added the code you requested that contains my query operation and how it is connected to flat list.\n- That's very interesting. I've spent a few hours trying to troubleshoot this with no likely explanation. It wouldn't have occurred to me specify the variables again, particularly when I already noted them in \"readQuery\" in my case. Oh well, live and learn. Upvoted!\n- THANKS and happy new year (from Asia)\n- Thanks, this worked but I literally have no idea why it should\n- busted my day because of missing variables param π","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":244,"estimatedTokens":1857}}598{"id":"stack-46309272","source":"stackoverflow","questionId":46309272,"title":"github graphql query for project contributors","tags":["github","graph","graphql","github-graphql"],"text":"Title: github graphql query for project contributors\nTags: github, graph, graphql, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI want to query using GitHub Graphql api for project contributors, can anyone give me any hints how to make it? Just been trying for some time, and I guess that I am missing some small element. \n\nI'd like to get sth like https://api.github.com/repos/facebook/react/contributors?page=15 but only for amount of conttributions \n\nGreetings!\n\n========================================\n\nTop Answer:\nThe Github graphql v4 API does not seem to support contributor nodes unless you have push access to a repo.\n\nI get this error when i try to get a list of a repo's collaborators\n\n```\n\"errors\": [\n{\n \"message\": \"Must have push access to view repository collaborators.\",\n \"type\": \"FORBIDDEN\",\n```\n\n========================================\n\nCode:\n```text\nquery {\n repository(owner: \"peek\", name: \"peek\") {\n id\n name\n\n collaborators(first: 10, affiliation: ALL) {\n edges {\n permission\n node {\n id\n login\n name\n }\n }\n }\n }\n\n rateLimit {\n cost\n }\n}\n```\n\n```text\ncontributors\n```\n\n```text\ncollaborators\n```\n\n```text\n\"errors\": [\n{\n \"message\": \"Must have push access to view repository collaborators.\",\n \"type\": \"FORBIDDEN\",\n```\n\n```text\nquery {\n repository(owner: \"peek\", name: \"peek\") {\n id\n name\n mentionableUsers {\n totalCount\n }\n }\n}\n```\n\n```text\n/repos/$USER/$REPO/contributors\n```\n\n========================================\n\nComments:\n- github... now supports querying contributors. Update my answer. Thanks!\n- This is collaborators, not contributors. You can not (as of April 2018) get the v3 API equivalent to `/repos/$USER/$REPO/contributors` through the GraphQL API.\n- This is not the solution. collaborators shows more then I expect. On the webpage I see only 2 collaborators for a given repository whereas the api returns many more.\n- I updated the answer to reflect the status Thanks Michael & Marco\n- All users who watch the repo are counted as mentionableUsers. So this list can be 1-3 orders of magnitude larger than real contributors.\n- I did some metadata collection just recently and you are right, the mentionable users are not the same as the number of contributors as can be seen on the repo landing page. However in most cases the reported number is smaller than the watchers count, so it's something different (the list seems to be populated by various actions of users like being part in discussions etc.)\n- Yes, thank you for clarification. It's a shame it's not documented what \"mentionableUsers\" actually are. According to my new exploration this category consists primarily of: 1. Owners (users with a permission to push, even if never commited) 2. Some contributors (unclear by which criteria) Not sure about other metrics.","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":93,"estimatedTokens":720}}599{"id":"stack-54163467","source":"stackoverflow","questionId":54163467,"title":"How to access relationship ID from Parent's joined field in NestJS/TypeORM","tags":["node.js","graphql","nestjs","typeorm"],"text":"Title: How to access relationship ID from Parent's joined field in NestJS/TypeORM\nTags: node.js, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm setting up a NestJS GraphQL API that utilizes TypeORM, and am having trouble implementing relationships between entities.\n\nSpecifically, the TypeORM relationships are working great, and the entities are linking correctly in the database. However, the problem comes in when I try to query the API to get the results.\n\nRight now I have 2 entities, each with their own resolver: Users and Photos. Each User can have multiple Photos, while each Photo is only connected to one User (Many-to-One).\n\n### Here's how the entities are linked with TypeORM\n\n*Photo Entity, with a relationship to the User Entity*\n\n```\n@ManyToOne(type => User, user => user.photos, {\n onDelete: 'CASCADE',\n})\n@JoinColumn()\nuser: User;\n```\n\n*User Entity, completing connection to the Photo Entity*\n\n```\n@OneToMany(type => Photo, photo => photo.user, {\n eager: true,\n})\nphotos: Photo[];\n```\n\n### This code works, and let's us retrieve a User's Photos\n\n*User resolver*\n\n```\n@ResolveProperty('photos')\nasync photos(@Parent() user): Promise {\n return await this.service.readPhotos(user.id);\n}\n```\n\n*User service*\n\n```\nasync readPhotos(userId): Promise {\n return await this.photoRepository.find({\n where: {\n user: userId\n }\n });\n}\n```\n\n*** *Note that the photoRepository is able to be filtered by the 'user' field.* ***\n\n### This code, however, does not work. It should let us view which User is connected to the Photo, instead it returns null.\n\n*Photo resolver*\n\n```\n@ResolveProperty('user')\nasync user(@Parent() photo): Promise {\n console.log(photo);\n return await this.service.readUser(photo.user);\n}\n```\n\nThis Photo resolver seems to contain the problem; the photo object being output by the console indicates that while the @Parent photo object has all of its static fields available (like the ID, datePublished, URL), for some reason the actual 'user' field is not accessible here. So the 'photo.user' variable is null.\n*** *Note that this seems to indicated that the photoRepository is UNABLE to be filtered by/access the 'user' field.* ***\n\n*Photo service*\n\n```\nasync readUser(userId): Promise {\n return await this.userRepository.findOne({\n where: {\n user: userId\n }\n });\n}\n```\n\nThis returns null since the userId is blank, due to the previous Photo resolver not being able to access the 'user' field.\n\n### Conclusion\n\nWhy can't the Photo resolver access the @Parent photo 'user' field? The User service seems to be able to filter by the 'user' field just fine, yet I can't seem to be able to access the Photo 'user' field directly.\n\nThank you for any help on this! I've been stumped on this for the last two days...\n\n========================================\n\nTop Answer:\nI was struggling with a similar problem and although @bashleigh's solution works if you want the entire entity returned I only needed the id. So if that's your case you can pass the `loadRelationIds` option, and set it to `true`.\n\n```\nreturn await this.photoRepository.find({\n where: {\n id: photoId\n },\n loadRelationIds: true\n});\n```\n\nThis will return user as just the id (string or int).\n\n========================================\n\nCode:\n```text\n@ManyToOne(type => User, user => user.photos, {\n onDelete: 'CASCADE',\n})\n@JoinColumn()\nuser: User;\n```\n\n```text\n@OneToMany(type => Photo, photo => photo.user, {\n eager: true,\n})\nphotos: Photo[];\n```\n\n```text\n@ResolveProperty('photos')\nasync photos(@Parent() user): Promise<Photo[]> {\n return await this.service.readPhotos(user.id);\n}\n```\n\n```text\nasync readPhotos(userId): Promise<Photo[]> {\n return await this.photoRepository.find({\n where: {\n user: userId\n }\n });\n}\n```\n\n```text\n@ResolveProperty('user')\nasync user(@Parent() photo): Promise<User> {\n console.log(photo);\n return await this.service.readUser(photo.user);\n}\n```\n\n```text\nasync readUser(userId): Promise<User> {\n return await this.userRepository.findOne({\n where: {\n user: userId\n }\n });\n}\n```\n\n```text\nasync readPhotos(userId): Promise<Photo[]> {\n return await this.photoRepository.find({\n where: {\n user: userId\n },\n relations: ['user'],\n });\n}\n```\n\n```text\nasync readUser(userId): Promise<User> {\n return await this.userRepository.findOne({\n where: {\n user: userId\n },\n relations: ['photos'],\n });\n}\n```\n\n```text\nphoto.user\n```\n\n```text\nFindOptions\n```\n\n```text\nphoto.user\n```\n\n```text\nuser.photos\n```\n\n```text\nPhoto\n```\n\n```text\nFindOptions\n```\n\n```text\nreturn await this.photoRepository.find({\n where: {\n id: photoId\n },\n loadRelationIds: true\n});\n```\n\n```text\nloadRelationIds\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- Can you your GraphQL schema as well? Specifically the definitions for your Photo and User","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":228,"estimatedTokens":1229}}600{"id":"stack-44436233","source":"stackoverflow","questionId":44436233,"title":"How in graphql get last 3 element","tags":["express","sequelize.js","graphql","graphql-js"],"text":"Title: How in graphql get last 3 element\nTags: express, sequelize.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nHow in graphql.js get last 3 created_at element from mysql db table?\nI use sequelize.js\n\nLike this:\n\n```\nquery: '{\n elements(last:3){ \n id\n }\n}'\n```\n\nThis is my file db.js\n\n```\nconst Conn = new Sequelize(/*connection config*/);\nConn.define('elements', {\n id: {\n type: Sequelize.STRING(36),\n primaryKey: true,\n allowNull: false\n }\n});\nexport default Conn;\n```\n\nThis is my file schema.js\n\n```\nconst Query = new GraphQLObjectType({\n name: 'Query',\n description: 'Root query object',\n fields() {\n return {\n elements: {\n type: new GraphQLList(Element),\n args: {\n id: {\n type: GraphQLString\n }\n },\n resolve (root, args) {\n return Db.models.elements.findAll({ where: args });\n }\n }\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\nquery: '{\n elements(last:3){ \n id\n }\n}'\n```\n\n```text\nconst Conn = new Sequelize(/*connection config*/);\nConn.define('elements', {\n id: {\n type: Sequelize.STRING(36),\n primaryKey: true,\n allowNull: false\n }\n});\nexport default Conn;\n```\n\n```text\nconst Query = new GraphQLObjectType({\n name: 'Query',\n description: 'Root query object',\n fields() {\n return {\n elements: {\n type: new GraphQLList(Element),\n args: {\n id: {\n type: GraphQLString\n }\n },\n resolve (root, args) {\n return Db.models.elements.findAll({ where: args });\n }\n }\n }\n }\n});\n```\n\n```text\n...\nreturn Db.models.elements.findAll({ \n limit: 3, \n where: args, \n order: [['created_at', 'DESC']] \n});\n```\n\n========================================\n\nComments:\n- Thanks for answer. But how i can change my scheme.js? Like this? `lastThreeElements: { type: new GraphQLList(Element), args: { id: { type: GraphQLString } }, resolve (root, args) { return Db.models.elements.findAll({ limit: 3, where: args, order: [['created_at', 'DESC']] }); } }`\n- @pmnazar put it into a new question not a comment ... enjoy","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":115,"estimatedTokens":544}}601{"id":"stack-41557536","source":"stackoverflow","questionId":41557536,"title":"Custom map keys in GraphQL response","tags":["php","graphql","graphql-php"],"text":"Title: Custom map keys in GraphQL response\nTags: php, graphql, graphql-php\nSource: Stack Overflow\n\nQuestion:\nI've been looking into GraphQL as a replacement for some REST APIs of mine, and while I think I've wrapped my head around the basics and like most of what I see so far, there's one important feature that seems to be missing.\n\nLet's say I've got a collection of items like this:\n\n```\n{\n \"id\": \"aaa\",\n \"name\": \"Item 1\",\n ...\n}\n```\n\nAn application needs a map of all those objects, indexed by ID as such:\n\n```\n{\n \"allItems\": {\n \"aaa\": {\n \"name\": \"Item 1\",\n ...\n },\n \"aab\": {\n \"name\": \"Item 2\",\n ...\n }\n }\n}\n```\n\nEvery API I've ever written has been able to give results back in a format like this, but I'm struggling to find a way to do it with GraphQL. I keep running across issue 101, but that deals more with unknown schemas. In my case, I know exactly what all the fields are; this is purely about output format. I know I could simply return all the items in an array and reformat it client-side, but that seems like overkill given that it's never been needed in the past, and would make GraphQL feel like a step backwards. I'm not sure if what I'm trying to do is impossible, or I'm just using all the wrong terminology. Should I keep digging, or is GraphQL just not suited to my needs? If this is possible, what might a query look like to retrieve data like this?\n\nI'm currently working with graphql-php on the server, but I'm open to higher-level conceptual responses.\n\n========================================\n\nCode:\n```text\n{\n \"id\": \"aaa\",\n \"name\": \"Item 1\",\n ...\n}\n```\n\n```text\n{\n \"allItems\": {\n \"aaa\": {\n \"name\": \"Item 1\",\n ...\n },\n \"aab\": {\n \"name\": \"Item 2\",\n ...\n }\n }\n}\n```\n\n```text\nconst GraphQLAnyObject = new GraphQLScalarType({\n name: 'AnyObject',\n description: 'Any JSON object. This type bypasses type checking.',\n serialize: value => {\n return value;\n },\n parseValue: value => {\n return value;\n },\n parseLiteral: ast => {\n if (ast.kind !== Kind.OBJECT) {\n throw new GraphQLError(\"Query error: Can only parse object but got a: \" + ast.kind, [ast]);\n }\n return ast.value;\n }\n});\n```\n\n```text\ntype MyType implements Node {\n id: ID!\n myKeyedCollection: AnyObject\n}\n```\n\n```text\nquery {\n getMyType(id: abc) {\n myKeyedCollection # note there is no { ... }\n }\n}\n```\n\n========================================\n\nComments:\n- \"and would make GraphQL feel like a step backwards\" -- in your case, perhaps you know what each and every client of the Web service will need. Otherwise, you are making the assumption that a map is what the client needs. Clients that need the opposite of what the Web service returns have to do some sort of conversion. IMHO, the decision of whether to return a map or an array-style collection is a wash, as it's 50:50 whether the client wants one or the other.\n- @CommonsWare the API I have in mind at the moment is only used internally to an organization, so yes, I can say with certainty that all clients need that data in the format they've always been getting it in. This is called on page load as a quick index for local search purposes, and extended item details are retrieved (in a format easily represented by GraphQL) as needed. The question is simply whether what I'm trying to do is possible.\n- \"all clients need that data in the format they've always been getting it in\" -- converting a collection to a map takes 1-3 lines of code in most modern programming languages. \"is GraphQL just not suited to my needs?\" -- if you are requiring the Web service to return a specific JSON structure, then GraphQL is not suitable. Even if you got past this case (and I don't know of a solution), you'll hit something else. You don't have absolute control over the structure of the JSON, which is dictated by the schema, and the schema isn't designed to handle arbitrary structures.","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":104,"estimatedTokens":987}}602{"id":"stack-42829819","source":"stackoverflow","questionId":42829819,"title":"graphQL join on common column","tags":["join","graphql","graphql-js"],"text":"Title: graphQL join on common column\nTags: join, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nhow we can do data join on a common column in graphQL. \n\nFor example in SQL : Select t.name and z.address where t.id=z.id;\n\nhow is this managed by graphQL query.","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":10,"estimatedTokens":66}}603{"id":"stack-52588436","source":"stackoverflow","questionId":52588436,"title":"Is it possible to put variables inside a GraphQL-tag?","tags":["graphql","graphql-js","graphql-tag"],"text":"Title: Is it possible to put variables inside a GraphQL-tag?\nTags: graphql, graphql-js, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nRight now I have this tag below. It's static and will always get a comment with the id of 3. Is there a possible way to put a variable inside this graphQL-tag. So I can re-use the graphQL-tag, and just change the variable ID?\n\n```\nexport const GET_COMMENTS: any = gql`\n {\n comments(id: 3) {\n userId,\n text,\n creationDate,\n }\n }\n`;\n```\n\n**Thanks in advance!**\n\n========================================\n\nCode:\n```text\nexport const GET_COMMENTS: any = gql`\n {\n comments(id: 3) {\n userId,\n text,\n creationDate,\n }\n }\n`;\n```\n\n```text\nexport const GET_COMMENTS: any = gql`\n query GET_COMMENTS($id: Int){ // $id is the variable name\n comments(id: $id) {\n userId,\n text,\n creationDate,\n }\n }\n`;\n```\n\n```text\n$xyz\n```\n\n========================================\n\nComments:\n- In your code why `query GET_COMMENTS` is not there? You can check my answer below...\n- Thanks a lot! I found out. That i used some of my queries the wrong way. Implemented your method, and now works :-)\n- can someone help me with what is wrong here? export const getMeSomething = gql` query GetSomething( $X: ID! $Y: ID! $Z: ID! ) { getSomething( X: $X Y: $Y ) { Funds(filter: { MyID: { eq: $Z } }) { items { Amount MyID } } } } `;\n- @Rajul What error are you getting?","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":59,"estimatedTokens":367}}604{"id":"stack-58038945","source":"stackoverflow","questionId":58038945,"title":"Apollo GraphQL keeps receiving requests with no queries or mutations being made","tags":["javascript","node.js","typescript","graphql","apollo"],"text":"Title: Apollo GraphQL keeps receiving requests with no queries or mutations being made\nTags: javascript, node.js, typescript, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI was learning GraphQL and about to finish the tutorial and this never happened before.\n\nThe problem is that the GraphQL server keeps receiving requests after opening GraphQL Playground in the browser even though no query or mutation is made.\n\nI see these sort of responses being returned by the server:\n\n```\n{\n \"name\":\"deprecated\",\n \"description\":\"Marks an element of a GraphQL schema as no longer supported.\",\n \"locations\":[\n \"FIELD_DEFINITION\",\n \"ENUM_VALUE\"\n ],\n \"args\":[\n {\n \"name\":\"reason\",\n \"description\":\"Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).\",\n \"type\":{\n \"kind\":\"SCALAR\",\n \"name\":\"String\",\n \"ofType\":null\n },\n \"defaultValue\":\"\\\"No longer supported\\\"\"\n }\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n{\n \"name\":\"deprecated\",\n \"description\":\"Marks an element of a GraphQL schema as no longer supported.\",\n \"locations\":[\n \"FIELD_DEFINITION\",\n \"ENUM_VALUE\"\n ],\n \"args\":[\n {\n \"name\":\"reason\",\n \"description\":\"Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).\",\n \"type\":{\n \"kind\":\"SCALAR\",\n \"name\":\"String\",\n \"ofType\":null\n },\n \"defaultValue\":\"\\\"No longer supported\\\"\"\n }\n ]\n}\n```\n\n```text\n'schema.polling.enable': true, // enables automatic schema polling\n 'schema.polling.endpointFilter': '*localhost*', // endpoint filter for schema polling\n 'schema.polling.interval': 2000, // schema polling interval in ms\n```\n\n========================================\n\nComments:\n- Thanks! After I disabled `schema.polling`, it doesn't happen anymore.","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":70,"estimatedTokens":523}}605{"id":"stack-68459215","source":"stackoverflow","questionId":68459215,"title":"Hot Chocolate (GraphQL) interceptor/middleware to get IQueryable before data fetch","tags":["c#","asp.net-core","graphql",".net-5","hotchocolate"],"text":"Title: Hot Chocolate (GraphQL) interceptor/middleware to get IQueryable before data fetch\nTags: c#, asp.net-core, graphql, .net-5, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI need to do something extra with the IQueryable generated, but im not able to create an interceptor in order to get the IQueryable (e.g log the query created by the GraphQL request).\n\nIm still diving into the great material that is Hot chocolate, but for starters i have this:\n\nhttps://i.sstatic.net/2snV1.png\n\nStraight forward right? But now want an interceptor(or something like that) that gives me the rest of the generated IQueryable before the result to the body response.\n\nThank you,\n\n========================================\n\nCode:\n```cs\npublic class Query\n{\n [UseYourCustom]\n [UseProjection]\n [UseFiltering]\n [UseSorting]\n public IQueryable<Person> GetPersons() => //...\n}\n\npublic class UseYourCustomAttribute : ObjectFieldDescriptorAttribute\n{\n public override void OnConfigure(\n IDescriptorContext context,\n IObjectFieldDescriptor descriptor,\n MemberInfo member)\n {\n descriptor.Use(next => async context =>\n {\n // before the resolver pipeline\n await next(context);\n // after the resolver pipeline\n\n if (context.Result is IQueryable<Person> query)\n {\n // all middleware are applied to `query`\n }\n });\n }\n}\n```\n\n```cs\npublic class Query\n{\n [UseProjection]\n [UseFiltering]\n [UseSorting]\n public IQueryable<Person> GetPersons(IResolverContext context)\n {\n IQueryable<Person> person = //...\n\n var allMiddlewareApplied = persons\n .Sort(context)\n .Filter(context)\n .Project(context);\n\n return allMiddlewareApplied\n }\n}\n```\n\n========================================\n\nComments:\n- Dear Pascal, i really need this behavior now, but mine is to get the list of ids from the where filtering of the GraphQL query, and rewrite the EF LINQ query before Hotchocolate creates the select, my question goes here : stackoverflow.com/questions/74809250/…\n- How can I add paging middleware to this? with ApplyCursorPaginationAsync()?","metadata":{"transformedAt":"2026-08-18T18:32:36.070Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":75,"estimatedTokens":556}}606{"id":"stack-54238696","source":"stackoverflow","questionId":54238696,"title":"What is query_hash in instagram?","tags":["graphql"],"text":"Title: What is query_hash in instagram?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI was working for the first time on graphql, and I saw that Instagram hash their queries.\n\nI searched something, but I don't know if it is correct. The hash is like a persistedquery stored in a cache memory?\n\nOr am I wrong?\n\nExample: this is my request payload\n\n```\n{\n \"operationName\":\"user\",\n \"variables\":{},\n \"query\":\"query user {\\n users {\\n username\\n createdAt\\n _id\\n }\\n}\\n\"\n}\n```\n\nthis is instagram:\n\n```\nquery_hash: 60b755363b5c230111347a7a4e242001\n variables: %7B%22only_stories%22%3Atrue%7D\n```\n\n(it is in urlencode mode). \n\nNow, how could I hash my query? I'm using NodeJS as backend and react js as frontend. \nI would like to understand how it works x)! Thank you guys!\n\n========================================\n\nTop Answer:\n`query_hash` (or `query_id`) does not hash the variables or the parameters, it hashes the payload.\nLets say your actual path is `/graphql` and your payload is\n\n```\n{\n \"user\": {\n \"profile\": [\n \"username\",\n \"user_id\",\n \"profile_picture\"\n ],\n \"feed\": {\n \"posts\": {\n \"data\": [\n \"image_url\"\n ],\n \"page_size\": \"{{variables.max_count}}\"\n }\n }\n }\n}\n```\n\nThen this graphql payload will be hashed and it becomes `d4d88dc1500312af6f937f7b804c68c3`. Now instead of doing that on `/graphql` you do `/graphql/query/?query_hash=d4d88dc1500312af6f937f7b804c68c3`. This way you hashed the payload, as in you hashed the \"keys\" that are required from the graphql. So when you pass `variables` as a `param` then the payload does not actually change, because the variables are constant as well, and you are changing them on the backend, and not in the payload.\n\n========================================\n\nCode:\n```text\n{\n \"operationName\":\"user\",\n \"variables\":{},\n \"query\":\"query user {\\n users {\\n username\\n createdAt\\n _id\\n }\\n}\\n\"\n}\n```\n\n```text\nquery_hash: 60b755363b5c230111347a7a4e242001\n variables: %7B%22only_stories%22%3Atrue%7D\n```\n\n```text\nmemcached\n```\n\n```text\nredis\n```\n\n```text\n{\n \"user\": {\n \"profile\": [\n \"username\",\n \"user_id\",\n \"profile_picture\"\n ],\n \"feed\": {\n \"posts\": {\n \"data\": [\n \"image_url\"\n ],\n \"page_size\": \"{{variables.max_count}}\"\n }\n }\n }\n}\n```\n\n```text\nquery_hash\n```\n\n```text\nquery_id\n```\n\n```text\n/graphql\n```\n\n```text\nd4d88dc1500312af6f937f7b804c68c3\n```\n\n```text\n/graphql\n```\n\n```text\n/graphql/query/?query_hash=d4d88dc1500312af6f937f7b804c68c3\n```\n\n```text\nvariables\n```\n\n```text\nparam\n```\n\n========================================\n\nComments:\n- Just another question: the cache is different foreach user or not? It's like a database stored server-side (so, the same for all user) and not client-side ?\n- The hash is different based on the query content, itβs has nothing to do with the user. And yes, itβs stored on the server only\n- Does the hash expires or changes for each type of query content?","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":143,"estimatedTokens":751}}607{"id":"stack-58683303","source":"stackoverflow","questionId":58683303,"title":"How to narrow Typescript Types autogenerated by graphQL codegen?","tags":["typescript","graphql","aws-amplify","aws-appsync"],"text":"Title: How to narrow Typescript Types autogenerated by graphQL codegen?\nTags: typescript, graphql, aws-amplify, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI get a TypeScript type autogenerated from AWS-Amplify GraphQL (which uses apollo-codegen I believe) like such:\n\n```\nexport type GetNoteQuery = {\n getNote: {\n __typename: \"Note\",\n id: string,\n createdAt: string | null,\n updatedAt: string | null,\n title: boolean | null,\n content: string | null,\n } | null,\n```\n\nI want to generate a base type of \"Note\" to use as \"base\" type to use in my code when using the returned data. I.e. mapping notes onto a React component, etc.\n\nIs there a way to narrow this type that is auto generated, or to extend it in some way, to have it look like:\n\n```\ntype Note = {\n id: string,\n createdAt: string | null,\n updatedAt: string | null,\n title: boolean | null,\n content: string | null\n}\n```\n\n========================================\n\nTop Answer:\nGraphQL-Codegen creator here.\n\nJust some background on the decision to generate this kind of TS code:\nWe started `typescript` as a plugin for creating an exact representation of the GraphQL schema.\nThen, `typescript-operations` take operations and fragments (that picks specific fields and data from the schema) and generates code that takes the same fields and data fields from the generated types by `typescript` plugin.\n\nWe saw some developers prefer cleaner code, so you can use `preResolveTypes: true` to avoid using `Pick` and just use the primitive type in-place.\nYou can also use `onlyOperationTypes: true` in order to tell the codegen to avoid generating types that are not needed.\n\n========================================\n\nCode:\n```text\nexport type GetNoteQuery = {\n getNote: {\n __typename: \"Note\",\n id: string,\n createdAt: string | null,\n updatedAt: string | null,\n title: boolean | null,\n content: string | null,\n } | null,\n```\n\n```js\ntype Note = {\n id: string,\n createdAt: string | null,\n updatedAt: string | null,\n title: boolean | null,\n content: string | null\n}\n```\n\n```text\nexport type GetNoteQuery = {\n getNote: {\n __typename: \"Note\",\n id: string,\n createdAt: string | null,\n updatedAt: string | null,\n title: boolean | null,\n content: string | null,\n } | null\n}\n\ntype Note = Omit<Exclude<GetNoteQuery['getNote'], null>, '__typename'>\n```\n\n```text\ninterface Note extends Omit<Exclude<GetNoteQuery['getNote'], null>, '__typename'> { }\n```\n\n```text\ngetNote\n```\n\n```text\nExclude\n```\n\n```text\nnull\n```\n\n```text\nOmit\n```\n\n```text\ntypescript\n```\n\n```text\ntypescript-operations\n```\n\n```text\ntypescript\n```\n\n```text\npreResolveTypes: true\n```\n\n```text\nPick\n```\n\n```text\nonlyOperationTypes: true\n```\n\n========================================\n\nComments:\n- Thank you! What do you mean by using an interface to \"get a stronger name for the type\"?\n- @StephenA.Lizcano type aliases get expanded in errors and tooltips, so you might see something like `Pick<Exclude<....` instead of `Note`. Interface names are always preserved.\n- Appreciate your answer @dotan! Will definitely try asap and provide feedback, seems really usable for us.","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":135,"estimatedTokens":783}}608{"id":"stack-56004929","source":"stackoverflow","questionId":56004929,"title":"How to resolve graphene.Union Type?","tags":["graphql","graphene-django"],"text":"Title: How to resolve graphene.Union Type?\nTags: graphql, graphene-django\nSource: Stack Overflow\n\nQuestion:\nI want to create a UnionType(graphene.Union) of two existing types (FirstType and SecondType) and be able to resolve the query of this union type.\n\n### Schema\n\n```\nclass FirstType(DjangoObjectType):\n class Meta:\n model = FirstModel\n\n class SecondType(DjangoObjectType):\n class Meta:\n model = SecondModel\n\n class UnionType(graphene.Union):\n class Meta:\n types = (FirstType, SecondType)\n```\n\nSo with this schema I want to query all objects from FirstType and SecondType with pk in some list [pks]\n\n```\nquery {\n all_items(pks: [1,2,5,7]){\n ... on FirstType{\n pk,\n color, \n }\n\n ... on SecondType{ \n pk, \n size,\n }\n }\n }\n```\n\nPKs from FirstType are normally not in the SecondType. \n\nI tried like one below\n\n```\ndef resolve_items(root, info, ids):\n queryset1 = FirstModel.objects.filter(id__in=pks)\n queryset2 = SecondModel.objects.filter(id__in=pks)\n return queryset1 | queryset2\n```\n\nbut it gives an error: 'Cannot combine queries on two different base models.'\n\nI expect the following response from query:\n\n```\n{ 'data':\n {'all_items':[\n {'pk': 1,\n 'color': blue\n },\n {'pk': 2,\n 'size': 50.0\n },\n ...\n ]}\n }\n```\n\nSo how the resolver should look like?\n\n========================================\n\nTop Answer:\nThe graphene Documentation on union types is very sparse. Here is a working example of how to do it correctly:\n\n```\nfrom graphene import ObjectType, Field, List, String, Int, Union\n\nmock_data = {\n \"episode\": 3,\n \"characters\": [\n {\n \"type\": \"Droid\",\n \"name\": \"R2-D2\",\n \"primaryFunction\": \"Astromech\"\n },\n {\n \"type\": \"Human\",\n \"name\": \"Luke Skywalker\",\n \"homePlanet\": \"Tatooine\"\n },\n {\n \"type\": \"Starship\",\n \"name\": \"Millennium Falcon\",\n \"length\": 35\n }\n ]\n}\n\nclass Human(ObjectType):\n name = String()\n homePlanet = String()\n\nclass Droid(ObjectType):\n name = String()\n primaryFunction = String()\n\nclass Starship(ObjectType):\n name = String()\n length = Int()\n\nclass Character(Union):\n class Meta:\n types = (Human, Droid, Starship)\n\n @classmethod\n def resolve_type(cls, instance, info):\n if instance[\"type\"] == \"Human\":\n return Human\n if instance[\"type\"] == \"Droid\":\n return Droid\n if instance[\"type\"] == \"Starship\":\n return Starship\n\nclass RootQuery(ObjectType):\n result = Field(SearchResult)\n\n def resolve_result(_, info):\n return mock_data\n```\n\nThen, for a query like\n\n```\nquery Humans {\n result {\n episode\n characters {\n ... on Droid {\n name\n }\n ... on Starship {\n name\n }\n ... on Human {\n name\n }\n }\n }\n }\n```\n\nit returns the correct result.\n\n========================================\n\nCode:\n```text\nclass FirstType(DjangoObjectType):\n class Meta:\n model = FirstModel\n\n class SecondType(DjangoObjectType):\n class Meta:\n model = SecondModel\n\n class UnionType(graphene.Union):\n class Meta:\n types = (FirstType, SecondType)\n```\n\n```text\nquery {\n all_items(pks: [1,2,5,7]){\n ... on FirstType{\n pk,\n color, \n }\n\n ... on SecondType{ \n pk, \n size,\n }\n }\n }\n```\n\n```text\ndef resolve_items(root, info, ids):\n queryset1 = FirstModel.objects.filter(id__in=pks)\n queryset2 = SecondModel.objects.filter(id__in=pks)\n return queryset1 | queryset2\n```\n\n```text\n{ 'data':\n {'all_items':[\n {'pk': 1,\n 'color': blue\n },\n {'pk': 2,\n 'size': 50.0\n },\n ...\n ]}\n }\n```\n\n```text\ndef resolve_items(root, info, ids):\n items = []\n queryset1 = FirstModel.objects.filter(id__in=pks)\n items.extend(queryset1)\n queryset2 = SecondModel.objects.filter(id__in=pks)\n items.extend(queryset2)\n return items\n```\n\n```py\nfrom graphene import ObjectType, Field, List, String, Int, Union\n\nmock_data = {\n \"episode\": 3,\n \"characters\": [\n {\n \"type\": \"Droid\",\n \"name\": \"R2-D2\",\n \"primaryFunction\": \"Astromech\"\n },\n {\n \"type\": \"Human\",\n \"name\": \"Luke Skywalker\",\n \"homePlanet\": \"Tatooine\"\n },\n {\n \"type\": \"Starship\",\n \"name\": \"Millennium Falcon\",\n \"length\": 35\n }\n ]\n}\n\n\nclass Human(ObjectType):\n name = String()\n homePlanet = String()\n\n\nclass Droid(ObjectType):\n name = String()\n primaryFunction = String()\n\n\nclass Starship(ObjectType):\n name = String()\n length = Int()\n\n\nclass Character(Union):\n class Meta:\n types = (Human, Droid, Starship)\n\n @classmethod\n def resolve_type(cls, instance, info):\n if instance[\"type\"] == \"Human\":\n return Human\n if instance[\"type\"] == \"Droid\":\n return Droid\n if instance[\"type\"] == \"Starship\":\n return Starship\n\n\nclass RootQuery(ObjectType):\n result = Field(SearchResult)\n\n def resolve_result(_, info):\n return mock_data\n```\n\n```text\nquery Humans {\n result {\n episode\n characters {\n ... on Droid {\n name\n }\n ... on Starship {\n name\n }\n ... on Human {\n name\n }\n }\n }\n }\n```\n\n========================================\n\nComments:\n- Just wanna say your solution worked for me! I simplified it a little by unpacking the lists directly in the return: `return [*queryset1, *queryset2]`\n- this works for now but wiould be glad if I found a way.. amy polymorphic models has like 100 models and this would be so tiresome. if you anyone found a way then please update us\n- What is SearchResult in `result = Field(SearchResult)` ?\n- I think this is supposed to be: result = Field(Character)\n- class SearchResult(ObjectType): episode = Int() characters = List(Character)","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":308,"estimatedTokens":1451}}609{"id":"stack-43469685","source":"stackoverflow","questionId":43469685,"title":"In GraphQL, how to handle the `resolveType` and `isTypeOf` when use the `interfaces` feature a lot?","tags":["graphql","graphql-js"],"text":"Title: In GraphQL, how to handle the `resolveType` and `isTypeOf` when use the `interfaces` feature a lot?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI had read through this great gist - **GraphQLInterfaceType**\n\nBut still have some confusions:\n\nIs that really necessary to define `ES6 classes` for all GraphQL schema types? \n\n- Main concern here is: we will end up with lots of empty `ES6 classes` and equivalent amount of `GraphQL types`.\n\n- If it is not, then how to handle the `resolveType` and `isTypeOf` properly when use the `interfaces` features a lot?\n\n- Even I defined all the `ES6 classes` for all the `GraphQL types`, but the raw data are constructed in different place with different tech like `grpc+protobuf`, which has no any relation to these classes definitions, so how does the `isTypeOf: (value) => value instanceof Dog` work here?\n\n========================================\n\nCode:\n```text\nES6 classes\n```\n\n```text\nES6 classes\n```\n\n```text\nGraphQL types\n```\n\n```text\nresolveType\n```\n\n```text\nisTypeOf\n```\n\n```text\ninterfaces\n```\n\n```text\nES6 classes\n```\n\n```text\nGraphQL types\n```\n\n```text\ngrpc+protobuf\n```\n\n```text\nisTypeOf: (value) => value instanceof Dog\n```\n\n```text\nSELECT\n id,\n body,\n author_id,\n post_id,\n 'Comment' AS \"$type\" -- leave a hint to resolve the type\nFROM comments\nUNION\nSELECT\n id,\n body,\n author_id,\n NULL AS post_id,\n 'Post' AS \"$type\" -- leave a hint to resolve the type\nFROM posts\n```\n\n```text\nresolveType\n```\n\n```text\nisTypeOf\n```\n\n```text\nresolveType\n```\n\n========================================\n\nComments:\n- It's worth noting that instead of a \"hint\" you can also just return a property named `__typename` with the appropriate type name, in which case you don't have to provide either a `resolveType` or `isTypeOf` function. GraphQL's default `isTypeOf` function looks for that property and infers the type that way.","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":94,"estimatedTokens":473}}610{"id":"stack-43138757","source":"stackoverflow","questionId":43138757,"title":"Graphene mutation not mapping Models in SQL Alchemy","tags":["python","flask","sqlalchemy","graphql","graphene-python"],"text":"Title: Graphene mutation not mapping Models in SQL Alchemy\nTags: python, flask, sqlalchemy, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI am trying to perform mutation on User models declared using SQL ALCHEMY.\nHere is the code for my models.py file \n\n```\n# blog/models.py\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import (scoped_session, sessionmaker, relationship,\n backref)\nfrom sqlalchemy.ext.declarative import declarative_base \nengine = create_engine('sqlite:///database.sqlite3', convert_unicode=True)\ndb_session = scoped_session(sessionmaker(autocommit=False,\n autoflush=False,\n bind=engine))\nBase = declarative_base()\n# We will need this for querying\nBase.query = db_session.query_property()\n\nclass User(Base):\n __tablename__ = 'user'\n id = Column(Integer, primary_key= True)\n name = Column(String)\n email = Column(String)\n posts = relationship(\"Post\", backref=\"user\")\n\nclass Post(Base):\n __tablename__ = 'post'\n id = Column(Integer, primary_key= True)\n title = Column(String)\n text = Column(Text)\n user_id = Column(Integer, ForeignKey('user.id'))\n```\n\nThis is Schema.py file\n\n```\nimport graphene\nfrom graphene import relay\nfrom graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField\nfrom models import db_session,User as UserModel, Post as PostModel\nfrom sqlalchemy import *\n\nclass User(SQLAlchemyObjectType):\n class Meta:\n model = UserModel\n interfaces = (relay.Node, )\n\nclass Post(SQLAlchemyObjectType):\n class Meta:\n model = PostModel\n interfaces = (relay.Node, )\n\nclass CreateUser(graphene.Mutation):\n class Input:\n name = graphene.String()\n\n ok = graphene.Boolean()\n user = graphene.Field(User)\n\n @classmethod\n def mutate(cls, instance, args, context, info):\n new_user = User(name=args.get('name'))\n\n db_session.add(new_user)\n db_session.commit()\n ok = True\n return CreateUser(user=new_user, ok=ok)\n\nclass Query(graphene.ObjectType):\n node = relay.Node.Field()\n user = relay.Node.Field(User)\n allUsers = SQLAlchemyConnectionField(User)\n\nclass MyMutations(graphene.ObjectType):\n create_user = CreateUser.Field()\n\nschema = graphene.Schema(query=Query, mutation = MyMutations, types = [User, Post])\n```\n\nWhen i try performing following mutation, this is the error i get :\n\n```\n--Query--\n mutation Test{\n createUser(name:\"tess\"){\n ok\n user{\n name\n }\n }\n }\n\n --Result--\n {\n \"errors\": [\n {\n \"message\": \"Class 'schema2.User' is not mapped\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ]\n }\n ],\n \"data\": {\n \"createUser\": null\n }\n }\n```\n\n========================================\n\nCode:\n```text\n# blog/models.py\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import (scoped_session, sessionmaker, relationship,\n backref)\nfrom sqlalchemy.ext.declarative import declarative_base \nengine = create_engine('sqlite:///database.sqlite3', convert_unicode=True)\ndb_session = scoped_session(sessionmaker(autocommit=False,\n autoflush=False,\n bind=engine))\nBase = declarative_base()\n# We will need this for querying\nBase.query = db_session.query_property()\n\nclass User(Base):\n __tablename__ = 'user'\n id = Column(Integer, primary_key= True)\n name = Column(String)\n email = Column(String)\n posts = relationship(\"Post\", backref=\"user\")\n\nclass Post(Base):\n __tablename__ = 'post'\n id = Column(Integer, primary_key= True)\n title = Column(String)\n text = Column(Text)\n user_id = Column(Integer, ForeignKey('user.id'))\n```\n\n```text\nimport graphene\nfrom graphene import relay\nfrom graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField\nfrom models import db_session,User as UserModel, Post as PostModel\nfrom sqlalchemy import *\n\nclass User(SQLAlchemyObjectType):\n class Meta:\n model = UserModel\n interfaces = (relay.Node, )\n\nclass Post(SQLAlchemyObjectType):\n class Meta:\n model = PostModel\n interfaces = (relay.Node, )\n\nclass CreateUser(graphene.Mutation):\n class Input:\n name = graphene.String()\n\n ok = graphene.Boolean()\n user = graphene.Field(User)\n\n @classmethod\n def mutate(cls, instance, args, context, info):\n new_user = User(name=args.get('name'))\n\n db_session.add(new_user)\n db_session.commit()\n ok = True\n return CreateUser(user=new_user, ok=ok)\n\nclass Query(graphene.ObjectType):\n node = relay.Node.Field()\n user = relay.Node.Field(User)\n allUsers = SQLAlchemyConnectionField(User)\n\nclass MyMutations(graphene.ObjectType):\n create_user = CreateUser.Field()\n\nschema = graphene.Schema(query=Query, mutation = MyMutations, types = [User, Post])\n```\n\n```text\n--Query--\n mutation Test{\n createUser(name:\"tess\"){\n ok\n user{\n name\n }\n }\n }\n\n --Result--\n {\n \"errors\": [\n {\n \"message\": \"Class 'schema2.User' is not mapped\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ]\n }\n ],\n \"data\": {\n \"createUser\": null\n }\n }\n```\n\n========================================\n\nComments:\n- Thank you , i really missed that. Spent hours figuring out whats wrong .","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":225,"estimatedTokens":1303}}611{"id":"stack-47481059","source":"stackoverflow","questionId":47481059,"title":"React GraphQL Relay - How to do a simple query?","tags":["reactjs","graphql","relay","relaymodern"],"text":"Title: React GraphQL Relay - How to do a simple query?\nTags: reactjs, graphql, relay, relaymodern\nSource: Stack Overflow\n\nQuestion:\n**The Goal:** \n\nI'm trying to query a specific character from a GraphQL server with relay.\n\n**The Problem:**\n\nThe query works in GraphiQL. But here, when running `\"relay-compiler\": \"^1.4.1\"` I'm getting...\n\n ERROR: Parse error: Error: FindGraphQLTags: Operation names in graphql\n tags must be prefixed with the module name and end in \"Mutation\",\n \"Query\", or \"Subscription\". Got `clientQuery` in module `Jedi`. in\n \"components/Jedi.js\"\n\n**The Question:**\n\nCan't I just query that specific character like in GraphiQL ? How can I achieve this?\n\n**The Code:**\n\n```\nimport React from 'react'\nimport { QueryRenderer, graphql } from 'react-relay'\n\nconst BlogPostPreview = props => {\n return (\n {props.post.name}\n )\n}\n\nexport default QueryRenderer(BlogPostPreview, {\npost: graphql`\n query clientQuery {\n character(id: 1000) {\n id\n name\n appearsIn\n }\n }\n `\n})\n```\n\n========================================\n\nTop Answer:\nHere are examples. If query is in:\n\n- `/app/foo.js` - `fooQuery` or `fooAnythingQuery`\n\n- `/app/foo/index.js` - `fooQuery` or `fooAnythingQuery`\n\n- `/app/Foo/index.js` - `FooQuery` or `FooAnythingQuery`\n\n- `/app/foo/bar.js` - `barQuery` or `barAnythingQuery`\n\n========================================\n\nCode:\n```jsx\nimport React from 'react'\nimport { QueryRenderer, graphql } from 'react-relay'\n\nconst BlogPostPreview = props => {\n return (\n <div key={props.post.id}>{props.post.name}</div>\n )\n}\n\nexport default QueryRenderer(BlogPostPreview, {\npost: graphql`\n query clientQuery {\n character(id: 1000) {\n id\n name\n appearsIn\n }\n }\n `\n})\n```\n\n```text\n\"relay-compiler\": \"^1.4.1\"\n```\n\n```text\nclientQuery\n```\n\n```text\nJedi\n```\n\n```text\n/app/foo.js\n```\n\n```text\nfooQuery\n```\n\n```text\nfooAnythingQuery\n```\n\n```text\n/app/foo/index.js\n```\n\n```text\nfooQuery\n```\n\n```text\nfooAnythingQuery\n```\n\n```text\n/app/Foo/index.js\n```\n\n```text\nFooQuery\n```\n\n```text\nFooAnythingQuery\n```\n\n```text\n/app/foo/bar.js\n```\n\n```text\nbarQuery\n```\n\n```text\nbarAnythingQuery\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":145,"estimatedTokens":541}}612{"id":"stack-66433132","source":"stackoverflow","questionId":66433132,"title":"\"Unknown directive model\" when setting up AWS Amplify GraphQL API in WebStorm","tags":["angular","amazon-web-services","graphql","webstorm","aws-amplify"],"text":"Title: \"Unknown directive model\" when setting up AWS Amplify GraphQL API in WebStorm\nTags: angular, amazon-web-services, graphql, webstorm, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI'm using the following AWS Amplify tutorial for Angular:\n\nhttps://docs.amplify.aws/start/getting-started/data-model/q/integration/angular#model-the-data-with-graphql-transform\n\nWhen I generate the GraphQL API I get red warning messages for the `@model` directive:\n\nhttps://i.sstatic.net/Agct0.png\n\nI'm using WebStorm. How can I get my editor to not throw these red warning errors? Do I need to install some @types package or install some plugin?\n\n========================================\n\nTop Answer:\n### Amplify Repository Updates\n\nIt looks like all the Amplify transformer directives were published at this `@aws-amplify` repo subdirectory two weeks ago:\n\n- https://github.com/aws-amplify/amplify-category-api/tree/main/packages\n\nYou can dig into the source files to find the exact definitions. For example if you dig down to this file:\n\n- https://github.com/aws-amplify/amplify-category-api/blob/main/packages/amplify-graphql-default-value-transformer/src/graphql-default-value-transformer.ts\n\nYou will find:\n\n```\nconst directiveDefinition = `\n directive @${directiveName}(value: String!) on FIELD_DEFINITION\n`;\n```\n\nYou can also take a look at this NPM page that lists all the individual directive packages that depend on **@aws-amplify/.graphql-transformer-core**\n\n### Default Transformer\n\nThe **Default Transformer** page includes this helpful information:\n\n- Default Transformer Image\n\n========================================\n\nCode:\n```text\n@model\n```\n\n```text\n{\n \"schemaPath\": \"schema.graphql\",\n \"includes\": [\"*\"],\n \"extensions\": {\n \"endpoints\": {}\n }\n}\n```\n\n```text\nimport gql from 'graphql-tag';\n\nconst clientSchemaExtensions = gql`\n directive @model on OBJECT\n scalar AWSDateTime\n`;\n```\n\n```text\n.graphqlconfig\n```\n\n```text\ngraphql-directives.js\n```\n\n```text\nconst directiveDefinition = `\n directive @${directiveName}(value: String!) on FIELD_DEFINITION\n`;\n```\n\n```text\n@aws-amplify\n```\n\n========================================\n\nComments:\n- ... ask support?\n- Thanks! This works perfectly! I created graphql-directives.js under amplify directory. I made this definition file to cover all (most?) of directives and types for Amplify here; gist.github.com/pikanji/dcb6749293ddb4c68332c56ee910d1ba","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":93,"estimatedTokens":601}}613{"id":"stack-70524028","source":"stackoverflow","questionId":70524028,"title":"ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py)","tags":["python","python-3.x","django","graphql","graphene-django"],"text":"Title: ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py)\nTags: python, python-3.x, django, graphql, graphene-django\nSource: Stack Overflow\n\nQuestion:\nI get the error below when I add **'graphene_django'** inside ***INSTALLED_APPS*** in the settings.py.\n\nAfter running\n\n```\npython3 manage.py runserver\n```\n\ngraphene_django is installed successfully using\n\n```\npip install django graphene_django\n```\n\nThis is full error that I get:\n\n```\nWatching for file changes with StatReloader\nException in thread django-main-thread:\nTraceback (most recent call last):\n File \"/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py\", line 973, in _bootstrap_inner\n self.run()\n File \"/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py\", line 910, in run\n self._target(*self._args, **self._kwargs)\n File \"/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py\", line 64, in wrapper\n fn(*args, **kwargs)\n File \"/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py\", line 115, in inner_run\n autoreload.raise_last_exception()\n File \"/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py\", line 87, in raise_last_exception\n raise _exception[1]\n File \"/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py\", line 381, in execute\n autoreload.check_errors(django.setup)()\n File \"/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py\", line 64, in wrapper\n fn(*args, **kwargs)\n File \"/usr/local/lib/python3.9/site-packages/django/__init__.py\", line 24, in setup\n apps.populate(settings.INSTALLED_APPS)\n File \"/usr/local/lib/python3.9/site-packages/django/apps/registry.py\", line 91, in populate\n app_config = AppConfig.create(entry)\n File \"/usr/local/lib/python3.9/site-packages/django/apps/config.py\", line 223, in create\n import_module(entry)\n File \"/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py\", line 127, in import_module\n return _bootstrap._gcd_import(name[level:], package, level)\n File \"\", line 1030, in _gcd_import\n File \"\", line 1007, in _find_and_load\n File \"\", line 986, in _find_and_load_unlocked\n File \"\", line 680, in _load_unlocked\n File \"\", line 850, in exec_module\n File \"\", line 228, in _call_with_frames_removed\n File \"/usr/local/lib/python3.9/site-packages/graphene_django/__init__.py\", line 1, in \n from .fields import DjangoConnectionField, DjangoListField\n File \"/usr/local/lib/python3.9/site-packages/graphene_django/fields.py\", line 18, in \n from .utils import maybe_queryset\n File \"/usr/local/lib/python3.9/site-packages/graphene_django/utils/__init__.py\", line 2, in \n from .utils import (\n File \"/usr/local/lib/python3.9/site-packages/graphene_django/utils/utils.py\", line 6, in \n from django.utils.encoding import force_text\nImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py)\n```\n\nAny idea on what's going wrong here?\n\n========================================\n\nTop Answer:\nInstall graphene-django in this way. This resolves the issue for me.\n\n```\npip install \"graphene-django==3.0.0b7\"\n```\n\n========================================\n\nCode:\n```text\npython3 manage.py runserver\n```\n\n```text\npip install django graphene_django\n```\n\n```text\nWatching for file changes with StatReloader\nException in thread django-main-thread:\nTraceback (most recent call last):\n File \"/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py\", line 973, in _bootstrap_inner\n self.run()\n File \"/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py\", line 910, in run\n self._target(*self._args, **self._kwargs)\n File \"/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py\", line 64, in wrapper\n fn(*args, **kwargs)\n File \"/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py\", line 115, in inner_run\n autoreload.raise_last_exception()\n File \"/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py\", line 87, in raise_last_exception\n raise _exception[1]\n File \"/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py\", line 381, in execute\n autoreload.check_errors(django.setup)()\n File \"/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py\", line 64, in wrapper\n fn(*args, **kwargs)\n File \"/usr/local/lib/python3.9/site-packages/django/__init__.py\", line 24, in setup\n apps.populate(settings.INSTALLED_APPS)\n File \"/usr/local/lib/python3.9/site-packages/django/apps/registry.py\", line 91, in populate\n app_config = AppConfig.create(entry)\n File \"/usr/local/lib/python3.9/site-packages/django/apps/config.py\", line 223, in create\n import_module(entry)\n File \"/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py\", line 127, in import_module\n return _bootstrap._gcd_import(name[level:], package, level)\n File \"<frozen importlib._bootstrap>\", line 1030, in _gcd_import\n File \"<frozen importlib._bootstrap>\", line 1007, in _find_and_load\n File \"<frozen importlib._bootstrap>\", line 986, in _find_and_load_unlocked\n File \"<frozen importlib._bootstrap>\", line 680, in _load_unlocked\n File \"<frozen importlib._bootstrap_external>\", line 850, in exec_module\n File \"<frozen importlib._bootstrap>\", line 228, in _call_with_frames_removed\n File \"/usr/local/lib/python3.9/site-packages/graphene_django/__init__.py\", line 1, in <module>\n from .fields import DjangoConnectionField, DjangoListField\n File \"/usr/local/lib/python3.9/site-packages/graphene_django/fields.py\", line 18, in <module>\n from .utils import maybe_queryset\n File \"/usr/local/lib/python3.9/site-packages/graphene_django/utils/__init__.py\", line 2, in <module>\n from .utils import (\n File \"/usr/local/lib/python3.9/site-packages/graphene_django/utils/utils.py\", line 6, in <module>\n from django.utils.encoding import force_text\nImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py)\n```\n\n```text\nimport django\nfrom django.utils.encoding import force_str\ndjango.utils.encoding.force_text = force_str\n```\n\n```text\nfrom django.utils.encoding imort force_str\n```\n\n```text\nforce_text\n```\n\n```text\npip install \"graphene-django==3.0.0b7\"\n```\n\n```text\ngraphene-django==3.0.0b7\n```\n\n========================================\n\nComments:\n- What version of django are you using? Upgrade it to the latest.\n- this solution it works for me- stackoverflow.com/a/70679791/16697782\n- Does this answer your question? import error 'force_text' from 'django.utils.encoding'\n- I did not import `force_text` anywhere in my code\n- thats what your error is, on the latest django version `force_str` is used but your python tries using `force_text` which means either you made a mistake or your django is outdated/messed up, you can try either updating or reinstalling it\n- @SLDem: It's being included by `graphene-django`, which is why he can't change it without hacking the package, forking it and maintaining his own source code or engaging in some such endeavor. But the beta version of `graphene-django` works (3.0.0b7) as per Abir Hossain's answer. It just has to be installed speciflcally by version number (see his answer) until it's out of beta.\n- What an interesting hack. Not sure I love it, but I'm going to use it anyway. Thanks.","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":161,"estimatedTokens":1918}}614{"id":"stack-53886583","source":"stackoverflow","questionId":53886583,"title":"Null fields on a partial update mutation on GraphQL .NET","tags":["c#",".net","graphql","ef-core-2.1"],"text":"Title: Null fields on a partial update mutation on GraphQL .NET\nTags: c#, .net, graphql, ef-core-2.1\nSource: Stack Overflow\n\nQuestion:\nAt work, we're using EFCore on our data layer and graphql-dotnet to manage APIs requests, I'm having a problem updating some of our big objects using GraphQL mutations. When the user sends a partial update on the model, we would like to update on our database only the fields that actually were changed by the mutation. The problem we're having is that as we directly map the input to the entity, wheather some field was purposefully passed as null, or the field was not specified on the mutation at all, we get the property value as null. This way we can't send the changes to the database otherwise we would incorrectly update a bunch of fields to null.\n\nSo, we need a way to identify which fields are sent in a mutation and only update those. In JS this is achieved by checking if the property value is undefined, if the value is null we know that it was passed as null on purpose.\n\nSome workarounds we've been thinking were using reflection on a Dictionary to update only the specified fields. But we would need to spread reflection to every single mutation. Another solution was to have a isChanged property to every nullable property on our model and change ir on the refered property setter, but... cmon...\n\nI'm providing some code as example of this situation bellow:\n\nHuman class:\n\n```\npublic class Human\n{\n public Id { get; set; }\n public string Name { get; set; }\n public string HomePlanet { get; set; }\n}\n```\n\nGraphQL Type:\n\n```\npublic class HumanType : ObjectGraphType\n{\n public HumanType()\n {\n Name = \"Human\";\n Field(h => h.Id).Description(\"The id of the human.\");\n Field(h => h.Name, nullable: true).Description(\"The name of the human.\");\n Field(h => h.HomePlanet, nullable: true).Description(\"The home planet of the human.\");\n }\n}\n```\n\nInput Type:\n\n```\npublic class HumanInputType : InputObjectGraphType\n {\n public HumanInputType()\n {\n Name = \"HumanInput\";\n Field>(\"name\");\n //The problematic field\n Field(\"homePlanet\");\n }\n }\n```\n\nHuman Mutation:\n\n```\n/// Example JSON request for an update mutation without HomePlanet \n/// {\n/// \"query\": \"mutation ($human:HumanInput!){ createHuman(human: $human) { id name } }\",\n/// \"variables\": {\n/// \"human\": {\n/// \"name\": \"Boba Fett\"\n/// }\n/// }\n/// }\n///\npublic class StarWarsMutation : ObjectGraphType\n{\n public StarWarsMutation(StarWarsRepository data)\n {\n Name = \"Mutation\";\n\n Field(\n \"createOrUpdateHuman\",\n arguments: new QueryArguments(\n new QueryArgument> {Name = \"human\"}\n ),\n resolve: context =>\n {\n //After conversion human.HomePlanet is null. But it was not informed, we should keep what is on the database at the moment\n var human = context.GetArgument(\"human\");\n //On EFCore the Update method is equivalent to an InsertOrUpdate method\n return data.Update(human);\n });\n }\n}\n```\n\n========================================\n\nCode:\n```text\npublic class Human\n{\n public Id { get; set; }\n public string Name { get; set; }\n public string HomePlanet { get; set; }\n}\n```\n\n```text\npublic class HumanType : ObjectGraphType<Human>\n{\n public HumanType()\n {\n Name = \"Human\";\n Field(h => h.Id).Description(\"The id of the human.\");\n Field(h => h.Name, nullable: true).Description(\"The name of the human.\");\n Field(h => h.HomePlanet, nullable: true).Description(\"The home planet of the human.\");\n }\n}\n```\n\n```text\npublic class HumanInputType : InputObjectGraphType\n {\n public HumanInputType()\n {\n Name = \"HumanInput\";\n Field<NonNullGraphType<StringGraphType>>(\"name\");\n //The problematic field\n Field<StringGraphType>(\"homePlanet\");\n }\n }\n```\n\n```text\n/// Example JSON request for an update mutation without HomePlanet \n/// {\n/// \"query\": \"mutation ($human:HumanInput!){ createHuman(human: $human) { id name } }\",\n/// \"variables\": {\n/// \"human\": {\n/// \"name\": \"Boba Fett\"\n/// }\n/// }\n/// }\n///\npublic class StarWarsMutation : ObjectGraphType<object>\n{\n public StarWarsMutation(StarWarsRepository data)\n {\n Name = \"Mutation\";\n\n Field<HumanType>(\n \"createOrUpdateHuman\",\n arguments: new QueryArguments(\n new QueryArgument<NonNullGraphType<HumanInputType>> {Name = \"human\"}\n ),\n resolve: context =>\n {\n //After conversion human.HomePlanet is null. But it was not informed, we should keep what is on the database at the moment\n var human = context.GetArgument<Human>(\"human\");\n //On EFCore the Update method is equivalent to an InsertOrUpdate method\n return data.Update(human);\n });\n }\n}\n```\n\n```text\npublic StarWarsMutation(StarWarsRepository data)\n{\n Name = \"Mutation\";\n\n Field<HumanType>(\n \"createOrUpdateHuman\",\n arguments: new QueryArguments(\n new QueryArgument<NonNullGraphType<HumanInputType>> {Name = \"human\"}\n ),\n resolve: context =>\n {\n //After conversion human.HomePlanet is null. But it was not informed, we should keep what is on the database at the moment\n var human = context.GetArgument<dynamic>(\"human\");\n var humanDb = data.GetHuman(human[\"id\"]);\n var json = JsonConvert.SerializeObject(human);\n JsonConvert.PopulateObject(json, humanDb);\n //On EFCore the Update method is equivalent to an InsertOrUpdate method\n return data.Update(humanDb);\n });\n}\n```\n\n```text\nJsonConvert.PopulateObject\n```\n\n```text\nGetArgument\n```\n\n```text\nGetArgument<dynamic>\n```\n\n```text\nJsonConvert.SerializeObject\n```\n\n```text\nJsonConvert.PopulateObject\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":202,"estimatedTokens":1442}}615{"id":"stack-51336464","source":"stackoverflow","questionId":51336464,"title":"Update graphql context in a mutation for the output object of the same mutation","tags":["javascript","graphql","javascript-objects","graphql-js"],"text":"Title: Update graphql context in a mutation for the output object of the same mutation\nTags: javascript, graphql, javascript-objects, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI want to use a single mutation for the application to send user info to server and then get the top level query in the output. (I know this is not a good convention but I want to do this to test if I can improve performance).\n\nSo as a result, there will only be one mutation that takes user's info and returns the feed. This mutation updates the information about the user that is fetched in every query as the context of request. The context is used to generate personalized feed. However when I call this mutation, the output returned is calculated using old context. What I need to do is update the context for this same mutation too.\n\nI put down a simplified version of the code to show what's happening:\n\n```\nconst UserType = new GraphQLObjectType({\n name: 'User',\n fields: () => ({\n someData: {\n type: GraphQLList(Post),\n resolve: (user, args, context) => getFeed(context) // context in here is the old context.\n },\n })\n})\n\nconst someMutation = mutationWithClientMutationId({\n name: 'someMutation',\n inputFields: {\n location: { type: GraphQLString },\n },\n outputFields: {\n user: {\n type: UserType,\n resolve: (source, args, context) => getUser(context.location),\n },\n },\n mutateAndGetPayload: async (data, context) => {\n\n updateUserInfo(data)\n // I have tried updating context like this but it's not working.\n context = { location: data.location }\n\n return {\n // I even tried putting user here like this:\n // user: getUser(data.location)\n // However, the resulting query fails when running getFeed(context)\n // the context is still the old context\n }\n },\n})\n```\n\n========================================\n\nCode:\n```text\nconst UserType = new GraphQLObjectType({\n name: 'User',\n fields: () => ({\n someData: {\n type: GraphQLList(Post),\n resolve: (user, args, context) => getFeed(context) // context in here is the old context.\n },\n })\n})\n\nconst someMutation = mutationWithClientMutationId({\n name: 'someMutation',\n inputFields: {\n location: { type: GraphQLString },\n },\n outputFields: {\n user: {\n type: UserType,\n resolve: (source, args, context) => getUser(context.location),\n },\n },\n mutateAndGetPayload: async (data, context) => {\n\n updateUserInfo(data)\n // I have tried updating context like this but it's not working.\n context = { location: data.location }\n\n return {\n // I even tried putting user here like this:\n // user: getUser(data.location)\n // However, the resulting query fails when running getFeed(context)\n // the context is still the old context\n }\n },\n})\n```\n\n```text\nfunction makeTrue (value) {\n value = true\n console.log(value) // true\n}\n\nvar myVariable = false\nmakeTrue(myVariable)\nconsole.log(myVariable) // false\n```\n\n```text\nfunction makeItTrue (value) {\n value.it = true\n console.log(value.it) // true\n}\n\nvar myVariable = { it: false }\nmakeTrue(myVariable)\nconsole.log(myVariable.it) // true\n```\n\n```text\ncontext\n```\n\n========================================\n\nComments:\n- So all I have to do instead of `context = {location: data.location}` would be to do `context.location = newLocation`, right?","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":120,"estimatedTokens":824}}616{"id":"stack-54251935","source":"stackoverflow","questionId":54251935,"title":"Graphql no resolver definied for interface/union - java","tags":["java","graphql","graphql-java"],"text":"Title: Graphql no resolver definied for interface/union - java\nTags: java, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI have problem adding resolver using this approach in `graphql`:\n\n```\n@RestController\n@RequestMapping(\"/api/dictionary/\")\n@RequiredArgsConstructor(onConstructor = @__(@Autowired))\npublic class DictionaryController {\n @Value(\"classpath:items.graphqls\")\n private Resource schemaResource;\n private GraphQL graphQL;\n private final DictionaryService dictionaryService;\n\n @PostConstruct\n public void loadSchema() throws IOException {\n File schemaFile = schemaResource.getFile();\n TypeDefinitionRegistry registry = new SchemaParser().parse(schemaFile);\n RuntimeWiring wiring = buildWiring();\n GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(registry, wiring);\n graphQL = GraphQL.newGraphQL(schema).build();\n }\n\nprivate RuntimeWiring buildWiring() {\n DataFetcher> fetcher6 = dataFetchingEnvironment -> dictionaryService.getClaimSubType();\n\n return RuntimeWiring.newRuntimeWiring()\n .type(\"Query\", typeWriting ->\n typeWriting\n .dataFetcher(\"getClaimSubType\", fetcher6)\n )\n .build();\n }\n\npublic List getClaimSubType() {\n return dictionaryService.getClaimSubType();\n }\n }\n```\n\n`items.graphqls` file content:\n\n```\ntype Query {\n getClaimSubType: [DictionaryItemWithParentDto]\n}\n\ntype DictionaryItemWithParentDto {\n code: String!\n name: String\n parents: [DictionaryItemDto]\n}\n\ntype DictionaryItemDto {\n code: String!\n name: String\n description: String\n}\n```\n\nIn java I have `Vehicle` interface and two classes that implement it: `Airplane` and `Car`. When i add to schema this line:\n\n```\nunion SearchResult = Airplane | Car\n```\n\nI get following error:\n\n```\nThere is no type resolver defined for interface / union 'Vehicle' type, There is no type resolver defined for interface / union 'SearchResult' type]}\n```\n\nI am not sure how to handle it.\n\nIf instead i add:\n\n```\ninterface Vehicle {\n maxSpeed: Int\n}\n\ntype Airplane implements Vehicle {\n maxSpeed: Int\n wingspan: Int\n}\n\ntype Car implements Vehicle {\n maxSpeed: Int\n licensePlate: String\n}\n```\n\nI get following error:\n\n```\nerrors=[There is no type resolver defined for interface / union 'Vehicle' type]\n```\n\nHow can i handle these errors using my approach ? Is there another approach to handle it?\n\n**Edit**\n\nAdding these lines of code fix the issue partway i guess:\n\n```\nTypeResolver t = new TypeResolver() {\n @Override\n public GraphQLObjectType getType(TypeResolutionEnvironment env) {\n Object javaObject = env.getObject();\n if (javaObject instanceof Car) {\n return env.getSchema().getObjectType(\"Car\");\n } else if (javaObject instanceof Airplane) {\n return env.getSchema().getObjectType(\"Airplane\");\n } else {\n return env.getSchema().getObjectType(\"Car\");\n }\n }\n};\n```\n\nAnd adding to `RuntimeWiring` builder this:\n\n```\n.type(\"Vehicle\", typeWriting ->\n typeWriting\n .typeResolver(t)\n )\n\n @PostMapping(\"getVehicle\")\n public ResponseEntity getVehicleMaxSpeed(@RequestBody String query) \n {\n ExecutionResult result = graphQL.execute(query);\n return new ResponseEntity(result, HttpStatus.OK);\n }\n```\n\nWhen asking for:\n\n```\nquery {\n getVehicle(maxSpeed: 30) {\n maxSpeed\n\n }\n}\n```\n\nI get the `maxSpeed` but when i add `wingspan` i get an error \n\n```\nField 'wingspan' in type 'Vehicle' is undefined @ 'getVehicle/wingspan'\",\n```\n\nI added \n\n```\ngetVehicle(maxSpeed: Int): Vehicle\n```\n\nTo the `graphqls` file. I thought that polymorphism would work here.\n\n========================================\n\nCode:\n```text\n@RestController\n@RequestMapping(\"/api/dictionary/\")\n@RequiredArgsConstructor(onConstructor = @__(@Autowired))\npublic class DictionaryController {\n @Value(\"classpath:items.graphqls\")\n private Resource schemaResource;\n private GraphQL graphQL;\n private final DictionaryService dictionaryService;\n\n @PostConstruct\n public void loadSchema() throws IOException {\n File schemaFile = schemaResource.getFile();\n TypeDefinitionRegistry registry = new SchemaParser().parse(schemaFile);\n RuntimeWiring wiring = buildWiring();\n GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(registry, wiring);\n graphQL = GraphQL.newGraphQL(schema).build();\n }\n\nprivate RuntimeWiring buildWiring() {\n DataFetcher<List<DictionaryItemWithParentDto>> fetcher6 = dataFetchingEnvironment -> dictionaryService.getClaimSubType();\n\n return RuntimeWiring.newRuntimeWiring()\n .type(\"Query\", typeWriting ->\n typeWriting\n .dataFetcher(\"getClaimSubType\", fetcher6)\n )\n .build();\n }\n\n\npublic List<DictionaryItemWithParentDto> getClaimSubType() {\n return dictionaryService.getClaimSubType();\n }\n }\n```\n\n```text\ntype Query {\n getClaimSubType: [DictionaryItemWithParentDto]\n}\n\ntype DictionaryItemWithParentDto {\n code: String!\n name: String\n parents: [DictionaryItemDto]\n}\n\ntype DictionaryItemDto {\n code: String!\n name: String\n description: String\n}\n```\n\n```text\nunion SearchResult = Airplane | Car\n```\n\n```text\nThere is no type resolver defined for interface / union 'Vehicle' type, There is no type resolver defined for interface / union 'SearchResult' type]}\n```\n\n```text\ninterface Vehicle {\n maxSpeed: Int\n}\n\ntype Airplane implements Vehicle {\n maxSpeed: Int\n wingspan: Int\n}\n\ntype Car implements Vehicle {\n maxSpeed: Int\n licensePlate: String\n}\n```\n\n```text\nerrors=[There is no type resolver defined for interface / union 'Vehicle' type]\n```\n\n```text\nTypeResolver t = new TypeResolver() {\n @Override\n public GraphQLObjectType getType(TypeResolutionEnvironment env) {\n Object javaObject = env.getObject();\n if (javaObject instanceof Car) {\n return env.getSchema().getObjectType(\"Car\");\n } else if (javaObject instanceof Airplane) {\n return env.getSchema().getObjectType(\"Airplane\");\n } else {\n return env.getSchema().getObjectType(\"Car\");\n }\n }\n};\n```\n\n```text\n.type(\"Vehicle\", typeWriting ->\n typeWriting\n .typeResolver(t)\n )\n\n\n @PostMapping(\"getVehicle\")\n public ResponseEntity<Object> getVehicleMaxSpeed(@RequestBody String query) \n {\n ExecutionResult result = graphQL.execute(query);\n return new ResponseEntity<Object>(result, HttpStatus.OK);\n }\n```\n\n```text\nquery {\n getVehicle(maxSpeed: 30) {\n maxSpeed\n\n }\n}\n```\n\n```text\nField 'wingspan' in type 'Vehicle' is undefined @ 'getVehicle/wingspan'\",\n```\n\n```text\ngetVehicle(maxSpeed: Int): Vehicle\n```\n\n```text\ngraphql\n```\n\n```text\nitems.graphqls\n```\n\n```text\nVehicle\n```\n\n```text\nAirplane\n```\n\n```text\nCar\n```\n\n```text\nRuntimeWiring\n```\n\n```text\nmaxSpeed\n```\n\n```text\nwingspan\n```\n\n```text\ngraphqls\n```\n\n```text\nTypeResolver t = new TypeResolver() {\n @Override\n public GraphQLObjectType getType(TypeResolutionEnvironment env) {\n Object javaObject = env.getObject();\n if (javaObject instanceof Car) {\n return env.getSchema().getObjectType(\"Car\");\n } else if (javaObject instanceof Airplane) {\n return env.getSchema().getObjectType(\"Airplane\");\n } else {\n return env.getSchema().getObjectType(\"Car\");\n }\n }\n};\n```\n\n```text\n.type(\"Vehicle\", typeWriting ->\n typeWriting\n .typeResolver(t)\n )\n\n\n @PostMapping(\"getVehicle\")\n public ResponseEntity<Object> getVehicleMaxSpeed(@RequestBody String query) \n {\n ExecutionResult result = graphQL.execute(query);\n return new ResponseEntity<Object>(result, HttpStatus.OK);\n }\n```\n\n```text\nquery {\n getVehicle(maxSpeed: 30) {\n maxSpeed\n\n }\n}\n```\n\n```text\nField 'wingspan' in type 'Vehicle' is undefined @ 'getVehicle/wingspan'\",\n```\n\n```text\ngetVehicle(maxSpeed: Int): Vehicle\n```\n\n```text\nquery {\n getVehicle(maxSpeed: 10) {\n maxSpeed\n ... on Airplane {\n wingspan\n }\n ... on Car {\n licensePlate\n }\n }\n}\n```\n\n```text\nRuntimeWiring\n```\n\n```text\nmaxSpeed\n```\n\n```text\nwingspan\n```\n\n```text\ngraphqls\n```\n\n========================================\n\nComments:\n- how did you compile this line? if (javaObject instanceof Car) { how this CAR class is generated?\n- It's normal `Java` class - made by hand\n- Is there a generic way to do it without creating the Car class?\n- @stark I have checked if `javaObject instanceof Map && ((Map)javaObject).get(\"__typename\")` and put the type name directly into the map value. You can do anything you want to determine the GraphQL type name, given a value, it doesn't *have* to be concrete-class-based (though it is a very Java-idiomatic option)","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":30,"totalLines":419,"estimatedTokens":2182}}617{"id":"stack-49237159","source":"stackoverflow","questionId":49237159,"title":"Display more than 100 entries through GraphQL API","tags":["graphql","github-api","github-graphql"],"text":"Title: Display more than 100 entries through GraphQL API\nTags: graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI have tired pagination using endCursor and hasNextPage in github grpahQL API to get more than 100 data. Query I used is:\n\n```\nquery {\n organization(login:\"XXX\") {\n repository(name:\"XX\") {\n pullRequests(first:100, states:[OPEN], after: \"XXX\" ) {\n pageInfo{\n hasNextPage\n endCursor\n }\n }\n }\n```\n\nIt is working. But in order to access further details,iterative pagination needs to be done. Can anyone provides an efficient alternative to traverse all pages programatically in GraphQL API?\n\n========================================\n\nTop Answer:\nTaking inspiration from Simon Willison's 'Paginating through the GitHub GraphQL API with Python' here's what I've been doing to paginate my queries:\n\n```\nquery {\n node(id: \"PROJECT_ID\") {\n ... on ProjectNext {\n items(first: 100 after: CURSOR) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n title\n fieldValues(first: 8) {\n nodes {\n value\n }\n }\n content {\n ... on Issue {\n number\n labels(first: 50) {\n nodes {\n name\n}}}}}}}}}\n```\n\nIn my Python code I'm splicing in `PROJECT_ID` with a variable set to the project ID I'm referencing.\n\nFor the cursor `after: CURSOR` is replaced with `\"\"` initially, and then for the next page I set `cursor = 'after:\\\\\"' + response[\"data\"][\"node\"][\"items\"][\"pageInfo\"][\"endCursor\"] + '\\\\\"'`\n\nMy full code is in the atdumpmemex module of my dump_cards utility.\n\nThe key here is to get `pageInfo` along with other relevant nodes, and then grab the `endCursor` each time `hasNextPage` is true so that it can be fed into the query for the next iteration.\n\npageInfo will look something like:\n\n```\n\"pageInfo\": {\n \"hasNextPage\": false,\n \"endCursor\": \"Y3Vyc29yOnYyOpHOAAhOsg==\"\n}\n```\n\nAt the moment the `endCursor` is base64 encoded `cursor:v2:XYZ`, but don't rely on that as GitHub have moved other IDs from being base64 encoded to other schemes.\n\n========================================\n\nCode:\n```text\nquery {\n organization(login:\"XXX\") {\n repository(name:\"XX\") {\n pullRequests(first:100, states:[OPEN], after: \"XXX\" ) {\n pageInfo{\n hasNextPage\n endCursor\n }\n }\n }\n```\n\n```json\nquery {\n node(id: \"PROJECT_ID\") {\n ... on ProjectNext {\n items(first: 100 after: CURSOR) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n title\n fieldValues(first: 8) {\n nodes {\n value\n }\n }\n content {\n ... on Issue {\n number\n labels(first: 50) {\n nodes {\n name\n}}}}}}}}}\n```\n\n```json\n\"pageInfo\": {\n \"hasNextPage\": false,\n \"endCursor\": \"Y3Vyc29yOnYyOpHOAAhOsg==\"\n}\n```\n\n```text\nPROJECT_ID\n```\n\n```text\nafter: CURSOR\n```\n\n```text\n\"\"\n```\n\n```text\ncursor = 'after:\\\\\"' + response[\"data\"][\"node\"][\"items\"][\"pageInfo\"][\"endCursor\"] + '\\\\\"'\n```\n\n```text\npageInfo\n```\n\n```text\nendCursor\n```\n\n```text\nhasNextPage\n```\n\n```text\nendCursor\n```\n\n```text\ncursor:v2:XYZ\n```\n\n========================================\n\nComments:\n- this is a limitation at the api level: developer.github.com/v4/guides/resource-limitations. Nothing you do in your code can change that","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":159,"estimatedTokens":826}}618{"id":"stack-49575203","source":"stackoverflow","questionId":49575203,"title":"Can AWS App-Sync be used without dynamoDB","tags":["mongodb","amazon-dynamodb","graphql","aws-appsync"],"text":"Title: Can AWS App-Sync be used without dynamoDB\nTags: mongodb, amazon-dynamodb, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI am interested in the offline and sync capabilities of Amazon's app-sync but I was wondering if it could be used without dynamoDB as the backend. The graphQL resolvers written in VTL for dynamoDB look atrocious. It seems it would be much nicer to use a mongo backend. Is that possible?\n\n========================================\n\nTop Answer:\nYes aws appsync can be used without dynamodb . In datasource section of your appsync module you can see options to which you want to link your appsync module. Even don't worry about schema generation. Appsync help you to do it automatically . Just enable auto generate schema .\nhttps://docs.aws.amazon.com/appsync/latest/devguide/tutorials.html\n\n========================================\n\nComments:\n- What about using mongodb?\n- You can use any DB by making Lambda as your resolver.","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":18,"estimatedTokens":240}}619{"id":"stack-40347983","source":"stackoverflow","questionId":40347983,"title":"Graphql schema returning null","tags":["node.js","graphql","graphql-js"],"text":"Title: Graphql schema returning null\nTags: node.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am trying to return a authentication token in response to a graphql query with username and password as arguments, but somehow graphql is always returning `null`. I am able to print the token just before returning it.\n\n```\nvar {\n GraphQLObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLString,\n GraphQLSchema\n} = require('graphql');\nlet MyUser = require('./modules/user/user');\n\nconst Query = new GraphQLObjectType({\n name: 'Query',\n description : 'UserQuery',\n fields: function(){\n return {\n Token :{\n type: GraphQLString,\n description : \"Authentication token\",\n args: {\n user_name: { type: GraphQLString },\n password: { type: GraphQLString },\n },\n resolve(root, args){\n let user = new MyUser();\n user.authenticateUser(args.user_name, args.password, function(result){\n console.log(\"token :\"+result);\n return result;\n })\n }\n }\n }\n }\n});\n\nconst Schema = new GraphQLSchema({\n query: Query\n});\n\nmodule.exports = Schema;\n```\n\nQuery look like\n\n```\nquery{\n Token(user_name: \"Thurman.Cassin@hotmail.com\" \n password: \"abc123\")\n}\n```\n\nResult \n\n```\n{\n \"data\": {\n \"Token\": null\n }\n}\n```\n\nwhat I am doing wrong here ?\n\n========================================\n\nTop Answer:\nNot related to your case, but as you are the first result for the Google search \"GraphQl query always returning null\", I my experience, with the hope to help some.\n\nHere was my original query, always returning null:\n\n```\nquery: new GraphQLObjectType({\n name: 'RootQueryType2',\n fields: {\n allDatalogs: {\n type: new GraphQLList(dataLogType),\n\n resolve: (root, source, fieldASTs) => {\n var foundItems = new Promise((resolve, reject) => {\n DataLogMongo.find({}, (err, users) => {\n if (err) {\n reject(err);\n } else {\n resolve(users);\n users.forEach(function (myDoc) {\n console.log(\"datalog: \" );\n console.log(myDoc);\n });\n }\n })\n return foundItems\n })\n\n }\n }\n```\n\nAs you can see, the return statement was inside the Promise(..) brackets. However, it had to be put obviously after, which gave:\n\n```\nallDatalogs: {\n type: new GraphQLList(dataLogType),\n\n resolve: (root, source, fieldASTs) => {\n var foundItems = new Promise((resolve, reject) => {\n DataLogMongo.find({}, (err, users) => {\n if (err) {\n reject(err);\n } else {\n resolve(users);\n users.forEach(function (myDoc) {\n console.log(\"datalog: \" );\n console.log(myDoc);\n });\n }\n })\n\n })\n return foundItems\n }\n }\n```\n\nThen I was able to get the results. Hope I helped :)\n\n========================================\n\nCode:\n```text\nvar {\n GraphQLObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLString,\n GraphQLSchema\n} = require('graphql');\nlet MyUser = require('./modules/user/user');\n\n\nconst Query = new GraphQLObjectType({\n name: 'Query',\n description : 'UserQuery',\n fields: function(){\n return {\n Token :{\n type: GraphQLString,\n description : \"Authentication token\",\n args: {\n user_name: { type: GraphQLString },\n password: { type: GraphQLString },\n },\n resolve(root, args){\n let user = new MyUser();\n user.authenticateUser(args.user_name, args.password, function(result){\n console.log(\"token :\"+result);\n return result;\n })\n }\n }\n }\n }\n});\n\n\nconst Schema = new GraphQLSchema({\n query: Query\n});\n\nmodule.exports = Schema;\n```\n\n```text\nquery{\n Token(user_name: \"Thurman.Cassin@hotmail.com\" \n password: \"abc123\")\n}\n```\n\n```text\n{\n \"data\": {\n \"Token\": null\n }\n}\n```\n\n```text\nnull\n```\n\n```text\nuser.authenticateUser(args.user_name, args.password, function(result){\n console.log(\"token :\"+result);\n return result;\n});\n```\n\n```text\nresolve(root, args){\n let user = new MyUser();\n return new Promise((resolve, reject) => {\n user.authenticateUser(args.user_name, args.password, function(result){\n console.log(\"token :\"+result);\n resolve(result);\n });\n })\n}\n```\n\n```text\nquery: new GraphQLObjectType({\n name: 'RootQueryType2',\n fields: {\n allDatalogs: {\n type: new GraphQLList(dataLogType),\n\n resolve: (root, source, fieldASTs) => {\n var foundItems = new Promise((resolve, reject) => {\n DataLogMongo.find({}, (err, users) => {\n if (err) {\n reject(err);\n } else {\n resolve(users);\n users.forEach(function (myDoc) {\n console.log(\"datalog: \" );\n console.log(myDoc);\n });\n }\n })\n return foundItems\n })\n\n }\n }\n```\n\n```text\nallDatalogs: {\n type: new GraphQLList(dataLogType),\n\n resolve: (root, source, fieldASTs) => {\n var foundItems = new Promise((resolve, reject) => {\n DataLogMongo.find({}, (err, users) => {\n if (err) {\n reject(err);\n } else {\n resolve(users);\n users.forEach(function (myDoc) {\n console.log(\"datalog: \" );\n console.log(myDoc);\n });\n }\n })\n\n })\n return foundItems\n }\n }\n```\n\n========================================\n\nComments:\n- This should work! Nice and clean\n- That worked like a charm, Thanks.","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":271,"estimatedTokens":1406}}620{"id":"stack-53974926","source":"stackoverflow","questionId":53974926,"title":"With Prisma, How can we add a comment for a Type?","tags":["schema","graphql","prisma","prisma-graphql"],"text":"Title: With Prisma, How can we add a comment for a Type?\nTags: schema, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nWith prisma.io (graphQl), we have:\n\n- File: `datamodel.graphql`\n\n```\n\"\"\"I am a great User\"\"\"\ntype User {\n id: ID! @unique\n email: String! @unique\n}\n```\n\nafter doing `prisma deploy`, it generates a file without the comment from the file `datamodel.graphql`\n\n- File `generated-schema.graphql`\n\n```\ntype User implements Node {\n id: ID!\n email: String!\n}\n```\n\nIn the prisma `playground`, I do not have the comment.\nhttps://i.sstatic.net/WRSbb.png\n\n**How can we add a comment for a Type in order to generate a documentation in playground?**\n\nWorkaround:\n\nIf I cheat and add a comment in the `generated-schema.graphql` (this file will be overridden after the next `prisma deploy`)\n\n`\"\"\"I am a great User\"\"\"\ntype User implements Node {\n id: ID!\n email: String!\n}`\n\nwe have: \nhttps://i.sstatic.net/A5LT4.png\n\nRelated topics:\n\nhttps://github.com/prisma/graphql-playground/issues/819\n\nhttps://www.prisma.io/forum/t/getting-prisma-comments-descriptions-to-appear-in-graphql-playground-schema/2980\n\nhttps://github.com/prisma/prisma/issues/2152\n\n========================================\n\nTop Answer:\nTools like Nexus allow for it. Optional descriptions could be included along with types and individual fields.\n\nRef to docs\n\n========================================\n\nCode:\n```text\n\"\"\"I am a great User\"\"\"\ntype User {\n id: ID! @unique\n email: String! @unique\n}\n```\n\n```text\ntype User implements Node {\n id: ID!\n email: String!\n}\n```\n\n```text\ndatamodel.graphql\n```\n\n```text\nprisma deploy\n```\n\n```text\ndatamodel.graphql\n```\n\n```text\ngenerated-schema.graphql\n```\n\n```text\nplayground\n```\n\n```text\ngenerated-schema.graphql\n```\n\n```text\nprisma deploy\n```\n\n```text\n\"\"\"I am a great User\"\"\"\ntype User implements Node {\n id: ID!\n email: String!\n}\n```\n\n```text\nCurrently, thereβs no easy way to resolve this. This is an open feature request, which you can learn more about here:\n```\n\n========================================\n\nComments:\n- Looks like the links are broken or the docs moved?","metadata":{"transformedAt":"2026-08-18T18:32:36.071Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":123,"estimatedTokens":527}}621{"id":"stack-68348307","source":"stackoverflow","questionId":68348307,"title":"How can I use redux and graphql with apollo client in the same react app?","tags":["javascript","reactjs","redux","graphql"],"text":"Title: How can I use redux and graphql with apollo client in the same react app?\nTags: javascript, reactjs, redux, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm working on a project, and I'm using apollo/client, graphql in react, and for the global state management, I have to use redux. I'm quite sure I'll have to handle more data in my project so I'll put it in my store.\nI'm wondering about how can I make redux actions to get data from graphql endpoint using apollo Client\n\nthe first part is my index.js where I set up the apollo client.\n\n```\nimport React from \"react\";\n import ReactDOM from \"react-dom\";\n import App from './App.jsx';\n import {BrowserRouter} from \"react-router-dom\";\n import store from \"./store\";\n import { Provider } from \"react-redux\";\n import ApolloClient from 'apollo-boost';\n import { ApolloProvider } from 'react-apollo';\n import {InMemoryCache} from \"@apollo/client\";\n \n const client = new ApolloClient({\n uri: 'http://localhost:4000/graphql',\n cache: new InMemoryCache()\n });\n \n ReactDOM.render(\n \n \n \n \n \n \n \n \n ,\n document.getElementById(\"root\")\n );\n```\n\nI have a problem with completing the action file of redux.\nit didn't send data to the rest of the app.\n\n```\nimport {\n FETCH_PRODUCTS,\n FETCH_PRODUCTS_FAIL,\n FETCH_PRODUCTS_SUCCESS } from \"../types\";\n import {gql} from \"apollo-boost\";\n \n const getProductsQuery = gql`\n {\n category{\n products{\n name\n inStock\n gallery\n category\n prices{\n currency\n amount\n }\n }\n }\n \n }\n `\n \n const fetchProducts = () => async(dispatch) =>{\n dispatch({\n type: FETCH_PRODUCTS,\n });\n \n try{\n \n //how can I get data from GRAPHQL by using apollo client\n \n dispatch({\n type:FETCH_PRODUCTS_SUCCESS,\n payload:data,\n });\n \n }\n catch(error){\n dispatch({\n type: FETCH_PRODUCTS_FAIL,\n payload:error.message\n });\n }\n \n }\n // export default graphql(getProductsQuery);\n export {fetchProducts};\n```\n\n========================================\n\nCode:\n```text\nimport React from \"react\";\n import ReactDOM from \"react-dom\";\n import App from './App.jsx';\n import {BrowserRouter} from \"react-router-dom\";\n import store from \"./store\";\n import { Provider } from \"react-redux\";\n import ApolloClient from 'apollo-boost';\n import { ApolloProvider } from 'react-apollo';\n import {InMemoryCache} from \"@apollo/client\";\n \n const client = new ApolloClient({\n uri: 'http://localhost:4000/graphql',\n cache: new InMemoryCache()\n });\n \n ReactDOM.render(\n <React.StrictMode>\n <ApolloProvider client={client}>\n <Provider store={store}>\n <BrowserRouter>\n <App />\n </BrowserRouter>\n </Provider>\n </ApolloProvider>\n </React.StrictMode>,\n document.getElementById(\"root\")\n );\n```\n\n```text\nimport {\n FETCH_PRODUCTS,\n FETCH_PRODUCTS_FAIL,\n FETCH_PRODUCTS_SUCCESS } from \"../types\";\n import {gql} from \"apollo-boost\";\n \n const getProductsQuery = gql`\n {\n category{\n products{\n name\n inStock\n gallery\n category\n prices{\n currency\n amount\n }\n }\n }\n \n }\n `\n \n const fetchProducts = () => async(dispatch) =>{\n dispatch({\n type: FETCH_PRODUCTS,\n });\n \n try{\n \n //how can I get data from GRAPHQL by using apollo client\n \n dispatch({\n type:FETCH_PRODUCTS_SUCCESS,\n payload:data,\n });\n \n }\n catch(error){\n dispatch({\n type: FETCH_PRODUCTS_FAIL,\n payload:error.message\n });\n }\n \n }\n // export default graphql(getProductsQuery);\n export {fetchProducts};\n```\n\n========================================\n\nComments:\n- thanks for replying, but I need the data I have got by apollo to be used in redux action!! I can't really understand what I have to do .. how can I do it ??\n- You have that data available in your component when using the apollo hooks. Of course you can then send it to redux, but you really should reconsider that. For every type of request to the server, you should be using apollo, and the data is already accessible throughout your application by using apollo. That data should usually never touch redux.\n- @phry could you recommend some solution/s if we want a solid state management solution that works well with graphql? I really like the caching that comes out of the box with Apollo but also would like to have someting like Redux.\n- @ZenVentzi You can use RTK Query, but you could really also just use Apollo for server state and Redux for client state. Both perfectly valid. Just don't sync them.\n- @phry is this means that Apollo client actually caches the request/responses, as far as I see yes, but can you please confirm? I am a bit concern about performance if I trigger the same request a couple of times during lifespan of app /client is in the page browsing/\n- @Gesha yes. Apollo Client is a cache. Unless you set fetchPolicies that will trigger refetches, it will use the cache if you trigger the same query from multiple components.\n- and what if I need to combine my server and local state in a redux selector to produce a different state? I think the correct approach is to pass the apollo useQuery data to the redux selector in a parent component\n- @DavidRearte referencing Apollo data in a selector doesn't \"put it into the Redux store\", so yes, that's a valid use case.","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":191,"estimatedTokens":1390}}622{"id":"stack-40451636","source":"stackoverflow","questionId":40451636,"title":"Inspecting a remote graphql endpoint with graphiql","tags":["graphql","graphql-js"],"text":"Title: Inspecting a remote graphql endpoint with graphiql\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nThere is a graphql endpoint which I don't own but which provides a public endpoint. I'm hoping to introspect it using graphiql. I'm totally new to graphql, so I don't even know if this sort of thing is possible.\n\nI have the graphiql example running locally and am modifying server.js to try to make it work. Poking around at other SO threads has gotten me this far...\n\n```\nvar introspectionQuery = require('graphql/utilities').introspectionQuery;\nvar request = require('sync-request');\n\nvar url = 'http://endpoint.com/graphql';\nvar response = request('POST', url, { qs: { query: introspectionQuery } } );\nvar schema = JSON.parse(response.body.toString('utf-8'));\n\n// herein lies the rub\nschema = new GraphQLSchema(schema.data.__schema);\n\nvar app = express();\napp.use(express.static(__dirname));\napp.use('/graphql', graphqlHTTP(() => ({\n schema: schema,\n})));\napp.listen(8080);\n```\n\nThis code blows up in the GraphQLSchema constructor, trying to make a schema out of that introspection query. Clearly that's not quite the right approach?\n\n========================================\n\nTop Answer:\nI was trying this with a PHP GraphQL library. I hit lots of issues experimenting with the above around CORS (cross origin security stuff).\n\nThen I discovered GraphIQL is available as a Chrome app. That resolved my need, so noting here in case useful to anyone else who comes across this issue. You don't need to do any coding to get GraphIQL working with a remote endpoint.\n\n========================================\n\nCode:\n```text\nvar introspectionQuery = require('graphql/utilities').introspectionQuery;\nvar request = require('sync-request');\n\nvar url = 'http://endpoint.com/graphql';\nvar response = request('POST', url, { qs: { query: introspectionQuery } } );\nvar schema = JSON.parse(response.body.toString('utf-8'));\n\n// herein lies the rub\nschema = new GraphQLSchema(schema.data.__schema);\n\nvar app = express();\napp.use(express.static(__dirname));\napp.use('/graphql', graphqlHTTP(() => ({\n schema: schema,\n})));\napp.listen(8080);\n```\n\n```js\nvar buildClientSchema = require('graphql/utilities').buildClientSchema;\nvar introspectionQuery = require('graphql/utilities').introspectionQuery;\nvar request = require('sync-request');\n\nvar response = request('POST', url, { qs: { query: introspectionQuery } });\n// Assuming we're waiting for the above request to finish (await maybe)\nvar introspectionResult = JSON.parse(response.body.toString('utf-8'));\nvar schema = buildClientSchema(introspectionResult);\n```\n\n```text\ntype GraphQLSchemaConfig = {\n query: GraphQLObjectType;\n mutation?: ?GraphQLObjectType;\n subscription?: ?GraphQLObjectType;\n types?: ?Array<GraphQLNamedType>;\n directives?: ?Array<GraphQLDirective>;\n};\n```\n\n```text\nbuildClientSchema\n```\n\n```text\nbuildASTSchema\n```\n\n```text\nGraphQLSchema\n```\n\n```text\nGraphQLSchema\n```\n\n```text\nGraphQLSchemaConfig\n```\n\n```text\nbuildClientSchema\n```\n\n```text\nbuildASTSchema\n```\n\n========================================\n\nComments:\n- That worked! I just had to do `buildClientSchema(introspectionResult.data)`.\n- So then the followup question would be how to use graphiql to post queries back to that endpoint...\n- For that you could look at the example index.html code we have in here: github.com/graphql/graphiql/blob/master/example/index.html#L‌​95\n- Basically with your server implemented with `/graphql` endpoint, configure your graphiql by writing a `fetcher` function to pass your query from client side to server side.\n- maybe you would like to check this out gist.github.com/geocine/c93ba07c9956f403f0f11ff9c1b39a55","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":116,"estimatedTokens":932}}623{"id":"stack-33512889","source":"stackoverflow","questionId":33512889,"title":"Patterns for undo-redo state traversal with Relay-GraphQL mutations","tags":["immutable.js","graphql","relayjs"],"text":"Title: Patterns for undo-redo state traversal with Relay-GraphQL mutations\nTags: immutable.js, graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nAttaining undo/redo functionality with Immutable and a Flux implementation is basically trivial. This is in part due to the value-passing made possible by Immutable and in part because of the in-browser/in-memory nature of using Flux.\n\nConceptualizing this in terms of Relay-GraphQL mutations, however, is not obvious. Are there any known patterns out there that simplify this?\n\n========================================\n\nComments:\n- Can you clarify the use-case? Is the motivation for having undo/redo to enable debugging, or to provide a user-facing ability to undo/redo mutations that have been committed on the server?\n- @JoeSavona use-case is basically undo-redo functionality. But I've gotten to know GraphQL/Relay more since posting this question and it seems like that sort of functionality might be beyond their scope. Would be interesting to keep this in mind in terms of anything that *is* in scope and would aid in this type of functionality.\n- @JoeSavona thanks for your work and time. These are great projects.\n- To add to this I recommend using the very small libraries immutable-diff and immutable-patch to store mutations in the frontend, and then you can send the consolidated list of patches to the backend to perform the actual mutations.\n- This actually isn't true anymore. Relay does handle local state: relay.dev/docs/en/local-state-management.","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":17,"estimatedTokens":378}}624{"id":"stack-51720378","source":"stackoverflow","questionId":51720378,"title":"How to implement graphql subscription using apollo ios client","tags":["graphql","apollo-ios"],"text":"Title: How to implement graphql subscription using apollo ios client\nTags: graphql, apollo-ios\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement graphql subscription using apollo ios client. But not able to figure it out as lack of documentation examples.\nExample given on apollo documentation is:\n\n```\nlet apollo: ApolloClient = {\n let configuration = URLSessionConfiguration.default\n // Add additional headers as needed\n configuration.httpAdditionalHeaders = [\"Authorization\": \"Bearer \"] // Replace ``\n\n let url = URL(string: \"http://localhost:8080/graphql\")!\n\n return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))\n}()\n```\n\nAPOLLO IOS GUIDE: Creating a client\n\n========================================\n\nTop Answer:\nI'm getting close. I was getting rejected for not having the correct headers in my Websocket upgrade. I ended up having to set them directly on the `URLRequest` object.\n\n```\nvar apollo: ApolloClient? {\n let authHeaders = [\"X-Hasura-Access-Key\": \"\", \"Content-Type\": \"application/json\"]\n\n let configuration = URLSessionConfiguration.default\n // Add additional headers as needed\n configuration.httpAdditionalHeaders = authHeaders\n\n //The string to my graph QL Server run by Hasure on AWS RDS.\n let graphQLEndpoint = \"http:///v1alpha1/graphql\"\n let graphQLSubscriptionEndpoint = \"ws:///v1alpha1/graphql\"\n //Take my Ec2 Server string and make a URL for the graph QL and subscriptions\n guard let httpURL = URL(string: graphQLEndpoint), let webSocketURL = URL(string: graphQLSubscriptionEndpoint) else {\n return nil\n }\n\n let httpTransport = HTTPNetworkTransport(url: httpURL, configuration: configuration, sendOperationIdentifiers: false)\n\n var request = URLRequest(url: webSocketURL)\n\n request.setValue(\"\", forHTTPHeaderField: \"X-Hasura-Access-Key\")\n\n request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n\n let webSocketTransport = WebSocketTransport(request: request, sendOperationIdentifiers: false, connectingPayload: nil)\n\n let splitTransport = SplitNetworkTransport(httpNetworkTransport: httpTransport, webSocketNetworkTransport: webSocketTransport)\n\n //Initalize the APolloClient with that URL.\n return ApolloClient(networkTransport: splitTransport)\n }\n```\n\nThe upgrade worked after that.\n\n========================================\n\nCode:\n```text\nlet apollo: ApolloClient = {\n let configuration = URLSessionConfiguration.default\n // Add additional headers as needed\n configuration.httpAdditionalHeaders = [\"Authorization\": \"Bearer <token>\"] // Replace `<token>`\n\n let url = URL(string: \"http://localhost:8080/graphql\")!\n\n return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))\n}()\n```\n\n```text\nlazy var apollo: ApolloClient = {\n let authPayloads = [\n \"Authorization\": \"Bearer \"\n ]\n let configuration = URLSessionConfiguration.default\n configuration.httpAdditionalHeaders = authPayloads\n\nlet map: GraphQLMap = authPayloads \nlet wsEndpointURL = URL(string: \"ws://localhost:8080/subscriptions\")!\nlet endpointURL = URL(string: \"http://localhost:8080/api\")!\nlet websocket = WebSocketTransport(request: URLRequest(url: wsEndpointURL), connectingPayload: map)\nlet splitNetworkTransport = SplitNetworkTransport(\n httpNetworkTransport: HTTPNetworkTransport(\n url: endpointURL,\n configuration: configuration\n ), \n webSocketNetworkTransport: websocket\n)\nreturn ApolloClient(networkTransport: splitNetworkTransport)\n\n\n}()\nlet map: GraphQLMap = authPayloads \nlet wsEndpointURL = URL(string: \"ws://localhost:8080/subscriptions\")!\nlet endpointURL = URL(string: \"http://localhost:8080/api\")!\nlet websocket = WebSocketTransport(request: URLRequest(url: wsEndpointURL), connectingPayload: map)\nlet splitNetworkTransport = SplitNetworkTransport(\n httpNetworkTransport: HTTPNetworkTransport(\n url: endpointURL,\n configuration: configuration\n ), \n webSocketNetworkTransport: websocket\n)\nreturn ApolloClient(networkTransport: splitNetworkTransport)\n```\n\n```text\nlet map: GraphQLMap = authPayloads \nlet wsEndpointURL = URL(string: \"ws://localhost:8080/subscriptions\")!\nlet endpointURL = URL(string: \"http://localhost:8080/api\")!\nlet websocket = WebSocketTransport(request: URLRequest(url: wsEndpointURL), connectingPayload: map)\nlet splitNetworkTransport = SplitNetworkTransport(\n httpNetworkTransport: HTTPNetworkTransport(\n url: endpointURL,\n configuration: configuration\n ), \n webSocketNetworkTransport: websocket\n)\nreturn ApolloClient(networkTransport: splitNetworkTransport)\n```\n\n```text\npod 'Apollo'\n```\n\n```text\npod 'Apollo/WebSocket'\n```\n\n```text\npod install\n```\n\n```text\nAppDelegate.swift\n```\n\n```text\nWebSocketTransport\n```\n\n```text\nURLRequest\n```\n\n```text\nconnectingPayload\n```\n\n```text\nSplitNetworkTransport\n```\n\n```text\nhttp\n```\n\n```text\nwebsocket\n```\n\n```text\nhttpNetworkTransport\n```\n\n```text\nwebSocketNetworkTransport\n```\n\n```swift\nvar apollo: ApolloClient? {\n let authHeaders = [\"X-Hasura-Access-Key\": \"<my_Key>\", \"Content-Type\": \"application/json\"]\n\n let configuration = URLSessionConfiguration.default\n // Add additional headers as needed\n configuration.httpAdditionalHeaders = authHeaders\n\n //The string to my graph QL Server run by Hasure on AWS RDS.\n let graphQLEndpoint = \"http://<my_host>/v1alpha1/graphql\"\n let graphQLSubscriptionEndpoint = \"ws://<my_host>/v1alpha1/graphql\"\n //Take my Ec2 Server string and make a URL for the graph QL and subscriptions\n guard let httpURL = URL(string: graphQLEndpoint), let webSocketURL = URL(string: graphQLSubscriptionEndpoint) else {\n return nil\n }\n\n let httpTransport = HTTPNetworkTransport(url: httpURL, configuration: configuration, sendOperationIdentifiers: false)\n\n var request = URLRequest(url: webSocketURL)\n\n request.setValue(\"<my_key>\", forHTTPHeaderField: \"X-Hasura-Access-Key\")\n\n request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n\n let webSocketTransport = WebSocketTransport(request: request, sendOperationIdentifiers: false, connectingPayload: nil)\n\n let splitTransport = SplitNetworkTransport(httpNetworkTransport: httpTransport, webSocketNetworkTransport: webSocketTransport)\n\n //Initalize the APolloClient with that URL.\n return ApolloClient(networkTransport: splitTransport)\n }\n```\n\n```text\nURLRequest\n```\n\n```text\nlet connectingPayload = [\"authToken\": accessToken]\nlet urlRequest = URLRequest(url: baseURL)\nlet webSocketTransport = WebSocketTransport(request: urlRequest, sendOperationIdentifiers: false, connectingPayload: connectingPayload)\n\nlet apollo = ApolloClient(networkTransport: webSocketTransport)\n```\n\n========================================\n\nComments:\n- from where I get wsEndpointURL? and what is the next step I have to do to update UI?\n- can you help me, please","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":227,"estimatedTokens":1732}}625{"id":"stack-49147693","source":"stackoverflow","questionId":49147693,"title":"GraphQL - How to distinguish Public from Private fields?","tags":["node.js","graphql","access-control","graphql-js","role-based-access-control"],"text":"Title: GraphQL - How to distinguish Public from Private fields?\nTags: node.js, graphql, access-control, graphql-js, role-based-access-control\nSource: Stack Overflow\n\nQuestion:\n**Context**\n\nI have a GraphQL API and a NodeJS & Angular application with a MongoDB database that holds users. For each user, there is a public page with public information like `id` and `username`. When a user is logged in, there is a private profile page with extended information like an `email`.\n\nJust for context, I'm using jsonwebtoken with accesscontrol to authenticate and authorize a user. The information is stored on the Context of every GraphQL resolve function, so whatever is needed to identify a logged in user is available.\n\nI have a GraphQL query that retrieves a public user like so:\n\n```\nquery getUserById($id: ID!) {\n getUserById(id: $id) {\n id,\n username\n }\n}\n```\n\nI am trying to think of the proper implementation to retrieve either a public or a private user. Since GraphQL is strong typed, I'm having some trouble coming up with a proper solution.\n\n**Question**\n\nHow do I implement the distinction between a public and a private user?\n\n**Considerations** \n\n**1. Separate query**\n\nSo one of the options is to have a seperate query for both public and private fields:\n\n*public query* \n\n```\nquery getUserById($id: ID!) {\n getUserById(id: $id) {\n id,\n username\n }\n}\n```\n\n*private query*\n\n```\nquery getMe {\n getMe {\n id,\n username,\n email\n }\n}\n```\n\n**2. Using GraphQL Interfaces**\n\nI came across this Medium article that explains how GraphQL Interfaces are used to return different Types based on a `resolveType` function. So I would go something like so:\n\n```\nquery getUser($id: ID!) {\n getUser(id: $id) {\n ... on UserPrivate {\n id,\n username\n }\n ... on UserPublic {\n id,\n username,\n email\n }\n }\n}\n```\n\nI have not came across a proper solution and I'm unsure about either of the consideration I have so far.\n\nAny help is much appreciated!\n\n========================================\n\nCode:\n```text\nquery getUserById($id: ID!) {\n getUserById(id: $id) {\n id,\n username\n }\n}\n```\n\n```text\nquery getUserById($id: ID!) {\n getUserById(id: $id) {\n id,\n username\n }\n}\n```\n\n```text\nquery getMe {\n getMe {\n id,\n username,\n email\n }\n}\n```\n\n```text\nquery getUser($id: ID!) {\n getUser(id: $id) {\n ... on UserPrivate {\n id,\n username\n }\n ... on UserPublic {\n id,\n username,\n email\n }\n }\n}\n```\n\n```text\nid\n```\n\n```text\nusername\n```\n\n```text\nemail\n```\n\n```text\nresolveType\n```\n\n```text\ntype Post {\n id: ID!\n title: String!\n content: String!\n author: User!\n}\n```\n\n```text\nquery getUser($id: ID!) {\n getUser(id: $id) {\n id\n username\n\n # if you need a private field you can branch off here\n ... on UserPrivate {\n email\n }\n }\n}\n```\n\n```text\ngetUserById\n```\n\n```text\ngetMe\n```\n\n```text\nAddress\n```\n\n========================================\n\nComments:\n- Thank you, this helps a lot :)","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":183,"estimatedTokens":742}}626{"id":"stack-33210406","source":"stackoverflow","questionId":33210406,"title":"graphQL - type must be Output Type","tags":["node.js","mongoose","graphql","graphql-js"],"text":"Title: graphQL - type must be Output Type\nTags: node.js, mongoose, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am trying to set-up a graphQL route using `graffiti` with express and mongoose.\n\nHowever I get the following error :\n\n```\nError: myColl.myField field type must be Output Type but got: undefined.\n at invariant (/Users/nha/.../node_modules/graphql/jsutils/invariant.js:20:11)\n at /Users/nha/.../node_modules/graphql/type/definition.js:299:39\n```\n\nIn the mongoose schema, the type is : `type : Schema.Types.ObjectId`. Should it be changed for something else ?\n\nI should note that the versions are :\n\n```\n\"@risingstack/graffiti\": \"^1.0.2\"\n\"@risingstack/graffiti-mongoose\": \"^3.1.1\"\n\"mongoose\": \"~3.6.20\"\n```\n\n========================================\n\nTop Answer:\nThe error \n\n```\nError: ... field type must be Output Type but got: undefined.\n```\n\nmean, you have a problem with GraphQLFieldConfig.\n\nGraphQLFieldConfig need the type-field. If this field is missing or type-ref is bad (undefined etc.) this error appear.\n\n```\nclass GraphQLObjectType {\n constructor(config: GraphQLObjectTypeConfig)\n}\n\ntype GraphQLObjectTypeConfig = {\n name: string;\n interfaces?: GraphQLInterfacesThunk | Array;\n fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap;\n isTypeOf?: (value: any, info?: GraphQLResolveInfo) => boolean;\n description?: ?string\n}\n\ntype GraphQLInterfacesThunk = () => Array;\n\ntype GraphQLFieldConfigMapThunk = () => GraphQLFieldConfigMap;\n\n...\n\ntype GraphQLFieldConfig = {\n type: GraphQLOutputType;\n args?: GraphQLFieldConfigArgumentMap;\n resolve?: GraphQLFieldResolveFn;\n deprecationReason?: string;\n description?: ?string;\n}\n```\n\nhttp://graphql.org/graphql-js/type/#graphqlobjecttyp\n\n========================================\n\nCode:\n```text\nError: myColl.myField field type must be Output Type but got: undefined.\n at invariant (/Users/nha/.../node_modules/graphql/jsutils/invariant.js:20:11)\n at /Users/nha/.../node_modules/graphql/type/definition.js:299:39\n```\n\n```text\n\"@risingstack/graffiti\": \"^1.0.2\"\n\"@risingstack/graffiti-mongoose\": \"^3.1.1\"\n\"mongoose\": \"~3.6.20\"\n```\n\n```text\ngraffiti\n```\n\n```text\ntype : Schema.Types.ObjectId\n```\n\n```text\nmyField : {\n type : Schema.Types.ObjectId,\n ref : 'myRef'\n}\n```\n\n```text\n'myRef'\n```\n\n```text\nError: ... field type must be Output Type but got: undefined.\n```\n\n```text\nclass GraphQLObjectType {\n constructor(config: GraphQLObjectTypeConfig)\n}\n\ntype GraphQLObjectTypeConfig = {\n name: string;\n interfaces?: GraphQLInterfacesThunk | Array<GraphQLInterfaceType>;\n fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap;\n isTypeOf?: (value: any, info?: GraphQLResolveInfo) => boolean;\n description?: ?string\n}\n\ntype GraphQLInterfacesThunk = () => Array<GraphQLInterfaceType>;\n\ntype GraphQLFieldConfigMapThunk = () => GraphQLFieldConfigMap;\n\n...\n\ntype GraphQLFieldConfig = {\n type: GraphQLOutputType;\n args?: GraphQLFieldConfigArgumentMap;\n resolve?: GraphQLFieldResolveFn;\n deprecationReason?: string;\n description?: ?string;\n}\n```\n\n========================================\n\nComments:\n- What's the code which throws the error?","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":138,"estimatedTokens":781}}627{"id":"stack-64157794","source":"stackoverflow","questionId":64157794,"title":"Apollo Server: How to access 'context' outside of resolvers in Dataloader from REST API Datasource","tags":["javascript","graphql","apollo","apollo-server","dataloader"],"text":"Title: Apollo Server: How to access 'context' outside of resolvers in Dataloader from REST API Datasource\nTags: javascript, graphql, apollo, apollo-server, dataloader\nSource: Stack Overflow\n\nQuestion:\nhopefully someone can help me with this little problem, I just cannot figure it out right now.\n\n**Problem Statement:**\n\nI want to access 'context' for the sake of authentication in my `DataLoader`. This `DataLoader`is defined in a seperate path `/loaders`. In my `resolvers.js` file I can access my context nicely with `dataSources.userAPI.getAllUsers()`.\nBut how to access it anywhere else in my serverside application, like f.e. in my `/loaders` folder?\nI just cant get it how to get access to my context object to then pass the token to the `DataLoader` to then load the data from my API and then pass this data to my `resolvers.js` file.\nEvery help is highly appreciated, I don't know how to solve this simple thing .. Thanks!\n\n**Here comes the code:**\n\n**index.js**\n\n```\nconst express = require('express');\nconst connectDB = require('./config/db');\nconst path = require('path');\nvar app = express();\nconst cors = require('cors')\nconst axios = require('axios')\n\n// apollo graphql\nconst { ApolloServer } = require('apollo-server-express');\nconst DataLoader = require('dataloader')\nconst { userDataLoader } = require('./loaders/index')\n\n// Connect Database\nconnectDB();\n\n// gql import\nconst typeDefs = require('./schema');\nconst resolvers = require('./resolvers')\n\n// apis\nconst UserAPI = require('./datasources/user')\n\n// datasources\nconst dataSources = () => ({\n userAPI: new UserAPI(),\n});\n\n// context\nconst context = ({ req, res }) => ({\n\n token: req.headers.authorization || null,\n loaders: {\n userLoader: userDataLoader,\n },\n res\n})\n\n// init server\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n dataSources,\n context\n});\n\n// middleware\napp.use(express.json());\n\n// cors\nvar corsOptions = {\n credentials: true\n}\napp.use(cors(corsOptions))\n\n// serve middleware\nserver.applyMiddleware({\n app\n});\n\n// run server\napp.listen({ port: 4000 }, () =>\n console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)\n);\n\nmodule.exports = {\n dataSources,\n context,\n typeDefs,\n resolvers,\n loaders,\n ApolloServer,\n UserAPI,\n server,\n};\n```\n\n**loaders/index.js**\n\n```\nconst userDataLoader = require('./user')\n\nmodule.exports = {\n userDataLoader\n}\n```\n\n**loaders/user.js**\n\n```\nconst UserAPI = require('../datasources/users')\n// init loader\nconst userDataLoader = new DataLoader(keys => batchUser(keys))\n\n// batch\nconst batchUsers = async (keys) => {\n\n // this part is not working!\n // How to access the UserAPI methods in my DataLoader?\n // Or lets say: How to access context from here,\n // so I can add auth for the server I am requesting data from?\n\n const userAPI = new UserAPI()\n const users = userAPI.getAllUsers()\n .then(res => {\n return res.data\n })\n\n return keys.map(userId => users.find(user=> user._id === userId))\n}\n\nmodule.exports = userDataLoader\n```\n\n**resolvers.js**\n\n```\n// here is just my api call to get the data from my\n// dataloader with userLoader.load() and this works perfectly\n// if I just make API calls with axios in my loaders/user\n// here just a little snippet from the resolver file\n\n....\nusers: async (parent, args, { loaders }) => {\n const { userLoader } = loaders\n if (!parent.users) {\n return null;\n }\n return await userLoader.load(parent.user)\n },\n....\n```\n\n**datasources/user.js**\n\n```\nconst { RESTDataSource } = require('apollo-datasource-rest');\n\nclass UserAPI extends RESTDataSource {\n constructor() {\n super()\n this.baseURL = 'http://mybaseurl.com/api'\n }\n\n willSendRequest(request) {\n request.headers.set('Authorization',\n this.context.token\n );\n }\n\n async getUserById(id) {\n return this.get(`/users/${id}`)\n }\n\n async getAllUsers() {\n const data = await this.get('/users');\n return data;\n }\n}\n\nmodule.exports = UserAPI;\n```\n\n========================================\n\nCode:\n```text\nconst express = require('express');\nconst connectDB = require('./config/db');\nconst path = require('path');\nvar app = express();\nconst cors = require('cors')\nconst axios = require('axios')\n\n// apollo graphql\nconst { ApolloServer } = require('apollo-server-express');\nconst DataLoader = require('dataloader')\nconst { userDataLoader } = require('./loaders/index')\n\n// Connect Database\nconnectDB();\n\n// gql import\nconst typeDefs = require('./schema');\nconst resolvers = require('./resolvers')\n\n// apis\nconst UserAPI = require('./datasources/user')\n\n\n// datasources\nconst dataSources = () => ({\n userAPI: new UserAPI(),\n});\n\n// context\nconst context = ({ req, res }) => ({\n\n token: req.headers.authorization || null,\n loaders: {\n userLoader: userDataLoader,\n },\n res\n})\n\n\n// init server\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n dataSources,\n context\n});\n\n// middleware\napp.use(express.json());\n\n\n// cors\nvar corsOptions = {\n credentials: true\n}\napp.use(cors(corsOptions))\n\n\n// serve middleware\nserver.applyMiddleware({\n app\n});\n\n\n// run server\napp.listen({ port: 4000 }, () =>\n console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)\n);\n\nmodule.exports = {\n dataSources,\n context,\n typeDefs,\n resolvers,\n loaders,\n ApolloServer,\n UserAPI,\n server,\n};\n```\n\n```text\nconst userDataLoader = require('./user')\n\nmodule.exports = {\n userDataLoader\n}\n```\n\n```text\nconst UserAPI = require('../datasources/users')\n// init loader\nconst userDataLoader = new DataLoader(keys => batchUser(keys))\n\n// batch\nconst batchUsers = async (keys) => {\n\n // this part is not working!\n // How to access the UserAPI methods in my DataLoader?\n // Or lets say: How to access context from here,\n // so I can add auth for the server I am requesting data from?\n\n const userAPI = new UserAPI()\n const users = userAPI.getAllUsers()\n .then(res => {\n return res.data\n })\n\n\n return keys.map(userId => users.find(user=> user._id === userId))\n}\n\nmodule.exports = userDataLoader\n```\n\n```text\n// here is just my api call to get the data from my\n// dataloader with userLoader.load() and this works perfectly\n// if I just make API calls with axios in my loaders/user\n// here just a little snippet from the resolver file\n\n....\nusers: async (parent, args, { loaders }) => {\n const { userLoader } = loaders\n if (!parent.users) {\n return null;\n }\n return await userLoader.load(parent.user)\n },\n....\n```\n\n```text\nconst { RESTDataSource } = require('apollo-datasource-rest');\n\nclass UserAPI extends RESTDataSource {\n constructor() {\n super()\n this.baseURL = 'http://mybaseurl.com/api'\n }\n\n\n willSendRequest(request) {\n request.headers.set('Authorization',\n this.context.token\n );\n }\n\n async getUserById(id) {\n return this.get(`/users/${id}`)\n }\n\n async getAllUsers() {\n const data = await this.get('/users');\n return data;\n }\n}\n\nmodule.exports = UserAPI;\n```\n\n```text\nDataLoader\n```\n\n```text\nDataLoader\n```\n\n```text\n/loaders\n```\n\n```text\nresolvers.js\n```\n\n```text\ndataSources.userAPI.getAllUsers()\n```\n\n```text\n/loaders\n```\n\n```text\nDataLoader\n```\n\n```text\nresolvers.js\n```\n\n```js\nmodule.exports.createDataloaders = function createDataLoaders(options) {\n const batchUsers = ids => {\n const users = await fetch('/users/', { headers: { Authorization: options.auth } });\n // ...\n }\n\n return {\n userLoader: new Dataloader(batchUsers);\n };\n}\n\n// now in index.js\n// context\nconst context = ({ req, res }) => ({\n token: req.headers.authorization || null,\n loaders: createDataloaders({ auth: req.headers.authorization || null }),\n res\n})\n\n\n// init server\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n context\n});\n```\n\n```text\nconst { RESTDataSource } = require('apollo-datasource-rest');\n\nclass UserAPI extends RESTDataSource {\n constructor() {\n super()\n this.baseURL = 'http://mybaseurl.com/api'\n this.dataloader = new Dataloader(ids => {\n // use this.get here\n });\n }\n\n\n willSendRequest(request) {\n request.headers.set('Authorization',\n this.context.token\n );\n }\n\n async getUserById(id) {\n return this.dataloader.load(id);\n }\n\n async getAllUsers() {\n const data = await this.get('/users');\n return data;\n }\n}\n\nmodule.exports = UserAPI;\n```\n\n========================================\n\nComments:\n- this worked - many thanks! I rearranged my dataloaders now in a separate folder and import them in my index.js","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":443,"estimatedTokens":2158}}628{"id":"stack-48482817","source":"stackoverflow","questionId":48482817,"title":"In my query, could I use the result of a parameter to get more info in that query?","tags":["graphql","graphql-js"],"text":"Title: In my query, could I use the result of a parameter to get more info in that query?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nForgive my terribly-worded question but here's some code to explain what I'm trying to do (`slug` and `value` are provided outside this query):\n\n```\nconst query = `{\n post(slug: \"${slug}\") {\n content\n createdAt\n id I *just* got started with GraphQL and I'm loving the fact that I can query multiple databases in one go. It'd be great if I could also perform some \"queryception\" but I'm not sure if this is possible.\n\n========================================\n\nCode:\n```text\nconst query = `{\n post(slug: \"${slug}\") {\n content\n createdAt\n id <--- I want this id for my reply query\n slug\n }\n\n reply(replyTo: \"id\") { <--- The second query in question\n content\n createdAt\n id\n slug\n }\n\n user(id: \"${value}\") {\n username\n }\n}`;\n```\n\n```text\nslug\n```\n\n```text\nvalue\n```\n\n```text\npost\n```\n\n```text\nPost\n```\n\n```text\ncontent\n```\n\n```text\ncreatedAt\n```\n\n```text\ncontent\n```\n\n```text\npost\n```\n\n```text\nreply\n```\n\n```text\nuser\n```\n\n```text\npost\n```\n\n```text\nreply\n```\n\n```text\npost\n```\n\n```text\nreply\n```\n\n```text\nreplies\n```\n\n========================================\n\nComments:\n- Ah okay, thanks for your insight! I thought about your last point but I didn't want to run the risk of having enormous objects. Plus, I'm enabling editing so I'd theoretically have to update state across several objects. Looks like two queries is the way to go.\n- For what it's worth, it's best practice to use variables instead of directly injecting inputs into your query. And if you're tying your queries to component state, Apollo handles that kind of thing very cleanly: apollographql.com/docs/react","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":104,"estimatedTokens":439}}629{"id":"stack-59746258","source":"stackoverflow","questionId":59746258,"title":"How to use graphql to get data from Cloud Firestore from Firebase using flutter?","tags":["firebase","flutter","google-cloud-firestore","graphql","google-cloud-functions"],"text":"Title: How to use graphql to get data from Cloud Firestore from Firebase using flutter?\nTags: firebase, flutter, google-cloud-firestore, graphql, google-cloud-functions\nSource: Stack Overflow\n\nQuestion:\nIs it possible to query results from Firestore firebase in flutter using graphql.\nI have to narrow down some results and have to bring them to the frontend.\nPlease help me through this.\nThanks in advance","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":9,"estimatedTokens":102}}630{"id":"stack-49981885","source":"stackoverflow","questionId":49981885,"title":"Filtering results in GraphQL using PostGraphile","tags":["graphql","postgraphql","postgraphile"],"text":"Title: Filtering results in GraphQL using PostGraphile\nTags: graphql, postgraphql, postgraphile\nSource: Stack Overflow\n\nQuestion:\nI'm trying to wrap my head around GraphQL and I though using PostGraphile to easily and quickly map my PostgreSQL database and expose it using GraphQL. However, I've been stuck a long time on some things that in simple SQL would be a matter of minutes to do -\n\nFirst, I'm trying to get all records from my database after a defined date, couldn't do this so far, and I end up getting *all* records which is highly inefficient.\n\nSecond, I'd like to get all records which a nullable field in them isn't null (meaning, only if it has something in it, it will show up in the GraphQL results)\n\nIf anyone could shed some light on how to do this, or point me to a good tutorial that explains in a simple way how to write custom filtering functions that would be great.\n\n========================================\n\nTop Answer:\nTo extend @Benjie's answer, first install the plugin:\n\n```\nyarn add postgraphile-plugin-connection-filter\n```\n\nThen you can run postgraphile from the console:\n\n```\npostgraphile --append-plugins --connection \n```\n\ne.g. on Linux:\n\n```\npostgraphile --append-plugins `pwd`/node_modules/postgraphile-plugin-connection-filter/index.js --connection mydb\n```\n\nor on Windows:\n\n```\npostgraphile --append-plugins /users/bburns/desktop/moveto/site/node_modules/postgraphile-plugin-connection-filter/index.js --connection mydb\n```\n\nThen you can try the new filters using the graphiql endpoint at http://localhost:5000/graphiql. You can run queries like \n\n```\n{\n allProperties(first: 5, filter: {\n appraisedValue: {lessThan: 100000}\n }) {\n nodes {\n propertyId\n appraisedValue\n acres\n }\n }\n}\n```\n\nNote: The documentation at https://www.graphile.org/postgraphile/extending/ says you can just give the name of the npm package, but that doesn't seem to work on Windows.\n\n========================================\n\nCode:\n```text\nyarn add postgraphile-plugin-connection-filter\n```\n\n```text\npostgraphile --append-plugins <plugin path> --connection <dbname>\n```\n\n```text\npostgraphile --append-plugins `pwd`/node_modules/postgraphile-plugin-connection-filter/index.js --connection mydb\n```\n\n```text\npostgraphile --append-plugins /users/bburns/desktop/moveto/site/node_modules/postgraphile-plugin-connection-filter/index.js --connection mydb\n```\n\n```text\n{\n allProperties(first: 5, filter: {\n appraisedValue: {lessThan: 100000}\n }) {\n nodes {\n propertyId\n appraisedValue\n acres\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks @Benjie! This is exactly what I did eventually, worked like a charm!\n- Thanks for expanding on my answer π You don't need to use the full path if you've installed from npm, you can just use `--append-plugins postgraphile-plugin-connection-filter`; the full-path stuff is only necessary if you're using a local module (because we use `require(...)` to load it).\n- Thanks @Benjie, and for your work on postgraphile - it's a great library!","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":97,"estimatedTokens":760}}631{"id":"stack-49061701","source":"stackoverflow","questionId":49061701,"title":"Upload images with apollo-upload-client in React Native","tags":["react-native","graphql","apollo","prisma"],"text":"Title: Upload images with apollo-upload-client in React Native\nTags: react-native, graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying out Prisma and React Native right now. Currently I'm trying to upload images to my db with the package _apollo-upload-client (https://github.com/jaydenseric/apollo-upload-client). But it's not going so well. \n\nCurrently I can select an image with the `ImagePicker` from Expo. And then I'm trying to do my mutation with the Apollo Client:\n\n```\nawait this.props.mutate({\n variables: {\n name,\n description,\n price,\n image,\n },\n});\n```\n\nBut I get the following error:\n\n```\nNetwork error: JSON Parse error: Unexpected identifier \"POST\"\n- node_modules/apollo-client/bundle.umd.js:76:32 in ApolloError\n- node_modules/apollo-client/bundle.umd.js:797:43 in error\n```\n\nAnd I believe it's from these lines of code:\n\n```\nconst image = new ReactNativeFile({\n uri: imageUrl,\n type: 'image/png',\n name: 'i-am-a-name',\n});\n```\n\nWhich is almost identical from the their example, https://github.com/jaydenseric/apollo-upload-client#react-native.\n\n`imageUrl` is from my state. And when I console.log `image` I get the following:\n\n```\nReactNativeFile {\n \"name\": \"i-am-a-name\",\n \"type\": \"image/png\",\n \"uri\": \"file:///Users/martinnord/Library/Developer/CoreSimulator/Devices/4C297288-A876-4159-9CD7-41D75303D07F/data/Containers/Data/Application/8E899238-DE52-47BF-99E2-583717740E40/Library/Caches/ExponentExperienceData/%2540anonymous%252Fecommerce-app-e5eacce4-b22c-4ab9-9151-55cd82ba58bf/ImagePicker/771798A4-84F1-4130-AB37-9F382546AE47.png\",\n}\n```\n\nSo something is popping out. But I can't get any further and I'm hoping I could get some tips from someone. \n\nI also didn't include any code from the backend since I believe the problem lays on the frontend. *But* if anyone would like to take a look at the backend I can update the question, or you could take a look here: https://github.com/Martinnord/Ecommerce-server/tree/image_uploads.\n\nThanks a lot for reading! Cheers.\n\n### Update\n\nAfter someone asked after the logic in the server I have decided to past it below:\n\n*Product.ts*\n\n```\n// import shortid from 'shortid'\nimport { createWriteStream } from 'fs'\n\nimport { getUserId, Context } from '../../utils'\n\nconst storeUpload = async ({ stream, filename }): Promise => {\n // const path = `images/${shortid.generate()}`\n const path = `images/test`\n\n return new Promise((resolve, reject) =>\n stream\n .pipe(createWriteStream(path))\n .on('finish', () => resolve({ path }))\n .on('error', reject),\n )\n }\n\nconst processUpload = async upload => {\n const { stream, filename, mimetype, encoding } = await upload\n const { path } = await storeUpload({ stream, filename })\n return path\n}\n\nexport const product = {\n async createProduct(parent, { name, description, price, image }, ctx: Context, info) {\n // const userId = getUserId(ctx)\n const userId = 1;\n console.log(image);\n const imageUrl = await processUpload(image);\n console.log(imageUrl);\n return ctx.db.mutation.createProduct(\n {\n data: {\n name,\n description,\n price,\n imageUrl,\n seller: {\n connect: { id: userId },\n },\n },\n },\n info\n )\n },\n}\n```\n\n========================================\n\nTop Answer:\nCrawling through your code, I have found this repository, which must be the front-end code if I am not mistaken?\n\nAs you've mentioned, **apollo-upload-server** requires some additional set-up and same goes for the front-end part of your project. You can find more about it here.\n\nAs far as I know, the problematic part of your code must be the initialisation of the Apollo Client. From my observation, you've put everything Apollo requires inside of `src/index` folder, but haven't included `Apollo Upload Client` itself. \n\nI have created a gist from one of my projects which initialises Apollo Upload Client alongside some other things, but I think you'll find yourself out. \n\nhttps://gist.github.com/maticzav/86892448682f40e0bc9fc4d4a3acd93a\n\nHope this helps you! π\n\n========================================\n\nCode:\n```text\nawait this.props.mutate({\n variables: {\n name,\n description,\n price,\n image,\n },\n});\n```\n\n```text\nNetwork error: JSON Parse error: Unexpected identifier \"POST\"\n- node_modules/apollo-client/bundle.umd.js:76:32 in ApolloError\n- node_modules/apollo-client/bundle.umd.js:797:43 in error\n```\n\n```text\nconst image = new ReactNativeFile({\n uri: imageUrl,\n type: 'image/png',\n name: 'i-am-a-name',\n});\n```\n\n```text\nReactNativeFile {\n \"name\": \"i-am-a-name\",\n \"type\": \"image/png\",\n \"uri\": \"file:///Users/martinnord/Library/Developer/CoreSimulator/Devices/4C297288-A876-4159-9CD7-41D75303D07F/data/Containers/Data/Application/8E899238-DE52-47BF-99E2-583717740E40/Library/Caches/ExponentExperienceData/%2540anonymous%252Fecommerce-app-e5eacce4-b22c-4ab9-9151-55cd82ba58bf/ImagePicker/771798A4-84F1-4130-AB37-9F382546AE47.png\",\n}\n```\n\n```text\n// import shortid from 'shortid'\nimport { createWriteStream } from 'fs'\n\nimport { getUserId, Context } from '../../utils'\n\nconst storeUpload = async ({ stream, filename }): Promise<any> => {\n // const path = `images/${shortid.generate()}`\n const path = `images/test`\n\n return new Promise((resolve, reject) =>\n stream\n .pipe(createWriteStream(path))\n .on('finish', () => resolve({ path }))\n .on('error', reject),\n )\n }\n\nconst processUpload = async upload => {\n const { stream, filename, mimetype, encoding } = await upload\n const { path } = await storeUpload({ stream, filename })\n return path\n}\n\nexport const product = {\n async createProduct(parent, { name, description, price, image }, ctx: Context, info) {\n // const userId = getUserId(ctx)\n const userId = 1;\n console.log(image);\n const imageUrl = await processUpload(image);\n console.log(imageUrl);\n return ctx.db.mutation.createProduct(\n {\n data: {\n name,\n description,\n price,\n imageUrl,\n seller: {\n connect: { id: userId },\n },\n },\n },\n info\n )\n },\n}\n```\n\n```text\nImagePicker\n```\n\n```text\nimageUrl\n```\n\n```text\nimage\n```\n\n```text\nError: Cannot use GraphQLNonNull \"User!\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.\n```\n\n```text\nsrc/index\n```\n\n```text\nApollo Upload Client\n```\n\n========================================\n\nComments:\n- Where in your server is the file uploading logic? I can't find it.\n- @marktani I have updated the question. Thanks for asking.\n- Also, most of the code behind the server side is from `graphql-yogas` example. github.com/graphcool/graphql-yoga/blob/master/examples/…\n- Thanks for your reply. I will take a closer look at your code when I get home. You said that I havenβt included Apollo Upload Link itself and I wonder if you where on the correct branch. Since on the branch image_uploads Iβve included it. Here: github.com/Martinnord/Ecommerce-app/blob/image_uploads/src/…\n- I am sorry, yes I was on the wrong branch because I thought you only had one. I will try to look into it again - hope I can find anything more useful.\n- No worries. I appriciate that you are taking your time to help me.\n- Hi, I got stuck with this apollo-upload-server stuff. I already setup correctly the client . and it send the request to apollo-server. in the server it received the 'createReadStream' but it's only an object.. how do I wrote a file from this `createReadStream()` object ?","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":256,"estimatedTokens":1981}}632{"id":"stack-46872331","source":"stackoverflow","questionId":46872331,"title":"How to unit test express-graphql mutations?","tags":["graphql","jestjs","graphql-js","express-graphql"],"text":"Title: How to unit test express-graphql mutations?\nTags: graphql, jestjs, graphql-js, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI have an Express-GraphQL API with a query and a mutation which works in GraphiQL, unit tests of query works, but a unit test of mutation returns a 405 error.\nmy GraphQL schema is as follows:\n\n```\ntype Subject {\n type: String\n}\n\ntype Category {\n name: String\n}\n\ntype SubjectCategories {\n subject: Subject\n categories: [Category]\n}\n\ntype Query {\n subjectCategories(subjectType: String!): SubjectCategories\n}\n\ntype Mutation {\n addSubjectCategory(subjectType: String! categoryName: String!): SubjectCategories\n}\n```\n\nfor simplifying this question, the implementation of these methods just echo back: \n\n```\nechoGetSubjectCategory({subjectType}, context) {\n const subject = new Subject(subjectType);\n const category = new Category(\"blah\");\n const retval = {\n subject,\n categories: [category],\n };\n return retval;\n}\nechoMutateSubjectCategory({subjectType, categoryName}, context) {\n const subject = new Subject(subjectType);\n const category = new Category(categoryName);\n const retval = {\n subject,\n categories: [category],\n };\n return retval;\n}\n```\n\nvia Graphiql, everything works:\n\n```\nmutation {\n addSubjectCategory(subjectType: \"s1\" categoryName: \"c1\"){\n subject {\n type\n }\n categories {\n name\n }\n }\n}\n```\n\nyields\n\n```\n{\n \"data\": {\n \"addSubjectCategory\": {\n \"subject\": {\n \"type\": \"s1\"\n },\n \"categories\": [\n {\n \"name\": \"c1\"\n }\n ]\n }\n }\n}\n```\n\nand \n\n```\n{\n subjectCategories(subjectType: \"s1\"){\n subject {\n type\n }\n categories {\n name\n }\n }\n}\n```\n\nyields the same.\n\nin my API unit tests (using request from 'supertest-as-promised'), the **query returns 200**\n\n```\nconst req = request(app)\n .get('/graphql')\n .set('Content-Type', 'application/json')\n .set('Accept', 'application/json')\n .send(JSON.stringify({\n query: \"query {subjectCategories(subjectType: \\\"categorized\\\" ) { subject {type } categories {name} } }\",\n }));\nconst res = await req;\nexpect(res.statusCode).toBe(200);\n```\n\nbut this test *fails*:\n\n```\nconst req = request(app)\n .get('/graphql')\n .set('Content-Type', 'application/json')\n .set('Accept', 'application/json')\n .send(JSON.stringify({\n query: \"mutation {addSubjectCategory(subjectType: \\\"categorized\\\" categoryName: \\\"Politics\\\" ) { subject {type } categories {name} } }\",\n }));\nconst res = await req;\nexpect(res.statusCode).toBe(200);\n```\n\n**the mutation returns 405**\nthe error message is very opaque:\n\n```\nExpected value to be (using ===):\n 200\n Received:\n 405\nat Object. (test/api.test.js:171:28)\n at Generator.next ()\n at step (test/api.test.js:7:368)\n at test/api.test.js:7:528\n at \n```\n\nSo how can I form this json payload to make this unit test of express-graphql pass ?\n\n========================================\n\nCode:\n```text\ntype Subject {\n type: String\n}\n\ntype Category {\n name: String\n}\n\ntype SubjectCategories {\n subject: Subject\n categories: [Category]\n}\n\ntype Query {\n subjectCategories(subjectType: String!): SubjectCategories\n}\n\ntype Mutation {\n addSubjectCategory(subjectType: String! categoryName: String!): SubjectCategories\n}\n```\n\n```text\nechoGetSubjectCategory({subjectType}, context) {\n const subject = new Subject(subjectType);\n const category = new Category(\"blah\");\n const retval = {\n subject,\n categories: [category],\n };\n return retval;\n}\nechoMutateSubjectCategory({subjectType, categoryName}, context) {\n const subject = new Subject(subjectType);\n const category = new Category(categoryName);\n const retval = {\n subject,\n categories: [category],\n };\n return retval;\n}\n```\n\n```text\nmutation {\n addSubjectCategory(subjectType: \"s1\" categoryName: \"c1\"){\n subject {\n type\n }\n categories {\n name\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"addSubjectCategory\": {\n \"subject\": {\n \"type\": \"s1\"\n },\n \"categories\": [\n {\n \"name\": \"c1\"\n }\n ]\n }\n }\n}\n```\n\n```text\n{\n subjectCategories(subjectType: \"s1\"){\n subject {\n type\n }\n categories {\n name\n }\n }\n}\n```\n\n```text\nconst req = request(app)\n .get('/graphql')\n .set('Content-Type', 'application/json')\n .set('Accept', 'application/json')\n .send(JSON.stringify({\n query: \"query {subjectCategories(subjectType: \\\"categorized\\\" ) { subject {type } categories {name} } }\",\n }));\nconst res = await req;\nexpect(res.statusCode).toBe(200);\n```\n\n```text\nconst req = request(app)\n .get('/graphql')\n .set('Content-Type', 'application/json')\n .set('Accept', 'application/json')\n .send(JSON.stringify({\n query: \"mutation {addSubjectCategory(subjectType: \\\"categorized\\\" categoryName: \\\"Politics\\\" ) { subject {type } categories {name} } }\",\n }));\nconst res = await req;\nexpect(res.statusCode).toBe(200);\n```\n\n```text\nExpected value to be (using ===):\n 200\n Received:\n 405\nat Object.<anonymous> (test/api.test.js:171:28)\n at Generator.next (<anonymous>)\n at step (test/api.test.js:7:368)\n at test/api.test.js:7:528\n at <anonymous>\n```\n\n```text\nconst req = request(app)\n .post('/graphql')\n .set('Content-Type', 'application/json')\n .set('Accept', 'application/json')\n .send({\n query: \"mutation {addSubjectCategory(subjectType: \\\"categorized\\\" categoryName: \\\"Politics\\\" ) { subject {type } categories {name} } }\"\n });\nconst res = await req;\nexpect(res.statusCode).toBe(200);\n```\n\n```text\nGET\n```\n\n```text\nPOST\n```\n\n```text\nPOST\n```\n\n========================================\n\nComments:\n- Thank you for posting this code snippet... I had done `mutation: 'mutation....'` instead of `query: 'mutation .....'` >______<\n- You can also pass a string literal for the query property so you don't have to escape any of the quotation marks (inverted commas).\n- You're life saver!","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":306,"estimatedTokens":1451}}633{"id":"stack-32226857","source":"stackoverflow","questionId":32226857,"title":"How does Relay / GraphQL 'resolve' works?","tags":["javascript","reactjs","graphql","relayjs","graphql-js"],"text":"Title: How does Relay / GraphQL 'resolve' works?\nTags: javascript, reactjs, graphql, relayjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am trying out Relay and GraphQL. When I am doing the schema I am doing this:\n\n```\nlet articleQLO = new GraphQLObjectType({\n name: 'Article',\n description: 'An article',\n fields: () => ({\n _id: globalIdField('Article'),\n title: {\n type: GraphQLString,\n description: 'The title of the article',\n resolve: (article) => article.getTitle(),\n },\n author: {\n type: userConnection,\n description: 'The author of the article',\n resolve: (article) => article.getAuthor(),\n },\n }),\n interfaces: [nodeInterface],\n})\n```\n\nSo, when I ask for an article like this:\n\n```\n{\n article(id: 1) {\n id,\n title,\n author\n }\n}\n```\n\nWill it do 3 queries to the database? I mean, each field has a resolve method (`getTitle`, `getAuthor`, etc.) which does a request to the database. Am I doing this wrong?\n\nThis is an example of `getAuthor` (I use mongoose):\n\n```\narticleSchema.methods.getAuthor = function(id){\n let article = this.model('Article').findOne({_id: id})\n return article.author\n}\n```\n\n========================================\n\nCode:\n```text\nlet articleQLO = new GraphQLObjectType({\n name: 'Article',\n description: 'An article',\n fields: () => ({\n _id: globalIdField('Article'),\n title: {\n type: GraphQLString,\n description: 'The title of the article',\n resolve: (article) => article.getTitle(),\n },\n author: {\n type: userConnection,\n description: 'The author of the article',\n resolve: (article) => article.getAuthor(),\n },\n }),\n interfaces: [nodeInterface],\n})\n```\n\n```text\n{\n article(id: 1) {\n id,\n title,\n author\n }\n}\n```\n\n```text\narticleSchema.methods.getAuthor = function(id){\n let article = this.model('Article').findOne({_id: id})\n return article.author\n}\n```\n\n```text\ngetTitle\n```\n\n```text\ngetAuthor\n```\n\n```text\ngetAuthor\n```\n\n```text\nlet articleQLO = new GraphQLObjectType({\n name: 'Article',\n description: 'An article',\n fields: () => ({\n _id: globalIdField('Article'),\n title: {\n type: GraphQLString,\n description: 'The title of the article',\n resolve: (article) => article.title,\n },\n author: {\n type: userConnection,\n description: 'The author of the article',\n resolve: (article) => article.author,\n },\n }),\n interfaces: [nodeInterface],\n})\n```\n\n```text\narticleSchema.methods.getAuthor = function() {\n return article.author;\n}\n```\n\n```text\narticleSchema.methods.getAuthor = function(callback) {\n return this.model('Author').find({ _id: this.author_id }, cb);\n}\n```\n\n```text\nresolve\n```\n\n```text\narticle\n```\n\n```text\nSchema.methods\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":148,"estimatedTokens":672}}634{"id":"stack-41206123","source":"stackoverflow","questionId":41206123,"title":"Authorization in GraphQL servers","tags":["authorization","graphql","relayjs","graphql-js"],"text":"Title: Authorization in GraphQL servers\nTags: authorization, graphql, relayjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nHow to handle Authorization in GraphQL servers?\n\nShall I pass the JWT token in the Authentication header of every requests and check for the authorized user after `resolve()` and check for the role of user on every `query` and `mutation`\n\n========================================\n\nCode:\n```text\nresolve()\n```\n\n```text\nquery\n```\n\n```text\nmutation\n```\n\n```text\nquery {\n allAnswers(filter:{\n authorId: $userId,\n id: $nodeId\n }) {\n id\n }\n}\n```\n\n```text\nUser\n```\n\n```text\nEVERYONE\n```\n\n```text\nAUTHENTICATED\n```\n\n```text\nMODERATOR\n```\n\n```text\nEVERYONE\n```\n\n```text\nallQuestions\n```\n\n```text\nallAnswers\n```\n\n```text\ntext\n```\n\n```text\nAUTHENTICATED\n```\n\n```text\nMODERATOR\n```\n\n```text\nMODERATOR\n```\n\n```text\nallQuestions\n```\n\n```text\nMODERATOR\n```\n\n```text\ndeleteQuestion\n```\n\n```text\nnull\n```\n\n```text\n$userId\n```\n\n```text\n$nodeId\n```\n\n```text\nfilter\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":106,"estimatedTokens":248}}635{"id":"stack-50007271","source":"stackoverflow","questionId":50007271,"title":"How display a Contentul image with Gatsby","tags":["reactjs","graphql","gatsby"],"text":"Title: How display a Contentul image with Gatsby\nTags: reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI'm trying to display a single image which is stored on Contentful. This is my query to get the url and the title of the image : \n\n```\ncontentfulAsset(title: {eq: \"kevin\"}) {\n file {\n url\n fileName\n }\n}\n```\n\nI use the **gatsby-image** plugin but there is no explanation to know how to use this query to display a single image. \n\nThey only explain the situation with multiples images and a node...\n\n```\n{node.image[0].resolutions.src && (\n \n)}\n```\n\n========================================\n\nCode:\n```text\ncontentfulAsset(title: {eq: \"kevin\"}) {\n file {\n url\n fileName\n }\n}\n```\n\n```text\n{node.image[0].resolutions.src && (\n <Img\n style={{ margin: 0 }}\n resolutions={node.image[0].resolutions}\n />\n)}\n```\n\n```text\ncontentfulAsset(title: { eq: \"kevin\"}}) {\n title\n file {\n url\n }\n}\n```\n\n```text\n// ...\nconst MyComponent = props => {\n const myImage = props.data.contentfulAsset;\n\n return <img src={myImage.file.url} alt={myImage.title} />\n}\n```\n\n```text\ncontentfulAsset(title: { eq: \"kevin\"}}) {\n title\n sizes(quality: 100) {\n ...GatsbyContentfulSizes_withWebp\n }\n}\n```\n\n```text\nconst MyComponent = props => {\n const myImage = props.data.contentfulAsset;\n\n return <Img sizes={myImage.sizes} alt={myImage.title} />\n}\n```\n\n```text\nmyImage\n```\n\n```text\nAsset\n```\n\n```text\n<img />\n```\n\n```text\n<img />\n```\n\n```text\ngatsby-image\n```\n\n```text\nresolutions\n```\n\n```text\nsizes\n```\n\n```text\ngatsby-source-contentful\n```\n\n```text\nWebp\n```\n\n```text\nresolutions\n```\n\n```text\nsizes\n```\n\n```text\nexamples\n```\n\n========================================\n\nComments:\n- Thanks ! I'm having a issue : screenshot **My query :** ` contentfulAsset(title: {eq: \"kevin\"}) { file { url fileName } } ` **My component** ` const ImageKevin = props => { const Image = props.data.contentfulAsset.file; return } `\n- It looks like `data` is `undefined`. It means that something is wrong with your graphql query. Could you please your code on a fiddle or codepen ?\n- I found 2 issues in your code: 1) You don't pass any props to your `ImageKevin` props. The graphQL query will only pass props to your exported page Component. 2) you graphql query of the image must contains the `sizes` child node. Here is my modification suggestion Can you give it a try ?\n- I'm tring to display a second image, but it's seems I can only use the contentfulAsset query juste one time... screenshot My code : codepen\n- You can but you have to rename your node query. `imageKevin: contentfulAsset(title: { eq: \"kevin}) { ### }` and then you use it with `data.imageKevin`\n- Actually, I don't know where I use the `data.imageKevin` inside `const ImageKevin = ({ image }) => { return }`\n- Use it outside your `ImageKevin` Component. When you pass the image props to it actually.","metadata":{"transformedAt":"2026-08-18T18:32:36.072Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":140,"estimatedTokens":716}}636{"id":"stack-64400452","source":"stackoverflow","questionId":64400452,"title":"Add featuredImage in a Gatsby blog with MDX","tags":["graphql","gatsby"],"text":"Title: Add featuredImage in a Gatsby blog with MDX\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add a featured image on my Gatsby blog but can't make it work. I tried several things found here and there but I just keep having this error message : `Field \"featuredImage\" must not have a selection since type \"String\" has no subfields.`\n\nHere is my blog structure :\n\n```\nsrc\n |- images\n |- house.jpeg\n | - pages\n |- actualites\n |- house.mdx\n```\n\nMy `house.mdx` has the following frontmatter :\n\n```\n---\ntitle: House\npath: /house\ndate: 2019-01-29\nfeaturedImage: ../../images/house.jpeg\n---\n```\n\nAnd my `gatsby-plugin` looks like this :\n\n```\nplugins: [\n `gatsby-plugin-resolve-src`,\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/images`,\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/pages`,\n },\n },\n {\n resolve: `gatsby-transformer-remark`,\n options: {\n plugins: [\n {\n resolve: `gatsby-remark-images`,\n options: {\n maxWidth: 800,\n },\n },\n ],\n },\n },\n {\n resolve: `gatsby-plugin-mdx`,\n options: {\n gatsbyRemarkPlugins: [\n {\n resolve: `gatsby-remark-images`,\n options: {\n maxWidth: 1200,\n },\n },\n ],\n },\n },\n `gatsby-transformer-sharp`,\n `gatsby-plugin-sharp`,\n ],\n```\n\nI can't figure out what I'm doing wrong... The http://localhost:8000/___graphql shows me my `featuredImage` but not the subfields for the image, so I guess it doesn't understand that my field is an image.\n\nCould you please help me point what I am missing ?\n\nThank you π\n\n========================================\n\nTop Answer:\nThe issue usually comes from multiple sources:\n\n- When there are differences in the naming of the strings paths (images in your case). For example, if you are looking for: `../../images/house.jpeg` but the image is placed or named `house.jpg` (not `jpeg`). Being relative paths, I assume that the issue comes from there. Try changing it to something like `./path/to/image.jpg`\n\n- Check spelling\n\n- Check plugins order\n\n- Use GraphQL playground (`localhost:8000/___graphql`) to check the correct paths of the images by creating a specific query there.\n\nReferences/useful resources:\n\n- https://github.com/gatsbyjs/gatsby/issues/13322\n\n- https://github.com/gatsbyjs/gatsby/issues/4123\n\n- https://dev.to/stephencweiss/error-field-image-must-not-have-a-selection-since-type-string-has-no-subfields-3a76\n\n- https://spectrum.chat/gatsby-js/general/this-error-field-img-must-not-have-a-selection-since-type-string~05669aa2-8045-4875-a82b-c52e53df791e\n\n========================================\n\nCode:\n```text\nsrc\n |- images\n |- house.jpeg\n | - pages\n |- actualites\n |- house.mdx\n```\n\n```text\n---\ntitle: House\npath: /house\ndate: 2019-01-29\nfeaturedImage: ../../images/house.jpeg\n---\n```\n\n```text\nplugins: [\n `gatsby-plugin-resolve-src`,\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/images`,\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/pages`,\n },\n },\n {\n resolve: `gatsby-transformer-remark`,\n options: {\n plugins: [\n {\n resolve: `gatsby-remark-images`,\n options: {\n maxWidth: 800,\n },\n },\n ],\n },\n },\n {\n resolve: `gatsby-plugin-mdx`,\n options: {\n gatsbyRemarkPlugins: [\n {\n resolve: `gatsby-remark-images`,\n options: {\n maxWidth: 1200,\n },\n },\n ],\n },\n },\n `gatsby-transformer-sharp`,\n `gatsby-plugin-sharp`,\n ],\n```\n\n```text\nField \"featuredImage\" must not have a selection since type \"String\" has no subfields.\n```\n\n```text\nhouse.mdx\n```\n\n```text\ngatsby-plugin\n```\n\n```text\nfeaturedImage\n```\n\n```text\nallSitePage\n```\n\n```text\nallMdx\n```\n\n```text\n../../images/house.jpeg\n```\n\n```text\nhouse.jpg\n```\n\n```text\njpeg\n```\n\n```text\n./path/to/image.jpg\n```\n\n```text\nlocalhost:8000/___graphql\n```\n\n========================================\n\nComments:\n- Have you tried by adding a `name`? gatsbyjs.com/plugins/gatsby-source-filesystem\n- Yes, I tried. But it didn't changed anything so I removed it.\n- Thanks for your answer. I saw in other posts before posting here that usually the naming of the file or the path are the cause of the problems. So I checked multiple times and the name and path are correct. In the GraphQL playground, I don't have the possibility to query my field as an image. What do you mean with plugin order ? Does it have an incidence ?\n- Have you tried changing the relative paths? The `../..` to `./` or similar. The order of the plugins is also important, in your case is correct in the snippet (I assume in your project too) but it is a thing to check. In the playground, you can create another query to get the path of the image, that may be useful to check the paths.\n- Yes I tried changing the path, and also moved the `sharp` plugins to the top of the list, but I still get the same issue. I really don't know what to do, I'm stuck :/","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":225,"estimatedTokens":1272}}637{"id":"stack-36852619","source":"stackoverflow","questionId":36852619,"title":"What are the intended use cases for the resolve function's context and rootValue parameters?","tags":["graphql"],"text":"Title: What are the intended use cases for the resolve function's context and rootValue parameters?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nThe `0.5.0` release of graphql-js contains a breaking change to the `resolve` function - it now receives an additional `context` parameter.\n\nIt looks to me like `context` is intended to carry user session data. What is the use case for the `rootValue` parameter, now?\n\n========================================\n\nCode:\n```text\n0.5.0\n```\n\n```text\nresolve\n```\n\n```text\ncontext\n```\n\n```text\ncontext\n```\n\n```text\nrootValue\n```\n\n```text\ntype Mutation {\n someMutationField: Query\n}\n\ntype Query {\n someField: String\n}\n\nschema {\n query: Query\n mutation: Mutation\n}\n```\n\n========================================\n\nComments:\n- I'm also confused, but I think `context` is mainly for general auth related data, and `rootValue` is for other app specific data.\n- Since almost every app needs auth based access control, I think they decided to put it as a third argument for convenience rather than destructoring it everytime from the info arg.\n- `rootValue` is only passed to top-level resolvers whereas `context` is available in every resolver. But I'm not sure why that distinction is in place or how `rootValue` is useful anymore.","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":53,"estimatedTokens":317}}638{"id":"stack-48261057","source":"stackoverflow","questionId":48261057,"title":"Graphql - Apollo Server - Hot update schema","tags":["node.js","express","graphql","graphql-js","apollo-server"],"text":"Title: Graphql - Apollo Server - Hot update schema\nTags: node.js, express, graphql, graphql-js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am looking to hot reload my GraphQL schema on my apollo-server-express server. Anyone would have any idea about how to do that?\n\nI'm currently using schemas stitching to gather multiple API's schemas, however I do not want to have to restart my application every time one of these schema changes.\n\nI've tried to look for the express route and remove it but that dit not work, I also tried to call `graphQLExpress()` again on the same route and that did not update it. \n\nThanks for your help!\n\n========================================\n\nTop Answer:\nI managed to get it done by removing the express route and then re-creating it. But actually I discovered that because `makeRemoteExecutableSchema` is sending the introspection query at every request, you actually don't need to update your schema, it gets updated by itself. That does not imply Graphiql though.\n\n========================================\n\nCode:\n```text\ngraphQLExpress()\n```\n\n```text\nlet schema = createSchema();\napp.use('/graphql', bodyParser.json(), function(req, res, next) {\n // ensure latest schema is always passed in, we'll reload it automatically\n const graphql = graphqlExpress({ schema });\n graphql(req, res, next);\n});\n```\n\n```text\ngraphqlExpress\n```\n\n```text\nschema\n```\n\n```text\nmakeRemoteExecutableSchema\n```\n\n========================================\n\nComments:\n- Sounds good, I'm going to try that calling my schemas stitching function with an interval. ππ»\n- You're right it's working, so what I ended up doing is having another endpoint that I can call which override the schema variable by regenerating the different schemas. I also tried with an interval to have an \"auto refresh\" it works too. Thanks, that's a good solution!","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":51,"estimatedTokens":464}}639{"id":"stack-58874939","source":"stackoverflow","questionId":58874939,"title":"Can you nest fragments in GraphQL?","tags":["graphql","graphql-fragments"],"text":"Title: Can you nest fragments in GraphQL?\nTags: graphql, graphql-fragments\nSource: Stack Overflow\n\nQuestion:\nSay you have fragment B, which depends on fragment A. I wonder whether you can plug-and-play fragment B in a query.\n\n========================================\n\nCode:\n```text\nfragment Bar on Foo {\n bar {\n id\n }\n}\n\nfragment Baz on Foo {\n baz {\n id\n }\n}\n\n\nfragment MetaFoo on Foo {\n id\n ...Bar\n ...Baz\n}\n\nquery Qux {\n foo {\n ...MetaFoo\n }\n}\n```\n\n```text\nQux\n```\n\n========================================\n\nComments:\n- What exactly is 'on'? is Foo a type? Like say I have Guild query, which inside provides an array of type Member called `members`. Would I then do something like `fragment memberList on Members`?","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":45,"estimatedTokens":184}}640{"id":"stack-63428895","source":"stackoverflow","questionId":63428895,"title":"AWS Amplify: The variables input contains a field name that is not defined for input object type","tags":["graphql","aws-amplify"],"text":"Title: AWS Amplify: The variables input contains a field name that is not defined for input object type\nTags: graphql, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI dont understad what happen here.\n\nThis is my schema:\n\n```\ntype MonthResume @model @auth(rules: [{allow: owner, identityClaim: \"sub\"}]){\n id: ID!\n incomes: Float!\n spendingByCategory: [Category]\n}\n\ntype Category @model @auth(rules: [{allow: owner, identityClaim: \"sub\"}]){\n id: ID!\n name: String!\n amount: Float!\n}\n```\n\nThis is the autogenerated update mutation that Amplify gives to me:\n\n```\nexport const updateMonthResume = /* GraphQL */ `\n mutation UpdateMonthResume(\n $input: UpdateMonthResumeInput!\n $condition: ModelMonthResumeConditionInput\n ) {\n updateMonthResume(input: $input, condition: $condition) {\n id\n incomes\n spendingByCategory {\n id\n name\n amount\n createdAt\n updatedAt\n owner\n }\n createdAt\n updatedAt\n owner\n}\n}\n`;\n```\n\nAnd this is my input:\n\n```\n{\n \"input\": {\n \"id\": \"d7f-ee2971fd3ae5\",\n \"incomes\": 220,\n \"spendingByCategory\": null,\n \"createdAt\": \"2020-08-15T17:06:22.192Z\",\n \"updatedAt\": \"2020-08-15T17:06:22.192Z\",\n \"owner\": \"subId\"\n }\n}\n```\n\nI just want update the incomes amount, fot that reason I call the api in this way:\n\n```\nconst input = {\n incomes: 0,\n}\n\nawait API.graphql(graphqlOperation(updateMonthResume, input));\n```\n\nAnd then, I got the error.\n\nI dont understand, I dont want to update more than the income, does I need change my input? But I sent a null (Amplify does automatically) for the objetc spendingByCategory.\n\n```\ninput CreateMonthResumeInput {\n id: ID\n incomes: Float!\n```\n\n}\n\n========================================\n\nTop Answer:\nI encountered with the same problem , in my case when I queried data, amplify puts \"__typename\" field. If I make edits on this object and send directly using update mutation then this error occurs. In order to get rid of this , I deleted \"__typename\" property.\n\n========================================\n\nCode:\n```text\ntype MonthResume @model @auth(rules: [{allow: owner, identityClaim: \"sub\"}]){\n id: ID!\n incomes: Float!\n spendingByCategory: [Category]\n}\n\ntype Category @model @auth(rules: [{allow: owner, identityClaim: \"sub\"}]){\n id: ID!\n name: String!\n amount: Float!\n}\n```\n\n```text\nexport const updateMonthResume = /* GraphQL */ `\n mutation UpdateMonthResume(\n $input: UpdateMonthResumeInput!\n $condition: ModelMonthResumeConditionInput\n ) {\n updateMonthResume(input: $input, condition: $condition) {\n id\n incomes\n spendingByCategory {\n id\n name\n amount\n createdAt\n updatedAt\n owner\n }\n createdAt\n updatedAt\n owner\n}\n}\n`;\n```\n\n```text\n{\n \"input\": {\n \"id\": \"d7f-ee2971fd3ae5\",\n \"incomes\": 220,\n \"spendingByCategory\": null,\n \"createdAt\": \"2020-08-15T17:06:22.192Z\",\n \"updatedAt\": \"2020-08-15T17:06:22.192Z\",\n \"owner\": \"subId\"\n }\n}\n```\n\n```text\nconst input = {\n incomes: 0,\n}\n\nawait API.graphql(graphqlOperation(updateMonthResume, input));\n```\n\n```text\ninput CreateMonthResumeInput {\n id: ID\n incomes: Float!\n```\n\n```text\nUpdateMonthResumeInput\n```\n\n```text\nspendingByCategory\n```\n\n```text\nthe MonthResume body\n```\n\n```text\nspendingByCategory: [Category!]\n```\n\n========================================\n\nComments:\n- input object can only have properties defined in `UpdateMonthResumeInput` type, no more - can be less (if nullable/not required) - but all required\n- The rest of properties are defined by Amplify by default (createdAt, updatedAd and owner). The problem is that I just want and input with the property that I want to update, no more, but when Amplify sent the input, it add spendingByCategory as null and that give me the error.\n- UpdateMonthResumeInput defs?\n- to be complete ... your UpdateMonthResumeInput defs was...?\n- The correct input is without owner, createdAt and updateAt. That properties are on the mutation that Amplify generates, but you dont need to send them when you dispatch the mutation because Amplify does for you, that was my problem.\n- usually thats the difference between input types (used for mutation as input/params) and return types (result types for queries and mutations) - it was in generated **input type** ? can you show `UpdateMonthResumeInput` defs?\n- no, still not the right def (mutation one was already here) :) it should be like `input UpdateMonthResumeInput` - you can also get it from graphiql docs\n- Aaah, ok, ok. I found the file with this info (I didn't know about that). I update again ! Thanks a lot, because I didt know about this file !\n- Why in this input doesnt show the property spendingByCategory?\n- because it's not 'the MonthResume body` - it's from relation ... like create user then add user firend - no possibility to create user with friends at once - no nested mutation supported\n- Then just a question, if I want to add an array of objects, without relationship, what should specify? I set spendingByCategory: [Category!] just because I didt find the type Object.\n- every depth level is a separate type (and relation between types) in graphql ... you can only use 'customJSON type' (any serializable or unknown type content) without defining types for complex fields/properties\n- Very good resume about what happen, the log can be confuse.","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":193,"estimatedTokens":1305}}641{"id":"stack-47053844","source":"stackoverflow","questionId":47053844,"title":"Merging 2 REST endpoints to a single GraphQL response","tags":["json","rest","schema","graphql"],"text":"Title: Merging 2 REST endpoints to a single GraphQL response\nTags: json, rest, schema, graphql\nSource: Stack Overflow\n\nQuestion:\nNew to graphQL, I'm Using the following schema:\n\n```\ntype Item {\n id: String,\n valueA: Float,\n valueB: Float\n }\n\n type Query {\n items(ids: [String]!): [Item]\n }\n```\n\nMy API can return multiple items on a single request of each type (A & B) but not for both, i.e: \n\nREST Request for typeA : `api/a/items?id=[1,2]`\n\nResponse: \n\n```\n[\n {\"id\":1,\"value\":100},\n {\"id\":2,\"value\":30}\n]\n```\n\nREST Request for typeB : `api/b/items?id=[1,2]`\n\nResponse: \n\n```\n[\n {\"id\":1,\"value\":50},\n {\"id\":2,\"value\":20}\n]\n```\n\nI would like to merge those 2 api endpoints into a single graphQL Response like so:\n\n```\n[\n {\n id: \"1\",\n valueA: 100,\n valueB: 50\n },\n {\n id: \"2\",\n valueA: 30,\n valueB: 20\n }\n ]\n```\n\n**Q:** How would one write a resolver that will run a **single** fetch for each type (getting multiple items response) making sure no unnecessary fetch is triggered when the query is lacking the type i.e:\n\n```\n{items(ids:[\"1\",\"2\"]) {\n id\n valueA\n}}\n```\n\nThe above example should only fetch `api/a/items?id=[1,2]` and the graphQL response should be:\n\n```\n[\n {\n id: \"1\",\n valueA: 100\n },\n {\n id: \"2\",\n valueA: 30\n }\n]\n```\n\n========================================\n\nCode:\n```text\ntype Item {\n id: String,\n valueA: Float,\n valueB: Float\n }\n\n type Query {\n items(ids: [String]!): [Item]\n }\n```\n\n```text\n[\n {\"id\":1,\"value\":100},\n {\"id\":2,\"value\":30}\n]\n```\n\n```text\n[\n {\"id\":1,\"value\":50},\n {\"id\":2,\"value\":20}\n]\n```\n\n```text\n[\n {\n id: \"1\",\n valueA: 100,\n valueB: 50\n },\n {\n id: \"2\",\n valueA: 30,\n valueB: 20\n }\n ]\n```\n\n```text\n{items(ids:[\"1\",\"2\"]) {\n id\n valueA\n}}\n```\n\n```text\n[\n {\n id: \"1\",\n valueA: 100\n },\n {\n id: \"2\",\n valueA: 30\n }\n]\n```\n\n```text\napi/a/items?id=[1,2]\n```\n\n```text\napi/b/items?id=[1,2]\n```\n\n```text\napi/a/items?id=[1,2]\n```\n\n```text\n{\n items(ids:[\"1\",\"2\"]) {\n ...data\n }}\n\n fragment data on Item {\n id\n valueA\n }\n}\n```\n\n```text\nconst util = require('util');\n\nvar { graphql, buildSchema } = require('graphql');\n\nvar schema = buildSchema(`\n type Item {\n id: String,\n valueA: Float,\n valueB: Float\n }\n\n type Query {\n items(ids: [String]!): [Item]\n }\n`);\n\nvar root = { items: (source, args, root) => {\n var fields = root.fragments.data.selectionSet.selections.map(f => f.name.value);\n var ids = source[\"ids\"];\n\n var data = ids.map(id => {return {id: id}});\n if (fields.indexOf(\"valueA\") != -1)\n {\n // Query api/a/items?id=[ids]\n //append to data;\n console.log(\"calling API A\")\n data[0][\"valueA\"] = 0.12;\n data[1][\"valueA\"] = 0.15;\n }\n\n if (fields.indexOf(\"valueB\") != -1)\n {\n // Query api/b/items?id=[ids]\n //append to data;\n console.log(\"calling API B\")\n data[0][\"valueB\"] = 0.10;\n data[1][\"valueB\"] = 0.11;\n }\n return data\n},\n};\n\ngraphql(schema, `{items(ids:[\"1\",\"2\"]) {\n ...data\n }}\n\n fragment data on Item {\n id\n valueA\n }\n\n `, root).then((response) => {\n console.log(util.inspect(response, {showHidden: false, depth: null}));\n});\n```\n\n```text\ncalling API A\n{ data: \n { items: [ { id: '1', valueA: 0.12 }, { id: '2', valueA: 0.15 } ] } }\n```\n\n```text\n{\n items(ids:[\"1\",\"2\"]) {\n ...data\n }}\n\n fragment data on Item {\n id\n valueA\n valueB\n }\n}\n```\n\n```text\ncalling API A\ncalling API B\n{ data: \n { items: \n [ { id: '1', valueA: 0.12, valueB: 0.1 },\n { id: '2', valueA: 0.15, valueB: 0.11 } ] } }\n```\n\n========================================\n\nComments:\n- Works like charm :)\n- Another case study: What if the APIs have different fields, how then we solve issue merging 2 APIs into one common schema ?","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":264,"estimatedTokens":982}}642{"id":"stack-60499865","source":"stackoverflow","questionId":60499865,"title":"Import build schema from .graphql file","tags":["javascript","graphql"],"text":"Title: Import build schema from .graphql file\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI want to create a GraphQL API with the following schema\n\n```\napp.use(\n \"/graphql\",\n graphQlHttp({\n schema: buildSchema(`\n type Event {\n _id: ID!\n title: String!\n description: String!\n price: Float!\n }\n\n input EventInput {\n title: String!\n description: String!\n price: Float!\n }\n\n type QueryResolver {\n getEvents: [Event!]!\n }\n\n type MutationResolver {\n createEvent(eventInput: EventInput): [Event!]!\n }\n\n schema {\n query: QueryResolver\n mutation: MutationResolver\n }\n `),\n rootValue: {}\n })\n);\n```\n\nCurrently I am using it as a string in in the my main file. I want to separate it out in a graphql file. One way can be that we can read the file but I think it will not be efficient.\n\n**Can you please tell me how can I do this?**\n\n========================================\n\nTop Answer:\nYou can add this node module:\nhttps://github.com/ardatan/graphql-import-node\n\nThen move your schema to something like `mySchema.graphql`.\n\nThen, in JS:\n\n```\nconst mySchema = require('./mySchema.graphql');\n```\n\nor in TypeScript:\n\n```\nimport * as mySchema from './mySchema.graphql';\n```\n\n========================================\n\nCode:\n```text\napp.use(\n \"/graphql\",\n graphQlHttp({\n schema: buildSchema(`\n type Event {\n _id: ID!\n title: String!\n description: String!\n price: Float!\n }\n\n input EventInput {\n title: String!\n description: String!\n price: Float!\n }\n\n type QueryResolver {\n getEvents: [Event!]!\n }\n\n type MutationResolver {\n createEvent(eventInput: EventInput): [Event!]!\n }\n\n schema {\n query: QueryResolver\n mutation: MutationResolver\n }\n `),\n rootValue: {}\n })\n);\n```\n\n```text\nnpm i graphql-tag\n```\n\n```text\ngql\n```\n\n```text\nconst mySchema = require('./mySchema.graphql');\n```\n\n```text\nimport * as mySchema from './mySchema.graphql';\n```\n\n```text\nmySchema.graphql\n```\n\n```text\nconst { loadSchemaSync } = require(\"@graphql-tools/load\");\nconst { GraphQLFileLoader } = require(\"@graphql-tools/graphql-file-loader\");\nconst { addResolversToSchema } = require(\"@graphql-tools/schema\");\nconst { join } = require(\"path\");\n\nconst schemaWithResolvers = addResolversToSchema({\n schema: loadSchemaSync(join(__dirname, \"./(your graphql file).graphql\"), {\n loaders: [new GraphQLFileLoader()],\n }),\n resolvers: {},\n});\n```\n\n```text\ntype Event {\n _id: ID!\n title: String!\n description: String!\n price: Float!\n}\n\ninput EventInput {\n title: String!\n description: String!\n price: Float!\n}\n\ntype QueryResolver {\n getEvents: [Event!]!\n}\n\ntype MutationResolver {\n createEvent(eventInput: EventInput): [Event!]!\n}\n\nschema {\n query: QueryResolver\n mutation: MutationResolver\n}\n```\n\n```text\napp.use(\n \"/graphql\",\n graphQlHttp({\n schema: schemaWithResolvers \n })\n);\n```\n\n```text\nimport 'graphql-import-node';\nimport { buildASTSchema } from 'graphql';\nimport * as mySchema from './schema.graphql';\n\nexport = buildASTSchema(mySchema);\n```\n\n```text\nBuildSchema()\n```\n\n```text\nBuildASTSchema()\n```\n\n```text\nBuildSchema()\n```\n\n```text\nBuildASTSchema()\n```\n\n```text\nimport Schema from './schema.graphql?raw';\nconst schema = buildSchema(Schema);\n```\n\n========================================\n\nComments:\n- Can you explain a bit more about this\n- It's simply abstracting the string schema to a different file. The string schema you defined in your example (the argument to `buildSchema()`) can be placed in a separate `.graphql` file, and imported as a JS module. You can then use it as `buildSchema(myImportedSchema)`. The bonus here is that you can add GraphQL syntax support to your IDE for these .graphql file types.\n- Not working! showing identifier error, may be it's interpreting it as a js file\n- Can you add more detail on your error and how you are importing it? Are you using TypeScript or vanilla JS?\n- This gives me a DocumentNode rather than a parsed GraphQLSchema. A DocumentNode is not accepted by buildSchema so I don't understand the point of using this.","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":214,"estimatedTokens":1026}}643{"id":"stack-60048645","source":"stackoverflow","questionId":60048645,"title":"AWS AppSync - Defining GraphQL schema with custom directives","tags":["amazon-web-services","graphql","aws-appsync"],"text":"Title: AWS AppSync - Defining GraphQL schema with custom directives\nTags: amazon-web-services, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nWhile defining this custom directive:\n\n`directive @hashField on INPUT_FIELD_DEFINITION` \n\nI get this error on the AWS AppSync (Schema tab):\n\n Error parsing schema. Directive definitions are not supported.\n\nI understand AWS provides functions that can provide similar functionalities, but these functions won't work for my use case.\n\nWhat's the alternative for custom directives in AWS AppSync? Is it going to be supported in a future release?\n\n========================================\n\nTop Answer:\nInterestingly, using the AWS CDK, a Directive.custom method is available at both the field and object level e.g.\n\n```\nimport { Field, GraphqlType, InterfaceType, ObjectType, Directive } from '@aws-cdk/aws-appsync-alpha';\n\nnew ObjectType('MyObjectType', {\n definition: {\n id: GraphqlType.id({ isRequired: true }),\n name: new Field({ returnType: GraphqlType.string(), directives: [Directive.custom('@myCustomFieldDirective(param: \"value\")')] })\n },\n directives: [\n Directive.custom('@myCustomObjectDirective(param: \"value\")')\n ]\n});\n```\n\n========================================\n\nCode:\n```text\ndirective @hashField on INPUT_FIELD_DEFINITION\n```\n\n```text\nDirectives\n```\n\n```text\nimport { Field, GraphqlType, InterfaceType, ObjectType, Directive } from '@aws-cdk/aws-appsync-alpha';\n\nnew ObjectType('MyObjectType', {\n definition: {\n id: GraphqlType.id({ isRequired: true }),\n name: new Field({ returnType: GraphqlType.string(), directives: [Directive.custom('@myCustomFieldDirective(param: \"value\")')] })\n },\n directives: [\n Directive.custom('@myCustomObjectDirective(param: \"value\")')\n ]\n});\n```\n\n========================================\n\nComments:\n- in the middle of 2023... nothing arise about this?\n- Just a FYI, AWS AppSync does not support custom scalars...\n- How do you know that it is not on AWS roadmap ? Can you a link ?\n- I'm not sure about their roadmap actually, I was just referring that at that point in time (2020) they did not support it. Re-phrased my answer now to clarify that.","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":68,"estimatedTokens":544}}644{"id":"stack-41281245","source":"stackoverflow","questionId":41281245,"title":"GraphQL redirect when resolver throws error","tags":["node.js","http-redirect","graphql","apollo-server"],"text":"Title: GraphQL redirect when resolver throws error\nTags: node.js, http-redirect, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm using `graphql-server-express` to build a GraphQL server that consumes a REST API.\n\nI'm in the situation that a REST call could return a 301 or 401 status code when the user isn't authenticated to access the resource. I'm using a cookie that is set on the client and forwarded to the REST API while resolving the GraphQL query.\n\nIs it possible to send a 301 redirect to the client in response to a call to the GraphQL endpoint when such an error occurs?\n\nI've tried something like `res.sendStatus(301) β¦` in `formatError` but this doesn't work well as `graphql-server-express` tries to set headers after this.\n\nI've also tried to tried to short-circuit the `graphqlExpress` middleware with something like this:\n\n```\nexport default graphqlExpress((req, res) => {\n res.sendStatus(301);\n return;\n});\n```\n\nWhile the client receives the correct result, the server still prints errors (in this case `TypeError: Cannot read property 'formatError' of undefined` β most likely because the middleware receives empty options).\n\nIs there a good way how to get this to work? Thanks!\n\n========================================\n\nTop Answer:\nAnother way of handling redirects in graphql resolvers is by setting \"status\" as 302 (http status code for redirect) and \"Location\" in the response like below code,\n\n```\nthis.Query = {\n downloadFile: (parent, { url }, { res }) => {\n res.status(302);\n res.set('Location', url);\n\n return;\n}\n```\n\n========================================\n\nCode:\n```text\nexport default graphqlExpress((req, res) => {\n res.sendStatus(301);\n return;\n});\n```\n\n```text\ngraphql-server-express\n```\n\n```text\nres.sendStatus(301) β¦\n```\n\n```text\nformatError\n```\n\n```text\ngraphql-server-express\n```\n\n```text\ngraphqlExpress\n```\n\n```text\nTypeError: Cannot read property 'formatError' of undefined\n```\n\n```text\n// Setup\nexport default class UnauthorizedError extends Error {\n constructor({statusCode = 401, url}) {\n super('Unauthorized request to ' + url);\n this.statusCode = statusCode;\n }\n}\n\n// In a resolver\nthrow new UnauthorizedError({url});\n\n// Setup of the request handler\ngraphqlExpress(async (req, res) => ({\n schema: ...,\n formatError(error) {\n if (error.originalError instanceof UnauthorizedError) {\n res.status(error.originalError.statusCode);\n res.set('Location', 'http://domain.tld/login');\n } else {\n res.status(500);\n }\n\n return error;\n },\n});\n```\n\n```text\nconst networkInterface = createNetworkInterface();\n\nnetworkInterface.useAfter([{\n applyAfterware({response}, next) {\n if ([401, 403].includes(response.status)) {\n document.location = response.headers.get('Location');\n } else {\n next();\n }\n }\n}]);\n```\n\n```text\nthis.Query = {\n downloadFile: (parent, { url }, { res }) => {\n res.status(302);\n res.set('Location', url);\n\n return;\n}\n```\n\n========================================\n\nComments:\n- Redirect to where? Redirect in GraphQL does not really make sense. What if the client sends a query with two root nodes, one succeeds (no need for login) and one fails, what do you send, 300 or 200?\n- If at least one field fails, a redirect should be sent in my case.\n- But graphql queries are executed by JS code, not by browser directly, jsut sending the redirect does not mean the browser will load the login page. Your graphql client, needs to detect this response code then be hardcoded to do something when it happens.\n- It's better just to send the same information in your \"json error\" response and have your client react to it. Changing the response code does not help you at all.\n- You're actually right. I somehow thought that the 301 status code will cause the client to change it's location, but e.g. `fetch` just follows the redirect and will load that resource. So probably the best way is like you mentioned throwing a custom redirect error in my resolver which a client knows how to handle β maybe with an apollo client afterware (in the linked example they're actually using the status code of the response to react to the logout)","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":135,"estimatedTokens":1041}}645{"id":"stack-58312750","source":"stackoverflow","questionId":58312750,"title":"Why is GraphQL Variable Mutation Syntax So Redundant?","tags":["graphql"],"text":"Title: Why is GraphQL Variable Mutation Syntax So Redundant?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nGraphQL queries/mutations are super clean: they only require what they actually *require*, nothing else. Or at least the basic ones are.\n\nBut if you use variables with either one, then your syntax inevitably has redundancy in it:\n\n```\nquery HeroNameAndFriends($episode: Episode) {\n hero(episode: $episode) {\n name\n friends {\n name\n }\n }\n}\n```\n\nNote the `$episode: Episode` and `episode: $episode`. The thing is EVERY GraphQL mutation requires this same redundancy: if you use variables, every argument has to be defined twice (and if you're making *programmatic* queries, you undoubtedly are using variables).\n\nMy question is, why? It seems so unnecessary to make everyone who uses GraphQL have to repeat their arguments a second time.\n\nWhy not just make the syntax:\n\n```\nquery HeroNameAndFriends() {\n hero($episode: Episode) {\n name\n friends {\n name\n }\n }\n}\n```\n\nor if your really need to allow for differing variable names, allow an optional third part:\n\n```\nquery HeroNameAndFriends() {\n hero(episode: Episode : $episode) {\n name\n friends {\n name\n }\n }\n}\n```\n\nTo be clear, I understand that variable-using queries are different from non-variable ones, but what I'm asking about is, why pick a syntax for those queries that forces everyone to repeat themselves?\n\nIt just seems so ... not DRY! Surely I'm missing an important reason why this repetition *is* necessary?\n\n========================================\n\nCode:\n```text\nquery HeroNameAndFriends($episode: Episode) {\n hero(episode: $episode) {\n name\n friends {\n name\n }\n }\n}\n```\n\n```text\nquery HeroNameAndFriends() {\n hero($episode: Episode) {\n name\n friends {\n name\n }\n }\n}\n```\n\n```text\nquery HeroNameAndFriends() {\n hero(episode: Episode : $episode) {\n name\n friends {\n name\n }\n }\n}\n```\n\n```text\n$episode: Episode\n```\n\n```text\nepisode: $episode\n```\n\n```text\nconst getFullName = () => firstname + ' ' + lastname;\n```\n\n```text\nquery NestedInput($name: String) {\n user(where: { name: { contains: $name } }) { ... }\n}\n\nquery WithDirective($long: Boolean) {\n users {\n name\n bio @include(if: $long)\n friends(showAll: $long) {\n name\n }\n }\n}\n```\n\n```text\nfirstname\n```\n\n```text\nlastname\n```\n\n```text\n(_ + 2)\n```\n\n```text\n_.concat(_)\n```\n\n```text\nshowAll\n```\n\n```text\nmismatching types for variable $long. $long is Boolean but expected Int\n```\n\n```text\n$long is sometimes used as Boolean, sometimes as Int\n```\n\n```text\nshowAll\n```\n\n```text\nInt\n```\n\n========================================\n\nComments:\n- This answer was super helpful, and I appreciated the examples of variables used in other ways. But the part I'm still unclear on is: what is the value in the repetition? When you list arguments you're adding meaningful info (their order) which otherwise wouldn't be there: without that there's no way to use the args. But when you repeat `$foo`, you're not adding any new info, you're just repeating info already presented, which doesn't seem to be DRY **or** readable **or** less likely to result in an error. I just want to understand the (non-intuitive, to me) value that repetition gives.\n- Is it just that GraphQL syntax is optimized for queries that re-use variables (like how your `WithDirective` re-used `$long`), at the expense of queries that don't?\n- Well you are arguing that the declaration is repetition, right? I have added some benefits of the explicit syntax in my answer.\n- There is no redundancy here. You define some value that you're passing along with the request along with the type. Then you pass that value to one or more arguments on fields or directives. If the variable and the argument happen to have the same name, that's coincidental. It's really no different than defining a variable in a programming language and then using that variable by passing it to some function. `let x: number; function doWork(x: number): number { ... }; doWork(x);` We wouldn't say that this is redundant because we've typed `x` three times.\n- We could ask \"why do we have to define the types for the variables, why can't I just reference variables inside the operation and their types be implied by the arguments they are passed to\". I think Herku touched on a number of reasons why we do that -- the thing to highlight is that defining the variable types allows us to validate against those types *before any execution happens*. This means bad client input will just blow up the whole query instead of resulting in a potentially partial response.\n- The types are defined in schema, so there should be no need to redefine them on the client side in EACH query separately. Why checking against schema is not enough for any of the analysis purposes you guys mentioned? Also reusability is no argument for me - if you defined query like this: `query WithDirective($long) { users { name bio @include(if: $long) } }` than it should be a matter of including property `long` in the variables object to be able to reuse it.\n- Of course, there is 70 years of research in type systems, decades more if you include the underlying math and set theory. Just because something can be done does not mean it should be done. It comes with other tradeoffs, mostly simplicity. Haskell, for example, has a great type system but also often cryptic error messages, a steep learning curve and had to give up the idea of multiple compiler implementations of the Haskell standard. That is maybe fine for Haskell, but GraphQL lives from it's many implementations.\n- The burden of proof that redundancy is bad is on you. Because so far there has been no argument made. I even made arguments for why redundency can be good or helpful. And also that GraphQL is not the only language that makes this design choice.","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":165,"estimatedTokens":1456}}646{"id":"stack-66147045","source":"stackoverflow","questionId":66147045,"title":"Uncaught Invariant Violation: query option is required. You must specify your GraphQL document in the query option","tags":["reactjs","graphql","apollo","apollo-client","react-apollo"],"text":"Title: Uncaught Invariant Violation: query option is required. You must specify your GraphQL document in the query option\nTags: reactjs, graphql, apollo, apollo-client, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get a list of countries from a `graphql` server in my react app. The `getAllCountry` query works fine on playground but whenever I call the same query on the app, I get the following **errors**:\n\n- \"query option is required. You must specify your GraphQL document in the query option\" (error as seen on screen),\n\n- \"Uncaught Invariant Violation: query option is required. You must specify your GraphQL document in the query option.\" (error on console)\n\nHere's what my code looks like:\n\n```\n// gql query inside gqlQueries.js\n\nexport const GET_ALL_COUNTRIES = gql`\n query getAllCountry {\n getAllCountry {\n name\n id\n countryCode\n currencyCode\n }\n }\n`;\n\n// calling the query\n\n import { queries as gql } from \"./gqlQueries\";\n\n const getAllCountries = () => {\n client\n .query({\n query: gql.GET_ALL_COUNTRIES\n })\n .then((res) => {\n console.log(res.data);\n })\n .catch((err) => console.log(err));\n };\n```\n\nI'm very sure my client is configured correctly because I have other queries in my `gqlQueries.js` file and they all work fine except this particular one (`getAllCountry`).\n\n========================================\n\nTop Answer:\nI think the problem is the gql here:\n\n```\n.query({\n query: gql.GET_ALL_COUNTRIES\n })\n```\n\nIt should be like this:\n\n```\n.query({\n query: GET_ALL_COUNTRIES\n })\n```\n\ngql is already inside the const:\n\n```\nexport const GET_ALL_COUNTRIES = gql`\n query getAllCountry {\n getAllCountry {\n name\n id\n countryCode\n currencyCode\n }\n }`;\n```\n\n========================================\n\nCode:\n```js\n// gql query inside gqlQueries.js\n\nexport const GET_ALL_COUNTRIES = gql`\n query getAllCountry {\n getAllCountry {\n name\n id\n countryCode\n currencyCode\n }\n }\n`;\n\n// calling the query\n\n import { queries as gql } from \"./gqlQueries\";\n\n const getAllCountries = () => {\n client\n .query({\n query: gql.GET_ALL_COUNTRIES\n })\n .then((res) => {\n console.log(res.data);\n })\n .catch((err) => console.log(err));\n };\n```\n\n```text\ngraphql\n```\n\n```text\ngetAllCountry\n```\n\n```text\ngqlQueries.js\n```\n\n```text\ngetAllCountry\n```\n\n```text\nimport { GET_ALL_COUNTRIES } from \"./gqlQueries\";\n\n const getAllCountries = () => {\n client\n .query({\n query: GET_ALL_COUNTRIES\n })\n .then((res) => {\n console.log(res.data);\n })\n .catch((err) => console.log(err));\n };\n```\n\n```text\n.query({\n query: gql.GET_ALL_COUNTRIES\n })\n```\n\n```text\n.query({\n query: GET_ALL_COUNTRIES\n })\n```\n\n```text\nexport const GET_ALL_COUNTRIES = gql`\n query getAllCountry {\n getAllCountry {\n name\n id\n countryCode\n currencyCode\n }\n }`;\n```\n\n========================================\n\nComments:\n- network request body?\n- You mean I should post the how the network request body looks like?\n- You can rename the export, but you need to remove the part of accessing the query through the `gql.` variable. Like `import { GET_ALL_COUNTRIES as query } from ...` and use just `query`\n- Yes, after a lot of googling and asking for help, I tried importing the query directly and surprisingly, it worked. Thanks!\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":174,"estimatedTokens":903}}647{"id":"stack-63588287","source":"stackoverflow","questionId":63588287,"title":"Postman - Upload file and other argument with GraphQL","tags":["graphql","postman"],"text":"Title: Postman - Upload file and other argument with GraphQL\nTags: graphql, postman\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Postman to upload a file to GraphQL.\n\nI know how I can upload a file, however, in my mutation I have to pass a `String!` together with the `Upload!`.\n\nI am not sure where I can pass this `String!` in Postman.\n\n**My mutation:**\n\n```\nmutation AddBookImageOne($bookId: string, $bookImageOne: Upload!){\n addBookImageOne(bookId: $bookId, bookImageOne: $bookImageOne)\n}\n```\n\nI tried to pass `bookId` in the `variables` key but I keep getting the error:\n\n\"message\": \"Variable \"$bookId\" of required type \"String!\" was not provided.\",\n\nI checked this: Graphql mutation to upload file with other fields\nbut they use CURL\n\n**\"Operations\"** in postman field is:\n\n```\n{\"query\":\"mutation AddBookImageOne($bookId: String!, $bookImageOne: Upload!){\\n addBookImageOne(bookId: $bookId, bookImageOne: $bookImageOne)\\n}\"}\n```\n\nhttps://i.sstatic.net/vxm2i.png\n\n========================================\n\nCode:\n```text\nmutation AddBookImageOne($bookId: string, $bookImageOne: Upload!){\n addBookImageOne(bookId: $bookId, bookImageOne: $bookImageOne)\n}\n```\n\n```text\n{\"query\":\"mutation AddBookImageOne($bookId: String!, $bookImageOne: Upload!){\\n addBookImageOne(bookId: $bookId, bookImageOne: $bookImageOne)\\n}\"}\n```\n\n```text\nString!\n```\n\n```text\nUpload!\n```\n\n```text\nString!\n```\n\n```text\nbookId\n```\n\n```text\nvariables\n```\n\n```text\n{\"query\":\"mutation AddBookImageOne($bookId: String!, $bookImageOne: Upload!){\\n addBookImageOne(bookId: $bookId, bookImageOne: $bookImageOne)\\n}\", \"variables\": { \"bookImageOne\": null, \"bookId\": \"be96934c-d20c-4fad-b4bb-a1165468bad9\" } }`\n```\n\n```text\noperations\n```\n\n========================================\n\nComments:\n- pass variables in the `operations` arg - stackoverflow.com/a/62683397/6124657\n- { \"errors\": [ { \"message\": \"No query document supplied\" } ] } I get the following error on trying it out this way.","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":80,"estimatedTokens":491}}648{"id":"stack-62275663","source":"stackoverflow","questionId":62275663,"title":"GraphQL query to get file info from GitHub repository","tags":["github","graphql","github-api"],"text":"Title: GraphQL query to get file info from GitHub repository\nTags: github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nI would like to use GitHub repository for posts in my Gatsby site. Right now I'm using two queries, first to get the names of the files:\n\n```\n{\n viewer {\n repository(name: \"repository-name\") {\n object(expression: \"master:\") {\n id\n ... on Tree {\n entries {\n name\n }\n }\n }\n pushedAt\n }\n }\n}\n```\n\nAnd the second to get the contents of the files:\n\n```\n{\n viewer {\n repository(name: \"repository-name\") {\n object(expression: \"master:file.md\") {\n ... on Blob {\n text\n }\n }\n }\n }\n}\n```\n\nIs there any way to get information about when each file was created and last updated with GraphQL? Right now I can get only `pushedAt` for the whole repository and not individual files.\n\n========================================\n\nCode:\n```graphql\n{\n viewer {\n repository(name: \"repository-name\") {\n object(expression: \"master:\") {\n id\n ... on Tree {\n entries {\n name\n }\n }\n }\n pushedAt\n }\n }\n}\n```\n\n```graphql\n{\n viewer {\n repository(name: \"repository-name\") {\n object(expression: \"master:file.md\") {\n ... on Blob {\n text\n }\n }\n }\n }\n}\n```\n\n```text\npushedAt\n```\n\n```graphql\n{\n repository(owner: \"torvalds\", name: \"linux\") {\n content: object(expression: \"master:Makefile\") {\n ... on Blob {\n text\n }\n }\n info: ref(qualifiedName: \"master\") {\n target {\n ... on Commit {\n history(first: 1, path: \"Makefile\") {\n nodes {\n author {\n email\n }\n message\n pushedDate\n committedDate\n authoredDate\n }\n pageInfo {\n endCursor\n }\n totalCount\n }\n }\n }\n }\n }\n}\n```\n\n```json\n\"pageInfo\": {\n \"endCursor\": \"b29482fde649c72441d5478a4ea2c52c56d97a5e 0\"\n}\n\"totalCount\": 1806\n```\n\n```graphql\n{\n repository(owner: \"torvalds\", name: \"linux\") {\n info: ref(qualifiedName: \"master\") {\n target {\n ... on Commit {\n history(first: 1, after:\"b29482fde649c72441d5478a4ea2c52c56d97a5e 1804\", path: \"Makefile\") {\n nodes {\n author {\n email\n }\n message\n pushedDate\n committedDate\n authoredDate\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\n<static hash> <incremented_number>\n```\n\n```javascript\nconst graphql = require('graphql.js');\n\nconst token = \"YOUR_TOKEN\";\nconst queryVars = { name: \"linux\", owner: \"torvalds\" };\nconst file = \"Makefile\";\nconst branch = \"master\";\n\nvar graph = graphql(\"https://api.github.com/graphql\", {\n headers: {\n \"Authorization\": `Bearer ${token}`,\n 'User-Agent': 'My Application'\n },\n asJSON: true\n});\n\ngraph(`\n query ($name: String!, $owner: String!){\n repository(owner: $owner, name: $name) {\n content: object(expression: \"${branch}:${file}\") {\n ... on Blob {\n text\n }\n }\n info: ref(qualifiedName: \"${branch}\") {\n target {\n ... on Commit {\n history(first: 1, path: \"${file}\") {\n nodes {\n author {\n email\n }\n message\n pushedDate\n committedDate\n authoredDate\n }\n pageInfo {\n endCursor\n }\n totalCount\n }\n }\n }\n }\n }\n }\n`)(queryVars).then(function(response) {\n console.log(JSON.stringify(response, null, 2));\n var totalCount = response.repository.info.target.history.totalCount;\n if (totalCount > 1) {\n var cursorPrefix = response.repository.info.target.history.pageInfo.endCursor.split(\" \")[0];\n var nextCursor = `${cursorPrefix} ${totalCount-2}`;\n console.log(`total count : ${totalCount}`);\n console.log(`cursorPrefix : ${cursorPrefix}`);\n console.log(`get element after cursor : ${nextCursor}`);\n\n graph(`\n query ($name: String!, $owner: String!){\n repository(owner: $owner, name: $name) {\n info: ref(qualifiedName: \"${branch}\") {\n target {\n ... on Commit {\n history(first: 1, after:\"${nextCursor}\", path: \"${file}\") {\n nodes {\n author {\n email\n }\n message\n pushedDate\n committedDate\n authoredDate\n }\n }\n }\n }\n }\n }\n }`)(queryVars).then(function(response) {\n console.log(\"first commit info\");\n console.log(JSON.stringify(response, null, 2));\n }).catch(function(error) {\n console.log(error);\n });\n }\n}).catch(function(error) {\n console.log(error);\n});\n```\n\n```text\npushedAt\n```\n\n```text\ncommittedDate\n```\n\n```text\nauthorDate\n```\n\n```text\nendCursor\n```\n\n```text\nMakefile\n```\n\n```text\nb29482fde649c72441d5478a4ea2c52c56d97a5e 1804\n```\n\n```text\n\"b29482fde649c72441d5478a4ea2c52c56d97a5e 1804\"\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":267,"estimatedTokens":1323}}649{"id":"stack-55736780","source":"stackoverflow","questionId":55736780,"title":"What causes the [\"String\" has no subfields] image error in GraphQL/Gatsby?","tags":["graphql","gatsby"],"text":"Title: What causes the [\"String\" has no subfields] image error in GraphQL/Gatsby?\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nThe whole error message on terminal is:\n\n```\nerror GraphQL Error Field \"image\" must not have a selection since type \"String\" has no subfields.\n```\n\nThis seems like a real doozy of an error, it appears here:\n\ngatsby issue 4123\ngatsby issue 11412\ngatsby issue 11534\ngatsby issue 2050\ngatsby issue 3531\ngatsby remark plugin issue 2\nnetlify-cms issue 325 \n\nAs well as several Stackoverflow questions/answers. \n\nBut the answers/fixes are all over the place. Some people are spelling their files wrong or ordering plugins wrong (I think). Other times, the person needs to do a big rewrite within `exports.onCreateNode` in gatsby-node.js. Other times the fix is to reclone your repo and run npm install again.\n\nAnyway, I've tried what feels about everything. It seems many dozens or hundreds more people will have this error when they try to get started with Gatsby. What should they check? Where should they start to fix this? There seem to be 7 potential things to check...\n\n========================================\n\nTop Answer:\nTo add to the checklist when encountering this error:\n\nMake sure you actually have images in the folder configured in gatsby-conf.js:\n\n```\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `images`,\n path: `${__dirname}/src/images`,\n },\n}\n```\n\nand that they match whatever path is in your graphql. If \"myImage.png\" is returned by your query but this is not a file in your images, you will get this error.\n\n========================================\n\nCode:\n```text\nerror GraphQL Error Field \"image\" must not have a selection since type \"String\" has no subfields.\n```\n\n```text\nexports.onCreateNode\n```\n\n```text\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `images`,\n path: `${__dirname}/src/images`,\n },\n}\n```\n\n========================================\n\nComments:\n- In my case this code was miss from gatsby-node.js `exports.onCreateNode = ({ node, actions, getNode }) => { const { createNodeField } = actions fmImagesToRelative(node) // convert image paths for gatsby images if (node.internal.type ===`MarkdownRemark`) { const value = createFilePath({ node, getNode }) createNodeField({ name:`slug`, node, value, }) } }` After adding that code no more error of Field \"image\" must not have a selection since type \"String\" has no subfields.\n- @ZeeshanSafdar Thank you very much! But I would note that we should install gatsby-remark-relative-images at first.","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":72,"estimatedTokens":639}}650{"id":"stack-37906261","source":"stackoverflow","questionId":37906261,"title":"How to update data with GraphQL","tags":["mongodb","graphql"],"text":"Title: How to update data with GraphQL\nTags: mongodb, graphql\nSource: Stack Overflow\n\nQuestion:\nI am studying graphql.\n\nI can retrieve data from my mongo database with queries, I can create data with mutations.\n\nBut how I can modify existing data?\n\nI am a bit lost here... \n\nI have to create a new mutation?\n\n========================================\n\nCode:\n```text\ncompleted\n```\n\n```text\ntext\n```\n\n```text\nmarkTodoCompleted\n```\n\n```text\nupdateTodoText\n```\n\n```text\nupdateTodo\n```\n\n========================================\n\nComments:\n- hm but how? How can I edit one or all fields of some data object that, e.g. has a specific ID/key ?","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":42,"estimatedTokens":159}}651{"id":"stack-58140891","source":"stackoverflow","questionId":58140891,"title":"Nest JS GraphQL βCannot return null for non-nullableβ","tags":["javascript","node.js","typescript","graphql","nestjs"],"text":"Title: Nest JS GraphQL βCannot return null for non-nullableβ\nTags: javascript, node.js, typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI tried to resolve one error in my study code, but failed. Then I just try to launch this code...\n\nhttps://github.com/nestjs/nest/tree/master/sample/23-type-graphql\n\nand the same situation...\n\nError looks like\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field Recipe.id.\",\n \"locations\": [\n {\n \"line\": 3,\n \"column\": 5\n }\n ],\n \"path\": [\n \"recipe\",\n \"id\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Cannot return null for non-nullable field Recipe.id.\",\n \" at completeValue (/home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:560:13)\",\n \" at /home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:492:16\",\n \" at process._tickCallback (internal/process/next_tick.js:68:7)\"\n ]\n }\n }\n }\n ],\n \"data\": null\n}\n```\n\nHas someone ideas?\n\n========================================\n\nCode:\n```text\n{\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field Recipe.id.\",\n \"locations\": [\n {\n \"line\": 3,\n \"column\": 5\n }\n ],\n \"path\": [\n \"recipe\",\n \"id\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Cannot return null for non-nullable field Recipe.id.\",\n \" at completeValue (/home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:560:13)\",\n \" at /home/innistry/Downloads/nest-master/sample/23-type-graphql/node_modules/graphql/execution/execute.js:492:16\",\n \" at process._tickCallback (internal/process/next_tick.js:68:7)\"\n ]\n }\n }\n }\n ],\n \"data\": null\n}\n```\n\n```text\nimport { Field, ID, ObjectType } from 'type-graphql';\n\n@ObjectType()\nexport class Recipe {\n @Field(type => ID, { nullable: true })\n id?: string;\n\n @Field({ nullable: true })\n title?: string;\n\n @Field({ nullable: true })\n description?: string;\n\n @Field({ nullable: true })\n creationDate?: Date;\n\n @Field(type => [String], { nullable: true })\n ingredients?: string[];\n}\n```\n\n========================================\n\nComments:\n- If you have the same issue and reached this page as I did, I added an answer on this page. stackoverflow.com/questions/56319137/… I cannot add an answer on this page because this question is marked as a duplicated question.\n- Not a good way to solve it. Making the field nullable should be done intentionally, not to bypass a bug.\n- I had the exact same error message. It happened because I used a partial fixture in my test where I didn't filled all the necessary field in my entity. One should be looking for that kind of misuse instead of this quick fix workaround.\n- I believe it's much simpler if you go into the entity definition and append ? to the field name. This means that the property may or may not be present in instances of the class. That way; you wouldn't need to specify @Field({ nullable: true }) above all the properties; @Entity() @ObjectType() export class StoreProfile { fieldName?: string; }","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":111,"estimatedTokens":833}}652{"id":"stack-50541783","source":"stackoverflow","questionId":50541783,"title":"Spring + GraphQL - optional authorization","tags":["spring","spring-boot","spring-security","graphql","graphql-java"],"text":"Title: Spring + GraphQL - optional authorization\nTags: spring, spring-boot, spring-security, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI am currently using Spring Boot Starter and GraphQL Java Tools to use GraphQL in my Spring application. It works well together with my authorization filter, as long as i authorize the graphql endpoint. Now i would like to open certain mutations or queries to the public (thus no authorization required) and this is where i stumble. How can i open the graphql endpoint but still be able to use the `@PreAuthorize` annotation of Spring security for method level authorization? In other words: Is it possible to have \"optional\" authorization on an endpoint?\n\nThis is my configuration:\n\n```\n@Override\nprotected void configure(HttpSecurity http) throws Exception {\n log.debug(\"configureHttpSecurity\");\n\n // Only authorize the request if it is NOT in the permitAllEndpoints AND matches API_ROOT_URL OR\n // MESSAGING_ROOT_URL\n List requestMatchers = new ArrayList<>();\n requestMatchers.add(new SkipPathRequestMatcher(permitAllEndpointList, API_ROOT_URL));\n requestMatchers.add(new AntPathRequestMatcher(MESSAGING_ROOT_URL));\n OrRequestMatcher apiMatcher = new OrRequestMatcher(requestMatchers);\n\n http.csrf().disable()\n .sessionManagement()\n .sessionCreationPolicy(SessionCreationPolicy.STATELESS)\n .and()\n .authorizeRequests()\n .antMatchers(permitAllEndpointList.toArray(new String[0]))\n .permitAll()\n .and()\n .authorizeRequests()\n .antMatchers(API_ROOT_URL, MESSAGING_ROOT_URL)\n .authenticated()\n .and()\n .addFilterBefore(new CustomCorsFilter(),\n UsernamePasswordAuthenticationFilter.class)\n .addFilterBefore(new AuthenticationFilter(authenticationManager()),\n UsernamePasswordAuthenticationFilter.class)\n .addFilterBefore(new AuthorizationFilter(apiMatcher),\n UsernamePasswordAuthenticationFilter.class);\n}\n```\n\nThe `apiMatcher` is to open up certain REST endpoints.\nThis is my `AuthorizationFilter`:\n\n```\n@Override\npublic Authentication attemptAuthentication(HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse)\n throws AuthenticationException, IOException, ServletException {\n try {\n String authorization = httpServletRequest.getHeader(\"Authorization\");\n if (authorization != null && authorization.startsWith(\"Bearer \")) {\n return getAuthentication(authorization.replace(\"Bearer \", \"\"));\n }\n } catch (ExecutionException e) {\n httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN,\"The provided token was either not valid or is already expired!\");\n return null;\n } catch (IOException | InterruptedException e) {\n httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,\"There was a problem verifying the supplied token!\");\n return null;\n }\n httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, \"Unauthorized\");\n return null;\n}\n```\n\nIf i don't send an error at the end of `attemptAuthentication` i would be able to access REST endpoints which should not be open. Also if i just permit the GraphQL Endpoint then no authorization will happen and thus every `@PreAuthorize` will fail, even if i provide a valid JWT.\nIt might be that my approach to this is already wrong. If this is the case then please let me know.\n\n========================================\n\nCode:\n```text\n@Override\nprotected void configure(HttpSecurity http) throws Exception {\n log.debug(\"configureHttpSecurity\");\n\n // Only authorize the request if it is NOT in the permitAllEndpoints AND matches API_ROOT_URL OR\n // MESSAGING_ROOT_URL\n List<RequestMatcher> requestMatchers = new ArrayList<>();\n requestMatchers.add(new SkipPathRequestMatcher(permitAllEndpointList, API_ROOT_URL));\n requestMatchers.add(new AntPathRequestMatcher(MESSAGING_ROOT_URL));\n OrRequestMatcher apiMatcher = new OrRequestMatcher(requestMatchers);\n\n http.csrf().disable()\n .sessionManagement()\n .sessionCreationPolicy(SessionCreationPolicy.STATELESS)\n .and()\n .authorizeRequests()\n .antMatchers(permitAllEndpointList.toArray(new String[0]))\n .permitAll()\n .and()\n .authorizeRequests()\n .antMatchers(API_ROOT_URL, MESSAGING_ROOT_URL)\n .authenticated()\n .and()\n .addFilterBefore(new CustomCorsFilter(),\n UsernamePasswordAuthenticationFilter.class)\n .addFilterBefore(new AuthenticationFilter(authenticationManager()),\n UsernamePasswordAuthenticationFilter.class)\n .addFilterBefore(new AuthorizationFilter(apiMatcher),\n UsernamePasswordAuthenticationFilter.class);\n}\n```\n\n```text\n@Override\npublic Authentication attemptAuthentication(HttpServletRequest httpServletRequest,\n HttpServletResponse httpServletResponse)\n throws AuthenticationException, IOException, ServletException {\n try {\n String authorization = httpServletRequest.getHeader(\"Authorization\");\n if (authorization != null && authorization.startsWith(\"Bearer \")) {\n return getAuthentication(authorization.replace(\"Bearer \", \"\"));\n }\n } catch (ExecutionException e) {\n httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN,\"The provided token was either not valid or is already expired!\");\n return null;\n } catch (IOException | InterruptedException e) {\n httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,\"There was a problem verifying the supplied token!\");\n return null;\n }\n httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, \"Unauthorized\");\n return null;\n}\n```\n\n```text\n@PreAuthorize\n```\n\n```text\napiMatcher\n```\n\n```text\nAuthorizationFilter\n```\n\n```text\nattemptAuthentication\n```\n\n```text\n@PreAuthorize\n```\n\n```text\n@PreAuthorize\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.073Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":151,"estimatedTokens":1478}}653{"id":"stack-63748967","source":"stackoverflow","questionId":63748967,"title":"GraphQL/Apollo application with file download from server","tags":["reactjs","graphql","apollo"],"text":"Title: GraphQL/Apollo application with file download from server\nTags: reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm a little new to GraphQL and this question falls under \"It cannot possibly be this hard. I have to be missing something.\"\n\nI have a fairly standard GraphQL/Apollo/React application split into client and server. Everything is working well with the client making API calls and getting data back from the server. The client is even able to upload files to the server. However, I now need the server to stream back files saved on disk. That's it.\n\nThis is the \"I have to be missing something\" part. Everything I've seen in the docs and on Stackoverflow is some variation of pushing the file back from the server and through the GraphQL query as a base64-endocded string and then doing some very hacky stuff on the client, often involving a hidden href tag and a simulated click. To this I say, \"What???\"\n\nSeriously. There are files on disk that the server knows how to find. The client needs to show a button to the user that they can click on to download the file. That's it. Every other framework in every other language has an easy way to do this. Can someone show me the incredibly simple thing that I'm missing here?\n\nThanks,\nAlex\n\n========================================\n\nComments:\n- just return url, render img with src and browser will do the rest .... REST API relies on browser behaviour the same way ... taking 'pure' it should response with some data, instead some headers changes arriving data context, no response to sourcing client at all\n- Fair enough. I may need another sort of endpoint for files. Thanks for the response, it's actually really helpful as I'm still learning the framework to have someone just say \"no, don't do that.\"\n- can't we use apollo-link-rest for this?","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":22,"estimatedTokens":456}}654{"id":"stack-50805470","source":"stackoverflow","questionId":50805470,"title":"AppSync and GraphQL Enum mutations","tags":["amazon-web-services","graphql","aws-amplify","aws-appsync"],"text":"Title: AppSync and GraphQL Enum mutations\nTags: amazon-web-services, graphql, aws-amplify, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI have the following schema in AppSync for GraphQL\n\n```\ninput CreateTeamInput {\n name: String!\n sport: Sports!\n createdAt: String\n}\n\nenum Sports {\n baseball\n basketball\n cross_country\n}\ntype Mutation{\n createTeam(input: CreateTeamInput!): Team\n}\n```\n\nHowever when I try to execute the query using AWS Amplify library via\n\n```\nexport const CreateTeam = `mutation CreateTeam($name: String!, $sport: String!){\n createTeam(input:{name:$name, sport:$sport}) {\n id,\n name,\n sport\n }\n}\n`;\n\n....\n\nAPI.graphql(graphqlOperation(CreateTeam, this.state))\n```\n\nI get the following error: `Validation error of type VariableTypeMismatch: Variable type doesn't match`.\n\nHow can I update my code to work with this enum type?\n\n========================================\n\nTop Answer:\n$sport needs to be a Sports type not a String\n\n========================================\n\nCode:\n```text\ninput CreateTeamInput {\n name: String!\n sport: Sports!\n createdAt: String\n}\n\nenum Sports {\n baseball\n basketball\n cross_country\n}\ntype Mutation{\n createTeam(input: CreateTeamInput!): Team\n}\n```\n\n```text\nexport const CreateTeam = `mutation CreateTeam($name: String!, $sport: String!){\n createTeam(input:{name:$name, sport:$sport}) {\n id,\n name,\n sport\n }\n}\n`;\n\n....\n\nAPI.graphql(graphqlOperation(CreateTeam, this.state))\n```\n\n```text\nValidation error of type VariableTypeMismatch: Variable type doesn't match\n```\n\n```text\nexport const CreateTeam = `mutation CreateTeam($name: String!, $sport: Sports!){\n createTeam(input:{name:$name, sport:$sport}) {\n id,\n name,\n sport\n }\n};\n```\n\n```text\nenum SPORTS {\n BASEBALL\n BASKETBALL\n CROSS_COUNTRY\n}\n```\n\n```text\nCreateTeamInput.sport\n```\n\n```text\n$sport\n```\n\n========================================\n\nComments:\n- Can you provide your mutation definition? We don't know here what the createTeam mutation expects\n- @VasileiosLekakis post has been updated with the mutation\n- How do I actually specify a Sports type though? I was able to create it no problem in my schema.graphql file used on the server side (in the code snippet above enum Sports{...}), but how do I create it from a client request?\n- I couldn't add a comment on multiple lines so I created an answer above. @DanRamos\n- Well this was a brain fart on my part. I was under the assumption since the schema type of \"Sports\" existed just on my graphql server, that the client query would have idea what to do with `$sports: Sports!`, but it worked just fine. Thank you!","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":123,"estimatedTokens":657}}655{"id":"stack-57888591","source":"stackoverflow","questionId":57888591,"title":"Interface extends multiple interfaces in GraphQL Schema","tags":["inheritance","graphql","multiple-inheritance"],"text":"Title: Interface extends multiple interfaces in GraphQL Schema\nTags: inheritance, graphql, multiple-inheritance\nSource: Stack Overflow\n\nQuestion:\nIs it poslible in GraphQL that one interface extends multiple other interfaces?\n\nI need something like this: \n\n```\ninterface A\n{\n valueA: String\n}\n\ninterface B\n{\n valueB: String\n}\n\ninterface C extend interface A & B\n{\n valueA: String\n valueB: String\n}\n\ntype D implements C{\n valueA: String\n valueB: String\n}\n```\n\nThe solution provided Is it possible to implement multiple interfaces in GraphQL? refers to one **type** implementing multiple interfaces, not one **interface** extending multiple **interfaces**\n\n========================================\n\nTop Answer:\nOnly types can *implement* an interface. An interface cannot implement another interface. You can see the syntax for interfaces defined here, which distinctly lacks the `ImplementsInterfaces` definition shown here.\n\n========================================\n\nCode:\n```text\ninterface A\n{\n valueA: String\n}\n\ninterface B\n{\n valueB: String\n}\n\ninterface C extend interface A & B\n{\n valueA: String\n valueB: String\n}\n\ntype D implements C{\n valueA: String\n valueB: String\n}\n```\n\n```text\ninterface Node {\n id: ID!\n}\n\n# Ideally we'd like to write `interface Pet implements Node`\n# but that's not possible (yet)\ninterface Pet {\n id: ID!\n name: String!\n}\n\ntype Cat implements Node, Pet {\n id: ID!\n name: String!\n prefersWetFood: Boolean!\n}\n```\n\n```text\nquery {\n node(id: \"sylviathecat\") {\n ... on Pet {\n name\n }\n }\n}\n```\n\n```text\nPet\n```\n\n```text\nNode\n```\n\n```text\nPet\n```\n\n```text\nid: ID!\n```\n\n```text\nImplementsInterfaces\n```\n\n========================================\n\nComments:\n- The answere here refers to one **type** implementing multiple interfaces...Please don't mark this as a duplicate, since this is a different type of problem..Please see my description carefully. I need that one **interface** extends multiple interfaces, not that one **type** imoplements multiple interfaces.Tnx\n- weird thing is that it's not possible to do `interface B extends AnotherInterface {}` and `type A implements B`\n- Your answer is detailed and useful, but you should edit it nonetheless. The question is about extending interfaces not implementing them. Maybe edit with something similar to \"...The answer to this question today is still No, although it is possible for interfaces to implement other interfaces,\" would suffice? I would also suggest to add that graphql-js@15.0.0 was just released.\n- > The question is about extending interfaces not implementing them. The distinction between extending and implementing seems rather pedantic here. The original question used the word extending but the code sample given would actually be classified as interfaces *implementing* other interfaces.\n- In some ways you are right, but there is already another question about implementing interfaces in graphql and adnan.mujkic specifically commented that he question is not a duplicate of it.\n- Although i have to agree with you in some part. I personally don't see the difference between implementing and extending interfaces in graphql. If it was elsewhere an interface cannot implement another one. It is normally for classes. And the question that he refers is about types implementing interfaces... All in all i probably was being pedantic as you say :)\n- Here in 2023 just to add that this works fine in graphql-js, I'm currently on 15.3.0 but 16.6.0 is the latest one.","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":124,"estimatedTokens":873}}656{"id":"stack-61844633","source":"stackoverflow","questionId":61844633,"title":"How to get response header from useQuery of Apollo Client","tags":["javascript","graphql","react-hooks","apollo-client","response-headers"],"text":"Title: How to get response header from useQuery of Apollo Client\nTags: javascript, graphql, react-hooks, apollo-client, response-headers\nSource: Stack Overflow\n\nQuestion:\nI haven't been able to find a way to do this at all. Does anyone know if this is supported? Thanks.\n\n========================================\n\nCode:\n```text\nconst link = onError(({ graphQLErrors, networkError, operation }) => {\n const { response } = operation.getContext();\n const { headers, status } = response;\n \n // do something with the headers\n});\n```\n\n```text\nHttpLink\n```\n\n```text\nContextLink\n```\n\n```text\nErrorLink\n```\n\n```text\nErrorLink\n```\n\n```text\nHttpLink\n```\n\n```text\nfetch\n```\n\n========================================\n\nComments:\n- why do you need this?\n- For troubleshooting of errors.\n- what kind exactly? for data related errors usually `error` property gives enough info ... you can get network errors, too... just explore this object\n- @xadm the backend sends a correlation id as a response header. I need to get my hands on it to correlate the error with other things happening in the backend.\n- you can reach `response` in error-link (apollographql.com/docs/react/data/error-handling/…)\n- @xadm I can get `response` but I still don't see headers. `response` contains `data` and `errors`. None of them has headers.\n- stackoverflow.com/a/47479911/6124657 ?\n- Is there anything special I need to do with ErrorLink? When an error happens, the `error` object still doesn't contain headers,\n- Same here. operation.getContext() does not contain property response. I am trying to access response header but not able to.","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":55,"estimatedTokens":404}}657{"id":"stack-44159862","source":"stackoverflow","questionId":44159862,"title":"How to pass GraphQLEnumType in mutation as a string value","tags":["graphql","graphql-js"],"text":"Title: How to pass GraphQLEnumType in mutation as a string value\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have following GraphQLEnumType\n\n```\nconst PackagingUnitType = new GraphQLEnumType({\n name: 'PackagingUnit',\n description: '',\n values: {\n Carton: { value: 'Carton' },\n Stack: { value: 'Stack' },\n },\n});\n```\n\nOn a mutation query if i pass PackagingUnit value as Carton (without quotes) it works. But If i pass as string 'Carton' it throws following error\n\n```\nIn field \"packagingUnit\": Expected type \"PackagingUnit\", found \"Carton\"\n```\n\nIs there a way to pass the enum as a string from client side?\n\nEDIT:\nI have a form in my front end, where i collect the PackagingUnit type from user along with other fields. PackagingUnit type is represented as a string in front end (not the graphQL Enum type), Since i am not using Apollo Client or Relay, i had to construct the graphQL query string by myself.\nRight now i am collecting the form data as JSON and then do JSON.stringify() and then remove the double Quotes on properties to get the final graphQL compatible query.\n\neg. my form has two fields packagingUnitType (An GraphQLEnumType) and noOfUnits (An GraphQLFloat)\nmy json structure is \n\n```\n{ \n packagingUnitType: \"Carton\",\n noOfUnits: 10\n}\n```\n\nconvert this to string using JSON.stringify()\n\n```\n'{\"packagingUnitType\":\"Carton\",\"noOfUnits\":10}'\n```\n\nAnd then remove the doubleQuotes on properties\n\n```\n{packagingUnitType:\"Carton\",noOfUnits:10}\n```\n\nNow this can be passed to the graphQL server like\n\n```\nnewStackMutation(input: {packagingUnitType:\"Carton\", noOfUnits:10}) {\n...\n}\n```\n\nThis works only if the enum value does not have any quotes. like below\n\n```\nnewStackMutation(input: {packagingUnitType:Carton, noOfUnits:10}) {\n...\n}\n```\n\nThanks\n\n========================================\n\nCode:\n```text\nconst PackagingUnitType = new GraphQLEnumType({\n name: 'PackagingUnit',\n description: '',\n values: {\n Carton: { value: 'Carton' },\n Stack: { value: 'Stack' },\n },\n});\n```\n\n```text\nIn field \"packagingUnit\": Expected type \"PackagingUnit\", found \"Carton\"\n```\n\n```text\n{ \n packagingUnitType: \"Carton\",\n noOfUnits: 10\n}\n```\n\n```text\n'{\"packagingUnitType\":\"Carton\",\"noOfUnits\":10}'\n```\n\n```text\n{packagingUnitType:\"Carton\",noOfUnits:10}\n```\n\n```text\nnewStackMutation(input: {packagingUnitType:\"Carton\", noOfUnits:10}) {\n...\n}\n```\n\n```text\nnewStackMutation(input: {packagingUnitType:Carton, noOfUnits:10}) {\n...\n}\n```\n\n```text\n// JSON body\n{\n \"query\": \"query MyQuery { ... }\",\n \"variables\": {\n \"variable1\": ...,\n }\n}\n```\n\n```text\nquery MyMutation($input: NewStackMutationInput) {\n newStackMutation(input: $input) {\n ...\n }\n}\n```\n\n```text\n{\n \"input\": {\n \"packagingUnitType\": \"Carton\",\n \"noOfUnits\": 10\n }\n}\n```\n\n```text\nquery\n```\n\n```text\nvariables\n```\n\n```text\npackagingUnitType\n```\n\n========================================\n\nComments:\n- Are you using Relay, Apollo, or making the request in GraphiQL-or equivalent- ?\n- I am not using any of those. I am constructing the query and making a post request to the graphiql server. But I tried this in GraphiQL, it does not allows me to pass the Enum as string.\n- This is normal, as this is an enum, you need to type the value without string. Why do you want to pass it as a string ?\n- i have updated my question. Thanks","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":161,"estimatedTokens":831}}658{"id":"stack-48770276","source":"stackoverflow","questionId":48770276,"title":"Handling Apollo errors on the component side","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: Handling Apollo errors on the component side\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\n### Question\n\nHow can I *react* to Apollo errors in my components?\n\nI'd like for example to display a red banner if a \"network offline\" error was thrown; or show a modal if an error of a certain type is displayed; or render a `` (from `react-routed-dom`) if another kind of error is thrown.\n\n### What I tried\n\nI read the documentation chapter about error handling but it only explains how to setup an Apollo link that acts as a middleware to requests in order to catch errors there. As far as I know it's not possible to pass data from that link down to components given that it's a *terminating link*.\n\nI tried to use error boundary components but it seems like Apollo errors are not really thrown. Not even when using the `await` syntax.\n\n========================================\n\nTop Answer:\nI fixed my issue by setting the errorPolicy of the query to `none` then you can catch the `graphQLErrors` object thrown from the query.\n\n**Example**:\n\n```\nyourQuery()\n .then()\n .catch((error) => { error.graphQLErrors });\n```\n\n========================================\n\nCode:\n```text\n<Redirect>\n```\n\n```text\nreact-routed-dom\n```\n\n```text\nawait\n```\n\n```html\nimport { History, createBrowserHistory } from 'history';\n \n/* If using Typescript, you can make this object Readonly as follows */\nexport type ReadonlyBrowserHistory = Readonly<History>\nconst browserHistory: ReadonlyBrowserHistory = createBrowserHistory();\n\nexport default browserHistory;\n```\n\n```html\nimport browserHistory from './browserHistory'\nimport apolloClient from './apolloClient'\n\n... \n\nReactDOM.render((\n <ApolloProvider client={apolloClient}>\n <Router history={browserHistory}>\n <App />\n </Router>\n </ApolloProvider>\n), document.getElementById(\"root\"));\n```\n\n```html\nimport browserHistory from './browserHistory'\n\nconst errorLink = onError(({ networkError, graphQLErrors }) => {\n if (graphQLErrors) {\n browserHistory.push(\"/error\", { errors: graphQLErrors });\n }\n else if (networkError) {\n browserHistory.push(\"/error\", { errors: networkError });\n };\n});\n\nconst httpLink = new HttpLink({\n uri: httpUri\n});\n\nconst httpLinkWithErrorHandling = ApolloLink.from([\n errorLink,\n httpLink,\n]);\n\nconst apolloClient = new ApolloClient({\n link,\n ...\n});\n\nexport default apolloClient;\n```\n\n```html\nconst ErrorPage = ({ location: { state } }) => {\n\n console.log(state);\n\n return (<div>error page</div>)\n};\n```\n\n```text\napollo-link-error\n```\n\n```text\nreact-router-dom\n```\n\n```js\nyourQuery()\n .then()\n .catch((error) => { error.graphQLErrors });\n```\n\n```text\nnone\n```\n\n```text\ngraphQLErrors\n```\n\n========================================\n\nComments:\n- If downvoters would like to explain their downvotes that would be helpful.\n- Why would anyone give a downvote (actually 2) to a question?\n- There are trolls everywhere...\n- This wouldn't allow me to simply mutate the state of the current page without redirecting. In all error cases I don't want to redirect to a whole new page. I just want to either show a modal error (which can be canceled) or a red banner on top to show the user that we are offline, but that it can still access the data that is in cache.\n- Yes you are right. If you want to handle a mutation differently you would have to use the `operation` property in the callback to not handle the general error handling. In the component where you use the mutation you could use the `.catch()` function of the Promise to handle the error and show a popup. Should i edit my answer?\n- If am using UseQuery how will i get the graphQL errors in functional component ?","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":139,"estimatedTokens":931}}659{"id":"stack-49776031","source":"stackoverflow","questionId":49776031,"title":"How to pass request headers through to graphql resolvers","tags":["node.js","jwt","graphql","graphql-js","apollo-server"],"text":"Title: How to pass request headers through to graphql resolvers\nTags: node.js, jwt, graphql, graphql-js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI have a graphql endpoint which is authorised by a JWT. My JWT strategy verifies the JWT then adds the user object to the request object. \n\nIn a restful route, I would access my users' data like so:\n\n```\nrouter.get('/', (req, res, next) => {\n console.log('user', req.user)\n}\n```\n\nI want to access req.user object within my graphql resolver in order to extract the users' ID. However, when I try log the `context` variable, it is always empty. \n\nDo I need to configure my graphql endpoint to pass through the `req` data to the resolver?\n\nMy app.js has my graphql set up like this:\n\n```\nimport { graphqlExpress, graphiqlExpress } from 'apollo-server-express';\n\napp.use('/graphql', [passport.authenticate('jwt', { session: false }), bodyParser.json()], graphqlExpress({ schema }));\n```\n\nThen I have my resolvers like so:\n\n```\nconst resolvers = {\n Query: { \n user: async (obj, {email}, context) => {\n console.log('obj', obj) // undefined\n console.log('email', email) // currently passed through in graphql query but I want to replace this with the user data passed in req / context\n console.log('context', context) // {}\n return await UserService.findOne(email)\n },\n};\n\n// Put together a schema\nconst schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n});\n```\n\nHow can I access my JWT user data in my resolvers?\n\n========================================\n\nCode:\n```text\nrouter.get('/', (req, res, next) => {\n console.log('user', req.user)\n}\n```\n\n```text\nimport { graphqlExpress, graphiqlExpress } from 'apollo-server-express';\n\napp.use('/graphql', [passport.authenticate('jwt', { session: false }), bodyParser.json()], graphqlExpress({ schema }));\n```\n\n```text\nconst resolvers = {\n Query: { \n user: async (obj, {email}, context) => {\n console.log('obj', obj) // undefined\n console.log('email', email) // currently passed through in graphql query but I want to replace this with the user data passed in req / context\n console.log('context', context) // {}\n return await UserService.findOne(email)\n },\n};\n\n// Put together a schema\nconst schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n});\n```\n\n```text\ncontext\n```\n\n```text\nreq\n```\n\n```text\napp.use('/graphql', [auth_middleware, bodyParser.json()], (req, res) => graphqlExpress({ schema, context: req.user })(req, res) );\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":93,"estimatedTokens":618}}660{"id":"stack-46186518","source":"stackoverflow","questionId":46186518,"title":"How do I set up GraphQL query so one or another argument is required, but not both","tags":["graphql","graphql-js"],"text":"Title: How do I set up GraphQL query so one or another argument is required, but not both\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm just getting to grips with GraphQL,\n\nI have set up the following query:\nβ\n\n```\ntype: UserType,\nargs: {\n id: { name: 'id', type: new GraphQLNonNull(GraphQLID) },\n email: { name: 'email', type: new GraphQLNonNull(GraphQLString) }\n},\nresolve: (root, { id, email }, { db: { User } }, fieldASTs) => {\n ...\n}\n```\n\nI would like to be able to pass either an 'id' or 'email' to the query, however, with this setup it requires both an id and email to be passed. \n\nIs there a way to set up the query so only one argument is required, either id or email, but not both?\n\n========================================\n\nTop Answer:\nDefine an interface `credentials` and have that implemented as `id` or `email`.\n\n========================================\n\nCode:\n```text\ntype: UserType,\nargs: {\n id: { name: 'id', type: new GraphQLNonNull(GraphQLID) },\n email: { name: 'email', type: new GraphQLNonNull(GraphQLString) }\n},\nresolve: (root, { id, email }, { db: { User } }, fieldASTs) => {\n ...\n}\n```\n\n```text\nresolve: (root, { id, email }, { db: { User } }, fieldASTs) => {\n if (!id && !email) return Promise.reject(new Error('Must pass in either an id or email'))\n if (id && email) return Promise.reject(new Error('Must pass in either an id or email, but not both.'))\n // the rest of your resolver\n}\n```\n\n```text\nGraphQLNonNull\n```\n\n```text\ncredentials\n```\n\n```text\nid\n```\n\n```text\nemail\n```\n\n========================================\n\nComments:\n- github.com/graphql/graphql-js/blob/master/src/__tests__/…\n- Input types cannot implement an Interface","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":73,"estimatedTokens":428}}661{"id":"stack-69307384","source":"stackoverflow","questionId":69307384,"title":"Vercel app with graphql-codegen endpoint error Unable to find any GraphQL type definitions for the following pointers","tags":["graphql","next.js","vercel","graphql-codegen"],"text":"Title: Vercel app with graphql-codegen endpoint error Unable to find any GraphQL type definitions for the following pointers\nTags: graphql, next.js, vercel, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nI load my GraphQL schema like:\n\n```\nconst schema = loadSchemaSync('./src/graphql/server/schema/*.gql', {\n loaders: [new GraphQLFileLoader()],\n})\n```\n\nThis works fine locally, however, when deploying to vercel I get the error:\n\n```\nUnable to find any GraphQL type definitions for the following pointers:\n - ./src/graphql/server/schema/*.gql\n```\n\nI think this is because vercel is dropping the relevant files after build?\n\n========================================\n\nCode:\n```text\nconst schema = loadSchemaSync('./src/graphql/server/schema/*.gql', {\n loaders: [new GraphQLFileLoader()],\n})\n```\n\n```text\nUnable to find any GraphQL type definitions for the following pointers:\n - ./src/graphql/server/schema/*.gql\n```\n\n```text\n// src/graphql/schema.ts\n\nimport { gql } from \"apollo-server-core\";\n\nexport default gql`\n type Query {\n greet: String!\n }\n`;\n```\n\n```text\n// src/pages/api/graphql.ts\n\nimport { ApolloServerPluginLandingPageGraphQLPlayground } from \"apollo-server-core\";\n\nimport Schema from \"../../graphql/schema\";\n\nconst apolloServer = new ApolloServer({\n typeDefs: Schema,\n resolvers,\n plugins: [ApolloServerPluginLandingPageGraphQLPlayground],\n introspection: true,\n});\n```\n\n```text\n// codegen.ts\n\nimport { CodegenConfig } from \"@graphql-codegen/cli\";\n\nconst config: CodegenConfig = {\n schema: \"src/graphql/schema.ts\",\n documents: [\"./src/**/*.{ts,tsx}\"],\n ignoreNoDocuments: true,\n generates: {\n \"src/graphql/types/server.ts\": {\n plugins: [\n \"@graphql-codegen/typescript\",\n \"@graphql-codegen/typescript-resolvers\",\n ],\n },\n \"src/graphql/types/client/\": {\n preset: \"client\",\n plugins: [],\n },\n },\n};\n\nexport default config;\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":88,"estimatedTokens":478}}662{"id":"stack-56322284","source":"stackoverflow","questionId":56322284,"title":"Nexus-prisma: order nested connections","tags":["javascript","graphql","prisma-graphql","nexus-prisma"],"text":"Title: Nexus-prisma: order nested connections\nTags: javascript, graphql, prisma-graphql, nexus-prisma\nSource: Stack Overflow\n\nQuestion:\nWhat is the best way to keep order of nested objects in the schema.\n\nMy schema:\n\n```\ntype Article {\n id: ID! @id\n pages: [Page!]!\n}\n\ntype Page {\n id: ID! @id\n}\n```\n\nThis is how I'm trying to sort the pages(unsuccessfully):\n\n```\nupdateArticle({\n variables: {\n aricle.id,\n data: {\n pages: {\n connect: reorderPages(aricle.pages)\n }\n }\n }\n```\n\nThe resolver:\n\n```\nt.field(\"updateArticle\", {\n type: \"Article\",\n args: {\n id: idArg(),\n data: t.prismaType.updateArticle.args.data\n },\n resolve: (_, { id, data }) => {\n return ctx.prisma.updateArticle({\n where: { id },\n data\n });\n }\n });\n```\n\nI understand why this approach is wrong. I guess that the order should be written in the database by an order index in the connection table. I don't know how to process that by GraphQL/Nexus/Prisma/MySQL.\n\n========================================\n\nCode:\n```text\ntype Article {\n id: ID! @id\n pages: [Page!]!\n}\n\ntype Page {\n id: ID! @id\n}\n```\n\n```text\nupdateArticle({\n variables: {\n aricle.id,\n data: {\n pages: {\n connect: reorderPages(aricle.pages)\n }\n }\n }\n```\n\n```text\nt.field(\"updateArticle\", {\n type: \"Article\",\n args: {\n id: idArg(),\n data: t.prismaType.updateArticle.args.data\n },\n resolve: (_, { id, data }) => {\n return ctx.prisma.updateArticle({\n where: { id },\n data\n });\n }\n });\n```\n\n```text\ntype Article {\n id: ID! @id\n title: String!\n items: [ArticleItemEdge!]! \n}\n\ntype ArticleItemEdge {\n id: ID! @id\n article: Article! @relation(link: INLINE)\n item: Item! @relation(link: INLINE)\n order: Int!\n}\n\ntype Item {\n id: ID! @id\n title: String!\n articles: [ArticleItemEdge!]!\n}\n```\n\n```text\nquery {\n articles {\n items(orderBy: order_ASC) {\n item {\n title\n }\n }\n }\n}\n```\n\n```text\ntype Article {\n id: ID! @id\n items: [Item!]!\n}\n\ntype Item {\n id: ID! @id\n article: Article! @relation(link: INLINE)\n order: Int!\n}\n```\n\n```text\nquery {\n articles {\n id\n items(orderBy: order_ASC) {\n id\n }\n }\n}\n```\n\n========================================\n\nComments:\n- Why are you not using the orderBy argument?\n- So do you please mean to update all the nested object with an order index and then sort them by orderBy?","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":158,"estimatedTokens":600}}663{"id":"stack-53268991","source":"stackoverflow","questionId":53268991,"title":"AWS AppSync React: how to work with \"complex\" GraphQL schema?","tags":["reactjs","amazon-dynamodb","graphql","aws-appsync","aws-amplify"],"text":"Title: AWS AppSync React: how to work with \"complex\" GraphQL schema?\nTags: reactjs, amazon-dynamodb, graphql, aws-appsync, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI am trying to get started with AWS AppSync and AWS Amplify.\n\nSo far, I managed to the AWS documentation (especially here and here) to successfully create a sample TODO app (third code snippet) and enable the AppSync GraphQL API like so:\n\n```\n$ amplify add api\n? Please select from one of the below mentioned services GraphQL\n? Provide API name: MySampleTodoAPI\n? Choose an authorization type for the API API key\n? Do you have an annotated GraphQL schema? No\n? Do you want a guided schema creation? true\n? What best describes your project: Single object with fields (e.g., βTodoβ with ID, name, description)\n```\n\nThis generates this \"trivial\" `schema.graphql` (i.e. containing only a single object):\n\n```\ntype Todo @model {\n id: ID!\n name: String!\n description: String\n}\n```\n\n`amplify push` generates a much more involved, secondary `schema.graphql` from the file above, creates JavaScript code with objects for mutations, queries, etc. and also sets up AWS resources (i.e. DynamoDB table, S3 buckets, etc.). The app seems to have bugs, but essentially works - including adding data entered in the UI to the DynamoDB table.\n\nI have created a second sample Blog app in the same way as above, only this time choosing `Single object with fields (e.g., βTodoβ with ID, name, description)` instead of `Single object with fields ...`.\n\nThis generates this \"complex\" `schema.graphql` (i.e. containing multiple, connected objects):\n\n```\ntype Blog @model {\n id: ID!\n name: String!\n posts: [Post] @connection(name: \"BlogPosts\")\n}\ntype Post @model {\n id: ID!\n title: String!\n blog: Blog @connection(name: \"BlogPosts\")\n comments: [Comment] @connection(name: \"PostComments\")\n}\ntype Comment @model {\n id: ID!\n content: String\n post: Post @connection(name: \"PostComments\")\n}\n```\n\n**Question:** How do I deal with \"complex\" objects in a React application when talking to the AWS AppSync GraphQL backend ?\n\nAs a (contrived) example, assuming I want to add a new `Blog` object with one `Post` and one `Comment` object, can I somehow pass all objects to a single mutation in a single `Connect` React component ? Or do I have to first trigger a `Blog` mutation, followed by the other two ? Or do I have to look into customizing the (secondary) `schema.graphql` and JavaScript files that Amplify generates for me ?\n\nUnfortunately, the AWS sample code only deals with \"trivial\" schemas, not \"complex\" ones - and Amplify seems to be so fresh out of the box that all the third party posts and sample projects use other technologies...\n\nThank you very much for your consideration! :-)\n\n========================================\n\nCode:\n```text\n$ amplify add api\n? Please select from one of the below mentioned services GraphQL\n? Provide API name: MySampleTodoAPI\n? Choose an authorization type for the API API key\n? Do you have an annotated GraphQL schema? No\n? Do you want a guided schema creation? true\n? What best describes your project: Single object with fields (e.g., βTodoβ with ID, name, description)\n```\n\n```text\ntype Todo @model {\n id: ID!\n name: String!\n description: String\n}\n```\n\n```text\ntype Blog @model {\n id: ID!\n name: String!\n posts: [Post] @connection(name: \"BlogPosts\")\n}\ntype Post @model {\n id: ID!\n title: String!\n blog: Blog @connection(name: \"BlogPosts\")\n comments: [Comment] @connection(name: \"PostComments\")\n}\ntype Comment @model {\n id: ID!\n content: String\n post: Post @connection(name: \"PostComments\")\n}\n```\n\n```text\nschema.graphql\n```\n\n```text\namplify push\n```\n\n```text\nschema.graphql\n```\n\n```text\nSingle object with fields (e.g., βTodoβ with ID, name, description)\n```\n\n```text\nSingle object with fields ...\n```\n\n```text\nschema.graphql\n```\n\n```text\nBlog\n```\n\n```text\nPost\n```\n\n```text\nComment\n```\n\n```text\nConnect\n```\n\n```text\nBlog\n```\n\n```text\nschema.graphql\n```\n\n========================================\n\nComments:\n- Thank you very much for your response! It seems there is a lot of valuable information in it, but for the moment, I had to halt work on the GraphQL API and postpone that until I have learned more about Amplify, React and JavaScript in general. I will get back to this eventually.\n- Would be nice, if there would be more tutorials about it. I understand, that editing CF templates is not much Youtube friendly, but transactions in AWS Amplify are not documented very well.","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":155,"estimatedTokens":1119}}664{"id":"stack-74326921","source":"stackoverflow","questionId":74326921,"title":"GraphQL schema to python dataclasses codegen","tags":["python","graphql","code-generation"],"text":"Title: GraphQL schema to python dataclasses codegen\nTags: python, graphql, code-generation\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQL schema defined from server and I'd like to write a nice Python GraphQL client for it. I'm looking for a way to transform my GraphQL schema into python classes with type hints such that I'll be able to see all available queries, mutations, their fields(names & types) and return vals.\n\nI cannot write manually all python classes due to schema complexity, I have many filters on each field. see this example from ent on `TodoWhereInput` to understand how error prune this will be. I really enjoy using `GraphQL playground` with auto completion, I want that experience in my python client.\n\nFor example, given this schema as an input:\n\n```\ntype Book {\n title: String\n year: Int\n}\n\ntype Author {\n name: String\n books: [Book]\n}\n```\n\nI'd like to generate this python code as an output:\n\n```\nfrom dataclasses import dataclass\n\n@dataclass\nclass Book:\n title: str\n year: int\n\n@dataclass\nclass Author:\n name: str\n books: list[Book]\n```\n\nsame for `Input`s in schema.\n\nI already looked at:\n\ncodegen which is awesome for typescript! but doesn't have python support :/\n\ngql_schema_codegen nice, but generating `TypedDict` which isn't dataclasses, I have to change each dict and pass `total=False` so it won't required all fields by default.\n\nsgqlc code-generator which doesn't allow type hints. writing queries is still dynamically and error prune.\n\n========================================\n\nTop Answer:\nYet another example on how to generate classes from a GQL schema can be found in qenerate. It creates simple data classes for queries and even supports the use of fragments to reduce repetitive class generation. The schema is obtained by leveraging GraphQL's Introspection feature.\n\nqenerate itself is not a client. It is intended to be used along-side other GQL clients. It solely focuses on generating corresponding classes for given query/fragment definitions.\n\nDisclaimer: I work on the team that created qenerate.\n\n========================================\n\nCode:\n```text\ntype Book {\n title: String\n year: Int\n}\n\ntype Author {\n name: String\n books: [Book]\n}\n```\n\n```text\nfrom dataclasses import dataclass\n\n@dataclass\nclass Book:\n title: str\n year: int\n\n@dataclass\nclass Author:\n name: str\n books: list[Book]\n```\n\n```text\nTodoWhereInput\n```\n\n```text\nGraphQL playground\n```\n\n```text\nInput\n```\n\n```text\nTypedDict\n```\n\n```text\ntotal=False\n```\n\n```text\nAriadne\n```\n\n```text\nclass Book(GQLObject):\n title: str\n year: int\n\nclass Author(GQLObject):\n name: str\n books: list[Book]\n```\n\n========================================\n\nComments:\n- Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.\n- This works perfectly if you already have a graphql.schema file. The documentation says to run the render command, but it doesn't exists. Instead use the generate command and pass in the config file.","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":126,"estimatedTokens":764}}665{"id":"stack-32166851","source":"stackoverflow","questionId":32166851,"title":"How to create a list of custom objects in GraphQL","tags":["javascript","graphql"],"text":"Title: How to create a list of custom objects in GraphQL\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI am currently playing around with a bunch of new technology of Facebook.\n\nI have a little problem with GraphQL schemas.\nI have this model of an object:\n\n```\n{\n id: '1',\n participants: ['A', 'B'],\n messages: [\n {\n content: 'Hi there',\n sender: 'A'\n },\n {\n content: 'Hey! How are you doing?',\n sender: 'B'\n },\n {\n content: 'Pretty good and you?',\n sender: 'A'\n },\n ];\n }\n```\n\nNow I want to create a GraphQL model for this. I did this:\n\n```\nvar theadType = new GraphQLObjectType({\n name: 'Thread',\n description: 'A Thread',\n fields: () => ({\n id: {\n type: new GraphQLNonNull(GraphQLString),\n description: 'id of the thread'\n },\n participants: {\n type: new GraphQLList(GraphQLString),\n description: 'Participants of thread'\n },\n messages: {\n type: new GraphQLList(),\n description: 'Messages in thread'\n }\n\n })\n});\n```\n\nI know there are more elegant ways to structure the data in the first place. But for the sake of experimenting, I wanted to try it like this.\n\nEverything works fine, besides my messages array, since I do not specify the Array type. I have to specify what kind of data goes into that array. But since it is an custom object, I don't know what to pass into the GraphQLList(). \n\nAny idea how to resolve this besides creating an own type for messages?\n\n========================================\n\nTop Answer:\nI don't think you can do this in GraphQL. Think that it's a bit against GraphQL philosophy of asking for the fields \"you need\" in each component against asking for \"them all\". \n\nWhen the app scales, your approach will provoque higher loads of data. I know that for the purpose of testing the library looks a bit too much but it seems this is how it is designed. Types allowed in current GraphQL library (0.2.6) are:\n\n- GraphQLSchema\n\n- GraphQLScalarType\n\n- GraphQLObjectType\n\n- GraphQLInterfaceType\n\n- GraphQLUnionType\n\n- GraphQLEnumType\n\n- GraphQLInputObjectType\n\n- GraphQLList\n\n- GraphQLNonNull\n\n- GraphQLInt\n\n- GraphQLFloat\n\n- GraphQLString\n\n- GraphQLBoolean\n\n- GraphQLID\n\n========================================\n\nCode:\n```text\n{\n id: '1',\n participants: ['A', 'B'],\n messages: [\n {\n content: 'Hi there',\n sender: 'A'\n },\n {\n content: 'Hey! How are you doing?',\n sender: 'B'\n },\n {\n content: 'Pretty good and you?',\n sender: 'A'\n },\n ];\n }\n```\n\n```text\nvar theadType = new GraphQLObjectType({\n name: 'Thread',\n description: 'A Thread',\n fields: () => ({\n id: {\n type: new GraphQLNonNull(GraphQLString),\n description: 'id of the thread'\n },\n participants: {\n type: new GraphQLList(GraphQLString),\n description: 'Participants of thread'\n },\n messages: {\n type: new GraphQLList(),\n description: 'Messages in thread'\n }\n\n })\n});\n```\n\n```text\nmessageType\n```\n\n```text\ntheadType\n```\n\n```text\nnew GraphQLList(messageType)\n```\n\n========================================\n\nComments:\n- Why the downvote? As Peter Hilton said you have to use a GraphQLList to achieve what you wanted but you explicitly said that you didn't want\n- Thanks for the response, i get a problem \"..must have a sub selection.\" when i request for sub-element. can you give an example of get query to fetch messages.","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":159,"estimatedTokens":864}}666{"id":"stack-45730927","source":"stackoverflow","questionId":45730927,"title":"How to set cookies in Graphene Python mutation?","tags":["python","graphql","graphene-python"],"text":"Title: How to set cookies in Graphene Python mutation?\nTags: python, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nIn Graphene Python, how should one go about setting cookies in the `schema.py` when there is no access to the `HttpResponse` object to set the cookie on?\n\nMy current implementation is to set the cookie by overriding the GraphQLView's dispatch method by catching the `data.operationName`. This involves hard-coding of the operation names / mutations that I need cookies to be set on. \n\nIn views.py:\n\n```\nclass PrivateGraphQLView(GraphQLView):\n data = self.parse_body(request)\n operation_name = data.get('operationName')\n # hard-coding === not pretty.\n if operation_name in ['loginUser', 'createUser']:\n ...\n response.set_cookie(...)\n return response\n```\n\nIs there a cleaner way of setting cookies for specific Graphene Python mutations?\n\n========================================\n\nTop Answer:\nI had a similar problem. I needed to be able to set the language cookie in a mutation and ended up using the request instance in combination with a custom middleware.\n\nHere's the simplified code:\n\n```\nclass SetLanguage(Mutation):\n class Arguments:\n code = String(required=True)\n\n ok = Field(Boolean)\n language = Field(LanguageType)\n\n def mutate(root, info, code):\n info.context.set_language_cookie = code\n return SetLanguage(ok=True, language=code)\n```\n\nThe mutation doesn't have access to the response so it temporarily stores the value on the request instance. Once the response has been created a custom middleware retrieves it and sets the cookie:\n\n```\nclass LanguageConfigMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n\n if code := getattr(request, \"set_language_cookie\", None):\n response.set_cookie(settings.LANGUAGE_COOKIE_NAME, code)\n\n return response\n```\n\n========================================\n\nCode:\n```text\nclass PrivateGraphQLView(GraphQLView):\n data = self.parse_body(request)\n operation_name = data.get('operationName')\n # hard-coding === not pretty.\n if operation_name in ['loginUser', 'createUser']:\n ...\n response.set_cookie(...)\n return response\n```\n\n```text\nschema.py\n```\n\n```text\nHttpResponse\n```\n\n```text\ndata.operationName\n```\n\n```text\nclass CookieMiddleware(object):\n\n def resolve(self, next, root, args, context, info):\n \"\"\"\n Set cookies based on the name/type of the GraphQL operation\n \"\"\"\n\n # set cookie here and pass to dispatch method later to set in response\n ...\n```\n\n```text\nclass MyCustomGraphQLView(GraphQLView): \n\n def dispatch(self, request, *args, **kwargs):\n response = super(MyCustomGraphQLView, self).dispatch(request, *args, **kwargs)\n # Set response cookies defined in middleware\n if response.status_code == 200:\n try:\n response_cookies = getattr(request, CookieMiddleware.MIDDLEWARE_COOKIES)\n except:\n pass\n else:\n for cookie in response_cookies:\n response.set_cookie(cookie.get('key'), cookie.get('value'), **cookie.get('kwargs'))\n return response\n```\n\n```text\nviews.py\n```\n\n```py\nclass SetLanguage(Mutation):\n class Arguments:\n code = String(required=True)\n\n ok = Field(Boolean)\n language = Field(LanguageType)\n\n def mutate(root, info, code):\n info.context.set_language_cookie = code\n return SetLanguage(ok=True, language=code)\n```\n\n```py\nclass LanguageConfigMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n\n if code := getattr(request, \"set_language_cookie\", None):\n response.set_cookie(settings.LANGUAGE_COOKIE_NAME, code)\n\n return response\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":145,"estimatedTokens":974}}667{"id":"stack-51611400","source":"stackoverflow","questionId":51611400,"title":"Prisma: What's the workflow?","tags":["graphql","prisma","prisma-graphql"],"text":"Title: Prisma: What's the workflow?\nTags: graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nJust started using Prisma as a way to integrate GraphQL and MySQL into a new project I am working on. It's great, I love how simply it lays things out. I have a few questions which are bothering me though regarding the workflow to when developing with Prisma. \n\nFor example:\n\nYesterday I setup the basic Prisma and GraphQL server as per the tutorial. It all worked well. I only have a single type modelled in my datamodel.graphql. \n\nThis morning I wake up and start work on another type and add that to my datamodel.graphql. Docker is running, I update the index.js with resolvers to support the new Model and it's Querys/Mutations. However, when it comes to running the system using `node ./index.js` I get an error saying it isn't aware of the new Model. I suspect the Prisma schema hasn't been refreshed/updated so i run `graphql get-schema --project prisma` but it tells me that nothing has changed. \n\nObviously I'm missing something. I am not working with Prisma in a way it would like. Can anyone illuminate me as to the order of events which have to take place for things to run smoothly?\n\nThe tutorial is great for getting you up and running but I feel like it doesn't well introduce developers into the flow of using Prisma on a day-to-day continuous development cycle. \n\nAny info/insight/links would be very useful. \n\nMany thanks,\n\nA\n\n**UPDATE**\n\nFor anyone else who has become a little lost about the workflow. Take a look at the CLI reference. It's very useful for all Prisma related tasks (not necessarily all things to do with your GraphQL server). LINK\n\n**TL;DR:** \n\nYou need to redeploy your prisma service each time the datamodel changes so that the generated prisma.graphql can be updated with new functionality to work with the DB. I ran `prisma deploy` and voila!\n\n========================================\n\nTop Answer:\nDon't forget to deploy your datamodel with `prisma deploy`.\n\nYou have a full working example here: \nhttps://github.com/alan345/naperg\n\n========================================\n\nCode:\n```text\nnode ./index.js\n```\n\n```text\ngraphql get-schema --project prisma\n```\n\n```text\nprisma deploy\n```\n\n```text\nprisma deploy\n```\n\n```text\nprisma deploy\n```\n\n```text\n// prisma.yml file\n\ndatamodel: datamodel.prisma\ngenerate:\n - generator: javascript-client\n output: ../src/generated/prisma-client\n\nhooks:\n post-deploy:\n - prisma generate\n```\n\n```text\nprisma deploy\n```\n\n```text\nprisma generate\n```\n\n```text\nprisma.yml\n```\n\n```text\nprisma generate\n```\n\n```text\nprisma deploy\n```\n\n========================================\n\nComments:\n- What tutorial did you use to get started with Prisma?\n- To make it more accurate, `prisma deploy` is to apply your changes and migrate the underlying database schema. But you also have to do `prisma generate` to update the auto-generated Prisma client so that it can expose CRUD methods for any newly added model.","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":100,"estimatedTokens":746}}668{"id":"stack-45595990","source":"stackoverflow","questionId":45595990,"title":"Are nested GraphQL queries with specific id values possible?","tags":["graphql"],"text":"Title: Are nested GraphQL queries with specific id values possible?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI've successfully built a GraphQL API which allows nested queries. Using the generic examples of Countries & States, I can perform a query like this:\n\n\r\n\r\n\n```\nquery{\r\n country(id:\"Q291bnRyeTo0Nw==\") {\r\n states {\r\n edges {\r\n node {\r\n id,\r\n name,\r\n area,\r\n population\r\n }\r\n }\r\n }\r\n }\r\n }\n```\n\n\r\n\r\n\r\n\nWhat I've discovered I can't seem to do is this:\n\n\r\n\r\n\n```\nquery{\r\n country(id:\"Q291bnRyeTo0Nw==\") {\r\n state(id:\"U3RhdGU6MzM=\") {\r\n edges {\r\n node {\r\n id,\r\n name,\r\n area,\r\n population\r\n }\r\n }\r\n }\r\n }\r\n }\n```\n\n\r\n\r\n\r\n\nMight there be a way with GraphQL to specify a specific parent and specific child in one query?\n\nRobert\n\nUpdate: For Daniel's benefit, here is my current GraphQL Query code:\n\n\r\n\r\n\n```\nfrom .models import Country as CountryModel\r\nfrom .models import State as StateModel\r\n\r\nclass Query(graphene.AbstractType):\r\n\r\n country = graphene.Field(Country, id=graphene.String())\r\n countries = graphene.List(Country)\r\n\r\n state = graphene.Field(State, id=graphene.String())\r\n states = graphene.List(State)\r\n\r\n def resolve_country(self, args, context, info):\r\n id = args.get('id')\r\n\r\n if id is not None:\r\n return CountryModel.objects.get(id=Schema.decode(id))\r\n \r\n return None\r\n\r\n def resolve_countries(self, args, context, info):\r\n return CountryModel.objects.all()\r\n\r\n def resolve_state(self, args, context, info):\r\n id = args.get('id')\r\n\r\n if id is not None:\r\n return StateModel.objects.get(id=Schema.decode(id))\r\n \r\n return None\r\n\r\n def resolve_states(self, args, context, info):\r\n return StateModel.objects.all()\n```\n\n========================================\n\nCode:\n```html\nquery{\n country(id:\"Q291bnRyeTo0Nw==\") {\n states {\n edges {\n node {\n id,\n name,\n area,\n population\n }\n }\n }\n }\n }\n```\n\n```html\nquery{\n country(id:\"Q291bnRyeTo0Nw==\") {\n state(id:\"U3RhdGU6MzM=\") {\n edges {\n node {\n id,\n name,\n area,\n population\n }\n }\n }\n }\n }\n```\n\n```html\nfrom .models import Country as CountryModel\nfrom .models import State as StateModel\n\nclass Query(graphene.AbstractType):\n\n country = graphene.Field(Country, id=graphene.String())\n countries = graphene.List(Country)\n\n state = graphene.Field(State, id=graphene.String())\n states = graphene.List(State)\n\n def resolve_country(self, args, context, info):\n id = args.get('id')\n\n if id is not None:\n return CountryModel.objects.get(id=Schema.decode(id))\n \n return None\n\n def resolve_countries(self, args, context, info):\n return CountryModel.objects.all()\n\n def resolve_state(self, args, context, info):\n id = args.get('id')\n\n if id is not None:\n return StateModel.objects.get(id=Schema.decode(id))\n \n return None\n\n def resolve_states(self, args, context, info):\n return StateModel.objects.all()\n```\n\n```text\nimport { makeExecutableSchema } from 'graphql-tools';\n\nconst countries = [\n {\n id: 1,\n name: 'bar',\n states: [\n {\n name: 'foo',\n id: 20\n }\n ]\n },\n { id: 2 },\n];\n\nconst typeDefs = `\n type Query {\n country(id: Int!): Country\n }\n type Country {\n id: Int\n state(id: Int!): State\n }\n type State {\n id: Int\n name: String\n }\n`\n\nconst resolvers = {\n Query: {\n country: (obj, args, context) => {\n return countries.find(country => country.id === args.id)\n },\n },\n Country: {\n state: (obj, args, context) => {\n return obj.states.find(state => state.id === args.id)\n },\n }\n}\n\nexport const schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n})\n```\n\n```text\nclass Country(graphene.ObjectType):\n state = graphene.Field(State,\n id=graphene.String()\n )\n # other fields\n def resolve_state(self, args, context, info):\n id = args.get('id')\n if id is not None:\n return list(filter(lambda x: x.id == id, self.states)\n return None\n```\n\n```text\ncountry\n```\n\n```text\nstate\n```\n\n```text\ncountry\n```\n\n```text\nstate\n```\n\n```text\nid\n```\n\n```text\nstate\n```\n\n```text\nstates\n```\n\n```text\nCountryModel.objects.get(id=Schema.decode(id))\n```\n\n```text\nstates\n```\n\n========================================\n\nComments:\n- I'm not familiar with GraphQL, but is there a reason you have no closing parenthesis on the state line?\n- Typo. Now corrected. Thanks.\n- Daniel, thank you for your response. I must confess, however, that I don't understand your code. I'm guessing it's in Angular? I have updated my original posting to include my current GraphQL Query code.\n- @Robert My Python's rusty but I edited the answer to include a Graphene example. You may need to modify how you fetch the data from the db to make sure the `country` object you give GraphQL to resolve includes the `states`","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":279,"estimatedTokens":1256}}669{"id":"stack-39401739","source":"stackoverflow","questionId":39401739,"title":"GraphQL error \"fields must be an object with field names as keys or a function which returns such an object.\"","tags":["javascript","node.js","graphql","graphql-js"],"text":"Title: GraphQL error \"fields must be an object with field names as keys or a function which returns such an object.\"\nTags: javascript, node.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nWhy am I getting this error from my schema file? \n\nError:\n\n```\ngraphql/jsutils/invariant.js:19\nthrow new Error(message);\n^\n\nError: Entity fields must be an object with field names as keys or a function which returns such an object.\n```\n\nError is around the `entity` prop on `PersonType`. The msg indicates that each of the fields on the `Entity` should be an object, but I am not seeing any examples like this anywhere.\n\nBasically, I am trying to get some data from the DuckDuckGo API based on a value returned from a Person query. The data returned from the API is an object with many properties, of which I am trying to use two to populate an `entity` object on my `Person` object.\n\nI have taken a look at the type system docs but don't see the answer. http://graphql.org/docs/api-reference-type-system/\n\nThis is code running on Node and being served to a GraphiQL UI.\n\nAny advice on this would be appreciated! Thanks.\n\nCode:\n\n```\nconst PersonType = new GraphQLObjectType({\nname: 'Person',\ndescription: '...',\n\nfields: () => ({\n name: {\n type: GraphQLString,\n resolve: (person) => person.name\n },\n url: {\n type: GraphQLString,\n resolve: (person) => person.url\n },\n films: {\n type: new GraphQLList(FilmType),\n resolve: (person) => person.films.map(getEntityByURL)\n },\n vehicles: {\n type: new GraphQLList(VehicleType),\n resolve: (person) => person.vehicles.map(getEntityByURL)\n },\n species: {\n type: new GraphQLList(SpeciesType),\n resolve: (person) => person.species.map(getEntityByURL)\n },\n entity: {\n type: new GraphQLObjectType(EntityType),\n resolve: (person) => getEntityByName(person.name)\n }\n})\n});\n\nconst EntityType = new GraphQLObjectType({\nname: 'Entity',\ndescription: '...',\n\nfields: () => ({\n abstract: {\n type: GraphQLString,\n resolve: (entity) => entity.Abstract\n },\n image: {\n type: GraphQLString,\n resolve: (entity) => entity.Image\n }\n})\n});\n\nfunction getEntityByName(name) {\n return fetch(`${DDG_URL}${name}`)\n .then(res => res.json())\n .then(json => json);\n}\n```\n\n**Update**\nThis is the code I am referring to that was giving the problem:\n\n```\nentity: {\n type: EntityType, // getEntityByName(person.name)\n }\n```\n\n========================================\n\nTop Answer:\nIn my case it was an empty type which caused it. \n\nChanging \n\n```\ntype SomeType {\n}\n```\n\nto\n\n```\ntype SomeType {\n # Structs can't be empty but we have no useful fields to include so here we are.\n placeholder: String\n}\n```\n\nFixed the issue for me.\n\n========================================\n\nCode:\n```text\ngraphql/jsutils/invariant.js:19\nthrow new Error(message);\n^\n\nError: Entity fields must be an object with field names as keys or a function which returns such an object.\n```\n\n```text\nconst PersonType = new GraphQLObjectType({\nname: 'Person',\ndescription: '...',\n\nfields: () => ({\n name: {\n type: GraphQLString,\n resolve: (person) => person.name\n },\n url: {\n type: GraphQLString,\n resolve: (person) => person.url\n },\n films: {\n type: new GraphQLList(FilmType),\n resolve: (person) => person.films.map(getEntityByURL)\n },\n vehicles: {\n type: new GraphQLList(VehicleType),\n resolve: (person) => person.vehicles.map(getEntityByURL)\n },\n species: {\n type: new GraphQLList(SpeciesType),\n resolve: (person) => person.species.map(getEntityByURL)\n },\n entity: {\n type: new GraphQLObjectType(EntityType),\n resolve: (person) => getEntityByName(person.name)\n }\n})\n});\n\nconst EntityType = new GraphQLObjectType({\nname: 'Entity',\ndescription: '...',\n\nfields: () => ({\n abstract: {\n type: GraphQLString,\n resolve: (entity) => entity.Abstract\n },\n image: {\n type: GraphQLString,\n resolve: (entity) => entity.Image\n }\n})\n});\n\n\n\nfunction getEntityByName(name) {\n return fetch(`${DDG_URL}${name}`)\n .then(res => res.json())\n .then(json => json);\n}\n```\n\n```text\nentity: {\n type: EntityType, // <- no need to wrap this in GraphQLObjectType\n resolve: (person) => getEntityByName(person.name)\n }\n```\n\n```text\nentity\n```\n\n```text\nPersonType\n```\n\n```text\nEntity\n```\n\n```text\nentity\n```\n\n```text\nPerson\n```\n\n```text\nentity: {\n type: EntityType, // <-- Duh!\n resolve: (person) => getEntityByName(person.name)\n }\n```\n\n```text\nEntityType\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nEntityType\n```\n\n```text\nentity\n```\n\n```text\nPersonType\n```\n\n```text\ntype SomeType {\n}\n```\n\n```text\ntype SomeType {\n # Structs can't be empty but we have no useful fields to include so here we are.\n placeholder: String\n}\n```\n\n```text\nconst PropertyType = new GraphQLObjectType({\n name: 'Property',\n feilds: () => ({ // Typo in the 'fields' property \n id: { type: GraphQLID },\n name: { type: GraphQLString },\n area: { type: GraphQLString }\n }) \n});\n```\n\n```text\nfields\n```\n\n```text\nfields\n```\n\n```text\nGraphQLObjectFields\n```\n\n========================================\n\nComments:\n- this is not a very good answer only because the question does not show the block of code the answer actually refers to, making it unable to for others. Sadly also the top answer on google.\n- For those following along, I answered my own question. The code I am referring to in the answer is in the question. Please see update.","metadata":{"transformedAt":"2026-08-18T18:32:36.074Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":284,"estimatedTokens":1382}}670{"id":"stack-54585565","source":"stackoverflow","questionId":54585565,"title":"Schema Stitching resolve conflict by adding prefix","tags":["typescript","graphql","apollo","apollo-server","graphql-tools"],"text":"Title: Schema Stitching resolve conflict by adding prefix\nTags: typescript, graphql, apollo, apollo-server, graphql-tools\nSource: Stack Overflow\n\nQuestion:\nSo I have this two schemas\n\nSchema1\n\n```\ntype Permission {\n relation: Relation\n}\n\nenum Relation {\n ONE\n TWO\n THREE\n}\n```\n\nSchema2\n\n```\ntype Permission {\n relation: Relation\n}\n\nenum Relation {\n FOUR\n FIVE\n SIX\n}\n```\n\nThe expect result is something similar to: (but I'm open to different ideas)\nThe queries I would like to make after the merge are:\n\n```\n{\n permissions{\n relation\n }\n}\n```\n\nAnd get a result like\n\n```\n\"permissions\": [\n {\n \"relation\": \"ONE\"\n },\n {\n \"relation\": \"SIX\"\n }\n]\n```\n\nor\n\n```\n\"permissions\": [\n {\n \"relation\": \"schema1ONE\"\n },\n {\n \"relation\": \"schema2SIX\"\n }\n]\n```\n\nAnd mutations like:\n\n```\nmutation{\n createPermission(\n relation: ONE\n ){\n relation\n }\n}\n\nmutation{\n createPermission(\n relation: SIX\n ){\n relation\n }\n}\n```\n\nor\n\n```\nmutation{\n createPermission(\n relation: schema1ONE\n ){\n relation\n }\n}\n\nmutation{\n createPermission(\n relation: schema2SIX\n ){\n relation\n }\n}\n```\n\nI'm trying using the `transformSchema` function on graphql-tools but can't quite figure it out correctly:\n\n```\nconst Schema1 = await getRemoteSchema('schema1_url', 'schema1');\nconst Schema2 = await getRemoteSchema('schema2_url', 'schema2');\n\nconst schemas = [Schema1, Schema2]\n\nconst schema = mergeSchemas({\n schemas: schemas,\n resolvers: {}\n});\n```\n\ngetRemoteSchema definition\n\n```\nexport const getRemoteSchema = async (uri: string, schemaName: string): Promise => {\n const httpLink = new HttpLink({ uri, fetch });\n\n const schema = await introspectSchema(httpLink);\n\n const executableSchema = makeRemoteExecutableSchema({\n schema,\n httpLink,\n });\n\n // transform schema by renaming root fields and types\n const renamedSchema = transformSchema(\n executableSchema,\n [\n new RenameTypes(name => {\n if (name == 'Relation') {\n return schemaName + name\n } else {\n return name\n }\n }),\n // new RenameRootFields((operation, name) => `${schemaName}_${name}`)\n ]\n );\n\n return renamedSchema;\n}\n```\n\nI made this glitch https://glitch.com/edit/#!/schema-stitching-conflict\nSo it's easier to see the problem.\n\n========================================\n\nTop Answer:\nCurrently I don't see an easy-to-go way to achieve your desired behaviour using **graphql-tools** because in the implementation of `mergeSchemas()` the option `onTypeConflict` was first deprecated and later removed, even though it still exists on the public interface. With that option we were able to simply pass a callback that was aware of the conflicting types and their corresponding ASTs.\n\n`transformSchema()` however, as you try to use it, will only rename the enum type names but not the enum values. You will most likely need to implement your own transformation instead of using a pre-defined one to achieve your goals. I'd like to recommend having a look at the implementation of `ConvertEnumValues` though. This might give you a better sense of how to walk and manipulate the AST to your needs when implementing your own `Transform`.\n\nFor example I'd consider an implementation which keeps track of all `GraphQlEnumTypes` that it has seen and deep merges them, if it encounters a name collision. Either you keep track using variables within module scope or using instance properties in the `Transform`. If you do the latter, don't forget to instantiate it in advance and to pass it to subsequent `tranformSchema()` calls by reference.\n\n========================================\n\nCode:\n```text\ntype Permission {\n relation: Relation\n}\n\nenum Relation {\n ONE\n TWO\n THREE\n}\n```\n\n```text\ntype Permission {\n relation: Relation\n}\n\nenum Relation {\n FOUR\n FIVE\n SIX\n}\n```\n\n```text\n{\n permissions{\n relation\n }\n}\n```\n\n```text\n\"permissions\": [\n {\n \"relation\": \"ONE\"\n },\n {\n \"relation\": \"SIX\"\n }\n]\n```\n\n```text\n\"permissions\": [\n {\n \"relation\": \"schema1ONE\"\n },\n {\n \"relation\": \"schema2SIX\"\n }\n]\n```\n\n```text\nmutation{\n createPermission(\n relation: ONE\n ){\n relation\n }\n}\n\nmutation{\n createPermission(\n relation: SIX\n ){\n relation\n }\n}\n```\n\n```text\nmutation{\n createPermission(\n relation: schema1ONE\n ){\n relation\n }\n}\n\nmutation{\n createPermission(\n relation: schema2SIX\n ){\n relation\n }\n}\n```\n\n```text\nconst Schema1 = await getRemoteSchema('schema1_url', 'schema1');\nconst Schema2 = await getRemoteSchema('schema2_url', 'schema2');\n\nconst schemas = [Schema1, Schema2]\n\nconst schema = mergeSchemas({\n schemas: schemas,\n resolvers: {}\n});\n```\n\n```text\nexport const getRemoteSchema = async (uri: string, schemaName: string): Promise<GraphQLSchema> => {\n const httpLink = new HttpLink({ uri, fetch });\n\n const schema = await introspectSchema(httpLink);\n\n const executableSchema = makeRemoteExecutableSchema({\n schema,\n httpLink,\n });\n\n // transform schema by renaming root fields and types\n const renamedSchema = transformSchema(\n executableSchema,\n [\n new RenameTypes(name => {\n if (name == 'Relation') {\n return schemaName + name\n } else {\n return name\n }\n }),\n // new RenameRootFields((operation, name) => `${schemaName}_${name}`)\n ]\n );\n\n return renamedSchema;\n}\n```\n\n```text\ntransformSchema\n```\n\n```text\nconst {\n makeExecutableSchema,\n addMockFunctionsToSchema,\n transformSchema,\n RenameTypes,\n RenameRootFields\n} = require('graphql-tools');\n\nconst schema1 = makeExecutableSchema({\n typeDefs: `\n type Permission {\n id: ID!\n text: String\n relation: Relation\n }\n\n type Query {\n permissions: [Permission]\n permission(id: ID!): Permission\n }\n\n enum Relation {\n ONE\n TWO\n THREE\n }\n `\n});\n\naddMockFunctionsToSchema({ schema: schema1 });\n\nconst renamedSchema1 = transformSchema(\n schema1,\n [\n new RenameTypes(name => {\n if (name == 'Relation' || name == 'Permission') {\n return 'schema1_' + name\n } else {\n return name\n }\n }, { renameBuiltins: false, renameScalars: true }),\n new RenameRootFields((_op, name) => {\n return name.includes('ermission') ? `schema1_${name}` : name\n })\n ]\n);\n```\n\n```text\nRenameTypes\n```\n\n```text\nRenameRootFields\n```\n\n```text\nRenameTypes\n```\n\n```text\nPermission\n```\n\n```text\nRelation\n```\n\n```text\nschema1_Permission\n```\n\n```text\nschema2_Permission\n```\n\n```text\nschema1_Relation\n```\n\n```text\nschema1_Relation\n```\n\n```text\nRenameRootFields\n```\n\n```text\npermission(id: ID!): Permission\n```\n\n```text\nschema1_permission(id: ID!): schema1_Permission\n```\n\n```text\nschema2_permission(id: ID!): schema2_Permission\n```\n\n```text\npermissions: [Permission]\n```\n\n```text\nschema1_permissions: [schema1_Permission]\n```\n\n```text\nschema2_permissions: [schema2_Permission]\n```\n\n```text\nmergeSchemas()\n```\n\n```text\nonTypeConflict\n```\n\n```text\ntransformSchema()\n```\n\n```text\nConvertEnumValues\n```\n\n```text\nTransform\n```\n\n```text\nGraphQlEnumTypes\n```\n\n```text\nTransform\n```\n\n```text\ntranformSchema()\n```\n\n========================================\n\nComments:\n- So for one part is the renaming of the types, but also the joining of the permission types","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":458,"estimatedTokens":1784}}671{"id":"stack-56102339","source":"stackoverflow","questionId":56102339,"title":"How to fix 'main GraphQL source' error at code generation using Apollo?","tags":["android","graphql","apollo"],"text":"Title: How to fix 'main GraphQL source' error at code generation using Apollo?\nTags: android, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm trying to connect Android app with GraphQL using Apollo code generation. I'm getting this type of error:\n\n```\nERROR: Value 'main GraphQL source' specified for property '$1' cannot be converted to a file.\n```\n\nI made lot of tutorials on medium, used github instructions but none of them didn't help me. To generate schema.json I used apollo and also deprecated apollo-codegen.\n\nProject-level gradle dependecies:\n\n```\ndependencies {\n classpath 'com.android.tools.build:gradle:3.4.0'\n classpath 'com.apollographql.apollo:gradle-plugin:0.4.1'\n }\n```\n\nOn app-gradle I added one line:\n\n```\napply plugin: 'com.apollographql.android'\n```\n\nI also created a folder 'graphql' in my main folder, and I put getPosts.graphql file:\n\n```\nquery allPostsQuery{\n findAllUsers{\n username\n email\n }\n }\n```\n\nThen I'm generated schema.json using (a part with my query):\n\n```\n{\n \"kind\": \"OBJECT\",\n \"name\": \"Query\",\n \"description\": \"\",\n \"fields\": [\n {\n \"name\": \"findAllUsers\",\n \"description\": \"\",\n \"args\": [],\n \"type\": {\n \"kind\": \"NON_NULL\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"LIST\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"OBJECT\",\n \"name\": \"User\",\n \"ofType\": null\n }\n }\n },\n \"isDeprecated\": false,\n \"deprecationReason\": null\n },\n {\n \"name\": \"findUser\",\n \"description\": \"\",\n \"args\": [\n {\n \"name\": \"username\",\n \"description\": \"\",\n \"type\": {\n \"kind\": \"NON_NULL\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"SCALAR\",\n \"name\": \"String\",\n \"ofType\": null\n }\n },\n \"defaultValue\": null\n }\n ],\n \"type\": {\n \"kind\": \"NON_NULL\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"OBJECT\",\n \"name\": \"User\",\n \"ofType\": null\n }\n },\n \"isDeprecated\": false,\n \"deprecationReason\": null\n }\n ],\n \"inputFields\": null,\n \"interfaces\": [],\n \"enumValues\": null,\n \"possibleTypes\": null\n },\n```\n\nSchema-generation:\n\n```\napollo-codegen introspect-schema http://localhost:1100/graphql --output schema.json\n```\n\n========================================\n\nTop Answer:\nIn Project structure(File -> Project Structure -> Project) change your Gradle plugin version to 3.3.2 and Gradle version to 4.10.1.\n\nif it still didn't work, change the Gradle versions to the older.\n\nHope it will works. Worked the same for me.\n\n========================================\n\nCode:\n```text\nERROR: Value 'main GraphQL source' specified for property '$1' cannot be converted to a file.\n```\n\n```text\ndependencies {\n classpath 'com.android.tools.build:gradle:3.4.0'\n classpath 'com.apollographql.apollo:gradle-plugin:0.4.1'\n }\n```\n\n```text\napply plugin: 'com.apollographql.android'\n```\n\n```text\nquery allPostsQuery{\n findAllUsers{\n username\n email\n }\n }\n```\n\n```text\n{\n \"kind\": \"OBJECT\",\n \"name\": \"Query\",\n \"description\": \"\",\n \"fields\": [\n {\n \"name\": \"findAllUsers\",\n \"description\": \"\",\n \"args\": [],\n \"type\": {\n \"kind\": \"NON_NULL\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"LIST\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"OBJECT\",\n \"name\": \"User\",\n \"ofType\": null\n }\n }\n },\n \"isDeprecated\": false,\n \"deprecationReason\": null\n },\n {\n \"name\": \"findUser\",\n \"description\": \"\",\n \"args\": [\n {\n \"name\": \"username\",\n \"description\": \"\",\n \"type\": {\n \"kind\": \"NON_NULL\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"SCALAR\",\n \"name\": \"String\",\n \"ofType\": null\n }\n },\n \"defaultValue\": null\n }\n ],\n \"type\": {\n \"kind\": \"NON_NULL\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"OBJECT\",\n \"name\": \"User\",\n \"ofType\": null\n }\n },\n \"isDeprecated\": false,\n \"deprecationReason\": null\n }\n ],\n \"inputFields\": null,\n \"interfaces\": [],\n \"enumValues\": null,\n \"possibleTypes\": null\n },\n```\n\n```text\napollo-codegen introspect-schema http://localhost:1100/graphql --output schema.json\n```\n\n```text\nclasspath 'com.apollographql.apollo:gradle-plugin:0.4.1'\n```\n\n```text\nclasspath 'com.apollographql.apollo:apollo-gradle-plugin:1.0.0'\n```\n\n```text\nimplementation 'com.apollographql.apollo:apollo-runtime:1.0.0'\nimplementation \"com.apollographql.apollo:apollo-android-support:1.0.0\"\n```\n\n```text\nAndroid Gradle plugin\n```\n\n```text\nGradle\n```\n\n```text\nbuild.gradle\n```\n\n```text\napollo-runtime\n```\n\n```text\napollo android support library\n```\n\n```text\nbuild.gradle\n```\n\n========================================\n\nComments:\n- In your `main` folder, move your `graphql` folder into another package. Preferably one that matches the package where your java files reside. Something like `com.example.app.graphql`\n- In folder `main` I've got: `java\\com\\example\\graphqlapollo\\MainActivity` and `graphql\\com\\example\\graphqlapollo` . It's probably correct.\n- Okay, I done what you said, and there's more generated folders, but class still not generates. I also gets a new warning: `Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'` - I didn't use compile in my gradle, I don't know from where that warning comes.\n- Lets focus on `graphql\\com\\example\\graphqlapollo` inside `main`. This is where you need to put your `.graphql` files, also your `schema.json` should be here. The new warning you are getting could be due to one of your dependencies using `compile` instead of `api`/`implementation`. Im trying to build a project that would try to replicate your issue.\n- Try following the official Apollo android guide. Seems like you are depending on a past version of the plugin. Find the docs here: github.com/apollographql/apollo-android","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":262,"estimatedTokens":1507}}672{"id":"stack-52786666","source":"stackoverflow","questionId":52786666,"title":"GraphQL, how to return type of byte[]","tags":["java","spring-boot","graphql"],"text":"Title: GraphQL, how to return type of byte[]\nTags: java, spring-boot, graphql\nSource: Stack Overflow\n\nQuestion:\nI have thumbnails saved in my database as a byte array. I can't seem to workout how to return these to the frontend clients via GraphQL. \n\nIn a standard REST approach I just send a POJO back with the bytes and I can easily render that out. \n\nHowever trying to return a `byte[]` is throwing \n\n Unable to match type definition (ListType{type=NonNullType{type=TypeName{name='Byte'}}}) with java type (class java.lang.Byte): Java class is not a List or generic type information was lost: class java.lang.Byte\n\nThe error is descriptive and tells me what's wrong, but I don't know how to solve that. \n\nMy `thumbnail.graphqls` looks like: \n\n```\ntype Thumbnail {\n id: ID!\n resource: [Byte!]\n}\n```\n\nAnd the thumbnail POJO\n\n```\npublic class Thumbnail extends BaseEntity {\n byte[] resource;\n}\n```\n\nI'm using `graphql-spring-boot-starter` on the Java side to handle things, and I think it supports `Byte` out the box, so where have I gone wrong? \n\nVery fresh to GraphQL so this could just be an obvious mistake. \n\nCheers,\n\n========================================\n\nCode:\n```text\ntype Thumbnail {\n id: ID!\n resource: [Byte!]\n}\n```\n\n```text\npublic class Thumbnail extends BaseEntity {\n byte[] resource;\n}\n```\n\n```text\nbyte[]\n```\n\n```text\nthumbnail.graphqls\n```\n\n```text\ngraphql-spring-boot-starter\n```\n\n```text\nByte\n```\n\n```text\npublic class ThumbnailResolver extends GraphQLResolver<Thumbnail> {\n public String resource(Thumbnail th) { ... }\n //or List<Integer> resource(Thumbnail th) { ... }\n //or whatever\n }\n```\n\n```text\nresource: String\n#or resource:[Int]\n#or whatever\n```\n\n```text\nscalar ByteArray\n```\n\n========================================\n\nComments:\n- I think your issue is that you try to serialize a binary array to json (I guess you return json from your controller). How do you imagine thatyour response should look like?\n- I would expect the result from GraphQL to look the same as it does from a REST request. So effectively the `byte[]` would look like a string of bytes... It's just how do I get GraphQL to accept that is a valid response type?\n- this answer doesn't provide the issue solution, it's just an part of idea","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":94,"estimatedTokens":568}}673{"id":"stack-60357247","source":"stackoverflow","questionId":60357247,"title":"Mapping multiple graphQL schema files to separate resolvers - Spring Boot","tags":["java","graphql","graphql-java"],"text":"Title: Mapping multiple graphQL schema files to separate resolvers - Spring Boot\nTags: java, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI'm finding it really difficult to separate queries from one schema file. I want to have something like this:\n\n**car.graphqls**\n\n```\ntype Query {\n car(id: ID!): Car\n}\n\ntype Car {\n id: ID!,\n name: String!\n}\n```\n\n**house.graphqls**\n\n```\ntype Query {\n house(id: ID!): House\n}\n\ntype House {\n id: ID!,\n owner: String,\n street: String\n}\n```\n\nI searched a lot but I can't find a way to write two java classes and implement `getHouse()` in one of them and `getCar()` in other.\n\n```\n@Component\npublic class CarQuery implements GraphQLQueryResolver {\n\n @Autowired\n private CarService carService;\n\n public List getCar(final int id) {\n return this.carService.getCar(id);\n }\n}\n\npublic class HouseQuery implements GraphQLQueryResolver {\n\n @Autowired\n private HouseService houseService;\n\n public List getHouse(final int id) {\n return this.houseService.getHouse(id);\n }\n}\n```\n\nI found out that the `graphql-java-tools` package which I'm using will search through the project and finds all schema files (that end with `.graphqls`), but the code which I showed above gives me this error:\n\n```\nCaused by: com.coxautodev.graphql.tools.FieldResolverError: No method found with any of the following signatures (with or without one of [interface graphql.schema.DataFetchingEnvironment] as the last argument), in priority order:\n\n com.example.polls.resolvers.CarQuery.house(~count)\n com.example.polls.resolvers.CarQuery.getHouse(~count)\n```\n\nI also found some advises that I need to have only one Root Query in schema files, and to extend all other Query types in schema files. I tried to write to `house.graphqls` something like this, but failed:\n\n```\nextend Type Query {\n house(id: ID!): House\n}\n```\n\nIs there a way to tell graphql and java what schema file I want to be mapped to which java resolver file?\n\n========================================\n\nTop Answer:\nThanks AllirionX. Your answer was helpful.\n\nI would just like to summarize final solution to all who are looking for answer how to create multiple schema files with separate query types in each of them and map those query types to different Java Components using GraphQLQueryResolver.\n\nMy Spring Boot project structure\n\nI have two schema files A.graphqls and B.graphqls.\n\n```\nA.graphqls\n---------------\ntype Person {\n id: ID!,\n name: String\n}\n\ntype Query {\n getPerson(id: Int):Person\n}\n\ntype Mutation {\n createPerson(name: String):Int\n}\n\nB.graphqls\n---------------\ntype Book {\n id: ID!,\n title: String,\n owner: Person\n}\n\nextend type Query {\n getBooks(count: Int):[Book]\n}\n\nextend type Mutation {\n deleteBook(id: Int):Int\n}\n\nschema {\n query: Query,\n mutation: Mutation\n}\n```\n\nI will explain what I learned about rules we need to about this topic (I don't guarantee that this is all necessary, but that is how I managed to get it work how I wanted it to work).\n\nThe key here is to only have one schema definition. It doesn't matter in which file (A.graphqls or B.graphqls or C.graphqls...) - In example, I added it to B.graphqls file at the bottom.\n\nAlso, you can have only one \"type Query\" definition in ONE file. In all other schema files you will need to extend that type with \"extend type Query\" (yeah, I know, it makes sense now...). In which schema file you do that main definition for Query that is not relevant. Everything in this paragraph applies to mutations also.\n\nYou can use type defined in one .graphqls file in other .graphqls file. It will get recognized. So, in this example, you can use Person type reference in B.graphqls.\n\nJava resolvers:\n\n```\nimport com.coxautodev.graphql.tools.GraphQLQueryResolver;\nimport graphql.demo.model.Person;\nimport graphql.demo.service.PersonService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\nimport java.util.List;\n\n@Component\npublic class AQuery implements GraphQLQueryResolver {\n\n @Autowired\n private PersonService personService;\n\n public Person getPerson(final int id) {\n return this.personService.getPerson(id);\n }\n}\n```\n\nAnd second one...\n\n```\n@Component\npublic class BQuery implements GraphQLQueryResolver {\n\n @Autowired\n private BookService bookService;\n\n public List getBooks(final int count) {\n return this.bookService.getBooks(count);\n }\n}\n```\n\nNames of this classes are not important. We could also have only one class that implements GraphQLQueryResolver and we could implement all query methods from both A.graphqls and B.graphqls files (getBooks() and getPerson() methods). As long as we implement all methods, it's not important in which resolver class we implemented it graphql-java will find it.\nSame applies to mutations using GraphQLMutationResolver.\n\nI have full working example (MySQL, Spring Boot, React with Apollo client) on my github, so you can check it out. There is also mysql script for generating database used in project. There is plenty of tables, but there are just for testing purposes, what is important is file structure and files I explained above. If you are not interested in client app, you can test it using graphiql, of course. \n\nhttps://github.com/dusko-dime/spring-react-graphql\n\nHope this can be helpful to someone and thanks for helping me once again :)\n\n========================================\n\nCode:\n```text\ntype Query {\n car(id: ID!): Car\n}\n\ntype Car {\n id: ID!,\n name: String!\n}\n```\n\n```text\ntype Query {\n house(id: ID!): House\n}\n\ntype House {\n id: ID!,\n owner: String,\n street: String\n}\n```\n\n```text\n@Component\npublic class CarQuery implements GraphQLQueryResolver {\n\n @Autowired\n private CarService carService;\n\n public List<Car> getCar(final int id) {\n return this.carService.getCar(id);\n }\n}\n\npublic class HouseQuery implements GraphQLQueryResolver {\n\n @Autowired\n private HouseService houseService;\n\n public List<House> getHouse(final int id) {\n return this.houseService.getHouse(id);\n }\n}\n```\n\n```text\nCaused by: com.coxautodev.graphql.tools.FieldResolverError: No method found with any of the following signatures (with or without one of [interface graphql.schema.DataFetchingEnvironment] as the last argument), in priority order:\n\n com.example.polls.resolvers.CarQuery.house(~count)\n com.example.polls.resolvers.CarQuery.getHouse(~count)\n```\n\n```text\nextend Type Query {\n house(id: ID!): House\n}\n```\n\n```text\ngetHouse()\n```\n\n```text\ngetCar()\n```\n\n```text\ngraphql-java-tools\n```\n\n```text\n.graphqls\n```\n\n```text\nhouse.graphqls\n```\n\n```text\nGraphql-java-tools\n```\n\n```text\n.graphqls\n```\n\n```text\nGraphQLQueryResolver\n```\n\n```text\nGraphQLMutationResolver\n```\n\n```text\n@Component\n```\n\n```text\n@ComponentScan\n```\n\n```text\nNo method found with any of the following signature\n```\n\n```text\nA.graphqls\n---------------\ntype Person {\n id: ID!,\n name: String\n}\n\ntype Query {\n getPerson(id: Int):Person\n}\n\ntype Mutation {\n createPerson(name: String):Int\n}\n\nB.graphqls\n---------------\ntype Book {\n id: ID!,\n title: String,\n owner: Person\n}\n\nextend type Query {\n getBooks(count: Int):[Book]\n}\n\nextend type Mutation {\n deleteBook(id: Int):Int\n}\n\nschema {\n query: Query,\n mutation: Mutation\n}\n```\n\n```text\nimport com.coxautodev.graphql.tools.GraphQLQueryResolver;\nimport graphql.demo.model.Person;\nimport graphql.demo.service.PersonService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\nimport java.util.List;\n\n@Component\npublic class AQuery implements GraphQLQueryResolver {\n\n @Autowired\n private PersonService personService;\n\n public Person getPerson(final int id) {\n return this.personService.getPerson(id);\n }\n}\n```\n\n```text\n@Component\npublic class BQuery implements GraphQLQueryResolver {\n\n @Autowired\n private BookService bookService;\n\n public List<Book> getBooks(final int count) {\n return this.bookService.getBooks(count);\n }\n}\n```\n\n========================================\n\nComments:\n- Does your project work with a single graphqls file? If not, you should make sure it does first.\n- Yes, it works if I put all queries in one schema file and if I keep only one GraphQLQueryResolver with all required methods. I find it really strange how little documentation and examples I could find related to this topic. All examples usually focus on one schema file. Can't find nothing on two schema files and I think it will be really useful to be able to split queries on multiple schema files. Projects can get really big and it would be not convenient to keep it all in one schema file.\n- You said it works with one schema file and one big resolver, but does it work with one schema file and several small resolvers? That's how my graphql project is setup, so we should be able to make that work. From the logs, it looks like graphql-java-tools is parsing your graphqls file but cannot find your HouseQuery resolver.\n- @DulleX Did you find the solution? I am stuck with similar issue.\n- @Saloo Unfortunately, No. I was just doing research on graphql with Spring and I gave up after couple of days, because I could not make it work with more schema files and more resolvers and I can't see reason to get more into it, because I think that, on larger projects, code maintenance will be impossible with one schema file and one resolver.\n- @AllirionX I think I was not able to make it work even with one schema and more resolvers. I would really appreciate if someone in the future who read this question can provide some example for multiple schema files or multiple resolvers. I am pretty sure it can be done, but can't figure how.\n- @DulleX I know for sure that multiple resolver files should work. In your case, it probably doesn't because you forgot the Component annotation on the HouseQuery class. Once you have this sorted, having multiple schema files should be straight forward. See this question/answer for guidance stackoverflow.com/questions/56856688/…","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":374,"estimatedTokens":2495}}674{"id":"stack-57649608","source":"stackoverflow","questionId":57649608,"title":"graphql error Sub selection required for type object of field Query","tags":["java","graphql"],"text":"Title: graphql error Sub selection required for type object of field Query\nTags: java, graphql\nSource: Stack Overflow\n\nQuestion:\nI am getting following error while invoking GraphQL Query in java application -\n\n \"description\": \"Sub selection required for type Account of field\n accountQuery\",\n \"validationErrorType\": \"SubSelectionRequired\",\n \"queryPath\": [\n \"accountQuery\"\n ],\n\nHere is my schema - \n\n schema { query: Query }\n\n \n type Query { accountQuery(nbr: String): Account }\n\n \n type Account { \nnbr: String \n name: String ... \n}\n\nI have Account POJO defined and i am calling a Service in the backend based on the nbr value passed which is working fine.\n\nHere is the rest request i am sending - \n\n { accountQuery(nbr: \"123\") }\n\nIs the error due to missing id field and if so how do i mark \"nbr\" field as id ?\n\n========================================\n\nCode:\n```text\n{ accountQuery(nbr: \"123\") {name, nbr}}\n```\n\n```text\nAccount\n```\n\n```text\nselection set\n```\n\n========================================\n\nComments:\n- This was the problem, Thanks.","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":54,"estimatedTokens":261}}675{"id":"stack-50042878","source":"stackoverflow","questionId":50042878,"title":"ValidationError FieldUndefined SPQR GraphQL","tags":["java","graphql","graphql-java","graphql-spqr"],"text":"Title: ValidationError FieldUndefined SPQR GraphQL\nTags: java, graphql, graphql-java, graphql-spqr\nSource: Stack Overflow\n\nQuestion:\nI am getting the following and cant seem to find an answer.\n\n```\nError [ValidationError{validationErrorType=FieldUndefined, queryPath=[find_by_id], message=Validation error of type FieldUndefined: Field 'find_by_id' in type 'Query' is undefined @ 'find_by_id', locations=[SourceLocation{line=1, column=2}], description='Field 'find_by_id' in type 'Query' is undefined'}]\n```\n\nMy Code.\n\nQuery\n\n```\n@GraphQLQuery(name = \"find_by_id\")\npublic Event findById(@GraphQLArgument(name = \"id\") Long id) {\n```\n\nSchema Gen\n\n```\n@EJB\nprivate EventFacade eventFacade; // Normal stateless bean \n\nGraphQLSchema guestSchema = new GraphQLSchemaGenerator()\n .withOperationsFromSingleton(eventFacade)\n .withValueMapperFactory(new JacksonValueMapperFactory())\n .withDefaults()\n .generate();\n\nGraphQL graphQL = GraphQL.newGraphQL(guestSchema).build();\n```\n\nCode to Execute\n\n```\nString query = \"{find_by_id (id: 1){eventName}}\";\nExecutionResult result = graphQL.execute(query);\n```\n\nUsing the SPQR lib \n\nEvent POJO is basic with eventName as a String and an id from the abstract (Parent) class. Entity class is in a different jar (Entity Jar). Code to execute Query and build schema are in the EJB Jar.\n\nAny help / indication where i went wrong will be appreciated.\n\n**UPDATE**\nCreated a git issue to help solve Git Issue\n\n========================================\n\nTop Answer:\nI believe you must change this\n String query = \"{find_by_id (id: 1){eventName}}\";\nto\n String query = \"\\\"query\\\": {find_by_id (id: 1){eventName}}\";\n\n========================================\n\nCode:\n```text\nError [ValidationError{validationErrorType=FieldUndefined, queryPath=[find_by_id], message=Validation error of type FieldUndefined: Field 'find_by_id' in type 'Query' is undefined @ 'find_by_id', locations=[SourceLocation{line=1, column=2}], description='Field 'find_by_id' in type 'Query' is undefined'}]\n```\n\n```text\n@GraphQLQuery(name = \"find_by_id\")\npublic Event findById(@GraphQLArgument(name = \"id\") Long id) {\n```\n\n```text\n@EJB\nprivate EventFacade eventFacade; // Normal stateless bean \n\nGraphQLSchema guestSchema = new GraphQLSchemaGenerator()\n .withOperationsFromSingleton(eventFacade)\n .withValueMapperFactory(new JacksonValueMapperFactory())\n .withDefaults()\n .generate();\n\nGraphQL graphQL = GraphQL.newGraphQL(guestSchema).build();\n```\n\n```text\nString query = \"{find_by_id (id: 1){eventName}}\";\nExecutionResult result = graphQL.execute(query);\n```\n\n```text\nGraphQLSchema schema = new GraphQLSchemaGenerator()\n .withBasePackages(basePackages)\n .withTypeTransformer(new DefaultTypeTransformer(true, true))\n .withOperationsFromSingleton(eventFacade).generate();\n```\n\n```text\n\"{Event(id: 1){eventName}}\"\n```\n\n========================================\n\nComments:\n- The lib i am using does not require it. See example from the lib\n- Getting the following if i add it graphql.GraphQL - Query failed to parse : '\"query\": {find_by_id (id: 1){eventName}}'\n- Tried it and it does not work. I believe the first part is only the name of the query and not the class / type\n- stackoverflow.com/questions/48968896/… did you check this answer gives a better understanding of how the query should be formed??\n- im not sure that you read through the lib. It will explain most of what im trying to do. Also not building my own schema as the lib are doing it for me\n- Is this required .withBasePackages(basePackages)?\n- No it is not required, also something I should have mentioned in my answer. You need to make sure `.withTypeTransformer` is before `.withOperationsFromSingleton`.","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":110,"estimatedTokens":936}}676{"id":"stack-56045957","source":"stackoverflow","questionId":56045957,"title":"Problem deploying Apollo Express server to Heroku: \"GET query missing.\"","tags":["node.js","heroku","graphql","apollo","apollo-server"],"text":"Title: Problem deploying Apollo Express server to Heroku: \"GET query missing.\"\nTags: node.js, heroku, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI wrote a simple GraphQL server using Apollo Express and deployed it to Heroku. After some messing around with Procfiles and the like, it built OK.\n\nWhen I hit the main URL https://limitless-atoll-59109.herokuapp.com I get the error\n\n Cannot GET /\n\nOK, then I thought the Express server must just be looking for a get on the graphql endpoint. But when I hit https://limitless-atoll-59109.herokuapp.com/graphql I get\n\n GET query missing.\n\nDo I need to include a port in the url? I've got the port set correctly in the code \n\n```\nconst PORT = process.env.PORT || 4000\n\n app.listen({port: PORT}, () =>\n\n console.log(`Server ready at http://localhost:${PORT}${server.graphqlPath}`)\n );\n```\n\nbut I don't think I need to include it when accessing the server on Heroku, do I?\n\nFor what it's worth, this is the error in the error logs\n\n 019-05-08T17:07:41.492327+00:00 heroku[router]: at=info method=GET\n path=\"/graphql\" host=limitless-atoll-59109.herokuapp.com\n request_id=b6171835-aac4-4b45-8a7b-daebbb3167ed fwd=\"139.47.21.74\"\n dyno=web.1 connect=0ms service=900ms status=400 bytes=196\n protocol=https\n\nThanks for any help!\n\n========================================\n\nTop Answer:\nIf you are using apollo server you can just enable it in production:\n\n```\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n introspection: true,\n playground: true,\n});\n```\n\n========================================\n\nCode:\n```text\nconst PORT = process.env.PORT || 4000\n\n app.listen({port: PORT}, () =>\n\n console.log(`Server ready at http://localhost:${PORT}${server.graphqlPath}`)\n );\n```\n\n```text\n/graphql\n```\n\n```text\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n introspection: true,\n playground: true,\n});\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":76,"estimatedTokens":470}}677{"id":"stack-48735707","source":"stackoverflow","questionId":48735707,"title":"graphql role based authorization","tags":["graphql","apollo","express-graphql"],"text":"Title: graphql role based authorization\nTags: graphql, apollo, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm new to GraphQL and going to build a solution using GraphQL.\n\nEverything looks cool but just concerned on how to implement the role based authorization inside GraphQL server (I'm considering using GraphQL.js/ apollo server)\n\nI will have a users table which contains all users. Inside the users table there's a roles field which contains the roles of the particular user. The queries and mutations will be granted based on the roles of the user.\n\nHow can I implement this structure? \n\nTHANKS!\n\n========================================\n\nTop Answer:\nFor apollo server developers, there have generally been 3 ways to implement authorization in Graphql:\n\n**Schema-based**: Adding a directive to the graphql types and fields you want to protect\n\n**Middleware-based**: Adding middleware (code that runs before and after your graphql resolvers have executed). This is the approach used by graphql-shield and other authorization libraries built on top of graphql-middleware.\n\n**Business logic layer**: This is the most primitive but granular approach. Basically, the function that returns data (i.e. a database query, etc) would implement its own permissions/authorization check.\n\n### Schema-based\n\n- With **schema-based authorization**, we would define custom schema directives and apply them wherever it is applicable.\n\nSource: https://www.apollographql.com/docs/graphql-tools/schema-directives/\n\n//schema.gql\n\n```\ndirective @auth(\n requires: Role = ADMIN,\n) on OBJECT | FIELD_DEFINITION\n\nenum Role {\n ADMIN\n REVIEWER\n USER\n UNKNOWN\n}\n\ntype User @auth(requires: USER) {\n name: String\n banned: Boolean @auth(requires: ADMIN)\n canPost: Boolean @auth(requires: REVIEWER)\n}\n```\n\n// main.js\n\n```\nclass AuthDirective extends SchemaDirectiveVisitor {\n visitObject(type) {\n this.ensureFieldsWrapped(type);\n type._requiredAuthRole = this.args.requires;\n }\n\n visitFieldDefinition(field, details) {\n this.ensureFieldsWrapped(details.objectType);\n field._requiredAuthRole = this.args.requires;\n }\n\n ensureFieldsWrapped(objectType) {\n if (objectType._authFieldsWrapped) return;\n objectType._authFieldsWrapped = true;\n\n const fields = objectType.getFields();\n\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n const { resolve = defaultFieldResolver } = field;\n field.resolve = async function (...args) {\n // Get the required Role from the field first, falling back\n // to the objectType if no Role is required by the field:\n const requiredRole =\n field._requiredAuthRole ||\n objectType._requiredAuthRole;\n\n if (! requiredRole) {\n return resolve.apply(this, args);\n }\n\n const context = args[2];\n const user = await getUser(context.headers.authToken);\n if (! user.hasRole(requiredRole)) {\n throw new Error(\"not authorized\");\n }\n\n return resolve.apply(this, args);\n };\n });\n }\n}\n\nconst schema = makeExecutableSchema({\n typeDefs,\n schemaDirectives: {\n auth: AuthDirective,\n authorized: AuthDirective,\n authenticated: AuthDirective\n }\n});\n```\n\n### Middleware-based\n\n- With **middleware-based authorization**, most libraries will intercept the resolver execution. The below example is specific to `graphql-shield` on `apollo-server`.\n\nGraphql-shield source: https://github.com/maticzav/graphql-shield\n\nImplementation for apollo-server source: https://github.com/apollographql/apollo-server/pull/1799#issuecomment-456840808\n\n// shield.js\n\n```\nimport { shield, rule, and, or } from 'graphql-shield'\n\nconst isAdmin = rule()(async (parent, args, ctx, info) => {\n return ctx.user.role === 'admin'\n})\n\nconst isEditor = rule()(async (parent, args, ctx, info) => {\n return ctx.user.role === 'editor'\n})\n\nconst isOwner = rule()(async (parent, args, ctx, info) => {\n return ctx.user.items.some(id => id === parent.id)\n})\n\nconst permissions = shield({\n Query: {\n users: or(isAdmin, isEditor),\n },\n Mutation: {\n createBlogPost: or(isAdmin, and(isOwner, isEditor)),\n },\n User: {\n secret: isOwner,\n },\n})\n```\n\n// main.js\n\n```\nconst { ApolloServer, makeExecutableSchema } = require('apollo-server');\nconst { applyMiddleware } = require('graphql-middleware');\nconst shieldMiddleware = require('shieldMiddleware');\n\nconst schema = applyMiddleware(\n makeExecutableSchema({ typeDefs: '...', resolvers: {...} }),\n shieldMiddleware,\n);\nconst server = new ApolloServer({ schema });\napp.listen({ port: 4000 }, () => console.log('Ready!'));\n```\n\n### Business logic layer\n\n- With **business logic layer authorization**, we would add permission checks inside our resolver logic. It is the most tedious because we would have to write authorization-checks on every resolver. The link below recommends placing the authorization logic in the business logic layer (i.e. sometimes called 'Models' or 'Application logic' or 'data-returning function').\n\nSource: https://graphql.org/learn/authorization/\n\n### Option 1: Auth logic in resolver\n\n// resolvers.js\n\n```\nconst Query = {\n users: function(root, args, context, info){\n if (context.permissions.view_users) {\n return ctx.db.query(`SELECT * FROM users`)\n }\n throw new Error('Not Authorized to view users')\n }\n}\n```\n\n### Option 2 (Recommended): Separating out authorization logic from resolver\n\n// resolver.js\n\n```\nconst Authorize = require('authorization.js')\n\nconst Query = {\n users: function(root, args, context, info){\n Authorize.viewUsers(context)\n }\n}\n```\n\n// authorization.js\n\n```\nconst validatePermission = (requiredPermission, context) => {\n return context.permissions[requiredPermission] === true\n}\n\nconst Authorize = {\n viewUsers = function(context){\n const requiredPermission = 'ALLOW_VIEW_USERS'\n\n if (validatePermission(requiredPermission, context)) {\n return context.db.query('SELECT * FROM users')\n }\n\n throw new Error('Not Authorized to view users')\n },\n viewCars = function(context){\n const requiredPermission = 'ALLOW_VIEW_CARS';\n\n if (validatePermission(requiredPermission, context)){\n return context.db.query('SELECT * FROM cars')\n }\n\n throw new Error('Not Authorized to view cars')\n }\n}\n```\n\n========================================\n\nCode:\n```text\nexport const isAdmin = async ({ id }) => {\n try {\n const exists = await ctx.db.exists.User({\n id: userId,\n role: 'ADMIN',\n });\n\n return exists\n } catch (err) {\n console.log(err);\n return false\n }\n}\n```\n\n```text\nconst resolvers = {\n ...your queries and mutations\n}\n\nconst permissions = {\n Query: {\n myQuery: isAdmin\n }\n}\n\nexport default shield(resolvers, permissions);\n```\n\n```text\nisAdmin\n```\n\n```text\ndirective @auth(\n requires: Role = ADMIN,\n) on OBJECT | FIELD_DEFINITION\n\nenum Role {\n ADMIN\n REVIEWER\n USER\n UNKNOWN\n}\n\ntype User @auth(requires: USER) {\n name: String\n banned: Boolean @auth(requires: ADMIN)\n canPost: Boolean @auth(requires: REVIEWER)\n}\n```\n\n```text\nclass AuthDirective extends SchemaDirectiveVisitor {\n visitObject(type) {\n this.ensureFieldsWrapped(type);\n type._requiredAuthRole = this.args.requires;\n }\n\n visitFieldDefinition(field, details) {\n this.ensureFieldsWrapped(details.objectType);\n field._requiredAuthRole = this.args.requires;\n }\n\n ensureFieldsWrapped(objectType) {\n if (objectType._authFieldsWrapped) return;\n objectType._authFieldsWrapped = true;\n\n const fields = objectType.getFields();\n\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n const { resolve = defaultFieldResolver } = field;\n field.resolve = async function (...args) {\n // Get the required Role from the field first, falling back\n // to the objectType if no Role is required by the field:\n const requiredRole =\n field._requiredAuthRole ||\n objectType._requiredAuthRole;\n\n if (! requiredRole) {\n return resolve.apply(this, args);\n }\n\n const context = args[2];\n const user = await getUser(context.headers.authToken);\n if (! user.hasRole(requiredRole)) {\n throw new Error(\"not authorized\");\n }\n\n return resolve.apply(this, args);\n };\n });\n }\n}\n\nconst schema = makeExecutableSchema({\n typeDefs,\n schemaDirectives: {\n auth: AuthDirective,\n authorized: AuthDirective,\n authenticated: AuthDirective\n }\n});\n```\n\n```text\nimport { shield, rule, and, or } from 'graphql-shield'\n\nconst isAdmin = rule()(async (parent, args, ctx, info) => {\n return ctx.user.role === 'admin'\n})\n\nconst isEditor = rule()(async (parent, args, ctx, info) => {\n return ctx.user.role === 'editor'\n})\n\nconst isOwner = rule()(async (parent, args, ctx, info) => {\n return ctx.user.items.some(id => id === parent.id)\n})\n\nconst permissions = shield({\n Query: {\n users: or(isAdmin, isEditor),\n },\n Mutation: {\n createBlogPost: or(isAdmin, and(isOwner, isEditor)),\n },\n User: {\n secret: isOwner,\n },\n})\n```\n\n```text\nconst { ApolloServer, makeExecutableSchema } = require('apollo-server');\nconst { applyMiddleware } = require('graphql-middleware');\nconst shieldMiddleware = require('shieldMiddleware');\n\nconst schema = applyMiddleware(\n makeExecutableSchema({ typeDefs: '...', resolvers: {...} }),\n shieldMiddleware,\n);\nconst server = new ApolloServer({ schema });\napp.listen({ port: 4000 }, () => console.log('Ready!'));\n```\n\n```text\nconst Query = {\n users: function(root, args, context, info){\n if (context.permissions.view_users) {\n return ctx.db.query(`SELECT * FROM users`)\n }\n throw new Error('Not Authorized to view users')\n }\n}\n```\n\n```text\nconst Authorize = require('authorization.js')\n\nconst Query = {\n users: function(root, args, context, info){\n Authorize.viewUsers(context)\n }\n}\n```\n\n```text\nconst validatePermission = (requiredPermission, context) => {\n return context.permissions[requiredPermission] === true\n}\n\nconst Authorize = {\n viewUsers = function(context){\n const requiredPermission = 'ALLOW_VIEW_USERS'\n\n if (validatePermission(requiredPermission, context)) {\n return context.db.query('SELECT * FROM users')\n }\n\n throw new Error('Not Authorized to view users')\n },\n viewCars = function(context){\n const requiredPermission = 'ALLOW_VIEW_CARS';\n\n if (validatePermission(requiredPermission, context)){\n return context.db.query('SELECT * FROM cars')\n }\n\n throw new Error('Not Authorized to view cars')\n }\n}\n```\n\n```text\ngraphql-shield\n```\n\n```text\napollo-server\n```\n\n========================================\n\nComments:\n- There are some limitations to graphql-shield, in that it tends to block/kill the entire query if any single permission fails. For example, the available functionality is `allow / deny`. It (so far) hasn't been able to `allowSome`. For example, if some permissions pass and some fail, it can't selectively allow parts of the query to succeed.","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":437,"estimatedTokens":2695}}678{"id":"stack-57372259","source":"stackoverflow","questionId":57372259,"title":"How to upload files with graphql-java?","tags":["java","file-upload","graphql","graphql-java","graphql-java-tools"],"text":"Title: How to upload files with graphql-java?\nTags: java, file-upload, graphql, graphql-java, graphql-java-tools\nSource: Stack Overflow\n\nQuestion:\nI can't find out how to upload files if i use graphql-java, can someone show me a demo? I will be appreciated!\n\nreference : https://github.com/graphql-java-kickstart/graphql-java-tools/issues/240\n\nI tried it in springboot by using graphql-java-kickstart graphql-java-tools, but it didn't work\n\n```\n@Component\npublic class FilesUpload implements GraphQLMutationResolver {\n\n public Boolean testMultiFilesUpload(List parts, DataFetchingEnvironment env) {\n // get file parts from DataFetchingEnvironment, the parts parameter is not used\n List attchmentParts = env.getArgument(\"files\");\n System.out.println(attchmentParts);\n return true;\n }\n}\n```\n\nthis is my schema\n\n```\ntype Mutation {\n testSingleFileUpload(file: Upload): UploadResult\n}\n```\n\nI expect this resolver can print attchmentParts,so i can get the file part.\n\n========================================\n\nTop Answer:\nThe main problem is that `graphql-java-tools` might have issues to do the field mapping for resolvers that contain fields of not basic types like `List`, `String`, `Integer`, `Boolean`, etc... \n\nWe solved this issue by just creating our own custom scalar that is basically like `ApolloScalar.Upload`. But instead of returning an object of the type `Part`, we return our own resolver type `FileUpload` which contains the contentType as `String` and the inputStream as `byte[]`, then the field mapping works and we can read the `byte[]` within the resolver.\n\nFirst, set up the new type to be used in the resolver:\n\n```\npublic class FileUpload {\n private String contentType;\n private byte[] content;\n\n public FileUpload(String contentType, byte[] content) {\n this.contentType = contentType;\n this.content = content;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n public byte[] getContent() {\n return content;\n }\n}\n```\n\nThen we make a custom scalar that looks pretty much like `ApolloScalars.Upload`, but returns our own resolver type `FileUpload`:\n\n```\npublic class MyScalars {\n public static final GraphQLScalarType FileUpload = new GraphQLScalarType(\n \"FileUpload\",\n \"A file part in a multipart request\",\n new Coercing() {\n\n @Override\n public Void serialize(Object dataFetcherResult) {\n throw new CoercingSerializeException(\"Upload is an input-only type\");\n }\n\n @Override\n public FileUpload parseValue(Object input) {\n if (input instanceof Part) {\n Part part = (Part) input;\n try {\n String contentType = part.getContentType();\n byte[] content = new byte[part.getInputStream().available()];\n part.delete();\n return new FileUpload(contentType, content);\n\n } catch (IOException e) {\n throw new CoercingParseValueException(\"Couldn't read content of the uploaded file\");\n }\n } else if (null == input) {\n return null;\n } else {\n throw new CoercingParseValueException(\n \"Expected type \" + Part.class.getName() + \" but was \" + input.getClass().getName());\n }\n }\n\n @Override\n public FileUpload parseLiteral(Object input) {\n throw new CoercingParseLiteralException(\n \"Must use variables to specify Upload values\");\n }\n });\n}\n```\n\nIn the resolver, you would now be able to get the file from the resolver arguments:\n\n```\npublic class FileUploadResolver implements GraphQLMutationResolver {\n\n public Boolean uploadFile(FileUpload fileUpload) {\n\n String fileContentType = fileUpload.getContentType();\n byte[] fileContent = fileUpload.getContent();\n\n // Do something in order to persist the file :)\n\n return true;\n }\n}\n```\n\nIn the schema, you declare it like:\n\n```\nscalar FileUpload\n\ntype Mutation {\n uploadFile(fileUpload: FileUpload): Boolean\n}\n```\n\nLet me know if it doesn't work for you :)\n\n========================================\n\nCode:\n```text\n@Component\npublic class FilesUpload implements GraphQLMutationResolver {\n\n public Boolean testMultiFilesUpload(List<Part> parts, DataFetchingEnvironment env) {\n // get file parts from DataFetchingEnvironment, the parts parameter is not used\n List<Part> attchmentParts = env.getArgument(\"files\");\n System.out.println(attchmentParts);\n return true;\n }\n}\n```\n\n```text\ntype Mutation {\n testSingleFileUpload(file: Upload): UploadResult\n}\n```\n\n```text\n@Configuration\npublic class GraphqlConfig {\n\n @Bean\n public GraphQLScalarType uploadScalarDefine() {\n return ApolloScalars.Upload;\n } \n}\n```\n\n```text\ntype Mutation {\n testMultiFilesUpload(files: [Upload!]!): Boolean\n}\n```\n\n```text\npublic Boolean testMultiFilesUpload(List<Part> parts, DataFetchingEnvironment env) {\n // get file parts from DataFetchingEnvironment, the parts parameter is not use\n List<Part> attachmentParts = env.getArgument(\"files\");\n int i = 1;\n for (Part part : attachmentParts) {\n String uploadName = \"copy\" + i;\n try {\n part.write(\"your path:\" + uploadName);\n } catch (IOException e) {\n e.printStackTrace();\n }\n i++;\n }\n return true; \n }\n}\n```\n\n```text\npublic class PartDeserializer extends JsonDeserializer<Part> {\n\n @Override\n public Part deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { \n return null;\n }\n}\n```\n\n```text\n@Bean\npublic ObjectMapper objectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);\n SimpleModule module = new SimpleModule();\n module.addDeserializer(Part.class, new PartDeserializer());\n objectMapper.registerModule(module);\n return objectMapper;\n}\n```\n\n```text\noperations\n\n{ \"query\": \"mutation($files: [Upload!]!) {testMultiFilesUpload(files:$files)}\", \"variables\": {\"files\": [null,null] } }\n\nmap\n\n{ \"file0\": [\"variables.files.0\"] , \"file1\":[\"variables.files.1\"]}\n\nfile0\n\nyour file\n\nfile1\n\nyour file\n```\n\n```text\nscalar Upload\n```\n\n```text\njavax.servlet.http.Part\n```\n\n```text\nList<Part> parts\n```\n\n```text\npublic class FileUpload {\n private String contentType;\n private byte[] content;\n\n public FileUpload(String contentType, byte[] content) {\n this.contentType = contentType;\n this.content = content;\n }\n\n public String getContentType() {\n return contentType;\n }\n\n public byte[] getContent() {\n return content;\n }\n}\n```\n\n```text\npublic class MyScalars {\n public static final GraphQLScalarType FileUpload = new GraphQLScalarType(\n \"FileUpload\",\n \"A file part in a multipart request\",\n new Coercing<FileUpload, Void>() {\n\n @Override\n public Void serialize(Object dataFetcherResult) {\n throw new CoercingSerializeException(\"Upload is an input-only type\");\n }\n\n @Override\n public FileUpload parseValue(Object input) {\n if (input instanceof Part) {\n Part part = (Part) input;\n try {\n String contentType = part.getContentType();\n byte[] content = new byte[part.getInputStream().available()];\n part.delete();\n return new FileUpload(contentType, content);\n\n } catch (IOException e) {\n throw new CoercingParseValueException(\"Couldn't read content of the uploaded file\");\n }\n } else if (null == input) {\n return null;\n } else {\n throw new CoercingParseValueException(\n \"Expected type \" + Part.class.getName() + \" but was \" + input.getClass().getName());\n }\n }\n\n @Override\n public FileUpload parseLiteral(Object input) {\n throw new CoercingParseLiteralException(\n \"Must use variables to specify Upload values\");\n }\n });\n}\n```\n\n```text\npublic class FileUploadResolver implements GraphQLMutationResolver {\n\n public Boolean uploadFile(FileUpload fileUpload) {\n\n String fileContentType = fileUpload.getContentType();\n byte[] fileContent = fileUpload.getContent();\n\n // Do something in order to persist the file :)\n\n\n return true;\n }\n}\n```\n\n```text\nscalar FileUpload\n\ntype Mutation {\n uploadFile(fileUpload: FileUpload): Boolean\n}\n```\n\n```text\ngraphql-java-tools\n```\n\n```text\nList\n```\n\n```text\nString\n```\n\n```text\nInteger\n```\n\n```text\nBoolean\n```\n\n```text\nApolloScalar.Upload\n```\n\n```text\nPart\n```\n\n```text\nFileUpload\n```\n\n```text\nString\n```\n\n```text\nbyte[]\n```\n\n```text\nbyte[]\n```\n\n```text\nApolloScalars.Upload\n```\n\n```text\nFileUpload\n```\n\n```text\npublic class FileUploadMapper implements TypeMapper {\n\n @Override\n public GraphQLOutputType toGraphQLType(\n final AnnotatedType javaType, final OperationMapper operationMapper,\n final Set<Class<? extends TypeMapper>> mappersToSkip, final BuildContext buildContext) {\n return MyScalars.FileUpload;\n }\n\n @Override\n public GraphQLInputType toGraphQLInputType(\n final AnnotatedType javaType, final OperationMapper operationMapper,\n final Set<Class<? extends TypeMapper>> mappersToSkip, final BuildContext buildContext) {\n return MyScalars.FileUpload;\n }\n\n @Override\n public boolean supports(final AnnotatedType type) {\n return type.getType().equals(FileUpload.class); //class of your fileUpload POJO from the previous answer\n }\n}\n```\n\n```text\npublic GraphQLSchema schema(GraphQLSchemaGenerator schemaGenerator) {\n return schemaGenerator\n .withTypeMappers(new FileUploadMapper()) //add this line\n .generate();\n }\n```\n\n```text\n@GraphQLMutation(name = \"fileUpload\")\n public void fileUpload( \n @GraphQLArgument(name = \"file\") FileUpload fileUpload //type here must be the POJO.class referenced in your TypeMapper\n ) {\n //do something with the byte[] from fileUpload.getContent();\n return;\n }\n```\n\n```text\ntype Mutation{ \n uploadCSV(filedatabase64: String!): Boolean\n}\n```\n\n```text\npublic DataFetcher<Boolean> uploadCSV() { \n return dataFetchingEnvironment -> {\n String input= dataFetchingEnvironment.getArgument(\"filedatabase64\");\n byte[] bytes = Base64.getDecoder().decode(input);\n //in my case is textfile:\n String strCSV = new String(bytes);\n //....\n return true;\n };\n}\n```\n\n```text\nimport requests\nimport base64\nimport json\n\nwith open('myfile.csv', 'r',encoding='utf-8') as file:\n content = file.read().rstrip()\nfile.close()\n \nbase64data = base64.b64encode(content.encode()).decode()\nurl = 'https://www.misite/graphql/'\nquery = \"mutation{uploadCSV(filedatabase64:\\\"\"+base64data+\"\\\")}\"\nr = requests.post(url, json={'query': query})\nprint(\"response \" + r.status_code + \" \" + r.text)\n```\n\n========================================\n\nComments:\n- Please check this : stackoverflow.com/questions/58846714/… what I'm doing wrong?\n- @Val Bonn you can check out my solution\n- To avoid global ObjectMapper overriding (which is not very good btw, as it could bring side effects where you don't expect :D ) you can better register this bean with same configuration: @Bean public PerFieldObjectMapperProvider perFieldObjectMapperProvider() {}\n- @SergeiDubinin is this outdated by now? I am trying to implement this answer with the `PerFieldObjectMapperProvider` but I can't get it to work.\n- @stereo I was able to make it working, but it wasn't great to use as graphql always converts data to JSON and vice versa and I changed that approach. I recommend you to upload files before submitting the data, so before submitting your mutation you already have URL to an uploaded file. It's much better\n- @stereo This anwser has been 2 yearsοΌI don't remember some detail, but what I can tell you is that we can now using Netflix DGS Graphql Framework: netflix.github.io/dgs which already implement file upload with graphql. you can find file upload doc here: netflix.github.io/dgs/advanced/file-uploads\n- yes,your solution did work for me, but there is a problem : upload file through graphql we can't delete the temp file that generate by graphql in tomcat tmp directory and i didn't solve this problem yet . Did you meet this problem?\n- Good call, but itβs not directly related to GraphQL I assume but to Part and the Java Servlet API. I think it has to do with the InputStream is not getting closed. If thatβs the case, you should be able to close it within the scalar right after declaration of the `byte[] content` variable. Check this thread stackoverflow.com/questions/31741477/…\n- I updated my code example and added `part.delete()`, havenβt run the code yet, but should be right :) Please let me know.\n- i use part.delete() in my try catch finally block, but it didn't work. Actually, part.delete() didn't delete temp file for us. And like you say the reason can be the InputStream is not getting closed.\n- 3 notes here 1. You are creating an empty array, there should be `byte[] content = inputStream.readAllBytes();` 2. Temporary files are deleted even without the `part.delete();` 3. You shouldn't read all bytes at once but you should only store `InputStream` in `FileUpload` (imagine 10 GB file)\n- Can you delete the tmp file after process the uploaded file?","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":476,"estimatedTokens":3309}}679{"id":"stack-56924857","source":"stackoverflow","questionId":56924857,"title":"How to handle Apollo Graphql query error in Vue.JS?","tags":["graphql","vue-apollo"],"text":"Title: How to handle Apollo Graphql query error in Vue.JS?\nTags: graphql, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI am using Vue.js with Vue-Apollo and trying to fetch shared member list using query. I am using the graphQL service in backend.\n\nI am using apollo 'error' function to handle GraphQL error. When the request is made with invalid input, I can see the errors in the network tab, I can see the JSON for the custom errors messages. But I can't console the errors in 'error' function.\n\nHere is the apollo query that is used to fetch shared member list -\n\n```\napollo: {\n sharedMembers: {\n query: gql`\n query item($uuid: ID) {\n item(uuid: $uuid) {\n ...itemTemplate\n members {\n ...member\n permission\n }\n }\n }\n ${ITEM_TEMPLATE}\n ${MEMBER}\n `,\n variables() {\n return {\n uuid: this.$route.params.uuid,\n }\n },\n update(data) {\n return data.item.members\n },\n error(error) {\n console.log('errors', error)\n }\n },\n },\n```\n\nThe network response I got -\n\nnetwork_error\n\n========================================\n\nTop Answer:\nunfortunately i couldn't find out how i'd handle errors in such of graphql method call, but as an option you could provide `onError` method to `ApolloClient` constructor options. first argument is the error object. hopefully it may help. like so..\n\n```\nconst apolloClient = new ApolloClient({\n uri: 'http://localhost:4000',\n onError(err) {\n console.log(err)\n },\n})\n```\n\n========================================\n\nCode:\n```text\napollo: {\n sharedMembers: {\n query: gql`\n query item($uuid: ID) {\n item(uuid: $uuid) {\n ...itemTemplate\n members {\n ...member\n permission\n }\n }\n }\n ${ITEM_TEMPLATE}\n ${MEMBER}\n `,\n variables() {\n return {\n uuid: this.$route.params.uuid,\n }\n },\n update(data) {\n return data.item.members\n },\n error(error) {\n console.log('errors', error)\n }\n },\n },\n```\n\n```text\nerror(error) {\n console.log('errors', error.graphQLErrors)\n}\n```\n\n```text\nerror({ graphQlErrors }) {\n console.log('errors', graphQLErrors)\n}\n```\n\n```text\nimport { onError } from \"apollo-link-error\";\n\nconst link = onError(({ graphQLErrors, networkError }) => {\n if (graphQLErrors)\n graphQLErrors.map(({ message, locations, path }) =>\n console.log(\n `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,\n ),\n );\n\n if (networkError) {\n // Add something like this to set the error message to the one from the server response\n networkError.message = networkError.result.errors[0].debugMessage\n\n console.log(`[Network error]: ${networkError}`)\n };\n});\n```\n\n```text\nerror(error) {\n console.log('error-message', error.message)\n}\n```\n\n```text\ndebugMessage\n```\n\n```text\nconst apolloClient = new ApolloClient({\n uri: 'http://localhost:4000',\n onError(err) {\n console.log(err)\n },\n})\n```\n\n```text\nonError\n```\n\n```text\nApolloClient\n```\n\n========================================\n\nComments:\n- Is error showing as `undefined`?\n- @DanielRearden, no nothing printed in console info. But getting this error. `Error: GraphQL error: Internal server error at new ApolloError (bundle.esm.js:63) at Object.next (bundle.esm.js:1003) at notifySubscription (Observable.js:130) at onNotify (Observable.js:165) at SubscriptionObserver.next (Observable.js:219) at bundle.esm.js:865 at Set.forEach () at Object.next (bundle.esm.js:865) at notifySubscription (Observable.js:130) at onNotify (Observable.js:165)`\n- @DanielRearden, I have also attached network response image above in question.","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":159,"estimatedTokens":907}}680{"id":"stack-53734213","source":"stackoverflow","questionId":53734213,"title":"Apollo Server + Lambda + Subscriptions","tags":["lambda","graphql","apollo","serverless","apollo-server"],"text":"Title: Apollo Server + Lambda + Subscriptions\nTags: lambda, graphql, apollo, serverless, apollo-server\nSource: Stack Overflow\n\nQuestion:\nIs it possible to run an Apollo GraphQL Lambda backend with subscriptions? As I understand, GraphQL subscriptions use websockets, so I suppose it won't be possible unless you use Redis as message broker but I want to validate it this as it's not stated in any part of Apollo Docs.\n\n========================================\n\nTop Answer:\nYes. \n\nAWS lambdas now have websocket support via API Gateway. The serverless framework also now supports websockets without a plugin, making it really easy to implement.","metadata":{"transformedAt":"2026-08-18T18:32:36.075Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":13,"estimatedTokens":161}}681{"id":"stack-56952799","source":"stackoverflow","questionId":56952799,"title":"How to send signed HTTP request from AWS Lambda to AppSync GraphQL?","tags":["javascript","amazon-web-services","aws-lambda","graphql","aws-appsync"],"text":"Title: How to send signed HTTP request from AWS Lambda to AppSync GraphQL?\nTags: javascript, amazon-web-services, aws-lambda, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI am not sure how to send signed http request do AppSync GraphQL endpoint. There is no library for do that in AWS.\n\n- `aws-amplify` don't work because works only in browser, not in Lambda function.\n\n- `aws-sdk` for AppSync is only for admin usage, it doesn't have methods for call user side api\n\nIt is possible to make IAM signed HTTP request from AWS Lambda? (in some easy way)\n\n========================================\n\nTop Answer:\nYou can use any graphql client or a sigv4 signed HTTP request. Here's how you create the signature for your request (https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). If you attach an execution role to your lambda you can access it access key from lambda environment variables (https://docs.aws.amazon.com/lambda/latest/dg/lambda-environment-variables.html).\n\n========================================\n\nCode:\n```text\naws-amplify\n```\n\n```text\naws-sdk\n```\n\n```js\n// ... more code here\n // POST the GraphQL mutation to AWS AppSync using a signed connection\n const uri = URL.parse(env.GRAPHQL_API);\n const httpRequest = new AWS.HttpRequest(uri.href, env.REGION);\n httpRequest.headers.host = uri.host;\n httpRequest.headers['Content-Type'] = 'application/json';\n httpRequest.method = 'POST';\n httpRequest.body = JSON.stringify(post_body);\n\n AWS.config.credentials.get(err => {\n const signer = new AWS.Signers.V4(httpRequest, \"appsync\", true);\n signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate());\n\n const options = {\n method: httpRequest.method,\n body: httpRequest.body,\n headers: httpRequest.headers\n };\n\n fetch(uri.href, options)\n// ... more code here\n```\n\n```js\n//(...)\n //refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()\n AWS.config.credentials.refresh(error => {\n if (error) {\n console.error(error);\n } else {\n // Instantiate aws sdk service objects now that the credentials have been updated.\n // example: var s3 = new AWS.S3();\n console.log('Successfully logged!'); // <-- replace this line\n }\n });\n//(...)\n```\n\n```text\nsigner\n```\n\n```text\nes\n```\n\n```text\nexecute-api\n```\n\n```text\nsigner.addAuthorization\n```\n\n```text\nAWS.config.credentials\n```\n\n```text\nAWS.EnvironmentCredentials('AWS')\n```\n\n========================================\n\nComments:\n- The updated link Backend GraphQL: How to trigger an AWS AppSync mutation from AWS Lambda","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":96,"estimatedTokens":682}}682{"id":"stack-48245570","source":"stackoverflow","questionId":48245570,"title":"react-apollo Network error: Server response was missing for query 'Hello'","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: react-apollo Network error: Server response was missing for query 'Hello'\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI am trying to set up react-apollo using this code:\n\n```\nimport React from 'react';\nimport {render} from 'react-dom';\n\nimport gql from 'graphql-tag';\nimport { ApolloProvider, graphql } from 'react-apollo';\nimport { ApolloClient } from 'apollo-client';\nimport { HttpLink } from 'apollo-link-http';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\n\nconst client = new ApolloClient({\n link: new HttpLink({ uri: 'http://localhost:5000/graphql' }),\n cache: new InMemoryCache()\n});\n\nclass App extends React.Component {\n render () {\n return Hello React project\n\n; }\n}\nconst MY_QUERY = gql`query Hello { hello }`;\n\nconst AppWithData = graphql(MY_QUERY)(App)\nrender(\n \n \n ,\n document.getElementById('app')\n);\n```\n\nHowever, I get this error:\nhttps://i.sstatic.net/ZJJCG.png\n\nLooking at the Network tab in chrome dev tools, I can see that the request is coming through:\nhttps://i.sstatic.net/PnnNm.png\n\nI am wondering if maybe I am missing some configuration setting to get the responses in the right format? Or maybe I need to return the data from my graphql endpoint in a different format? Any advice is appreciated, I am just learning graphql and apollo so it could be something super obvious. thanks!\n\n========================================\n\nCode:\n```text\nimport React from 'react';\nimport {render} from 'react-dom';\n\nimport gql from 'graphql-tag';\nimport { ApolloProvider, graphql } from 'react-apollo';\nimport { ApolloClient } from 'apollo-client';\nimport { HttpLink } from 'apollo-link-http';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\n\n\nconst client = new ApolloClient({\n link: new HttpLink({ uri: 'http://localhost:5000/graphql' }),\n cache: new InMemoryCache()\n});\n\n\n\nclass App extends React.Component {\n render () {\n return <p> Hello React project</p>; }\n}\nconst MY_QUERY = gql`query Hello { hello }`;\n\nconst AppWithData = graphql(MY_QUERY)(App)\nrender(\n <ApolloProvider client={client}>\n <AppWithData />\n </ApolloProvider>,\n document.getElementById('app')\n);\n```\n\n```text\n{\n \"data\": {\n \"hello\": \"hello\"\n } \n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":90,"estimatedTokens":559}}683{"id":"stack-53180817","source":"stackoverflow","questionId":53180817,"title":"Apollo client: Making optimistic updates while creation is still in progress","tags":["graphql","apollo","react-apollo","apollo-client","optimistic-ui"],"text":"Title: Apollo client: Making optimistic updates while creation is still in progress\nTags: graphql, apollo, react-apollo, apollo-client, optimistic-ui\nSource: Stack Overflow\n\nQuestion:\nI want to be able to do updates on an object while it is still being created.\n\nFor example: Say I have a to-do list where I can add items with names. I also want to be able to edit names of items.\n\nNow say a user with a slow connection creates an item. In that case I fire off a create item mutation and optimistically update my UI. That works great. So far no problem\n\nNow let's say the create item mutation is taking a bit of time due to a slow network. In that time, the user decides to edit the name of the item they just created. For an ideal experience:\n\n- The UI should immediately update with the new name\n\n- The new name should eventually be persisted in the server\n\nI can achieve #2 by waiting for the create mutation to finish (so that I can get the item ID), then making an update name mutation. But that means parts of my UI will remain unchanged until the create item mutation returns and the optimistic response of the update name mutation kicks in. This means #1 won't be achieved.\n\nSo I'm wondering how can I achieve both #1 and #2 using Apollo client.\n\nNote: I don't want to add spinners or disable editing. I want the app to feel responsive even with a slow connection.\n\n========================================\n\nTop Answer:\nI think the easiest way to achieve your desired effect is to actually drop optimistic updates in favor of managing the component state yourself. I don't have the bandwidth at the moment to write out a complete example, but your basic component structure would look like this:\n\n```\n\n {(client) => (\n \n {(create) => (\n \n {(edit) => (\n \n )}\n \n )}\n \n )}\n\n```\n\nLet's assume we're dealing with just a single field -- `name`. Your `Form` component would start out with an initial state of\n\n```\n{ name: '', created: null, updates: null }\n```\n\nUpon submitting, the Form would do something like:\n\n```\nonCreate () {\n this.props.create({ variables: { name: this.state.name } })\n .then(({ data, errors }) => {\n // handle errors whichever way\n this.setState({ created: data.created })\n if (this.state.updates) {\n const id = data.created.id\n this.props.update({ variables: { ...this.state.updates, id } })\n }\n })\n .catch(errorHandler)\n}\n```\n\nThen the edit logic looks something like this:\n\n```\nonEdit () {\n if (this.state.created) {\n const id = this.state.created.id\n this.props.update({ variables: { name: this.state.name, id } })\n .then(({ data, errors }) => {\n this.setState({ updates: null })\n })\n .catch(errorHandler)\n } else {\n this.setState({ updates: { name: this.state.name } })\n }\n}\n```\n\nIn effect, your edit mutation is either triggered immediately when the user submits (since we got a response back from our create mutation already)... or the changes the user makes are persisted and then sent once the create mutation completes.\n\nThat's a very rough example, but should give you some idea on how to handle this sort of scenario. The biggest downside is that there's potential for your component state to get out of sync with the cache -- you'll need to ensure you handle errors properly to prevent that.\n\nThat also means if you want to use this form for *just* edits, you'll need to fetch the data out of the cache and then use that to populate your initial state (i.e. `this.state.created` in the example above). You can use the `Query` component for that, just make sure you don't render the actual `Form` component until you have the `data` prop provided by the `Query` component.\n\n========================================\n\nCode:\n```text\nmutation {\n upsertTodoItem(\n where: {\n key: $itemKey # Some unique key generated on client\n }\n update: {\n listId: $listId\n text: $itemText\n }\n create: {\n key: $itemKey\n listId: $listId\n text: $itemText\n }\n ) {\n id\n key\n }\n}\n```\n\n```text\nupsert\n```\n\n```text\nkey\n```\n\n```text\n<ApolloConsumer>\n {(client) => (\n <Mutation mutation={CREATE_MUTATION}>\n {(create) => (\n <Mutation mutation={EDIT_MUTATION}>\n {(edit) => (\n <Form />\n )}\n </Mutation> \n )}\n </Mutation>\n )}\n</ApolloConsumer>\n```\n\n```text\n{ name: '', created: null, updates: null }\n```\n\n```text\nonCreate () {\n this.props.create({ variables: { name: this.state.name } })\n .then(({ data, errors }) => {\n // handle errors whichever way\n this.setState({ created: data.created })\n if (this.state.updates) {\n const id = data.created.id\n this.props.update({ variables: { ...this.state.updates, id } })\n }\n })\n .catch(errorHandler)\n}\n```\n\n```text\nonEdit () {\n if (this.state.created) {\n const id = this.state.created.id\n this.props.update({ variables: { name: this.state.name, id } })\n .then(({ data, errors }) => {\n this.setState({ updates: null })\n })\n .catch(errorHandler)\n } else {\n this.setState({ updates: { name: this.state.name } })\n }\n}\n```\n\n```text\nname\n```\n\n```text\nForm\n```\n\n```text\nthis.state.created\n```\n\n```text\nQuery\n```\n\n```text\nForm\n```\n\n```text\ndata\n```\n\n```text\nQuery\n```\n\n========================================\n\nComments:\n- do optimistic update like in the case of creation. In case of updates, keep the mutation ready and do it in background once the create operation is completed and you have the id","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":205,"estimatedTokens":1361}}684{"id":"stack-39256942","source":"stackoverflow","questionId":39256942,"title":"Dynamically creating graphql schema with circular references","tags":["graphql","circular-dependency","graphql-js","circular-reference"],"text":"Title: Dynamically creating graphql schema with circular references\nTags: graphql, circular-dependency, graphql-js, circular-reference\nSource: Stack Overflow\n\nQuestion:\nBy using graphql-js, I need to create graphql schema dynamically by iterating over array of some data, for example:\n\n```\n[{\n name: 'author',\n fields: [{\n field: 'name'\n }, {\n field: 'books',\n reference: 'book'\n }]\n}, {\n name: 'book',\n fields: [{\n field: 'title'\n }, {\n field: 'author',\n reference: 'author'\n }]\n}]\n```\n\nThe problem is circular references. When I'm creating AuthorType I need BookType to be already created and vise versa.\n\nSo resulting schema should look like:\n\n```\ntype Author : Object { \n id: ID!\n name: String,\n books: [Book]\n}\n\ntype Book : Object { \n id: ID!\n title: String\n author: Author\n}\n```\n\nHow can I solve this?\n\n========================================\n\nTop Answer:\nI solved this problem by using a thunk for the fields field.\n\n```\nconst User = new GraphQLObjectType({\n name: 'User',\n fields: () => ({\n id: { type: GraphQLID }\n })\n});\n```\n\nWhen you make your fields a thunk rather than an object literal you can use types that are defined later in the file. \n\nPlease see this post for more info Is there a way to avoid circular type dependencies in GraqhQL?\n\nBased on that post I think this is the correct way to do it.\n\n========================================\n\nCode:\n```text\n[{\n name: 'author',\n fields: [{\n field: 'name'\n }, {\n field: 'books',\n reference: 'book'\n }]\n}, {\n name: 'book',\n fields: [{\n field: 'title'\n }, {\n field: 'author',\n reference: 'author'\n }]\n}]\n```\n\n```text\ntype Author : Object { \n id: ID!\n name: String,\n books: [Book]\n}\n\ntype Book : Object { \n id: ID!\n title: String\n author: Author\n}\n```\n\n```text\nvar AddressType = new GraphQLObjectType({\n name: 'Address',\n fields: {\n street: { type: GraphQLString },\n number: { type: GraphQLInt },\n formatted: {\n type: GraphQLString,\n resolve(obj) {\n return obj.number + ' ' + obj.street\n }\n }\n }\n});\n\nvar PersonType = new GraphQLObjectType({\n name: 'Person',\n fields: () => ({\n name: { type: GraphQLString },\n bestFriend: { type: PersonType },\n })\n});\n```\n\n```text\nconst User = new GraphQLObjectType({\n name: 'User',\n fields: () => ({\n id: { type: GraphQLID }\n })\n});\n```\n\n========================================\n\nComments:\n- Use a fieldconfigmapthunk graphql.org/docs/api-reference-type-system\n- This answer is almost correct, it is true that you have to use function expression. In addition you have to iterate over your data twice. In first iteration you are creating all the types but fields function returns links on empty objects. And in second literation you need to fill these empty objects with actual data","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":142,"estimatedTokens":701}}685{"id":"stack-51722203","source":"stackoverflow","questionId":51722203,"title":"How to use GraphQLError for customize messaging?","tags":["graphql","express-graphql"],"text":"Title: How to use GraphQLError for customize messaging?\nTags: graphql, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to do customize messaging with GraphQLError. \n\nThere are few use cases that I want to handle with GraphQL Error:\n\nwhen username and password did not match, I want to return customize the message that username and password did not match.\n\nWhen the user entered an invalid email, I want to return customize the message that entered email is not valid.\n\nAnd few other use cases.\n\nI created a ValidateError.js File to use GraphQLError handling function:\n\n```\nconst { GraphQLError } = require('graphql');\n\nmodule.exports = class ValidationError extends GraphQLError {\n constructor(errors) {\n\n super('The request is invalid');\n\n var err = errors.reduce((result, error) => {\n\n if (Object.prototype.hasOwnProperty.call(result, error.key)) {\n result[error.key].push(error.message);\n } else {\n result[error.key] = [error.message];\n }\n\n return result;\n }, {});\n }\n}\n```\n\nHere is the code of my application index file app.js:\n\n```\napp.use('/graphql', graphqlExpress(req => ({\n schema,\n context: {\n user: req.user\n },\n formatError(err) {\n return {\n message: err.message,\n code: err.originalError && err.originalError.code, \n locations: err.locations,\n path: err.path\n };\n }\n})));\n```\n\nMy question is how can I use this function for grabbing graphQLError\n\n formatError\n\nThanks in advance.\n\n========================================\n\nTop Answer:\nInside of GraphQLError you should have access to GraphQLErrorExtensions which should allow you to append your custom messages when throwing errors.\n\nThis answer was written with knowledge of apollo server throwing custom errors through this extensions option. This may be achievable but more complex. I suggest checking out apollo server error: https://github.com/apollographql/apollo-server/blob/main/packages/apollo-server-errors/src/index.ts\n\nIt looks like what you can do is just pass any additional information through the extensions, but you will only be able to set it inside the constructor: `new GraphQLError('your error message', null, null, null, null, null, {\"message1\": [ \"custom message1\" ], \"message2\": [ \"customer message1\", \"custom message2\" ]})`\n\n========================================\n\nCode:\n```js\nconst { GraphQLError } = require('graphql');\n\nmodule.exports = class ValidationError extends GraphQLError {\n constructor(errors) {\n\n super('The request is invalid');\n\n var err = errors.reduce((result, error) => {\n\n if (Object.prototype.hasOwnProperty.call(result, error.key)) {\n result[error.key].push(error.message);\n } else {\n result[error.key] = [error.message];\n }\n\n return result;\n }, {});\n }\n}\n```\n\n```js\napp.use('/graphql', graphqlExpress(req => ({\n schema,\n context: {\n user: req.user\n },\n formatError(err) {\n return {\n message: err.message,\n code: err.originalError && err.originalError.code, \n locations: err.locations,\n path: err.path\n };\n }\n})));\n```\n\n```js\nclass AppError extends Error {\n constructor(opts) {\n super(opts.msg);\n this.code = opts.code;\n }\n}\n\nexports.AppError = AppError;\n```\n\n```js\nformatError: error => {\n const { code, message } = error.originalError;\n return { code, message };\n },\n```\n\n```js\nconst resolvers = {\n Query: {\n books: () => {\n throw new GraphQLError('something bad happened');\n }\n }\n};\n```\n\n```js\ngraphqlExpress(req => {\n return {\n schema,\n formatError: err => {\n console.log('format error');\n return err;\n }\n };\n })\n```\n\n```sh\nformat error\nGraphQLError: something bad happened\n at books (/Users/ldu020/workspace/apollo-server-express-starter/src/graphql-error/index.js:23:13)\n at /Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql-tools/dist/schemaGenerator.js:518:26\n at resolveFieldValueOrError (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:531:18)\n at resolveField (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:495:16)\n at /Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:364:18\n at Array.reduce (<anonymous>)\n at executeFields (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:361:42)\n at executeOperation (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:289:122)\n at executeImpl (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:154:14)\n at Object.execute (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:131:229)\n```\n\n```text\n\"apollo-server-express\": \"^1.3.5\"\n```\n\n```text\n\"graphql\": \"^0.13.2\"\n```\n\n```text\nresolver\n```\n\n```text\nformatError\n```\n\n```text\nappError.js\n```\n\n```text\nresolver\n```\n\n```text\nthrow new AppError({ msg: 'authorization failed', code: 1001 });\n```\n\n```text\nformatError\n```\n\n```text\nresolver\n```\n\n```text\nformatError\n```\n\n```text\nnew GraphQLError('your error message', null, null, null, null, null, {\"message1\": [ \"custom message1\" ], \"message2\": [ \"customer message1\", \"custom message2\" ]})\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":213,"estimatedTokens":1326}}686{"id":"stack-56954070","source":"stackoverflow","questionId":56954070,"title":"Why do I always get a cors error that wildcard * is not allowed, although I specified a origin on the server?","tags":["reactjs","express","cors","graphql"],"text":"Title: Why do I always get a cors error that wildcard * is not allowed, although I specified a origin on the server?\nTags: reactjs, express, cors, graphql\nSource: Stack Overflow\n\nQuestion:\nI created a simple graphQL Chat with Apollo Server and Apollo Client. \n\nIt also uses session cookies so I initialized the server with the npm package `cors` like this:\n\n```\napp.use(\n cors({\n credentials: true,\n origin: \"http://localhost:3000\"\n })\n);\n```\n\nOn the client side I use apollo client and create a http link like this:\n\n```\nconst httpLink = new HttpLink({\n uri: \"http://localhost:4000/graphql\",\n credentials: \"include\"\n});\n```\n\nSo I include credentials and the server has the origin of my client (which is indeed http://localhost:3000 - create-react-app default). \n\nWhen I want to run a query I get this error in my browser console:\n\n Access to fetch at 'http://localhost:4000/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.\n\nWhy does it say that the response header has a wildcard * set, but on cors I set a specific origin, so it should not be a wildcard right? \n\nWhat am I missing here guys? I also restarted both servers of course. \n\nWhen I set the client like this: \n\n```\nconst httpLink = new HttpLink({\n uri: \"http://localhost:4000/graphql\",\n credentials: \"same-origin\"\n});\n```\n\nI don't get an error message from cors, but I don't receive a cookie from the server. Cookies work because on graphQL Playground everything works as expected.\n\nIf you want to see the full code: https://github.com/SelfDevTV/graphql-simple-chat\n\n========================================\n\nTop Answer:\nYou can instead tell the Apollo server how to configure cors.\n\n```\nconst corsOptions = {\n origin: \"http://localhost:3000\",\n credentials: true\n}\n\nserver.applyMiddleware({\n app,\n cors: corsOptions\n})\n```\n\nThen you can eliminate the express cors middleware entirely.\n\n========================================\n\nCode:\n```text\napp.use(\n cors({\n credentials: true,\n origin: \"http://localhost:3000\"\n })\n);\n```\n\n```text\nconst httpLink = new HttpLink({\n uri: \"http://localhost:4000/graphql\",\n credentials: \"include\"\n});\n```\n\n```text\nconst httpLink = new HttpLink({\n uri: \"http://localhost:4000/graphql\",\n credentials: \"same-origin\"\n});\n```\n\n```text\ncors\n```\n\n```text\nindex.js\n```\n\n```text\nserver.applyMiddleware({ app });\n```\n\n```text\nserver.applyMiddleware({ app, cors: false });\n```\n\n```text\nconst corsOptions = {\n origin: \"http://localhost:3000\",\n credentials: true\n}\n\nserver.applyMiddleware({\n app,\n cors: corsOptions\n})\n```\n\n========================================\n\nComments:\n- This is just turning off cors. The better solution would be to set up a proxy for local development in your package.json `\"proxy\": \"http://localhost:4000/\",` which tells react to proxy port 4000 through your app for development. For production, you'll need to bundle your server and front-end together\n- Is it really turning it off? Because that would mean that credentials would not be passed to the client? So cookies would not work, but they do this way? Do I set this proxy you mentioned in the package.json from the create-react-app folder or the server's package.json?\n- Yes, `cors: false` is turning cors off, which has nothing to do with credentials or cookies. It's a security protection that is much better explained here: medium.com/@baphemot/understanding-cors-18ad6b478e2b As far as the proxy, you put that in your react package.json.\n- Ok when I set this proxy. What exactly do I have to do next. Enable cors with the cors package like this: `app.use( cors({ credentials: true, origin: [\"http://localhost:3000\"] }) );` And also set `cors:true` on the apollo server instance? And on the client I can set `{credentials: \"same-origin\" }`? Is this correct like this? **EDIT:** Does not work this way. `same-origin` works but no cookie. `include` same cors error with the wildcard.\n- You shouldn't have to do anything explicitly on either side, just set the proxy on the react side and it will hit `http://localhost:4000` as if it was hitting `http://localhost:3000`. Here are the official docs: facebook.github.io/create-react-app/docs/…\n- Another thing I tried. * Set proxy on the `package.json` * disable the cors package * enable cors like this on the server: `server.applyMiddleware({ app, cors: { credentials: true, origin: \"http://localhost:3000\" } });` This works but not when I set origin: `same-origin` on the client, so it's still not secure for production when I use `include` right?\n- The react proxy only works in development. For production you'll want to serve both the react build and the api endpoints from the same (express?) web server so it won't be a cross origin request. This doesn't work in a dev environment because typically you'll start react with `npm run start` and the server with something like `npm run server` and they can't the same port. The react proxy deals with that issue. For prod you'll want a static build and serve it up from where you serve up the API\n- Did you find a solution for this? I'm having the exact same issue\n- Hi, yes my problem is solved, see my solution up there.\n- Some comments here got me a bit worried, that maybe CORS processing was just off with `cors: false` . I tested it and verified that the app's CORS middleware was indeed invoked for all gql calls. Great tip.\n- This worked for me. I think this should be the accepted answer.\n- When I used `http://localhost:3000` or `true` as my origin it worked, but not when I added `*`, `/`, or `/*` on the end of the url, e.g. `http://localhost:3000/`. I also added this as a variable in my `env.dev` file: `CLIENT_URL=http://localhost:3000`, and then loaded it in the server index via `origin: process.env.CLIENT_URL`, which worked well","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":138,"estimatedTokens":1499}}687{"id":"stack-49718037","source":"stackoverflow","questionId":49718037,"title":"Why canβt we use GraphQL just with Redux","tags":["reactjs","redux","graphql","apollo","relayjs"],"text":"Title: Why canβt we use GraphQL just with Redux\nTags: reactjs, redux, graphql, apollo, relayjs\nSource: Stack Overflow\n\nQuestion:\nIβm wondering why people doesnβt seem to use GraphQL jus with Redux. \n\nIβve never used GraphQL before but Iβd like to start a new project, but neither Apollo and Relay doesnβt convince me. Currently Iβm creating an app that use react and redux and βold fashionβ rest api. And I love the idea of redux that it store whole informations about my app in one place.\n\nAnd now, as far as I understand both Apollo and relay does something similar but they use separate store and in both we mixing the logic and view even more than with just React, both of these things (another store and mixing code) seems to be a bit messy. The advantage is caching, am I right?\n\nSo why canβt we just send the query as we used to with normal rest api and put the data to the redux store (maybe try to store some kind information about sync for optimisation).\n\nSorry if there are thing that i missed, Iβm new here and Iβm not a pro, itβs why I ask some people that probably has more experience that me :)\n\n========================================\n\nCode:\n```text\nNoteSummary\n```\n\n```text\ntitle\n```\n\n```text\ntags\n```\n\n```text\nNoteDetails\n```\n\n```text\ndescription\n```\n\n```text\ncomments\n```\n\n```text\nNoteDetails\n```\n\n========================================\n\nComments:\n- Very good answer. I can totally relate: Over one year GraphQL in production and I never looked back to redux. Why should I worry about the store state, content or shape if a library can do this for me? Just today a backend engineer in my team said: Now that I'm learning React, GraphQL totally makes sense!\n- This is a good answer but one thing keeps me puzzled. How do I use Apollo with a native app, where the state is persisted (like in redux-persist) and offline first is important. How do I fetch all releant data for the app and still use small queries per component without having a normalized state like in apollo.","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":51,"estimatedTokens":499}}688{"id":"stack-41026900","source":"stackoverflow","questionId":41026900,"title":"Graphql, react-apollo how to transfer variable to query at loading component state","tags":["javascript","reactjs","react-router","graphql","react-apollo"],"text":"Title: Graphql, react-apollo how to transfer variable to query at loading component state\nTags: javascript, reactjs, react-router, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have a simple react component that must load data from server when user ask it. Problem is that i don't know how to transfer dynamic variable speakerUrl and access it in before component load state. Sure i can access it from `this.props.params`, but component is not loaded and i can't access it when i make a graphql query. Query - `QuerySpeaker` is working fine when i manualy set url variable.\n\n**Router**\n\n```\n\n```\n\n**Component - SpeakerPage**\n\n```\nimport React from 'react';\nimport { graphql } from 'react-apollo';\n\nimport { QuerySpeaker } from '../redux/graphql/querys';\n\nclass SpeakerPage extends React.Component {\n render( ) {\n console.log( this.props );\n return (\n \n \n \n Hello\n \n \n \n )\n }\n}\n\nexport default graphql(QuerySpeaker, {\n options: ({ url }) => ({ variables: { url } }) <- here is my problem, how can i set this url variable?\n})( SpeakerPage );\n```\n\n========================================\n\nCode:\n```text\n<Route path=\"/speaker/:speakerUrl\" component={SpeakerPage} />\n```\n\n```text\nimport React from 'react';\nimport { graphql } from 'react-apollo';\n\nimport { QuerySpeaker } from '../redux/graphql/querys';\n\nclass SpeakerPage extends React.Component {\n render( ) {\n console.log( this.props );\n return (\n <div className=\"ui container\">\n <div className=\"ui grid\">\n <div className=\"row\">\n Hello\n </div>\n </div>\n </div>\n )\n }\n}\n\nexport default graphql(QuerySpeaker, {\n options: ({ url }) => ({ variables: { url } }) <- here is my problem, how can i set this url variable?\n})( SpeakerPage );\n```\n\n```text\nthis.props.params\n```\n\n```text\nQuerySpeaker\n```\n\n```text\nexport default graphql(QuerySpeaker, {\n options: (props) => ({ variables: { url: props.match.params.speakerUrl } })\n})( SpeakerPage );\n```\n\n```text\nreact-apollo\n```\n\n```text\noptions\n```\n\n```text\nreact-router\n```\n\n```text\nparams\n```\n\n```text\nparams\n```\n\n```text\noptions\n```\n\n========================================\n\nComments:\n- Not very obvious in the docs considering how frequent this use case comes up in dev. Thank you!\n- Thank you Paul. I resolved a similar problem I had! Upvote from me.\n- In think that in react router v4, you should use the match property: props.match.params.speakerUrl\n- @yonih Yes, you're right. I wrote this while v4 was still in beta (or maybe alpha) and I believe that the API was slightly different at the time. Will update my answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":119,"estimatedTokens":668}}689{"id":"stack-57704820","source":"stackoverflow","questionId":57704820,"title":"GraphQL playground type detail multiline comment?","tags":["graphql","graphql-playground"],"text":"Title: GraphQL playground type detail multiline comment?\nTags: graphql, graphql-playground\nSource: Stack Overflow\n\nQuestion:\nI am trying to document my APIs using GraphQL. For readability issues, I want to leave comments in multi-line but it doesn't seem to work with regular '\\n' newline symbol\n\n```\n\"\"\"\n Return:\\n true : DB save successful\\n false : DB save unsuccessful\n\"\"\"\n```\n\nThis is what i tried\n\nHowever it outputs exactly the same without putting lines in the new line\n\n```\nReturn:\\n true : DB save successful\\n false : DB save unsuccessful\n```\n\nIs it possible to arrange texts in new line like:\n\n```\nReturn:\n true : DB save successful\n false : DB save unsuccessful\n```\n\n========================================\n\nCode:\n```text\n\"\"\"\n Return:\\n true : DB save successful\\n false : DB save unsuccessful\n\"\"\"\n```\n\n```text\nReturn:\\n true : DB save successful\\n false : DB save unsuccessful\n```\n\n```text\nReturn:\n true : DB save successful\n false : DB save unsuccessful\n```\n\n```text\n\"\"\"\nReturn:\ntrue : DB save successful\nfalse : DB save unsuccessful\n\"\"\"\n```\n\n```text\n\"Return:\\n true : DB save successful\\n false : DB save unsuccessful\"\n```\n\n```text\n\"\"\"\nReturn:\n\ntrue : DB save successful\n\nfalse : DB save unsuccessful\n\"\"\"\n```\n\n========================================\n\nComments:\n- Both don't seem to work for me... prints everything in one line in graphql playground\n- Are you referring to the DOCS tab in Playground?\n- yes. I'm writing comments in schema.graphql and viewing it in playground > docs\n- Done. didn't know about that. Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":77,"estimatedTokens":385}}690{"id":"stack-55011045","source":"stackoverflow","questionId":55011045,"title":"Error: Cannot use GraphQLObjectType \"__Directive\" from another module or realm","tags":["graphql","gatsby"],"text":"Title: Error: Cannot use GraphQLObjectType \"__Directive\" from another module or realm\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI am trying to query data from GraphQL using Gatsby. I followed Gatsby's instructions on querying data in pages with GraphQL but, I keep getting an error.\n\nError (this is what I need to fix more than the example below): \n\n Error: Cannot use GraphQLObjectType \"__Directive\" from another module\n or realm . Ensure that there is only one instance of \"graphql\" in\n the node_modules directory. If different versions of \"graphql\" are\n the dependencies of other relied on modules, use \"resolutions\" to\n ensure only one version is installed.\n\n https://yarnpkg.com/en/docs/selective-version-resolutions Duplicate\n \"graphql\" modules cannot be used at the same time since different\n\n versions may have different capabilities and behavior. The data from\n one version used in the function from another could produce\n confusing and spurious results.\n\nAny idea why this is happening? I only have one graphql instance in my node_modules folder\n\n**Example of what I am working with:**\n\nI am going to be importing my own data from GraphQL but for now as a proof of concept I am working on this Gatsby Rick and Morty Example (link above - I didnt bother with the axios demo yet).\n\nindex.js code:\n\n```\nimport React, { Component } from 'react'\nimport { graphql } from 'gatsby'\n\n// This query is executed at build time by Gatsby.\nexport const GatsbyQuery = graphql`\n {\n rickAndMorty {\n character(id: 1) {\n name\n image\n }\n }\n }\n`\n\nclass ClientFetchingExample extends Component {\n render() {\n const {\n rickAndMorty: { character },\n } = this.props.data\n\n return (\n \n \n\n### {character.name} With His Pupper\n\n Rick & Morty API data loads at build time.\n\n \n \n \n \n\n### Image of Rick's pupper\n\n This will come from a request on the client\n\n \n )\n }\n}\n\nexport default ClientFetchingExample\n```\n\ngatsby-config.js:\n\n```\nplugins: [\n {\n resolve: \"gatsby-source-graphql\",\n options: {\n typeName: \"RMAPI\",\n fieldName: \"rickAndMorty\",\n url: \"https://rickandmortyapi-gql.now.sh/\",\n },\n },\n...\n```\n\n========================================\n\nTop Answer:\nI checked https://rickandmortyapi-gql.now.sh/ and found, that you have error in your query. It should be like that:\n\n```\nexport const GatsbyQuery = graphql`\n query rickAndMorty {\n character(id: 1) {\n name\n image\n }\n }\n`\n```\n\nI guess you tried to make named query, but created that wrong.\n\n```\nplugins: [\n {\n resolve: \"gatsby-source-graphql\",\n options: {\n typeName: \"RMAPI\",\n fieldName: \"character\",\n url: \"https://rickandmortyapi-gql.now.sh/\",\n },\n },\n```\n\n...\n\n========================================\n\nCode:\n```text\nimport React, { Component } from 'react'\nimport { graphql } from 'gatsby'\n\n// This query is executed at build time by Gatsby.\nexport const GatsbyQuery = graphql`\n {\n rickAndMorty {\n character(id: 1) {\n name\n image\n }\n }\n }\n`\n\nclass ClientFetchingExample extends Component {\n render() {\n const {\n rickAndMorty: { character },\n } = this.props.data\n\n return (\n <div style={{ textAlign: \"center\", width: \"600px\", margin: \"50px auto\" }}>\n <h1>{character.name} With His Pupper</h1>\n <p>Rick & Morty API data loads at build time.</p>\n <div>\n <img\n src={character.image}\n alt={character.name}\n style={{ width: 300 }}\n />\n </div>\n <h2>Image of Rick's pupper</h2>\n <p>This will come from a request on the client</p>\n </div>\n )\n }\n}\n\nexport default ClientFetchingExample\n```\n\n```text\nplugins: [\n {\n resolve: \"gatsby-source-graphql\",\n options: {\n typeName: \"RMAPI\",\n fieldName: \"rickAndMorty\",\n url: \"https://rickandmortyapi-gql.now.sh/\",\n },\n },\n...\n```\n\n```text\n\"resolutions\": {\n \"graphql\": \"^14.1.0\"\n}\n```\n\n```text\nnode_modules/graphql\nnode_modules/gatsby/node_modules/graphql\n```\n\n```text\nyarn.lock\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql\n```\n\n```text\nnpm install\n```\n\n```text\nfind node_modules -name graphql\n```\n\n```text\ngrep version node_modules/graphql/package.json\n```\n\n```text\nexport const GatsbyQuery = graphql`\n query rickAndMorty {\n character(id: 1) {\n name\n image\n }\n }\n`\n```\n\n```text\nplugins: [\n {\n resolve: \"gatsby-source-graphql\",\n options: {\n typeName: \"RMAPI\",\n fieldName: \"character\",\n url: \"https://rickandmortyapi-gql.now.sh/\",\n },\n },\n```\n\n```text\nrm package-lock.json\nrm node_modules\n```\n\n```text\nnpm/yarn install\n```\n\n```text\nnpm uninstall -g @graphql-codegen/cli\nnpm install @graphql-codegen/cli\n```\n\n```text\nnpm install @graphql-codegen/cli @graphql-codegen/client-preset\n```\n\n```text\nnpm install -g npm@6.14.15\n```\n\n========================================\n\nComments:\n- I tried this but both come back with the error: 7:5 error Cannot query field \"rickAndMorty\" on type \"Query\"\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":268,"estimatedTokens":1293}}691{"id":"stack-61217878","source":"stackoverflow","questionId":61217878,"title":"How to return PDF file in an Graphql mutation?","tags":["python","django","reactjs","graphql","apollo"],"text":"Title: How to return PDF file in an Graphql mutation?\nTags: python, django, reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm using React and Graphql on the frontend and Django and Graphene on the backend.\n\nI want to be able to download a pdf file of a report. I try to do it using **mutation** as follows:\n\n```\nconst [createPdf, {loading: createPdfLoading, error: createPdfError}] = useMutation(CREATE_PDF)\nconst handleCreatePDF = async (reportId) => {\n const res = await createPdf({variables: {reportId: parseInt(reportId) }})\n debugger;\n };\n\nexport const CREATE_PDF = gql`\n mutation ($reportId: Int!) {\n createPdf (reportId: $reportId){\n reportId\n }\n }\n`;\n```\n\nOn the backend I have something like this:\n\n```\nclass CreatePDFFromReport(graphene.Mutation):\n report_id = graphene.Int()\n\n class Arguments:\n report_id = graphene.Int(required=True)\n\n def mutate(self, info, report_id):\n user = info.context.user\n\n if user.is_anonymous:\n raise GraphQLError(\"You are not logged in!\")\n\n report = Report.objects.get(id=report_id)\n if not report:\n raise GraphQLError(\"Report not found!\")\n\n if user != report.posted_by:\n raise GraphQLError(\"You are not permitted to do that!\")\n\n html_string = render_to_string('report.html', {'report_id': 1})\n\n pdf_file = HTML(string=html_string)\n response = HttpResponse(pdf_file, content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"rapport_{}\"'.format(report_id)\n return response\n\n # return CreatePDFFromReport(report_id=report_id)\n```\n\nWhen I uncomment `return CreatePDFFromReport(report_id=report_id)` it works fine.\n\nBut I want to return pdf file.\n\nIs there any possibility to do that?\n\nThanks.\n\n========================================\n\nTop Answer:\nYou can encode your PDF to Base64 and send it as a string.\nThen just decode it on the frontend.\n\nNote that the Base64 uses 4 bytes to encode every 3 bytes (3MB file becomes 4MB string).\n\n========================================\n\nCode:\n```text\nconst [createPdf, {loading: createPdfLoading, error: createPdfError}] = useMutation(CREATE_PDF)\nconst handleCreatePDF = async (reportId) => {\n const res = await createPdf({variables: {reportId: parseInt(reportId) }})\n debugger;\n };\n\nexport const CREATE_PDF = gql`\n mutation ($reportId: Int!) {\n createPdf (reportId: $reportId){\n reportId\n }\n }\n`;\n```\n\n```text\nclass CreatePDFFromReport(graphene.Mutation):\n report_id = graphene.Int()\n\n class Arguments:\n report_id = graphene.Int(required=True)\n\n def mutate(self, info, report_id):\n user = info.context.user\n\n if user.is_anonymous:\n raise GraphQLError(\"You are not logged in!\")\n\n report = Report.objects.get(id=report_id)\n if not report:\n raise GraphQLError(\"Report not found!\")\n\n if user != report.posted_by:\n raise GraphQLError(\"You are not permitted to do that!\")\n\n html_string = render_to_string('report.html', {'report_id': 1})\n\n pdf_file = HTML(string=html_string)\n response = HttpResponse(pdf_file, content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"rapport_{}\"'.format(report_id)\n return response\n\n\n # return CreatePDFFromReport(report_id=report_id)\n```\n\n```text\nreturn CreatePDFFromReport(report_id=report_id)\n```\n\n```text\nmutation ($reportId: Int!) {\n createPdf (reportId: $reportId){\n reportDownloadId\n }\n }\n```\n\n```text\nconst [addTodo, { data }] = useMutation(ADD_TODO);\n```\n\n```text\naddTodo({ \n variables: { type: input.value },\n onCompleted = {(data) => {\n // some action with 'data'\n // f.e. setDownloadUrl(data.reportDownloadId)\n // from 'const [downloadUrl, setDownloadUrl] = useState(null)'\n }}\n});\n```\n\n```text\n{downloadUrl && <DownloadReport url={downloadUrl}/>}\n\n{downloadUrl && <a href={downloadUrl}>Report ready - download it</a>}\n\n// render download, share, save in cloud, etc.\n```\n\n```text\nid\n```\n\n```text\nurl\n```\n\n```text\nid\n```\n\n```text\nurl\n```\n\n```text\nreportDownloadId\n```\n\n```text\ndata\n```\n\n```text\ndata\n```\n\n```text\n{ data }\n```\n\n```text\nonCompleted\n```\n\n========================================\n\nComments:\n- @xadm And what is the best way to do that? Add it as an answer and I will accept it.\n- sure, but 33% more ... method suitable to embedding icons, svg, small files ... or small scale\n- Does decoding on frontend automatically download the file?","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":200,"estimatedTokens":1111}}692{"id":"stack-60709951","source":"stackoverflow","questionId":60709951,"title":"filter query on multiple fields in single query","tags":["php","symfony","graphql","api-platform.com"],"text":"Title: filter query on multiple fields in single query\nTags: php, symfony, graphql, api-platform.com\nSource: Stack Overflow\n\nQuestion:\nMy setup is Symfony 5 with the latest API-Platform version running on PHP 7.3.\nSo I would like to be able to query both on name and username (maybe even email).\nDo I need to write a custom resolver?\n\nThis is what I've tried so far but this results in a WHERE name = $name AND username = $name.\n\n```\nquery SearchUsers ($name: String!) {\n users(name: $name, username: $name) {\n edges {\n cursor\n node {\n id\n username\n email\n avatar\n }\n }\n }\n}\n```\n\nMy entity:\n\n```\n/**\n * @ApiResource\n * @ApiFilter(SearchFilter::class, properties={\n * \"name\": \"ipartial\",\n * \"username\": \"ipartial\",\n * \"email\": \"ipartial\",\n * })\n *\n * @ORM\\Table(name=\"users\")\n * @ORM\\Entity(repositoryClass=\"Domain\\Repository\\UserRepository\")\n * @ORM\\HasLifecycleCallbacks()\n */\nclass User\n{\n private $name;\n private $username;\n private $email;\n // ... code omitted ...\n}\n```\n\n========================================\n\nTop Answer:\nI made such a custom filter for chapter 6 of my tutorial. I include its code below.\n\nYou can configure which properties it searches in the ApiFilter attribute. In your case that would be:\n\n```\n#[ApiFilter(filterClass: SimpleSearchFilter::class,\nproperties: ['name', 'username', 'email'])]\n```\n\nIt splits the search string into words and searches each of the properties case insensitive for each word, so a query string like:\n\n```\n?simplesearch=Katch sQuash\n```\n\nwill search in all specified properties both LOWER(..) LIKE '%katch%' OR LOWER(..) LIKE '%squash%'\n\nLimitations: It may be limited to string properties (depending on the DB) and it does not sort by relevance.\n\nThe code (apip 3.0):\n\n```\nsearchParameterName = $searchParameterName;\n }\n\n /** {@inheritdoc} */\n protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void\n {\n if (null === $value || $property !== $this->searchParameterName) {\n return;\n }\n\n $words = explode(' ', $value);\n foreach ($words as $word) {\n if (empty($word)) continue;\n\n $this->addWhere($queryBuilder, $word, $queryNameGenerator->generateParameterName($property), $queryNameGenerator, $resourceClass);\n }\n }\n\n private function addWhere($queryBuilder, $word, $parameterName, $queryNameGenerator, $resourceClass)\n {\n // Build OR expression\n $orExp = $queryBuilder->expr()->orX();\n foreach ($this->getProperties() as $prop => $ignoored) {\n $alias = $queryBuilder->getRootAliases()[0];\n // Thanks to Hasbert and Polo\n if ($this->isPropertyNested($prop, $resourceClass)) {\n [$alias, $prop] = $this->addJoinsForNestedProperty($prop, $alias, $queryBuilder, $queryNameGenerator, $resourceClass, Join::INNER_JOIN);\n }\n\n $orExp->add($queryBuilder->expr()->like('LOWER('. $alias. '.' . $prop. ')', ':' . $parameterName));\n }\n\n // Add it\n $queryBuilder\n ->andWhere('(' . $orExp . ')')\n ->setParameter($parameterName, '%' . strtolower($word). '%');\n }\n\n /** {@inheritdoc} */\n public function getDescription(string $resourceClass): array\n {\n $props = $this->getProperties();\n if (null===$props) {\n throw new InvalidArgumentException('Properties must be specified');\n }\n return [\n $this->searchParameterName => [\n 'property' => implode(', ', array_keys($props)),\n 'type' => 'string',\n 'required' => false,\n 'swagger' => [\n 'description' => 'Selects entities where each search term is found somewhere in at least one of the specified properties',\n ]\n ]\n ];\n }\n\n}\n```\n\nThe service needs configuration in api/config/services.yaml\n\n```\n'App\\Filter\\SimpleSearchFilter':\n arguments:\n $searchParameterName: 'ignoored'\n```\n\n($searchParameterName can actually be configured from the #ApiFilter attribute)\n\n========================================\n\nCode:\n```js\nquery SearchUsers ($name: String!) {\n users(name: $name, username: $name) {\n edges {\n cursor\n node {\n id\n username\n email\n avatar\n }\n }\n }\n}\n```\n\n```php\n/**\n * @ApiResource\n * @ApiFilter(SearchFilter::class, properties={\n * \"name\": \"ipartial\",\n * \"username\": \"ipartial\",\n * \"email\": \"ipartial\",\n * })\n *\n * @ORM\\Table(name=\"users\")\n * @ORM\\Entity(repositoryClass=\"Domain\\Repository\\UserRepository\")\n * @ORM\\HasLifecycleCallbacks()\n */\nclass User\n{\n private $name;\n private $username;\n private $email;\n // ... code omitted ...\n}\n```\n\n```text\nOR\n```\n\n```text\n#[ApiFilter(filterClass: SimpleSearchFilter::class,\nproperties: ['name', 'username', 'email'])]\n```\n\n```text\n?simplesearch=Katch sQuash\n```\n\n```text\n<?php\n\nnamespace App\\Filter;\n\nuse ApiPlatform\\Doctrine\\Orm\\Filter\\AbstractFilter;\nuse ApiPlatform\\Doctrine\\Orm\\Util\\QueryNameGeneratorInterface;\nuse ApiPlatform\\Metadata\\Operation;\nuse Doctrine\\ORM\\Query\\Expr\\Join;\nuse Doctrine\\ORM\\QueryBuilder;\nuse Doctrine\\Persistence\\ManagerRegistry;\nuse Psr\\Log\\LoggerInterface;\nuse Symfony\\Component\\Serializer\\NameConverter\\NameConverterInterface;\nuse ApiPlatform\\Exception\\InvalidArgumentException;\n\n/**\n * Selects entities where each search term is found somewhere\n * in at least one of the specified properties.\n * Search terms must be separated by spaces.\n * Search is case insensitive.\n * All specified properties type must be string. Nested properties are supported.\n * @package App\\Filter\n */\nclass SimpleSearchFilter extends AbstractFilter\n{\n private $searchParameterName;\n\n /**\n * Add configuration parameter\n * {@inheritdoc}\n * @param string $searchParameterName The parameter whose value this filter searches for\n */\n public function __construct(ManagerRegistry $managerRegistry, LoggerInterface $logger = null, array $properties = null, NameConverterInterface $nameConverter = null, string $searchParameterName = 'simplesearch')\n {\n parent::__construct($managerRegistry, $logger, $properties, $nameConverter);\n\n $this->searchParameterName = $searchParameterName;\n }\n\n /** {@inheritdoc} */\n protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void\n {\n if (null === $value || $property !== $this->searchParameterName) {\n return;\n }\n\n $words = explode(' ', $value);\n foreach ($words as $word) {\n if (empty($word)) continue;\n\n $this->addWhere($queryBuilder, $word, $queryNameGenerator->generateParameterName($property), $queryNameGenerator, $resourceClass);\n }\n }\n\n private function addWhere($queryBuilder, $word, $parameterName, $queryNameGenerator, $resourceClass)\n {\n // Build OR expression\n $orExp = $queryBuilder->expr()->orX();\n foreach ($this->getProperties() as $prop => $ignoored) {\n $alias = $queryBuilder->getRootAliases()[0];\n // Thanks to Hasbert and Polo\n if ($this->isPropertyNested($prop, $resourceClass)) {\n [$alias, $prop] = $this->addJoinsForNestedProperty($prop, $alias, $queryBuilder, $queryNameGenerator, $resourceClass, Join::INNER_JOIN);\n }\n\n $orExp->add($queryBuilder->expr()->like('LOWER('. $alias. '.' . $prop. ')', ':' . $parameterName));\n }\n\n // Add it\n $queryBuilder\n ->andWhere('(' . $orExp . ')')\n ->setParameter($parameterName, '%' . strtolower($word). '%');\n }\n\n /** {@inheritdoc} */\n public function getDescription(string $resourceClass): array\n {\n $props = $this->getProperties();\n if (null===$props) {\n throw new InvalidArgumentException('Properties must be specified');\n }\n return [\n $this->searchParameterName => [\n 'property' => implode(', ', array_keys($props)),\n 'type' => 'string',\n 'required' => false,\n 'swagger' => [\n 'description' => 'Selects entities where each search term is found somewhere in at least one of the specified properties',\n ]\n ]\n ];\n }\n\n}\n```\n\n```text\n'App\\Filter\\SimpleSearchFilter':\n arguments:\n $searchParameterName: 'ignoored'\n```\n\n```text\n/users/?or[username]=super&or[name]=john\n```\n\n```text\n/users/?and[name]=john&and[or][][email]=microsoft.com&and[or][][email]=apple.com\n```\n\n```text\n<?php\n\nnamespace App\\Filter;\n\nuse ApiPlatform\\Doctrine\\Orm\\Filter\\FilterInterface;\nuse ApiPlatform\\Doctrine\\Orm\\Filter\\OrderFilter;\nuse ApiPlatform\\Doctrine\\Orm\\Util\\QueryNameGeneratorInterface;\nuse ApiPlatform\\Metadata\\Operation;\nuse Doctrine\\ORM\\QueryBuilder;\nuse Doctrine\\ORM\\Query\\Expr;\nuse Doctrine\\Persistence\\ManagerRegistry;\nuse Psr\\Container\\ContainerInterface;\nuse Psr\\Log\\LoggerInterface;\nuse Symfony\\Component\\Serializer\\NameConverter\\NameConverterInterface;\nuse Doctrine\\ORM\\Query\\Expr\\Join;\n\n/**\n * Combines existing API Platform ORM Filters with AND and OR.\n * For usage and limitations see https://github.com/metaclass-nl/filter-bundle/blob/master/README.md\n *\n * Copyright (c) MetaClass, Groningen, 2021-2022. MIT License\n */\nclass FilterLogic implements FilterInterface\n{\n /** @var ContainerInterface */\n private $filterLocator;\n /** @var string Filter classes must match this to be applied with logic */\n private $classExp;\n /** @var FilterInterface[] */\n private $filters;\n\n /**\n * @param ContainerInterface $filterLocator\n * @param $regExp string Filter classes must match this to be applied with logic\n * @param $innerJoinsLeft bool Wheather to replace all inner joins by left joins.\n * This makes the standard Api Platform filters combine properly with OR,\n * but also changes the behavior of ExistsFilter =false.\n * {@inheritdoc}\n */\n public function __construct(ContainerInterface $filterLocator, ManagerRegistry $managerRegistry, ?LoggerInterface $logger = null, ?array $properties = null, ?NameConverterInterface $nameConverter = null, string $classExp='//')\n {\n $this->filterLocator = $filterLocator;\n $this->classExp = $classExp;\n }\n\n /** {@inheritdoc } */\n public function getDescription(string $resourceClass): array\n {\n // No description\n return [];\n }\n\n /**\n * {@inheritdoc}\n * @throws \\LogicException if assumption proves wrong\n */\n public function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void\n {\n if (!isset($context['filters']) || !\\is_array($context['filters'])) {\n throw new \\InvalidArgumentException('::apply without $context[filters] not supported');\n }\n\n $this->filters = $this->getFilters($operation);\n\n $logic = false; #15 when no where filter is used, do not replace inner joins by left joins\n if (isset($context['filters']['and']) ) {\n $expressions = $this->filterProperty('and', $context['filters']['and'], $queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);\n foreach($expressions as $exp) {\n $queryBuilder->andWhere($exp);\n $logic = true;\n };\n }\n if (isset($context['filters']['not']) ) {\n // NOT expressions are combined by parent logic, here defaulted to AND\n $expressions = $this->filterProperty('not', $context['filters']['not'], $queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);\n foreach($expressions as $exp) {\n $queryBuilder->andWhere(new Expr\\Func('NOT', [$exp]));\n $logic = true;\n };\n }\n #Issue 10: for security allways AND with existing criteria\n if (isset($context['filters']['or'])) {\n $expressions = $this->filterProperty('or', $context['filters']['or'], $queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);\n if (!empty($expressions)) {\n $queryBuilder->andWhere(new Expr\\Orx($expressions));\n $logic = true;\n }\n }\n\n }\n\n /**\n * @throws \\LogicException if assumption proves wrong\n */\n protected function doGenerate($queryBuilder, $queryNameGenerator, $resourceClass, Operation $operation = null, $context)\n {\n if (empty($context['filters'])) {\n return [];\n }\n $oldWhere = $queryBuilder->getDQLPart('where');\n\n // replace by marker expression\n $marker = new Expr\\Func('NOT', []);\n $queryBuilder->add('where', $marker);\n\n $assoc = [];\n $logic = [];\n foreach ($context['filters'] as $key => $value) {\n if (ctype_digit((string) $key)) {\n // allows the same filter to be applied several times, usually with different arguments\n $subcontext = $context; //copies\n $subcontext['filters'] = $value;\n $this->applyFilters($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $subcontext);\n\n // apply logic seperately\n if (isset($value['and'])) {\n $logic[]['and'] = $value['and'];\n }if (isset($value['or'])) {\n $logic[]['or'] = $value['or'];\n }if (isset($value['not'])) {\n $logic[]['not'] = $value['not'];\n }\n } elseif (in_array($key, ['and', 'or', 'not'])) {\n $logic[][$key] = $value;\n } else {\n $assoc[$key] = $value;\n }\n }\n\n // Process $assoc\n $subcontext = $context; //copies\n $subcontext['filters'] = $assoc;\n $this->applyFilters($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $subcontext);\n\n $newWhere = $queryBuilder->getDQLPart('where');\n $queryBuilder->add('where', $oldWhere); //restores old where\n\n // force $operator logic upon $newWhere\n $expressions = $this->getAppliedExpressions($newWhere, $marker);\n\n // Process logic\n foreach ($logic as $eachLogic) {\n $subExpressions = $this->filterProperty(key($eachLogic), current($eachLogic), $queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);\n if (key($eachLogic) == 'not') {\n // NOT expressions are combined by parent logic\n foreach ($subExpressions as $subExp) {\n $expressions[] = new Expr\\Func('NOT', [$subExp]);\n }\n } else {\n $expressions[] = key($eachLogic) == 'or'\n ? new Expr\\Orx($subExpressions)\n : new Expr\\Andx($subExpressions);\n }\n }\n\n return $expressions; // may be empty\n }\n\n /**\n * @throws \\LogicException if assumption proves wrong\n */\n protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, $context=[])\n {\n $subcontext = $context; //copies\n $subcontext['filters'] = $value;\n return $this->doGenerate($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $subcontext);\n }\n\n /** Calls ::apply on each filter in $filters */\n private function applyFilters($queryBuilder, $queryNameGenerator, $resourceClass, Operation $operation = null, $context)\n {\n foreach ($this->filters as $filter) {\n $filter->apply($queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);\n }\n }\n\n /**\n * ASSUMPTION: filters do not use QueryBuilder::where or QueryBuilder::add\n * and create semantically complete expressions in the sense that expressions\n * added to the QueryBundle through ::andWhere or ::orWhere do not depend\n * on one another so that the intended logic is not compromised if they are\n * recombined with the others by either Doctrine\\ORM\\Query\\Expr\\Andx\n * or Doctrine\\ORM\\Query\\Expr\\Orx.\n *\n * Get expressions from $where\n * andWhere and orWhere allways add their args at the end of existing or\n * new logical expressions, so we started with a marker expression\n * to become the deepest first part. The marker should not be returned\n * @param Expr\\Andx | Expr\\Orx $where Result from applying filters\n * @param Expr\\Func $marker Marks the end of logic resulting from applying filters\n * @return array of ORM Expression\n * @throws \\LogicException if assumption proves wrong\n */\n private function getAppliedExpressions($where, $marker)\n {\n if ($where === $marker) {\n return [];\n }\n if (!$where instanceof Expr\\Andx && !$where instanceof Expr\\Orx) {\n // A filter used QueryBuilder::where or QueryBuilder::add or otherwise\n throw new \\LogicException(\"Assumpion failure, unexpected Expression: \". $where);\n }\n $parts = $where->getParts();\n if (empty($parts)) {\n // A filter used QueryBuilder::where or QueryBuilder::add or otherwise\n throw new \\LogicException(\"Assumpion failure, marker not found\");\n }\n\n $firstPart = array_shift($parts);\n $parts = array_merge($parts, $this->getAppliedExpressions($firstPart, $marker));\n return $parts;\n }\n\n\n /**\n * @param Operation $operation\n * @return FilterInterface[] From resource except $this and OrderFilters\n */\n protected function getFilters(Operation $operation = null)\n {\n $resourceFilters = $operation ? $operation->getFilters() : [];\n\n $result = [];\n foreach ($resourceFilters as $filterId) {\n $filter = $this->filterLocator->has($filterId)\n ? $this->filterLocator->get($filterId)\n : null;\n if ($filter instanceof FilterInterface\n && !($filter instanceof OrderFilter)\n && $filter !== $this\n && preg_match($this->classExp, get_class($filter))\n ) {\n $result[$filterId] = $filter;\n }\n }\n return $result;\n }\n}\n```\n\n```text\n'App\\Filter\\FilterLogic':\n class: 'App\\Filter\\FilterLogic'\n arguments:\n - '@api_platform.filter_locator'\n public: false\n abstract: true\n autoconfigure: false\n```\n\n```text\nuse App\\Filter\\FilterLogic;\n#[ApiResource]\n#[ApiFilter(SearchFilter::class, properties: ['id' => 'exact', 'price' => 'exact', 'description' => 'partial'])]\n#[ApiFilter(FilterLogic::class)]\n```\n\n```text\n<?php\n\nnamespace App\\Filter;\n\nuse ApiPlatform\\Core\\Bridge\\Doctrine\\Orm\\Filter\\AbstractContextAwareFilter;\nuse ApiPlatform\\Core\\Bridge\\Doctrine\\Orm\\Util\\QueryNameGeneratorInterface;\nuse Doctrine\\ORM\\Query\\Expr\\Join;\nuse Doctrine\\ORM\\QueryBuilder;\nuse Doctrine\\Persistence\\ManagerRegistry;\nuse Psr\\Log\\LoggerInterface;\nuse Symfony\\Component\\HttpFoundation\\RequestStack;\nuse Symfony\\Component\\Serializer\\NameConverter\\NameConverterInterface;\nuse ApiPlatform\\Core\\Exception\\InvalidArgumentException;\nuse ApiPlatform\\Core\\Bridge\\Doctrine\\Common\\PropertyHelperTrait;\n\nclass SimpleSearchFilter extends AbstractContextAwareFilter\n{\n private $searchParameterName;\n\n /**\n * Add configuration parameter\n * {@inheritdoc}\n * @param string $searchParameterName The parameter whose value this filter searches for\n */\n public function __construct(ManagerRegistry $managerRegistry, ?RequestStack $requestStack = null, LoggerInterface $logger = null, array $properties = null, NameConverterInterface $nameConverter = null, string $searchParameterName = 'search')\n {\n parent::__construct($managerRegistry, $requestStack, $logger, $properties, $nameConverter);\n\n $this->searchParameterName = $searchParameterName;\n }\n\n /** {@inheritdoc} */\n protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null, array $context = [])\n {\n if (null === $value || $property !== $this->searchParameterName) {\n return;\n }\n\n $words = explode(' ', $value);\n foreach ($words as $word) {\n if (empty($word)) continue;\n $this->addWhere($queryBuilder, $word, $property, $queryNameGenerator,$resourceClass);\n }\n }\n\n private function addWhere($queryBuilder, $word, $property, $queryNameGenerator,$resourceClass)\n {\n $parameterName = $queryNameGenerator->generateParameterName($property);\n\n\n // Build OR expression\n $orExp = $queryBuilder->expr()->orX();\n foreach ($this->getProperties() as $property) {\n if ($this->isPropertyNested($property, $resourceClass)) {\n $alias = $queryBuilder->getRootAliases()[0];\n [$alias, $property ] = $this->addJoinsForNestedProperty($property, $alias, $queryBuilder, $queryNameGenerator, $resourceClass);\n }\n $orExp->add($queryBuilder->expr()->like('LOWER('. $alias. '.' . $property. ')', ':' . $parameterName));\n }\n\n $queryBuilder\n ->andWhere('(' . $orExp . ')')\n ->setParameter($parameterName, '%' . strtolower($word). '%');\n }\n}\n```\n\n========================================\n\nComments:\n- Thank you for the code. I made an improvement, which can also handle nested properties. To do so use the `use ApiPlatform\\Core\\Bridge\\Doctrine\\Common\\PropertyHelperTrait;` and modify the foreach loop inside `addWhere` to use `$this->addJoinsForNestedProperty`\n- This looks very good @MetaClass! I'll try this with unit tests and report back.\n- super awesome! Thanks!/Bedankt! :)\n- thx very much. You save my day :)","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":643,"estimatedTokens":5474}}693{"id":"stack-63293280","source":"stackoverflow","questionId":63293280,"title":"Optional argument - Mutation - TypeGraphQL","tags":["graphql","prisma-graphql","typegraphql"],"text":"Title: Optional argument - Mutation - TypeGraphQL\nTags: graphql, prisma-graphql, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI want to update the `firstName` and `lastName` of a `profile` entity.\n\nI would like the user to be able to update both of them or just one of them.\n**However** I do not know how to make the mutation such that one of the argument (`firstName` and `lastName`) is optional.\n\n**My Current code** It works if the user inputs both `firstName` and `lastName`\n\n```\n@Mutation(() => Boolean)\n @UseMiddleware(isAuth)\n async updateProfile(\n @Ctx() {payload}: MyContext,\n @Arg('firstName') firstName: string,\n @Arg('lastName') lastName: string,\n ) {\n\n try {\n const profile = await Profile.findOne({where: { user: payload!.userId}})\n if (profile) {\n profile.firstName = firstName\n profile.lastName = lastName\n await profile.save();\n\n return true\n }\n return false\n } catch(err) {\n return false\n }\n }\n```\n\nIf I run the mutation (excluding one argument):\n\n```\nmutation{\n updateProfile(firstName: \"test\")\n}\n```\n\nI get the error:\n\n\"message\": \"Field \"updateProfile\" argument \"lastName\" of type \"String!\" is required, but it was not provided.\n\nI was thinking that a workaround could be passing a default argument in the `@Arg` but then I realised that the default argument is static, not dynamic so I cannot pass the `firstName` or `lastName` for that specific profile\n\n========================================\n\nCode:\n```text\n@Mutation(() => Boolean)\n @UseMiddleware(isAuth)\n async updateProfile(\n @Ctx() {payload}: MyContext,\n @Arg('firstName') firstName: string,\n @Arg('lastName') lastName: string,\n ) {\n\n try {\n const profile = await Profile.findOne({where: { user: payload!.userId}})\n if (profile) {\n profile.firstName = firstName\n profile.lastName = lastName\n await profile.save();\n\n return true\n }\n return false\n } catch(err) {\n return false\n }\n }\n```\n\n```text\nmutation{\n updateProfile(firstName: \"test\")\n}\n```\n\n```text\nfirstName\n```\n\n```text\nlastName\n```\n\n```text\nprofile\n```\n\n```text\nfirstName\n```\n\n```text\nlastName\n```\n\n```text\nfirstName\n```\n\n```text\nlastName\n```\n\n```text\n@Arg\n```\n\n```text\nfirstName\n```\n\n```text\nlastName\n```\n\n```text\n@Arg('firstName', { nullable: true }) firstName: string,\n@Arg('lastName', { nullable: true }) lastName: string,\n```\n\n```text\n@Arg\n```\n\n========================================\n\nComments:\n- Thanks. Do you suggest to create a mutation for each argument? One to update the `firstName` and one to update the `lastName`? Can this be a solution? My fear is that I will have too many mutations if I this path\n- It really depends on your use case. As a rule of thumb, though, it's better to have more granular queries and mutations so that their intent is more clearly communicated to anyone consuming them.","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":139,"estimatedTokens":707}}694{"id":"stack-67392575","source":"stackoverflow","questionId":67392575,"title":"How to access Response object in NestJS GraphQL resolver","tags":["node.js","typescript","graphql","nestjs","typegraphql"],"text":"Title: How to access Response object in NestJS GraphQL resolver\nTags: node.js, typescript, graphql, nestjs, typegraphql\nSource: Stack Overflow\n\nQuestion:\nHow can I access pass `@Res()` into my graphql resolvers?\n\nthis doesn't work:\n\n```\n@Mutation(() => String)\n login(@Args('loginInput') loginInput: LoginInput, @Res() res: Response) {\n return this.authService.login(loginInput, res);\n }\n```\n\n========================================\n\nCode:\n```text\n@Mutation(() => String)\n login(@Args('loginInput') loginInput: LoginInput, @Res() res: Response) {\n return this.authService.login(loginInput, res);\n }\n```\n\n```text\n@Res()\n```\n\n```text\n@Res()\n```\n\n```text\nres\n```\n\n```text\ncontext\n```\n\n```text\ncontext: ({ req, res }) => ({ req, res })\n```\n\n```text\nGraphqlModule\n```\n\n```text\n@Context() ctx\n```\n\n```text\nctx.res\n```\n\n========================================\n\nComments:\n- Is there any way to implement this in a type-safe manner, without explicit type assertions that use the `as` operator?","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":62,"estimatedTokens":248}}695{"id":"stack-61468834","source":"stackoverflow","questionId":61468834,"title":"How to request the schema from a GraphQL service using curl?","tags":["graphql"],"text":"Title: How to request the schema from a GraphQL service using curl?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI have a curl script (as a standin for real code) that can POST to my company's GraphQL endoint and get data. It's working fine.\n\nIt appears that it should also be possible to get the \"schema\" by crafting the appropriate request, but I have not found any way to do that at a HTTP level.\n\nIf it is possible, what would the curl look like (the data)?\n\nAre there other requests other than \"query\" that I can use to gleen other information?\n\n========================================\n\nCode:\n```text\n{ \n \"query\": \"query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n description\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\"\n}\n```\n\n```text\ncurl -i -X POST http://localhost:8080/graphql -H \"Content-Type: application/json\" -d @introspection_query.json\n```\n\n========================================\n\nComments:\n- Introspection queries like these are the only way to get a JSON representation of the schema from the GraphQL service itself. But if you want to turn that into an actual schema object in the programming language of your choice, there's probably a function for that. For example, the JavaScript reference implementation has this.\n- I'm very happy you stole this! I would never have found it on my own and it never occurred to me to search on GraphQL and introspection (face palm!).\n- I just read this against my API and it worked!!! A request to anyone who finds this of interest: please visit the GitHub link above and Star the gist. Really, there wasn't a single star until I added one.\n- Although line breaks are not allowed in .json files (for valid json you need to replace spaces with \\n) this code still worked, thanks.","metadata":{"transformedAt":"2026-08-18T18:32:36.076Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":123,"estimatedTokens":814}}696{"id":"stack-57914065","source":"stackoverflow","questionId":57914065,"title":"How to extend the context object of a GraphQL call?","tags":["javascript","node.js","express","graphql","passport.js"],"text":"Title: How to extend the context object of a GraphQL call?\nTags: javascript, node.js, express, graphql, passport.js\nSource: Stack Overflow\n\nQuestion:\nI'm having the following GraphQL server call in a standard module:\n\n```\nexport default () => {\n return graphqlHTTP({\n schema: schema,\n graphiql: true,\n pretty: true,\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack,\n path: error.path\n })\n });\n};\n```\n\nThat is used together with passport:\n\n```\napp.use(\n \"/graphql\",\n passport.authenticate(\"jwt\", { session: false }),\n appGraphQL()\n);\n```\n\nEverything is working file. Passport extends my `req` to get a logged user object that is used on my GraphQL calls to queries or mutations:\n\n```\n...\n resolve(source, args, context) {\n console.log(\"CURRENT USER OBJECT\")\n console.log(context.user)\n...\n```\n\nAll fine. \n\nNow I need to extend my context to add some custom resolvers, so my first try is:\n\n```\nexport default () => {\n return graphqlHTTP({\n schema: schema,\n graphiql: true,\n pretty: true,\n context: resolvers,\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack,\n path: error.path\n })\n });\n};\n```\n\nAs GraphQL docs says, this overrides the original req context and my `context.user` on queries and mutations stops working.\n\nHow can I properly extend the current context to add some more fields, instead of overriding it? Another unsuccessfull try:\n\n```\nexport default (req) => {\n return graphqlHTTP({\n schema: schema,\n graphiql: true,\n pretty: true,\n context: {\n user: req.user,\n resolvers: resolvers\n },\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack,\n path: error.path\n })\n });\n};\n```\n\nThis approach is not working... I'm getting the following error:\n\n```\nuser: req.user,\n ^\n\nTypeError: Cannot read property 'user' of undefined\n```\n\n[edit]\nMy latest try is from my example on Apollo Docs:\n\n```\nexport default () => {\n return graphqlHTTP({\n schema: schema,\n graphiql: true,\n pretty: true,\n context: ({ req }) => ({\n user: req.user\n }),\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack,\n path: error.path\n })\n });\n};\n```\n\nNow my context is a function in my resolver:\n\n```\nconsole.log(context)\nconsole.log(context.user)\n```\n\nReturns:\n\n```\n[Function: context]\nundefined\n```\n\nGetting crazy with this simple thing...\n\n========================================\n\nTop Answer:\nI tried getting the data from the context in my resolver after passing it to my **graphqlHTTP** function to no avail. I later tried printing my request object and voila, it worked.\n\n```\n// app.js\n\napp.use(\n \"/graphql\",\n graphqlHTTP((req, res) => {\n return {\n schema: schema,\n rootValue: resolver,\n graphiql: true,\n context: { user, req, res }\n } \n })\n);\n```\n\n```\n// api.resolver.js\n\ngetUsers: ({}, request, context) => {\n console.log(request.user)\n return Object.values(db.user);\n}\n```\n\n========================================\n\nCode:\n```text\nexport default () => {\n return graphqlHTTP({\n schema: schema,\n graphiql: true,\n pretty: true,\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack,\n path: error.path\n })\n });\n};\n```\n\n```text\napp.use(\n \"/graphql\",\n passport.authenticate(\"jwt\", { session: false }),\n appGraphQL()\n);\n```\n\n```text\n...\n resolve(source, args, context) {\n console.log(\"CURRENT USER OBJECT\")\n console.log(context.user)\n...\n```\n\n```text\nexport default () => {\n return graphqlHTTP({\n schema: schema,\n graphiql: true,\n pretty: true,\n context: resolvers,\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack,\n path: error.path\n })\n });\n};\n```\n\n```text\nexport default (req) => {\n return graphqlHTTP({\n schema: schema,\n graphiql: true,\n pretty: true,\n context: {\n user: req.user,\n resolvers: resolvers\n },\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack,\n path: error.path\n })\n });\n};\n```\n\n```text\nuser: req.user,\n ^\n\nTypeError: Cannot read property 'user' of undefined\n```\n\n```text\nexport default () => {\n return graphqlHTTP({\n schema: schema,\n graphiql: true,\n pretty: true,\n context: ({ req }) => ({\n user: req.user\n }),\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack,\n path: error.path\n })\n });\n};\n```\n\n```text\nconsole.log(context)\nconsole.log(context.user)\n```\n\n```text\n[Function: context]\nundefined\n```\n\n```text\nreq\n```\n\n```text\ncontext.user\n```\n\n```text\napp.use(\n '/graphql',\n graphqlHTTP({ ... })\n)\n```\n\n```text\napp.use(\n '/graphql',\n graphqlHTTP((req, res, graphQLParams) => {\n return { ... }\n })\n)\n```\n\n```text\napp.use(\n '/graphql',\n graphqlHTTP((req, res, graphQLParams) => {\n return {\n schema,\n // other options\n context: {\n user: req.user,\n // whatever else you want\n }\n }\n })\n)\n```\n\n```text\nexpress-graphql\n```\n\n```text\ngraphqlHTTP\n```\n\n```text\nreq\n```\n\n```text\nres\n```\n\n```text\ngraphQLParams\n```\n\n```text\n// app.js\n\napp.use(\n \"/graphql\",\n graphqlHTTP((req, res) => {\n return {\n schema: schema,\n rootValue: resolver,\n graphiql: true,\n context: { user, req, res }\n } \n })\n);\n```\n\n```js\n// api.resolver.js\n\ngetUsers: ({}, request, context) => {\n console.log(request.user)\n return Object.values(db.user);\n}\n```\n\n========================================\n\nComments:\n- If you're getting that TypeError, it means you're not passing `req` to the exported function wherever it's being called in the rest of your code.\n- Sure... Check my last try... crazy...\n- Great explanation! The parameters comes from `graphqlHTTP`, not from the `app.use()` itself. Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":364,"estimatedTokens":1567}}697{"id":"stack-47876610","source":"stackoverflow","questionId":47876610,"title":"Cassandra/Scylla as graph database backen for JanusGraph and API exposed with GraphQl","tags":["cassandra","graphql","tinkerpop","janusgraph","scylla"],"text":"Title: Cassandra/Scylla as graph database backen for JanusGraph and API exposed with GraphQl\nTags: cassandra, graphql, tinkerpop, janusgraph, scylla\nSource: Stack Overflow\n\nQuestion:\nI am looking for a Graph database using Scylla or Cassandra as the backend and then expose the web api as GraphQl.\n\nCan you help me verify that I have got the followin stack right:\n\n- GraphQl or TinkerPop // Api schema, exposing api\n\n- JanusGraph(privious Titan) // Database layer facilitating grap structure\n\n- Cassasndra or Scylla\n\n========================================\n\nTop Answer:\nI like @MarcintheCloud's answer, just wanted to paraphrase and give my solution to the problem.\n\nGraphQL does not care or depend on any specific database type, KV, Graph, Document, etc and in fact markets itself as being able to fetch data from different sources. So you can create a UI to fetch the latest stock prices from redis, stock history from Mongo and similar stock by name from Elasticsearch. GraphQL will let you abstract that complexity away from your API (but it still exists elsewhere) allowing you to fetch all the data in one go. There is no relation between GraphQL and Graph databases.\n\nGremlin, in brief, is a powerful graph traversal comparable to what SQL is for some relational databases.\n\nDefinitions aside, how I use the both of them is by mapping GraphQL to Gremlin. I have attempted to create a standard around it https://github.com/The-Don-Himself/graphql2gremlin. Basically, it works by interchanging GraphQL arguments between vertexes and edges so a GraphQL query like this\n\n```\n{\n users(\n following: {\n users: {\n user_id: \"eq(5)\"\n }\n }\n ) {\n user_id\n username\n bio\n }\n}\n```\n\nMeans fetch a users followers for user_id 5 and get the id, username and bio fields. There are samples of much more complex GraphQL to Gremlin examples and it works perfect for my use case.\n\nThe gremlin traversal could look like this\n\n`g.V().hasLabel('users').has('user_id', eq(5)).in('following').hasLabel('users').values('user_id', 'username', 'bio')`\n\nI also open sourced a sample Twitter Graph in PHP if you want to play around with it https://github.com/The-Don-Himself/gremlin-ogm.\n\n========================================\n\nCode:\n```text\n{\n users(\n following: {\n users: {\n user_id: \"eq(5)\"\n }\n }\n ) {\n user_id\n username\n bio\n }\n}\n```\n\n```text\ng.V().hasLabel('users').has('user_id', eq(5)).in('following').hasLabel('users').values('user_id', 'username', 'bio')\n```\n\n========================================\n\nComments:\n- FYI, IBM chose JanusGraph and Scylla for their Compose DBaaS. Details about this choice were discussed at a conference: scylladb.com/tech-talk/…","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":77,"estimatedTokens":672}}698{"id":"stack-42058634","source":"stackoverflow","questionId":42058634,"title":"Upload image to GraphQL server","tags":["javascript","node.js","reactjs","graphql","react-apollo"],"text":"Title: Upload image to GraphQL server\nTags: javascript, node.js, reactjs, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm using react-dropzone and graphql-server-express-upload to upload an image all in GraphQL Apollo. In my client the file looks like this: https://i.sstatic.net/5V2wu.png\n\nBut in the server, when I log it, it looks like this:\n\n```\n{ preview: 'blob:http://localhost:3000/c622b0bd-3f0d-4f52-91f4-7676c8534c59' }\n```\n\nI'm following the instructions in the readme in graphql-server-express-upload, but no luck so far. How do I get the full image?\n\n========================================\n\nTop Answer:\nA different approach is to convert the binary image to BASE64 on the client side, before upload, then just populate the image as the BASE64 string on a GraphQLInputObjectType passed as an argument of a mutation. On the server the field can then simply be saved in a database column. For instance:\n\n```\nconst UserInputType = new GraphQLInputObjectType({\n name: 'UserInput',\n description: 'The user of our system',\n\n fields: () => ({\n username: {\n type: GraphQLString,\n description: 'Name of the user'\n },\n image: {\n type: GraphQLString,\n description: 'Image of the user'\n }\n })\n});\n```\n\n========================================\n\nCode:\n```text\n{ preview: 'blob:http://localhost:3000/c622b0bd-3f0d-4f52-91f4-7676c8534c59' }\n```\n\n```text\nconst UserInputType = new GraphQLInputObjectType({\n name: 'UserInput',\n description: 'The user of our system',\n\n fields: () => ({\n username: {\n type: GraphQLString,\n description: 'Name of the user'\n },\n image: {\n type: GraphQLString,\n description: 'Image of the user'\n }\n })\n});\n```\n\n```text\nconst UPLOAD_IMAGE = gql`\n mutation ($input: SetUploadImage!) {\n uploadImage(input: $input) {\n clientMutationId\n }\n }\n`;\n\n const Photo = ({ id }) => {\n const [ mutate ] = useMutation(UPLOAD_IMAGE);\n \n function onChange({target: { validity, files: [file] }}) {\n if (validity.valid) {\n mutate({\n variables: {\n input: {\n id,\n params: {\n image: file\n }\n }\n }\n });\n }\n }\n \n return (\n <div css={style}>\n <input type=\"file\" required onChange={onChange} />\n </div>\n )\n}\n```\n\n```text\nconst CLIENT = new ApolloClient({\n link: new createUploadLink({ ... })\n ...\n});\n```\n\n========================================\n\nComments:\n- why don't you use a static rest route for upload, and catch the response`filepath` of that rest route and update in the db with the response of filepath and fetch the image from path while the user queries\n- Could you add your code or github link? It would be much appreciated! there is little code out there I'm finding. Thank you!\n- Converting to Base64 is workable for smaller files. Base64 takes up more space than the original binary, so large files create an even larger payload. Also, don't store images in the DB. It bogs down the DB and clients can't use that data directly. Store images in a storage service such as S3.","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":111,"estimatedTokens":810}}699{"id":"stack-46135472","source":"stackoverflow","questionId":46135472,"title":"How to access the request object inside a GraphQL resolver (using Apollo-Server-Express)","tags":["javascript","express","passport.js","graphql","graphql-js"],"text":"Title: How to access the request object inside a GraphQL resolver (using Apollo-Server-Express)\nTags: javascript, express, passport.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have a standard express server using GraphQL\n\n```\nconst server = express();\n\nserver.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));\n```\n\nQuestion is: how can I access the `request` object inside a resolver? I want to check the JWT in some specific queries\n\nHere is the imported schema:\n\n```\nconst typeDefs = `\n type User {\n id: String,\n name: String,\n role: Int\n }\n type Query {\n user(id: String): User,\n users: [User]\n }\n`;\n\nconst resolvers = {\n Query: {\n user: (_, args, context, info) => users.find(u => u.id === args.id),\n users: (_, args, context, info) => users\n }\n}\n\nmodule.exports = makeExecutableSchema({typeDefs, resolvers});\n```\n\n========================================\n\nCode:\n```text\nconst server = express();\n\nserver.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));\n```\n\n```text\nconst typeDefs = `\n type User {\n id: String,\n name: String,\n role: Int\n }\n type Query {\n user(id: String): User,\n users: [User]\n }\n`;\n\nconst resolvers = {\n Query: {\n user: (_, args, context, info) => users.find(u => u.id === args.id),\n users: (_, args, context, info) => users\n }\n}\n\nmodule.exports = makeExecutableSchema({typeDefs, resolvers});\n```\n\n```text\nrequest\n```\n\n```text\nserver.use('/graphql', bodyParser.json(), graphqlExpress(req => ({\n schema,\n context: { user: req.user }\n}))\n```\n\n```text\nexpress-graphql\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":86,"estimatedTokens":402}}700{"id":"stack-57962916","source":"stackoverflow","questionId":57962916,"title":"How to use a Apollo GraphQL query result as the input of another one? Aka: request chaining","tags":["graphql","apollo","apollo-client","apollo-server"],"text":"Title: How to use a Apollo GraphQL query result as the input of another one? Aka: request chaining\nTags: graphql, apollo, apollo-client, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI know this has been asked a couple of times before, but I have found no definitive solution to whether this is possible with GraphQL. And I have a strong feeling this *should* be possible as it should be relatively easy to implement due to GraphQL queries running sequentially in Apollo.\n\nI have a situation where I'm doing a GraphQL mutation first on the client, and then immediately after doing a query which uses the results from the previous query. This causes a needlessly long response time waiting for the server to respond to both requests. The requests look like this:\n\n```\nmutation createWebSession($authId: ID!) {\n webSession: createWebSession(authId: $authId) {\n token\n userId\n }\n}\n\nquery listUserPaymentMethods($userId: ID!) {\n userPaymentMethods: paymentMethods(userId: $userId) {\n id\n }\n}\n```\n\nI know that one simple band-aid solution to **avoid** making 2 round trips to the server is creating a new single GraphQL mutation endpoint that does both services on the back end. But that seems to defeat the purpose of writing modular, reusable GraphQL endpoints. As such, I'm curious if someone knows if Apollo GraphQL supports a cleaner way to chain 2 requests in which the results from the previous one are available to the next one as inputs.\n\nAny help would be greatly appreciated, thanks.\n\n========================================\n\nCode:\n```text\nmutation createWebSession($authId: ID!) {\n webSession: createWebSession(authId: $authId) {\n token\n userId\n }\n}\n\nquery listUserPaymentMethods($userId: ID!) {\n userPaymentMethods: paymentMethods(userId: $userId) {\n id\n }\n}\n```\n\n```text\noperationName\n```\n\n```text\ncreateWebSession\n```\n\n```text\nQuery\n```\n\n========================================\n\nComments:\n- That is a fantastic, detailed explanation of the why it can't be done. Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":62,"estimatedTokens":499}}701{"id":"stack-65773349","source":"stackoverflow","questionId":65773349,"title":"Is there a way to ignore all fields by default on a GraphQL type and only add the wanted field?","tags":["asp.net",".net","graphql","hotchocolate"],"text":"Title: Is there a way to ignore all fields by default on a GraphQL type and only add the wanted field?\nTags: asp.net, .net, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nIs there a way to ignore all fields by default on a GraphQL type and only add the wanted field?\n\nHot Chocolate infers GraphQL type members form the C# type automatically.\n\nThis means that the following code ...\n\n```\npublic class Foo\n{\n public string Bar { get; set; }\n\n public string? Baz { get; set; }\n}\n```\n\n```\npublic class FooType : ObjectType\n{\n}\n```\n\nwill result in the following GraphQL type:\n\n```\ntype Foo {\n bar: String!\n baz: String\n}\n```\n\nIn my use-case I want to change this behavior and define explicitly which type member of my C# type is used in the GraphQL type.\n\n========================================\n\nCode:\n```cs\npublic class Foo\n{\n public string Bar { get; set; }\n\n public string? Baz { get; set; }\n}\n```\n\n```text\npublic class FooType : ObjectType<Foo>\n{\n}\n```\n\n```text\ntype Foo {\n bar: String!\n baz: String\n}\n```\n\n```text\npublic class FooType : ObjectType<Foo>\n{\n protected override void Configure(IObjectTypeDescriptor<Person> descriptor)\n {\n // this defines that fields shall only be defined explicitly\n descriptor.BindFieldsExplicitly();\n\n // now declare the fields that you want to define.\n descriptor.Field(t => t.Bar); \n }\n}\n```\n\n```text\ntype Foo {\n bar: String!\n}\n```\n\n```text\nservices\n .AddGraphQLServer()\n .AddQueryType<Query>()\n // this option will, by default, define that you want to declare everything explicitly.\n .ModifyOptions(c => c.DefaultBindingBehavior = BindingBehavior.Explicit);\n```\n\n========================================\n\nComments:\n- Is there a way to default to explicit binding behavior for filter and sorting only? something like `.AddFiltering(c => c.DefaultBindingBehavior = BindingBehavior.Explicit)`\n- For completeness sake, there is also a reversed option (which is the default): `descriptor.Field(...).Ignore()`\n- Tiny remark, the schema of the answer is incorrect I think. \"baz\" shouldn't be there as it is not explicitly defined. It's a bit confusing when you read it ;-)\n- true :) I fixed my answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":97,"estimatedTokens":552}}702{"id":"stack-69224864","source":"stackoverflow","questionId":69224864,"title":"Polymorphism in Prisma Schema - Best practices?","tags":["graphql","nexus","prisma","prisma-graphql","nexus-prisma"],"text":"Title: Polymorphism in Prisma Schema - Best practices?\nTags: graphql, nexus, prisma, prisma-graphql, nexus-prisma\nSource: Stack Overflow\n\nQuestion:\nThis is more a design question than a coding question. Suppose the following schema:\n\n```\n// schema.prisma\n// Solution 1\n\nmodel Entity {\n id Int @id @default(autoincrement())\n attrs EntityAttr[] \n}\n\nmodel EntityAttr {\n id Int @id @default(autoincrement())\n value Json // or String, doesnt matter much here\n // the point is I need to attach info on the\n // join table of this relation\n attr Attr @relation(fields: [attrId], references: [id])\n entity Entity @relation(fields: [entityId], references: [id])\n\n entityId Int\n attrId Int\n\n @@unique([entityId, attrId])\n}\n\nmodel Attr {\n id Int @id @default(autoincrement())\n entities EntityAttr[] \n}\n```\n\n```\n// Solution 2\nmodel Entity {\n id Int @id @default(autoincrement())\n dateAttrs DateAttr[]\n recordAttrs RecordAttr[]\n // ... this pattern could continue for more Attr-like models\n}\n\nmodel DateAttr {\n id Int @id @default(autoincrement())\n name String\n entity Entity @relation(fields: [entityId], references: [id])\n value DateTime // Stronger typing in generated code\n}\n\nmodel RecordAttr {\n // ... define another Entity @relation(...)\n name String\n value String\n // ...\n}\n\n// ... and so on\n```\n\n`Please note that the schema might not be 100% complete or accurate. It is mainly to get the point across.`\n\nSolution 1 has its merits where redundancy and the number of tables in the database is reduced significantly (depending on the number of `Attr`s). Its downfall comes as confusing queries`*`, possible case-specific type casting and no code-completion for the `value` field for each `Attr`-like model.\n\n`*` by confusing, I mean that the option for simplified m-n queries in `prisma` is functionally disabled when using a custom join table (e.g. `EntityAttr`)\n\nSolution 2 has its merits where the generated code results in more strongly typed code generation for the `value` field, however it falls in the number of generated tables (I don't actually know if more tables is a good thing or a bad thing, all I think is that if you have similar values, they ought to be in the same table).\n\n**What would you do in my shoes?**\n\n========================================\n\nTop Answer:\nSometimes the use case can't be generalized to abstract and have a typing's.\n\nif you control them and has a limited attribute sure you can create each attribute as a separate table each has it is own schema.\n\nSome Times more freedom is needed or the blocks are dynamic.\n\nUse Case: Build A Block Document Editor Like 'notion.so' and you want to let the user create custom blocks or configure them.\n\nyou can do it like :\n\n```\nmodel Document {\n id String @id\n blocks Block[]\n}\n\nmodel Block {\n id String @id\n value Json\n index Int\n customConfig Json?\n document Document? @relation(fields: [documentID], references: [id])\n documentID String?\n blockType BlockType @relation(fields: [blockTypeID], references: [id])\n blockTypeID String\n}\n\nmodel BlockType {\n id String @id\n name String\n config Json\n blocks Block[]\n}\n```\n\nwhere config and custom config can contains html,custom css classes, link attribute color or anything.\n\nusing type script you can create block.types.ts and add different let say templates for the config's .\n\nI hope that I was useful to you, To sum it, it depends on the requirements :>)\n\n========================================\n\nCode:\n```text\n// schema.prisma\n// Solution 1\n\nmodel Entity {\n id Int @id @default(autoincrement())\n attrs EntityAttr[] \n}\n\nmodel EntityAttr {\n id Int @id @default(autoincrement())\n value Json // or String, doesnt matter much here\n // the point is I need to attach info on the\n // join table of this relation\n attr Attr @relation(fields: [attrId], references: [id])\n entity Entity @relation(fields: [entityId], references: [id])\n\n entityId Int\n attrId Int\n\n @@unique([entityId, attrId])\n}\n\nmodel Attr {\n id Int @id @default(autoincrement())\n entities EntityAttr[] \n}\n```\n\n```text\n// Solution 2\nmodel Entity {\n id Int @id @default(autoincrement())\n dateAttrs DateAttr[]\n recordAttrs RecordAttr[]\n // ... this pattern could continue for more Attr-like models\n}\n\nmodel DateAttr {\n id Int @id @default(autoincrement())\n name String\n entity Entity @relation(fields: [entityId], references: [id])\n value DateTime // Stronger typing in generated code\n}\n\nmodel RecordAttr {\n // ... define another Entity @relation(...)\n name String\n value String\n // ...\n}\n\n// ... and so on\n```\n\n```text\nPlease note that the schema might not be 100% complete or accurate. It is mainly to get the point across.\n```\n\n```text\nAttr\n```\n\n```text\n*\n```\n\n```text\nvalue\n```\n\n```text\nAttr\n```\n\n```text\n*\n```\n\n```text\nprisma\n```\n\n```text\nEntityAttr\n```\n\n```text\nvalue\n```\n\n```text\nmodel Photo {\n id Int @id @default(autoincrement())\n\n likes Like[] @relation(\"PhotoLike\")\n}\n\nmodel Video {\n id Int @id @default(autoincrement())\n\n likes Like[] @relation(\"VideoLike\")\n}\n\nenum LikableType {\n Photo\n Video\n}\n\nmodel Like {\n id Int @id @default(autoincrement())\n\n Photo Photo? @relation(\"PhotoLike\", fields: [likableId], references: [id], map: \"photo_likableId\")\n Video Video? @relation(\"VideoLike\", fields: [likableId], references: [id], map: \"video_likableId\")\n\n likableId Int\n likableType LikableType\n}\n```\n\n```text\nprisma\n```\n\n```text\npolymorphism\n```\n\n```text\nmodel Document {\n id String @id\n blocks Block[]\n}\n\nmodel Block {\n id String @id\n value Json\n index Int\n customConfig Json?\n document Document? @relation(fields: [documentID], references: [id])\n documentID String?\n blockType BlockType @relation(fields: [blockTypeID], references: [id])\n blockTypeID String\n}\n\nmodel BlockType {\n id String @id\n name String\n config Json\n blocks Block[]\n}\n```\n\n```text\nmodel Obj{\n id String @default(cuid())\n objType ObjType\n user User?\n publisher Publisher?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n subscribers Subscription[]\n @@id([id,objType])\n}\n\nenum ObjType{\n Publisher\n User\n}\nmodel User {\n id String @id\n objType ObjType @default(User)\n obj Obj? @relation(fields: [id,objType],references: [id,objType],map:\"UserObj\")\n email String @unique\n phone String @unique\n otp String\n refreshToken String\n password String\n // posts Post[]\n roles Role[]\n subscriptions Subscription[] @relation(\"subscriber\")\n\n @@unique([id,objType])\n}\n\nmodel Publisher {\n id String @id\n objType ObjType @default(User)\n obj Obj? @relation(fields: [id,objType],references: [id,objType],map:\"PublisherObj\")\n name String\n @@unique([id,objType])\n}\n\n//subscription\nmodel Subscription {\n subscriber User @relation(\"subscriber\",fields: [subscriberId], references: [id])\n subscriberId String\n subscribed Obj @relation(fields: [subscribedId,subscribedType],references: [id,objType])\n subscribedId String\n subscribedType ObjType\n duration Int\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n @@id([subscriberId,subscribedId,subscribedType])\n}\n```\n\n```text\nmodel User {\n id Int @id @default(autoincrement())\n contents Content[]\n}\n \nmodel Content {\n id Int @id @default(autoincrement())\n published Boolean @default(false)\n owner User @relation(fields: [ownerId], references: [id])\n ownerId Int\n contentType String\n \n @@delegate(contentType)\n}\n\nmodel Post extends Content {\n title String\n}\n\nmodel Video extends Content {\n name String\n duration Int\n}\n```\n\n========================================\n\nComments:\n- Hi, You need to tell us about your use case to suggest the better way, there are more approaches than you mentioned.\n- I am getting Foreign key constraint failed on the field: `photo_likableId (index)` ----- if I pass likableId for video and I am getting Foreign key constraint failed on the field: `video_likableId (index)` if I pass likableId for photo.. Dit it worked on the insert operation?\n- thanks for your answer, suppose I have a subscription table that makes users related to the user and publisher table, how does Prisma distinguish subscriber users from the subscribed user in the user table?\n- as mr x says it does not work because of foreign key constraint failed\n- It works only if the `likeableId` provided on insert can be found both in the Photo and the Video tables. For example, if you provide `10` as `likeableId` and there is an Event with id `10` and a Video with id `10`, it works.\n- What does the `map:\"UserObj\"` do?\n- it is not needed. (map is required when you have multiple relation between same models)\n- Do you have any idea if there is a variation to this solution for MSSQL databases? Enums don't work in MSSQL\n- it is just metadata and is not needed. you can do it with a string or a relation to some external table that stores all your types. By the way, this type of polymorphism has some extra cost in the query and command and you should avoid using it in unnecessary situations.\n- it is better to have multiple subscription tables (or if it is needed a baseSubscription table and two separate PublisherSubscription and UserSubscription tables inherit from baseSubscription table) it is better design. (simpler and cleaner)","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":365,"estimatedTokens":2366}}703{"id":"stack-61930773","source":"stackoverflow","questionId":61930773,"title":"Graphene mutation with list as input","tags":["graphql","graphene-python"],"text":"Title: Graphene mutation with list as input\nTags: graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI have a graphene mutation like this:\n\n```\nclass User(ObjectType):\n username = String()\n\nclass ImportUsers(Mutation):\n class Arguments:\n users = List(User)\n Output = List(User)\n\n @staticmethod\n def mutation(root, info, users):\n ...\n```\n\nBut graphene gives me the following error: `AssertionError: Mutations.importUsers(users:) argument type must be Input Type but got: [User].`\n\nHow can I have a mutation in graphene which accepts a list of objects?\n\n========================================\n\nTop Answer:\nYeah so, basically, you need to have this:\n\n```\nclass User(graphene.ObjectType):\n username = graphene.String()\n\nclass ImportUsers(Mutation):\n class Arguments:\n users = graphene.List(User)\n\n Output = graphene.List(User)\n\n @staticmethod\n def mutation(root, info, users):\n ...\n```\n\nGraphene has a List type. Also, I don't know if it's just me or not, but I think you need to have graphene.(type), not just the type. I am working on something very similar right now to this, so hopefully you find or found your solution, and if you do, let me know how it went! Hopefully I helped xD. I am kinda new to all of this so ye\n\n========================================\n\nCode:\n```py\nclass User(ObjectType):\n username = String()\n\nclass ImportUsers(Mutation):\n class Arguments:\n users = List(User)\n Output = List(User)\n\n @staticmethod\n def mutation(root, info, users):\n ...\n```\n\n```text\nAssertionError: Mutations.importUsers(users:) argument type must be Input Type but got: [User].\n```\n\n```py\nclass User(graphene.InputObjectType): # <-- Changed to InputObjectType\n username = graphene.String()\n```\n\n```text\ngraphene.InputObjectType\n```\n\n```text\ngraphene.ObjectType\n```\n\n```text\nUser\n```\n\n```text\nclass User(graphene.ObjectType):\n username = graphene.String()\n\nclass ImportUsers(Mutation):\n class Arguments:\n users = graphene.List(User)\n\n Output = graphene.List(User)\n\n @staticmethod\n def mutation(root, info, users):\n ...\n```\n\n========================================\n\nComments:\n- I get an error (listOfUsers:) argument type must be Input Type but got: [User].\n- That is because the class User must be of the type graphene.InputObjectType, so it could be used as an Argument in Mutation class.","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":105,"estimatedTokens":589}}704{"id":"stack-56106736","source":"stackoverflow","questionId":56106736,"title":"Error: Valid values for the strategy argument of `@scalarList` are: RELATION","tags":["graphql","prisma","prisma-graphql"],"text":"Title: Error: Valid values for the strategy argument of `@scalarList` are: RELATION\nTags: graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nProgram pops up this -> (Valid values for the strategy argument of `@scalarList` are: RELATION.) after run prisma deploy. Any one knows why ? \n\n```\ntype User {\n id: ID! @id\n name: String!\n email: String! @unique\n password: String!\n age: Int\n img: String\n location: Location\n hostedEvents: [Event]! @relation(name: \"HostedEvents\", onDelete: CASCADE)\n joinedEvents: [Event]! @relation(name: \"EventMembers\", onDelete: CASCADE)\n pushNotificationTokens: [PushNotificationTokens]!\n createdAt: DateTime! @createdAt\n updatedAt: DateTime! @updatedAt\n}\n```\n\n```\ntype Event {\n id: ID! @id\n owner: User! @relation(name: \"HostedEvents\")\n name: String!\n imgs: [String]!\n description: String\n start: DateTime!\n end: DateTime!\n categories: [Category]!\n members: [User]! @relation(name: \"EventMembers\")\n chatRoom: GroupChatRoom!\n pendingRequests: [PendingRequest]!\n locations: [Location]!\n comments: [Comment]!\n createdAt: DateTime! @createdAt\n updatedAt: DateTime! @updatedAt\n}\n```\n\n========================================\n\nCode:\n```text\ntype User {\n id: ID! @id\n name: String!\n email: String! @unique\n password: String!\n age: Int\n img: String\n location: Location\n hostedEvents: [Event]! @relation(name: \"HostedEvents\", onDelete: CASCADE)\n joinedEvents: [Event]! @relation(name: \"EventMembers\", onDelete: CASCADE)\n pushNotificationTokens: [PushNotificationTokens]!\n createdAt: DateTime! @createdAt\n updatedAt: DateTime! @updatedAt\n}\n```\n\n```text\ntype Event {\n id: ID! @id\n owner: User! @relation(name: \"HostedEvents\")\n name: String!\n imgs: [String]!\n description: String\n start: DateTime!\n end: DateTime!\n categories: [Category]!\n members: [User]! @relation(name: \"EventMembers\")\n chatRoom: GroupChatRoom!\n pendingRequests: [PendingRequest]!\n locations: [Location]!\n comments: [Comment]!\n createdAt: DateTime! @createdAt\n updatedAt: DateTime! @updatedAt\n}\n```\n\n```text\n@scalarList\n```\n\n```text\ntype Event {\n id: ID! @id\n owner: User! @relation(name: \"HostedEvents\")\n name: String!\n imgs: [String!]! @scalarList(strategy: RELATION)\n description: String\n start: DateTime!\n end: DateTime!\n categories: [Category]!\n members: [User]! @relation(name: \"EventMembers\")\n chatRoom: GroupChatRoom!\n pendingRequests: [PendingRequest]!\n locations: [Location]!\n comments: [Comment]!\n createdAt: DateTime! @createdAt\n updatedAt: DateTime! @updatedAt\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":107,"estimatedTokens":631}}705{"id":"stack-54293234","source":"stackoverflow","questionId":54293234,"title":"GraphQl variable using grapiql - variable is undefined","tags":["java","graphql","graphql-java","graphiql"],"text":"Title: GraphQl variable using grapiql - variable is undefined\nTags: java, graphql, graphql-java, graphiql\nSource: Stack Overflow\n\nQuestion:\nI am using this endpoint:\n\n```\n@PostMapping(\"graphql\")\n public ResponseEntity getResource(@RequestBody Object query) { // String query\n ExecutionResult result;\n if (query instanceof String) {\n result = graphQL.execute(query.toString()); // if plain text\n } else{\n String queryString = ((HashMap) query).get(\"query\").toString();\n Object variables = ((HashMap) query).get(\"variables\");\n ExecutionInput input = ExecutionInput.newExecutionInput()\n .query(queryString)\n .variables((Map) variables) // \"var1\" -> \"test1\"\n .build();\n\n result = graphQL.execute(input);\n }\n return new ResponseEntity(result, HttpStatus.OK);\n }\n```\n\nWhen i don't have variable it works fine:\n\n```\nquery {\n getItem(dictionaryType: \"test1\") {\n code\n name\n description\n }\n}\n```\n\nhttps://i.sstatic.net/HCRSg.png\n\nWhen i add `variable` it starts to fail, see here:\n\n```\nquery {\n getItem(dictionaryType: $var1) {\n code\n name\n description\n }\n}\n```\n\nhttps://i.sstatic.net/jBbXj.png\n\nIn my `schema` i have defined the `query` section as followed:\n\n```\ntype Query {\n getItem(dictionaryType: String): TestEntity\n}\n```\n\nIn `java` code:\n\n```\n@Value(\"classpath:test.graphqls\")\nprivate Resource schemaResource;\nprivate GraphQL graphQL;\n\n@PostConstruct\nprivate void loadSchema() throws IOException {\n File schemaFile = schemaResource.getFile();\n TypeDefinitionRegistry registry = new SchemaParser().parse(schemaFile);\n RuntimeWiring wiring = buildWiring();\n GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(registry, wiring);\n graphQL = GraphQL.newGraphQL(schema).build();\n}\n\nprivate RuntimeWiring buildWiring() {\n initializeFetchers();\n return RuntimeWiring.newRuntimeWiring()\n .type(\"Query\", typeWriting -> typeWriting\n .dataFetcher(\"getItem\", dictionaryItemFetcher)\n\n )\n .build();\n}\n\nprivate void initializeFetchers() {\n dictionaryItemFetcher = dataFetchingEnvironment ->\n dictionaryService.getDictionaryItemsFirstAsString(dataFetchingEnvironment.getArgument(\"dictionaryType\"));\n}\n```\n\n========================================\n\nCode:\n```text\n@PostMapping(\"graphql\")\n public ResponseEntity<Object> getResource(@RequestBody Object query) { // String query\n ExecutionResult result;\n if (query instanceof String) {\n result = graphQL.execute(query.toString()); // if plain text\n } else{\n String queryString = ((HashMap) query).get(\"query\").toString();\n Object variables = ((HashMap) query).get(\"variables\");\n ExecutionInput input = ExecutionInput.newExecutionInput()\n .query(queryString)\n .variables((Map<String, Object>) variables) // \"var1\" -> \"test1\"\n .build();\n\n result = graphQL.execute(input);\n }\n return new ResponseEntity<Object>(result, HttpStatus.OK);\n }\n```\n\n```text\nquery {\n getItem(dictionaryType: \"test1\") {\n code\n name\n description\n }\n}\n```\n\n```text\nquery {\n getItem(dictionaryType: $var1) {\n code\n name\n description\n }\n}\n```\n\n```text\ntype Query {\n getItem(dictionaryType: String): TestEntity\n}\n```\n\n```text\n@Value(\"classpath:test.graphqls\")\nprivate Resource schemaResource;\nprivate GraphQL graphQL;\n\n@PostConstruct\nprivate void loadSchema() throws IOException {\n File schemaFile = schemaResource.getFile();\n TypeDefinitionRegistry registry = new SchemaParser().parse(schemaFile);\n RuntimeWiring wiring = buildWiring();\n GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(registry, wiring);\n graphQL = GraphQL.newGraphQL(schema).build();\n}\n\n\nprivate RuntimeWiring buildWiring() {\n initializeFetchers();\n return RuntimeWiring.newRuntimeWiring()\n .type(\"Query\", typeWriting -> typeWriting\n .dataFetcher(\"getItem\", dictionaryItemFetcher)\n\n )\n .build();\n}\n\nprivate void initializeFetchers() {\n dictionaryItemFetcher = dataFetchingEnvironment ->\n dictionaryService.getDictionaryItemsFirstAsString(dataFetchingEnvironment.getArgument(\"dictionaryType\"));\n}\n```\n\n```text\nvariable\n```\n\n```text\nschema\n```\n\n```text\nquery\n```\n\n```text\njava\n```\n\n```text\nquery OptionalButRecommendedQueryName ($var1: String) {\n getItem(dictionaryType: $var1) {\n code\n name\n description\n }\n}\n```\n\n========================================\n\nComments:\n- Please update your question. The images should be removed and replaced with the text of the query you were attempting as well as the error you received. That will help others encountering the same error find this question, and it will prevent issues if the images you posted are ever removed.\n- Daniel - in the future fell free to suggest edit - i will gladly accept it. I used an option available on stack-overflow - nothing more. I will edit the question in a moment.","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":206,"estimatedTokens":1248}}706{"id":"stack-75278888","source":"stackoverflow","questionId":75278888,"title":"Apollo GraphQL Lambda Handler Cannot read property 'method' of undefined","tags":["aws-lambda","graphql","apollo-server"],"text":"Title: Apollo GraphQL Lambda Handler Cannot read property 'method' of undefined\nTags: aws-lambda, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am trying to run Apollo GraphQL server inside my AWS lambda. I'm using the library from here. I'm also using CDK to deploy my lambda and the REST API Gateway.\n\nMy infrastructure is as follows:\n\n```\nconst helloFunction = new NodejsFunction(this, 'lambda', {\n entry: path.join(__dirname, \"lambda.ts\"),\n handler: \"handler\"\n});\n\nnew LambdaRestApi(this, 'apigw', {\n handler: helloFunction,\n});\n```\n\nThe lambda implementation is as follows:\n\n```\nconst typeDefs = `#graphql\n type Query {\n hello: String\n}`;\n\nconst resolvers = {\n Query: {\n hello: () => 'world',\n },\n};\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n introspection: true,\n})\n\nconsole.log('###? running lambda')\n\nexport const handler = startServerAndCreateLambdaHandler(\n server,\n handlers.createAPIGatewayProxyEventV2RequestHandler(), {\n middleware: [\n async (event) => {\n console.log('###? received event=' + JSON.stringify(event, null, 2))\n return async (result) => {\n console.log((\"###? result=\" + JSON.stringify(result, null, 2)))\n result\n }\n }\n ]\n });\n```\n\nWhen I POST to my endpoint with the appropriate query I get this error:\n\n```\n{\n \"statusCode\": 400,\n \"body\": \"Cannot read property 'method' of undefined\"\n}\n```\n\nI'm seeing my logging inside the lambda as expected and I can confirm the error is being returned in the 'result' from within startServerAndCreateLambdaHandler(). This code is based on the example for the @as-integrations/aws-lambda library. I don't understand why this is failing.\n\n========================================\n\nCode:\n```text\nconst helloFunction = new NodejsFunction(this, 'lambda', {\n entry: path.join(__dirname, \"lambda.ts\"),\n handler: \"handler\"\n});\n\nnew LambdaRestApi(this, 'apigw', {\n handler: helloFunction,\n});\n```\n\n```text\nconst typeDefs = `#graphql\n type Query {\n hello: String\n}`;\n\nconst resolvers = {\n Query: {\n hello: () => 'world',\n },\n};\n\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n introspection: true,\n})\n\nconsole.log('###? running lambda')\n\nexport const handler = startServerAndCreateLambdaHandler(\n server,\n handlers.createAPIGatewayProxyEventV2RequestHandler(), {\n middleware: [\n async (event) => {\n console.log('###? received event=' + JSON.stringify(event, null, 2))\n return async (result) => {\n console.log((\"###? result=\" + JSON.stringify(result, null, 2)))\n result\n }\n }\n ]\n });\n```\n\n```text\n{\n \"statusCode\": 400,\n \"body\": \"Cannot read property 'method' of undefined\"\n}\n```\n\n```text\nhandlers.createAPIGatewayProxyEventRequestHandler()\n```\n\n```text\nhandlers.createAPIGatewayProxyEventV2RequestHandler()\n```\n\n```text\nexport const handler = startServerAndCreateLambdaHandler(\n server,\n handlers.createAPIGatewayProxyEventRequestHandler(),\n {\n middleware: [\n async (event) => {\n console.log('###? received event=' + JSON.stringify(event))\n }\n ]\n }\n);\n```\n\n========================================\n\nComments:\n- I have several Apollo GraphQL lambdas running and I don't recognize a single line of the above code except for the *typeDefs*! (this kind of blows my mind) Which version of Apollo server are you using? Are you using the serverless package to deploy?\n- I am using \"@apollo/server\": \"^4.3.2\" and \"@as-integrations/aws-lambda\": \"^2.0.0\". \"aws-cdk\": \"2.61.1\" for deployment. I'm following the instructions here: npmjs.com/package/@as-integrations/aws-lambda\n- Hey, I'm using the same code, and having issue with API Gateway, when I test from AWS console requests works, but testing from curl I'm getting Forbidden error. Could you please your cloudformation template? Probably I'm missing something for permissions.\n- Thanks ! this worked. Can you explain ?","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":154,"estimatedTokens":991}}707{"id":"stack-53396717","source":"stackoverflow","questionId":53396717,"title":"How do I insert an optional field as null using AppSync Resolvers and Aurora?","tags":["amazon-web-services","graphql","aws-appsync","resolver","amazon-aurora"],"text":"Title: How do I insert an optional field as null using AppSync Resolvers and Aurora?\nTags: amazon-web-services, graphql, aws-appsync, resolver, amazon-aurora\nSource: Stack Overflow\n\nQuestion:\nI have an optional String field, *notes*, that is sometimes empty. If it's empty I want to insert *null*, otherwise I want to insert the string.\n\nHere is my resolver - \n\n```\n{\n \"version\" : \"2017-02-28\",\n \"operation\": \"Invoke\",\n #set($id = $util.autoId())\n #set($notes = $util.defaultIfNullOrEmpty($context.arguments.notes, 'null'))\n\n \"payload\": {\n \"sql\":\"INSERT INTO things VALUES ('$id', :NOTES)\",\n \"variableMapping\": {\n \":NOTES\" : $notes\n },\n \"responseSQL\": \"SELECT * FROM things WHERE id = '$id'\"\n }\n```\n\n} \n\nWith this graphql\n\n```\nmutation CreateThing{\n createThing() {\n id\n notes\n }\n}\n```\n\nI get -\n\n```\n{\n \"data\": {\n \"createRoll\": {\n \"id\": \"6af68989-0bdc-44e2-8558-aeb4c8418e93\",\n \"notes\": \"null\"\n }\n }\n```\n\n}\n\nwhen I really want *null* without the quotes.\n\nAnd with this graphql - \n\n```\nmutation CreateThing{\n createThing(notes: \"Here are some notes\") {\n id\n notes\n }\n}\n```\n\nI get -\n\n```\n{\n \"data\": {\n \"createThing\": {\n \"id\": \"6af68989-0bdc-44e2-8558-aeb4c8418e93\",\n \"notes\": \"Here are some notes\"\n }\n }\n}\n```\n\nwhich is what I want.\n\nHow do I get a quoteless null and a quoted string into the same field?\n\n========================================\n\nTop Answer:\nWe were looking into the same issue. For some reason, the accepted answer does not work for us. Maybe because it's a beta feature and there is a new resolver version (2018-05-29 vs 2017-02-28, changes here: Resolver Mapping Template Changelog).\n\nWe use this for the time being using `NULLIF()`:\n\n```\n{\n \"version\": \"2018-05-29\",\n \"statements\": [\n \"INSERT INTO sales_customers_addresses (`id`, `customerid`, `type`, `company`, `country`, `email`) VALUES (NULL, :CUSTOMERID, :TYPE, NULLIF(:COMPANY, ''), NULLIF(:COUNTRY, ''), :EMAIL)\"\n ],\n \"variableMap\": {\n \":CUSTOMERID\": $customerid,\n \":TYPE\": \"$type\",\n \":COMPANY\": \"$util.defaultIfNullOrEmpty($context.args.address.company, '')\",\n \":COUNTRY\": \"$util.defaultIfNullOrEmpty($context.args.address.country, '')\",\n \":EMAIL\": \"$context.args.address.email\"\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n \"version\" : \"2017-02-28\",\n \"operation\": \"Invoke\",\n #set($id = $util.autoId())\n #set($notes = $util.defaultIfNullOrEmpty($context.arguments.notes, 'null'))\n\n \"payload\": {\n \"sql\":\"INSERT INTO things VALUES ('$id', :NOTES)\",\n \"variableMapping\": {\n \":NOTES\" : $notes\n },\n \"responseSQL\": \"SELECT * FROM things WHERE id = '$id'\"\n }\n```\n\n```text\nmutation CreateThing{\n createThing() {\n id\n notes\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"createRoll\": {\n \"id\": \"6af68989-0bdc-44e2-8558-aeb4c8418e93\",\n \"notes\": \"null\"\n }\n }\n```\n\n```text\nmutation CreateThing{\n createThing(notes: \"Here are some notes\") {\n id\n notes\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"createThing\": {\n \"id\": \"6af68989-0bdc-44e2-8558-aeb4c8418e93\",\n \"notes\": \"Here are some notes\"\n }\n }\n}\n```\n\n```text\n#set($notes = $util.toJson($util.defaultIfNullOrEmpty($context.arguments.notes, null)))\n```\n\n```text\n#set($notes = $util.toJson($util.defaultIfNullOrEmpty($context.arguments.notes, null)))\n```\n\n```text\ntype Mutation {\n ...\n createPost(author: String!, content: String): Post\n ...\n}\ntype Post {\n id: ID!\n author: String!\n content: String\n views: Int\n comments: [Comment]\n}\n```\n\n```text\nfunction conditionallyCreatePostsTable(connection) {\n const createTableSQL = `CREATE TABLE IF NOT EXISTS posts (\n id VARCHAR(64) NOT NULL,\n author VARCHAR(64) NOT NULL,\n content VARCHAR(2048),\n views INT NOT NULL,\n PRIMARY KEY(id))`;\n return executeSQL(connection, createTableSQL);\n}\n```\n\n```text\n{\n \"version\" : \"2017-02-28\",\n \"operation\": \"Invoke\",\n #set($id = $util.autoId()) \n \"payload\": {\n \"sql\":\"INSERT INTO posts VALUES ('$id', :AUTHOR, :CONTENT, 1)\",\n \"variableMapping\": {\n \":AUTHOR\" : \"$context.arguments.author\",\n \":CONTENT\" : $util.toJson($util.defaultIfNullOrEmpty($context.arguments.content, null))\n },\n \"responseSQL\": \"SELECT id, author, content, views FROM posts WHERE id = '$id'\"\n }\n}\n```\n\n```text\n$util.toJson($context.result[0])\n```\n\n```text\nmutation CreatePost {\n createPost(author: \"Me\") {\n id\n author\n content\n views\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"createPost\": {\n \"id\": \"b42ee08c-956d-4b89-afda-60fe231e86d7\",\n \"author\": \"Me\",\n \"content\": null,\n \"views\": 1\n }\n }\n}\n```\n\n```text\nmutation CreatePost {\n createPost(author: \"Me\", content: \"content\") {\n id\n author\n content\n views\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"createPost\": {\n \"id\": \"c6af0cbf-cf05-4110-8bc2-833bf9fca9f5\",\n \"author\": \"Me\",\n \"content\": \"content\",\n \"views\": 1\n }\n }\n}\n```\n\n```text\n$util.toJson()\n```\n\n```text\n$context.arguments.notes\n```\n\n```text\n$notes\n```\n\n```text\ntoString()\n```\n\n```text\n$util.defaultIfNullOrEmpty($context.arguments.notes, 'null')\n```\n\n```text\n\"null\"\n```\n\n```text\n\"null\"\n```\n\n```text\n$util.defaultIfNullOrEmpty($context.arguments.notes, null)\n```\n\n```text\nnull\n```\n\n```text\n$notes\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\ncontent\n```\n\n```text\nposts\n```\n\n```text\ncontent\n```\n\n```text\ncreatePost\n```\n\n```text\n{\n \"version\": \"2018-05-29\",\n \"statements\": [\n \"INSERT INTO sales_customers_addresses (`id`, `customerid`, `type`, `company`, `country`, `email`) VALUES (NULL, :CUSTOMERID, :TYPE, NULLIF(:COMPANY, ''), NULLIF(:COUNTRY, ''), :EMAIL)\"\n ],\n \"variableMap\": {\n \":CUSTOMERID\": $customerid,\n \":TYPE\": \"$type\",\n \":COMPANY\": \"$util.defaultIfNullOrEmpty($context.args.address.company, '')\",\n \":COUNTRY\": \"$util.defaultIfNullOrEmpty($context.args.address.country, '')\",\n \":EMAIL\": \"$context.args.address.email\"\n }\n}\n```\n\n```text\nNULLIF()\n```\n\n========================================\n\nComments:\n- My answer is using the 2017-02-28 version because it's tied to a Lambda datasource not a RDS datasource. Lambda supports both 2017-02-28 and 2018-05-29 versions. The original question posted here was following this tutorial github.com/aws-samples/aws-appsync-rds-aurora-sample . It uses a Lambda as the AppSync datasource to proxy the RDS call. This tutorial was created before RDS was supported natively by AppSync, depending on your use case, it might make more sense now to use the RDS datasource directly.","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":358,"estimatedTokens":1642}}708{"id":"stack-45404808","source":"stackoverflow","questionId":45404808,"title":"graphql mutation gives syntax error: Expected Name","tags":["graphql"],"text":"Title: graphql mutation gives syntax error: Expected Name\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement mutations with a variable. But I get the following error:\n\n```\n\"Syntax Error GraphQL request (3:22) Expected Name, found $\n\n2: mutation {\n3: createProperty($property) {\n ^\n4: id\n\"\n```\n\nMy schema definitely doesn't say anything about a name, that's why I think this error is so strange.. I also don't think the documentations about graphql / apollo are very good.\n\n**Calling the mutation from client:**\n\n```\nconst property = {\n title: 'First house',\n cost: 849,\n bedrooms: 3,\n bathrooms: 2,\n car_spaces: 1,\n house_size: 60,\n };\n\n const createPropertyQuery =\n graphql(gql`\n mutation {\n createProperty($property) {\n id\n }\n }\n `, {\n options: {\n variables: {\n property,\n },\n },\n });\n\n const { data } = await apolloClient.query({\n query: createPropertyQuery,\n });\n```\n\n**Schema:**\n\n```\ntype Property {\n title: String!\n cost: Float\n user: User\n bedrooms: Int!\n bathrooms: Int!\n car_spaces: Int!\n house_size: Int!\n}\ninput propertyInput {\n title: String!\n cost: Float\n bedrooms: Int!\n bathrooms: Int!\n car_spaces: Int!\n house_size: Int!\n}\n\ntype RootMutation {\n createProperty (\n property: propertyInput\n ): Property\n}\n```\n\n========================================\n\nCode:\n```text\n\"Syntax Error GraphQL request (3:22) Expected Name, found $\n\n2: mutation {\n3: createProperty($property) {\n ^\n4: id\n\"\n```\n\n```text\nconst property = {\n title: 'First house',\n cost: 849,\n bedrooms: 3,\n bathrooms: 2,\n car_spaces: 1,\n house_size: 60,\n };\n\n const createPropertyQuery =\n graphql(gql`\n mutation {\n createProperty($property) {\n id\n }\n }\n `, {\n options: {\n variables: {\n property,\n },\n },\n });\n\n\n const { data } = await apolloClient.query({\n query: createPropertyQuery,\n });\n```\n\n```text\ntype Property {\n title: String!\n cost: Float\n user: User\n bedrooms: Int!\n bathrooms: Int!\n car_spaces: Int!\n house_size: Int!\n}\ninput propertyInput {\n title: String!\n cost: Float\n bedrooms: Int!\n bathrooms: Int!\n car_spaces: Int!\n house_size: Int!\n}\n\ntype RootMutation {\n createProperty (\n property: propertyInput\n ): Property\n}\n```\n\n```text\nmutation CreatePropertyMutatuin($property: propertyInput){\n createProperty(property: $property) {\n id\n }\n}\n```\n\n========================================\n\nComments:\n- You'll need to modify your query and actually declare the variable you are sending inside your operation definition. Please see this answer for a detailed explanation.\n- Possible duplicate of GraphQL - Syntax Error GraphQL request (5:15) Expected Name","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":162,"estimatedTokens":685}}709{"id":"stack-62558430","source":"stackoverflow","questionId":62558430,"title":"How does fetchMore return data to the component?","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: How does fetchMore return data to the component?\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI am trying to the example of cursor-based paginating with React Apollo (https://www.apollographql.com/docs/react/data/pagination/#cursor-based) but am struggling with *how my component that rendered the original data gets the new (appended) data*.\n\nThis is how we get the original data and pass it to the component:\n\n```\nconst { data: { comments, cursor }, loading, fetchMore } = useQuery(\n MORE_COMMENTS_QUERY\n);\n\n```\n\nWhat I'm unsure of is how the `fetchMore` function works.\n\n```\nonLoadMore={() =>\n fetchMore({\n query: MORE_COMMENTS_QUERY,\n variables: { cursor: cursor },\n updateQuery: (previousResult, { fetchMoreResult }) => {\n const previousEntry = previousResult.entry;\n const newComments = fetchMoreResult.moreComments.comments;\n const newCursor = fetchMoreResult.moreComments.cursor;\n\n return {\n // By returning `cursor` here, we update the `fetchMore` function\n // to the new cursor.\n cursor: newCursor,\n entry: {\n // Put the new comments in the front of the list\n comments: [...newComments, ...previousEntry.comments]\n },\n __typename: previousEntry.__typename\n };\n }\n })\n }\n```\n\nFrom what I understand, yes, once my component will cal this `onLoadMore` function (using a button's onClick for example), it will fetch the data based on a new cursor.\n\nMy question is this. I'm sorry if this is too simple and I'm not understanding something basic.\n\n**How does the component get the new data?**\n\nI know the data is there, because I console logged the `newComments` (in my case, it wasn't newComments, but you get the idea.) And I saw the new data! But those new comments, how are they returned to the component that needs the data? And if I click the button again, it is still stuck on the same cursor as before.\n\nWhat am I missing here?\n\n========================================\n\nTop Answer:\nIt depends on how you handle the offset. I'll try to simplify an example for you.\n\nThis is a simplified component that I use successfully:\n\n```\nconst PlayerStats = () => {\n const { data, loading, fetchMore } = useQuery(CUMULATIVE_STATS, {\n variables: sortVars,\n })\n\n const players = data.GetCumulativeStats\n\n const loadMore = () => {\n fetchMore({\n variables: { offset: players.length },\n updateQuery: (prevResult, { fetchMoreResult }) => {\n if (!fetchMoreResult) return prevResult\n return {\n ...prevResult,\n GetCumulativeStats: [\n ...prevResult.GetCumulativeStats,\n ...fetchMoreResult.GetCumulativeStats,\n ],\n }\n },\n })\n }\n```\n\nMy `CUMULATIVE_STATS` query returns 50 rows by default. I pass the length of that result array to my `fetchMore` query as `offset`. So when I execute `CUMULATIVE_STATS` with `fetchMore`, the variables of the query are both `sortVars` and `offset`.\n\nMy resolver in the backend handles the `offset` so that if it is, for example, 50, it ignores the first 50 results of the query and returns the next 50 from there (ie. rows 51-100).\n\nThen in the `updateQuery` I have two objects available: `prevResult` and `fetchMoreResult`. At this point I just combine them using spread operator. If no new results are returned, I return the previous results.\n\nWhen I have fetched more once, the results of `players.length` becomes 100 instead of 50. And that is my new offset and new data will be queried the next time I call `fetchMore`.\n\n========================================\n\nCode:\n```text\nconst { data: { comments, cursor }, loading, fetchMore } = useQuery(\n MORE_COMMENTS_QUERY\n);\n\n<Comments\n entries={comments || []}\n onLoadMore={...}\n/>\n```\n\n```text\nonLoadMore={() =>\n fetchMore({\n query: MORE_COMMENTS_QUERY,\n variables: { cursor: cursor },\n updateQuery: (previousResult, { fetchMoreResult }) => {\n const previousEntry = previousResult.entry;\n const newComments = fetchMoreResult.moreComments.comments;\n const newCursor = fetchMoreResult.moreComments.cursor;\n\n return {\n // By returning `cursor` here, we update the `fetchMore` function\n // to the new cursor.\n cursor: newCursor,\n entry: {\n // Put the new comments in the front of the list\n comments: [...newComments, ...previousEntry.comments]\n },\n __typename: previousEntry.__typename\n };\n }\n })\n }\n```\n\n```text\nfetchMore\n```\n\n```text\nonLoadMore\n```\n\n```text\nnewComments\n```\n\n```js\n{\n \"Query\": {\n \"cursor\": \"cursor1\",\n \"entry\": { \"comments\": [{ ... }, { ... }] }\n }\n} \n\n// normalised\n{\n \"Query\": {\n \"cursor\": \"cursor1\",\n \"entry\": Ref(\"Entry:1\"),\n }\n \"Entry:1\": {\n comments: [Ref(\"Comment:1\"), Ref(\"Comment:2\")],\n },\n \"Comment:1\": { ... },\n \"Comment:2\": { ... }\n}\n```\n\n```js\n{\n \"Query\": {\n \"cursor\": \"cursor2\",\n \"entry\": { \"comments\": [{ ... }, { ... }, { ... }, { ... }] }\n }\n}\n\n// normalised\n{\n \"Query\": {\n \"cursor\": \"cursor2\",\n \"entry\": Ref(\"Entry:1\"),\n }\n \"Entry:1\": {\n comments: [Ref(\"Comment:1\"), Ref(\"Comment:2\"), Ref(\"Comment:3\"), Ref(\"Comment:4\")],\n },\n \"Comment:1\": { ... },\n \"Comment:2\": { ... },\n \"Comment:3\": { ... },\n \"Comment:4\": { ... }\n}\n```\n\n```text\nupdateQuery\n```\n\n```text\nComment\n```\n\n```text\n2\n```\n\n```text\nupdateQuery\n```\n\n```text\nconst PlayerStats = () => {\n const { data, loading, fetchMore } = useQuery(CUMULATIVE_STATS, {\n variables: sortVars,\n })\n\n const players = data.GetCumulativeStats\n\n const loadMore = () => {\n fetchMore({\n variables: { offset: players.length },\n updateQuery: (prevResult, { fetchMoreResult }) => {\n if (!fetchMoreResult) return prevResult\n return {\n ...prevResult,\n GetCumulativeStats: [\n ...prevResult.GetCumulativeStats,\n ...fetchMoreResult.GetCumulativeStats,\n ],\n }\n },\n })\n }\n```\n\n```text\nCUMULATIVE_STATS\n```\n\n```text\nfetchMore\n```\n\n```text\noffset\n```\n\n```text\nCUMULATIVE_STATS\n```\n\n```text\nfetchMore\n```\n\n```text\nsortVars\n```\n\n```text\noffset\n```\n\n```text\noffset\n```\n\n```text\nupdateQuery\n```\n\n```text\nprevResult\n```\n\n```text\nfetchMoreResult\n```\n\n```text\nplayers.length\n```\n\n```text\nfetchMore\n```\n\n========================================\n\nComments:\n- I see what I was doing wrong. I was not returning data in the exact same shape/format as the original data. I had forgotten the `__typename`.","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":287,"estimatedTokens":1613}}710{"id":"stack-53385525","source":"stackoverflow","questionId":53385525,"title":"Apollo GraphQL - Import .graphql schema as typeDefs","tags":["graphql","apollo","apollo-server"],"text":"Title: Apollo GraphQL - Import .graphql schema as typeDefs\nTags: graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nWith graphql-yoga you can simply import your schema by doing the following: `typeDefs: './src/schema.graphql'`. Is there a similar way of doing so with apollo-server-express? \n\nIf there isn't, how does one import the typeDefs from an external `.graphql` file?\n\n========================================\n\nTop Answer:\nYou can use the function `makeExecutableSchema` to pass in the `typeDefs`. Something like this:\n\n```\nimport { makeExecutableSchema } from 'graphql-tools';\nimport mySchema from './src/schema.graphql';\n\nconst app = express();\n\nconst schema = makeExecutableSchema({\n typeDefs: [mySchema],\n resolvers: {\n ...\n },\n});\n\napp.use(\n '/graphql',\n graphqlExpress({ schema })\n);\n```\n\n========================================\n\nCode:\n```text\ntypeDefs: './src/schema.graphql'\n```\n\n```text\n.graphql\n```\n\n```text\nimport { ApolloServer } from 'apollo-server-express'\nimport { importSchema } from 'graphql-import'\nimport Query from './resolvers/Query'\n\nconst typeDefs = importSchema('./src/schema.graphql')\nconst server = new ApolloServer({\n typeDefs,\n resolvers: {\n Query\n }\n})\n\nconst app = express()\nserver.applyMiddleware({ app })\n\napp.listen({ port: 4000 })\n```\n\n```text\nasync function start() {\n const typeDefs = await importSchema(\".src/schema.graphql\")\n}\n```\n\n```text\nimportSchema\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\nimport { makeExecutableSchema } from 'graphql-tools';\nimport mySchema from './src/schema.graphql';\n\nconst app = express();\n\nconst schema = makeExecutableSchema({\n typeDefs: [mySchema],\n resolvers: {\n ...\n },\n});\n\napp.use(\n '/graphql',\n graphqlExpress({ schema })\n);\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\ntypeDefs\n```\n\n```js\nconst fs = require('fs');\nconst path = require('path');\n\nconst server = new ApolloServer({\n typeDefs: fs.readFileSync(\n path.join(__dirname, 'schema.graphql'),\n 'utf8'\n ),\n resolvers,\n})\n```\n\n```text\nconst { mergeTypeDefs } = require('@graphql-tools/merge')\nconst clientType = require('./clientType')\nconst productType = require('./productType')\n \nconst types = [clientType, productType]\n \nmodule.exports = mergeTypeDefs(types)\n```\n\n========================================\n\nComments:\n- Current version of graphql-import return a promise which results in a error!\n- @OtmanBouchari Just wrap it in an async function and await the result :)\n- Seems like the package `graphql-import` has been deprecated in favor of `graphql-tools` according to the announcement here","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":137,"estimatedTokens":650}}711{"id":"stack-44220597","source":"stackoverflow","questionId":44220597,"title":"How does one set up (database, or other) context in a GraphQL resolver?","tags":["node.js","graphql"],"text":"Title: How does one set up (database, or other) context in a GraphQL resolver?\nTags: node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nThe GraphQL docs give an example of a resolver function that accepts an argument called \"context\".\n\nThey have to say this about it -\n\n `context` A value which is provided to every resolver and holds important contextual information like the currently logged in user, or access to a database.\n\nAnd their code example looks like this -\n\n```\nQuery: {\n human(obj, args, context) {\n return context.db.loadHumanByID(args.id).then(\n userData => new Human(userData)\n )\n }\n}\n```\n\nThis seems to me a perfectly natural pattern to want database access inside a resolver function, and unsurprisingly it is what I need to do.\n\nThis database context is not set up automatically, obviously, since GraphQL is completely agnostic about your particular means of data persistence.\n\nMy question is, how does one configure this context to provide one's specific db interface? I can't find mention of this in the tutorials/docs, or anywhere really.\n\n========================================\n\nTop Answer:\ncontext is defined when you set up your server. I couldn't see it in the docs either.\n\n```\ngraphqlExpress(req => {\n return {\n schema: makeExecutableSchema({\n typeDefs: schema.ast,\n resolvers,\n logger\n }),\n context: {\n db: mongodb.MongoClient.connect(...)\n }\n };\n})\n```\n\n========================================\n\nCode:\n```text\nQuery: {\n human(obj, args, context) {\n return context.db.loadHumanByID(args.id).then(\n userData => new Human(userData)\n )\n }\n}\n```\n\n```text\ncontext\n```\n\n```text\ngraphql(\n schema: GraphQLSchema,\n requestString: string,\n rootValue?: ?any,\n contextValue?: ?any, // Arbitrary context\n variableValues?: ?{[key: string]: any},\n operationName?: ?string\n): Promise<GraphQLResult>\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql\n```\n\n```text\ngraphqlExpress(req => {\n return {\n schema: makeExecutableSchema({\n typeDefs: schema.ast,\n resolvers,\n logger\n }),\n context: {\n db: mongodb.MongoClient.connect(...)\n }\n };\n})\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":99,"estimatedTokens":525}}712{"id":"stack-52265518","source":"stackoverflow","questionId":52265518,"title":"Use number as key in GraphQL Schema?","tags":["graphql","apollo-server"],"text":"Title: Use number as key in GraphQL Schema?\nTags: graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nCan you use numbers as a key in GraphQL Schema using the GraphQL Schema Language? i.e. (this is a small snippet...)\n\n```\ntype tax_code_allocation_country_KOR_states {\n \"11\": tax_code_allocation_state_tax_query\n \"26\": tax_code_allocation_state_tax_query\n \"27\": tax_code_allocation_state_tax_query\n}\n```\n\nOR the below, which I realise is incorrect JSON:\n\n```\ntype tax_code_allocation_country_KOR_states {\n 11: tax_code_allocation_state_tax_query\n 26: tax_code_allocation_state_tax_query\n 27: tax_code_allocation_state_tax_query\n}\n```\n\n========================================\n\nCode:\n```text\ntype tax_code_allocation_country_KOR_states {\n \"11\": tax_code_allocation_state_tax_query\n \"26\": tax_code_allocation_state_tax_query\n \"27\": tax_code_allocation_state_tax_query\n}\n```\n\n```text\ntype tax_code_allocation_country_KOR_states {\n 11: tax_code_allocation_state_tax_query\n 26: tax_code_allocation_state_tax_query\n 27: tax_code_allocation_state_tax_query\n}\n```\n\n```text\ntype tax_code_allocation_country_KOR_states {\n _11: tax_code_allocation_state_tax_query\n _26: tax_code_allocation_state_tax_query\n _27: tax_code_allocation_state_tax_query\n}\n```\n\n```text\ntype tax_code_allocation_country_KOR_states {\n tax(code: 11): tax_code_allocation_state_tax_query\n tax(codes: [11, 26, 27]): [tax_code_allocation_state_tax_query]\n}\n\n# query subselection\n{ _11: tax(code: 11), _26: tax(code: 26), _27: tax(code: 27) }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.077Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":61,"estimatedTokens":381}}713{"id":"stack-46158288","source":"stackoverflow","questionId":46158288,"title":"GraphQL: How to reuse same type for query and mutation?","tags":["graphql"],"text":"Title: GraphQL: How to reuse same type for query and mutation?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nLet's say I have a query defined liked this:\n\n```\ntype Query {\n # The basic me query\n getUser(id:Int): [User]\n}\n\ntype User {\n id: ID!\n login: String!\n name: String \n}\n```\n\nBut now I need to have a mutation to add a user. My intuition would be to to something like this:\n\n```\ntype Mutation { \n addUser(newUser: User): [User]\n}\n```\n\nBut it is not working because a mutation cannot use \"query type\". It need to use \"input type\". I know that in this example, it is not really complicated to do, but if user was a really complex type with many sub-type used. How can I do that?\nIs there a was to re-use a type as a mutation argument?\n\n========================================\n\nCode:\n```text\ntype Query {\n # The basic me query\n getUser(id:Int): [User]\n}\n\ntype User {\n id: ID!\n login: String!\n name: String \n}\n```\n\n```text\ntype Mutation { \n addUser(newUser: User): [User]\n}\n```\n\n```text\nconst userFields = `\n id: ID!\n login: String!\n name: String\n`\nconst schema = `\n type User {\n ${userFields}\n }\n type UserInput {\n ${userFields}\n }\n`\n```\n\n```text\ntype\n```\n\n```text\ninput\n```\n\n```text\ninput\n```\n\n```text\ntype\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\nnon-null\n```\n\n```text\nfields\n```\n\n```text\nUser\n```\n\n```text\nUserInput\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":108,"estimatedTokens":348}}714{"id":"stack-63585893","source":"stackoverflow","questionId":63585893,"title":"GraphQL + NestJS - how can I access @Args in a guard?","tags":["graphql","nestjs","guard","args"],"text":"Title: GraphQL + NestJS - how can I access @Args in a guard?\nTags: graphql, nestjs, guard, args\nSource: Stack Overflow\n\nQuestion:\nI need the to somehow access the `objectId` from `@Args` inside the guard so as to check if the sender has the `objectId` assigned to his account. Any idea how I could implement it?\n\n```\n@Query(() => [Person])\n @UseGuards(ObjectMatch)\n async pplWithObject(@Args('objectId') id: string): Promise {\n return await this.objService.getPeopleWithObject(id);\n }\n```\n\nIs it possible to access the passed argument from the context?\n\n```\nconst ctx = GqlExecutionContext.create(context);\n const request = ctx.getContext().req;\n```\n\n========================================\n\nCode:\n```text\n@Query(() => [Person])\n @UseGuards(ObjectMatch)\n async pplWithObject(@Args('objectId') id: string): Promise<Person[]> {\n return await this.objService.getPeopleWithObject(id);\n }\n```\n\n```text\nconst ctx = GqlExecutionContext.create(context);\n const request = ctx.getContext().req;\n```\n\n```text\nobjectId\n```\n\n```text\n@Args\n```\n\n```text\nobjectId\n```\n\n```js\nconst ctx = GqlExecutionContext.create(context);\nconsole.log(ctx.getArgs()) // object with your query args\nctx.getArgs()['objectId']\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":55,"estimatedTokens":306}}715{"id":"stack-43937859","source":"stackoverflow","questionId":43937859,"title":"A Schema is required to be provided to GraphQLView","tags":["django","graphql"],"text":"Title: A Schema is required to be provided to GraphQLView\nTags: django, graphql\nSource: Stack Overflow\n\nQuestion:\nI was following this tutorial to integrate Graphql with Django, I did everything according to that tutorial when I'm hitting graphql URL on my local machine \n\n http://localhost:8000/graphql\n\nI'm geting the following error\n\n AssertionError at /graphql\n\n \n A Schema is required to be provided to GraphQLView.\n\nRequest Method: GET\nRequest URL: http://localhost:8000/graphql\nDjango Version: 1.11.1\nException Type: AssertionError\nException Value:\n\nA Schema is required to be provided to GraphQLView.\nException Location: /home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages/graphene_django/views.py in **init**, line 84\nPython Executable: /home/psingh/Projects/django_graphql/env/bin/python\nPython Version: 2.7.6\nPython Path:\n\n['/home/psingh/Projects/django_graphql/project',\n '/home/psingh/Projects/django_graphql/env/lib/python2.7',\n '/home/psingh/Projects/django_graphql/env/lib/python2.7/plat-x86_64-linux-gnu',\n '/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-tk',\n '/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-old',\n '/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-dynload',\n '/usr/lib/python2.7',\n '/usr/lib/python2.7/plat-x86_64-linux-gnu',\n '/usr/lib/python2.7/lib-tk',\n '/home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages',\n '/home/psingh/Projects/django_graphql/env/lib/python2.7/site-packages']\nServer time: Fri, 12 May 2017 12:18:31 +0000\n\nIn settings.py\n\n```\nGRAPHENE = {\n'SCHEMA': 'project.schema.schema'\n```\n\n}\n\nproject> schema.py\n\n```\nimport graphene\nimport mainapp.schema \nclass Query(mainapp.schema.Query, graphene.ObjectType):\n # This class will inherit from multiple Queries\n # as we begin to add more apps to our project\n pass\n\nschema = graphene.Schema(query=Query)\n```\n\napp>schema.py\n\n```\nimport graphene\nfrom graphene_django.types import DjangoObjectType\nfrom cookbook.ingredients.models import Category, Ingredient\n\nclass CategoryType(DjangoObjectType):\n class Meta:\n model = Category\n\n class IngredientType(DjangoObjectType):\n class Meta:\n model = Ingredient\n\n class Query(graphene.AbstractType):\n all_categories = graphene.List(CategoryType)\n all_ingredients = graphene.List(IngredientType)\n\n def resolve_all_categories(self, args, context, info):\n return Category.objects.all()\n\n def resolve_all_ingredients(self, args, context, info):\n # We can easily optimize query count in the resolve method\n return Ingredient.objects.select_related('category').all()\n```\n\nproject_urls.py\n\n```\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\n\nfrom graphene_django.views import GraphQLView\nimport schema\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^graphql', GraphQLView.as_view(graphiql=True)),\n url(r'^', include('mainapp.urls')), \n\n]\n```\n\nAny help would be great.I am new to the coding stuff.\nThanks in advance.\n\n========================================\n\nTop Answer:\nif you don't want to add `GRAPHENE` variable in `settings.py` then you can pass `scheme` parameter in `GraphQLView.as_view()` method call \n\n```\nfrom onlineshop_project.scheme import schema\n urlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^graphql', GraphQLView.as_view(graphiql=True, schema=schema)),\n ]\n```\n\nYou can check the documentation.\n\n========================================\n\nCode:\n```text\nGRAPHENE = {\n'SCHEMA': 'project.schema.schema'\n```\n\n```text\nimport graphene\nimport mainapp.schema \nclass Query(mainapp.schema.Query, graphene.ObjectType):\n # This class will inherit from multiple Queries\n # as we begin to add more apps to our project\n pass\n\nschema = graphene.Schema(query=Query)\n```\n\n```text\nimport graphene\nfrom graphene_django.types import DjangoObjectType\nfrom cookbook.ingredients.models import Category, Ingredient\n\nclass CategoryType(DjangoObjectType):\n class Meta:\n model = Category\n\n\n class IngredientType(DjangoObjectType):\n class Meta:\n model = Ingredient\n\n\n class Query(graphene.AbstractType):\n all_categories = graphene.List(CategoryType)\n all_ingredients = graphene.List(IngredientType)\n\n def resolve_all_categories(self, args, context, info):\n return Category.objects.all()\n\n def resolve_all_ingredients(self, args, context, info):\n # We can easily optimize query count in the resolve method\n return Ingredient.objects.select_related('category').all()\n```\n\n```text\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\n\nfrom graphene_django.views import GraphQLView\nimport schema\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^graphql', GraphQLView.as_view(graphiql=True)),\n url(r'^', include('mainapp.urls')), \n\n]\n```\n\n```text\nsettings.py\n```\n\n```text\nGRAPHENE = {\n 'SCHEMA': 'cookbook.schema.schema'\n}\n```\n\n```text\nschema.py\n```\n\n```text\nfrom onlineshop_project.scheme import schema\n urlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^graphql', GraphQLView.as_view(graphiql=True, schema=schema)),\n ]\n```\n\n```text\nGRAPHENE\n```\n\n```text\nsettings.py\n```\n\n```text\nscheme\n```\n\n```text\nGraphQLView.as_view()\n```\n\n========================================\n\nComments:\n- I have added that as GRAPHENE = { 'SCHEMA': 'project.schema.schema' }\n- I have edited the question with all the required codes.\n- Your answer doesn't seem to be different than the accepted answer. Also, the question was asked and answered 3 years ago. Be sure to look at the date of the original question when answering. Please read How to Answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":230,"estimatedTokens":1394}}716{"id":"stack-67922718","source":"stackoverflow","questionId":67922718,"title":"GraphQL multiple values eq filter","tags":["graphql","gatsby"],"text":"Title: GraphQL multiple values eq filter\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nHow do I filter multiple values in GraphQL? For example, I want both databaseID 59 and 170 to be filtered.\n\nI've tried with 170, 59 but it returns error `\"Syntax Error: Expected Name, found Int \\\"59\\\".\"`\n\nMy GraphQL Query:\n\n```\nquery MyQuery {\n allWpPage(filter: {databaseId: {eq: 170, 59}}) {\n nodes {\n title\n databaseId\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery MyQuery {\n allWpPage(filter: {databaseId: {eq: 170, 59}}) {\n nodes {\n title\n databaseId\n }\n }\n}\n```\n\n```text\n\"Syntax Error: Expected Name, found Int \\\"59\\\".\"\n```\n\n```text\nquery MyQuery {\n allWpPage(filter: {databaseId: {in: [170, 59]}}) {\n nodes {\n title\n databaseId\n }\n }\n}\n```\n\n========================================\n\nComments:\n- explore gatsby filtering docs? look for some `in` operator?","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":55,"estimatedTokens":231}}717{"id":"stack-46498143","source":"stackoverflow","questionId":46498143,"title":"Github Graphql Filter issues by Milestone","tags":["github","graphql","github-api","github-graphql"],"text":"Title: Github Graphql Filter issues by Milestone\nTags: github, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm wrestling with Github's graphql api (while learning graphql) trying to get it to list all issues in a certain milestone. I can't figure out how to do that from the API docs.\n\nI can query issues and see what milestone they're in (sorry, names redacted):\n\n```\nquery {\n repository(owner:\"me\", name:\"repo\") {\n issues(last:10) {\n nodes {\n milestone {\n id\n title\n }\n }\n }\n }\n}\n```\n\nI wish there was a way to say something like `issues(milestoneID:\"xyz\")`, or perhaps if Issue would define a `MilestoneConnection` (doesn't appear to exist).\n\nIn my reading / learning about GraphQL thus far, I haven't found a way to build arbitrary filters of fields if an explicit parameter is not defined in the schema (am I right about that?).\n\nI guess I can query all of issues in the repository and post-process the JSON response to filter out the milestone I want, but is there a better way to do this with github + graphql?\n\n========================================\n\nTop Answer:\nYou can use a search query with `milestone` filter : \n\n```\n{\n search(first: 100, type: ISSUE, query: \"user:callemall repo:material-ui milestone:v1.0.0-prerelease state:open\") {\n issueCount\n pageInfo {\n hasNextPage\n endCursor\n }\n edges {\n node {\n ... on Issue {\n createdAt\n title\n url\n }\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n repository(owner:\"me\", name:\"repo\") {\n issues(last:10) {\n nodes {\n milestone {\n id\n title\n }\n }\n }\n }\n}\n```\n\n```text\nissues(milestoneID:\"xyz\")\n```\n\n```text\nMilestoneConnection\n```\n\n```text\nquery($id:ID!) {\n node(id:$id) {\n ... on Milestone {\n issues(last:10) {\n edges {\n node {\n title\n author {\n login\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nquery($owner:String!,$name:String!,$milestoneNumber:Int!) {\n repository(owner:$owner,name:$name) {\n milestone(number:$milestoneNumber) {\n issues(last:10) {\n edges {\n node {\n title\n author {\n login\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\n{\n search(first: 100, type: ISSUE, query: \"user:callemall repo:material-ui milestone:v1.0.0-prerelease state:open\") {\n issueCount\n pageInfo {\n hasNextPage\n endCursor\n }\n edges {\n node {\n ... on Issue {\n createdAt\n title\n url\n }\n }\n }\n }\n}\n```\n\n```text\nmilestone\n```\n\n========================================\n\nComments:\n- Awesome thanks! One thing to note: if the milestone name has spaces, you need to again escape the quotes around the name. If you're using curl, and already escaping the quotes around the query string, that would be a double escape... i.e. `query: \\\"... milestone: \\\\\\\"a name\\\\\\\" ...\\\"`\n- Thanks this is great! This should now be the accepted answer, but I can't change it.","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":150,"estimatedTokens":777}}718{"id":"stack-57658931","source":"stackoverflow","questionId":57658931,"title":"Graphql - Is there a way how to insert two tables at the same time, but the second table is dependent on the return of from the first table?","tags":["javascript","graphql","mutation","hasura"],"text":"Title: Graphql - Is there a way how to insert two tables at the same time, but the second table is dependent on the return of from the first table?\nTags: javascript, graphql, mutation, hasura\nSource: Stack Overflow\n\nQuestion:\ni am new to graphql and i am having this issue and don't know how to solve it.\n\nfor example i have two tables: book and book_author;\n\nbook has book_id and name\nbook_author has book_author_id, book_id, author_name\n\nthat two tables needs to be inserted values at a single request but the book_author table needs the book_id which from the book table it self with be generated.\n\ncan someone help me with this? help is much appreciated.\n\nexpected result is when calling post request or upon inserting.\n\nfor ex. the system generated book_id *bk123*, the book_id in the table book_author should be the same too.\n\n========================================\n\nCode:\n```text\nmutation {\n insert_book_author(objects: {book: {data: {name: \"New Book\"}}, author_name: \"Sarah\"}) {\n affected_rows\n returning {\n book_author_id\n book {\n book_id\n name\n }\n }\n }\n}\n```\n\n```text\nbook\n```\n\n```text\nbook_author\n```\n\n```text\nbook\n```\n\n```text\nbook\n```\n\n```text\nbook_author\n```\n\n========================================\n\nComments:\n- thank you @avimoondra this really worked!!!!!! i applied it already on my codes. thank you","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":62,"estimatedTokens":340}}719{"id":"stack-57814293","source":"stackoverflow","questionId":57814293,"title":"My Apollo Server's Subscription doesn't works: Cannot read property 'headers' of undefined","tags":["javascript","graphql","subscription","apollo-server","express-graphql"],"text":"Title: My Apollo Server's Subscription doesn't works: Cannot read property 'headers' of undefined\nTags: javascript, graphql, subscription, apollo-server, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI tried to used it with the context connection, and adding the subscription params into the Apollo Server but it doesn't work. Is my first time using Apollo Server Subscriptions and i don't know if the error is in the server configuration or in the resolvers.\nI have no problems in the query or mutation, the problem is the subscription.\n\n### This is my index.js:\n\n```\nimport express from 'express';\n import { createServer } from 'http';\n import { ApolloServer } from 'apollo-server-express';\n import { typeDefs } from './data/schema';\n import { resolvers } from './data/resolvers';\n import cors from 'cors';\n import jwt from 'jsonwebtoken';\n\n const bodyParser = require('body-parser');\n const PORT = process.env.PORT || 4004;\n const app = express();\n\n app.use(bodyParser.json());\n app.use(cors());\n\n const server = new ApolloServer({\n typeDefs,\n resolvers,\n context: async({req, connection}) => {\n console.log(\"Context connection\", connection) \n const token = req.headers['authorization'];\n if(connection){\n return connection.context;\n } else {\n if(token !== \"null\"){\n try{\n\n //validate user in client.\n const currentUser = await jwt.verify(token, process.env.SECRET);\n\n //add user to request\n req.currentUser = currentUser;\n\n return {\n currentUser\n } \n }catch(err){\n return \"\";\n }\n\n }\n\n } \n\n },\n subscriptions: {\n path: \"/subscriptions\",\n onConnect: async (connectionParams, webSocket, context) => {\n console.log(`Subscription client connected using Apollo server's built-in SubscriptionServer.`)\n },\n onDisconnect: async (webSocket, context) => {\n console.log(`Subscription client disconnected.`)\n }\n }\n\n});\n\n server.applyMiddleware({app});\n\n const httpServer = createServer(app);\n server.installSubscriptionHandlers(httpServer);\n\n httpServer.listen({ port: PORT }, () =>{\n console.log(`π Server ready at \n http://localhost:${PORT}${server.graphqlPath}`)\n console.log(`π Subscriptions ready at \n ws://localhost:${PORT}${server.subscriptionsPath}`)\n })\n```\n\n### From Playground\n\n### My Mutation:\n\n```\nmutation {\n pushNotification(label:\"My septh notification\") {\n label\n }\n }\n```\n\n### My Query:\n\n```\nquery {\n notifications {\n label\n }\n }\n```\n\n### My Subscription:\n\n```\nsubscription {\n newNotification {\n label\n }\n }\n```\n\n### The error is:\n\n```\n{\n \"error\": {\n \"message\": \"Cannot read property 'headers' of undefined\"\n }\n }\n```\n\n========================================\n\nTop Answer:\nThe problem is, that in your line\n\n```\nconst token = req.headers['authorization'];\n```\n\nVariable `req` will be undefined for WebSocket connections. For the authentication of those, refer to https://www.apollographql.com/docs/graphql-subscriptions/authentication/\n\n========================================\n\nCode:\n```text\nimport express from 'express';\n import { createServer } from 'http';\n import { ApolloServer } from 'apollo-server-express';\n import { typeDefs } from './data/schema';\n import { resolvers } from './data/resolvers';\n import cors from 'cors';\n import jwt from 'jsonwebtoken';\n\n const bodyParser = require('body-parser');\n const PORT = process.env.PORT || 4004;\n const app = express();\n\n app.use(bodyParser.json());\n app.use(cors());\n\n const server = new ApolloServer({\n typeDefs,\n resolvers,\n context: async({req, connection}) => {\n console.log(\"Context connection\", connection) \n const token = req.headers['authorization'];\n if(connection){\n return connection.context;\n } else {\n if(token !== \"null\"){\n try{\n\n //validate user in client.\n const currentUser = await jwt.verify(token, process.env.SECRET);\n\n //add user to request\n req.currentUser = currentUser;\n\n return {\n currentUser\n } \n }catch(err){\n return \"\";\n }\n\n }\n\n } \n\n },\n subscriptions: {\n path: \"/subscriptions\",\n onConnect: async (connectionParams, webSocket, context) => {\n console.log(`Subscription client connected using Apollo server's built-in SubscriptionServer.`)\n },\n onDisconnect: async (webSocket, context) => {\n console.log(`Subscription client disconnected.`)\n }\n }\n\n});\n\n server.applyMiddleware({app});\n\n const httpServer = createServer(app);\n server.installSubscriptionHandlers(httpServer);\n\n httpServer.listen({ port: PORT }, () =>{\n console.log(`π Server ready at \n http://localhost:${PORT}${server.graphqlPath}`)\n console.log(`π Subscriptions ready at \n ws://localhost:${PORT}${server.subscriptionsPath}`)\n })\n```\n\n```text\nmutation {\n pushNotification(label:\"My septh notification\") {\n label\n }\n }\n```\n\n```text\nquery {\n notifications {\n label\n }\n }\n```\n\n```text\nsubscription {\n newNotification {\n label\n }\n }\n```\n\n```text\n{\n \"error\": {\n \"message\": \"Cannot read property 'headers' of undefined\"\n }\n }\n```\n\n```text\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n context: async ({ req, connection }) => {\n if (connection) {\n // check connection for metadata\n return connection.context;\n } else {\n // check from req\n const token = req.headers.authorization\n\n\n if(token !== \"null\"){\n try{\n\n //validate user in client.\n const currentUser = await jwt.verify(token, process.env.SECRET);\n\n //add user to request\n req.currentUser = currentUser;\n\n return {\n currentUser\n } \n }catch(err){\n return \"\";\n }\n }\n\n }\n },\n\n\n });\n```\n\n```text\nconst token = req.headers['authorization'];\n```\n\n```text\nreq\n```\n\n```text\nserver = new ApolloServer({\n schema: schema ,\n graphiql: true ,\n context:({req, connection} )=>\n if connection\n token = connection.context[\"x-access-token\"]\n decoded = await LoginService.verify token #verify by jwt\n\n if decoded == null\n throw new Error(\"auth required\")\n return connection.context\n headers = req.headers\n token = headers[\"x-access-token\"]\n decoded = await LoginService.verify token #verify by jwt\n return authed: decoded != null\n})\n```\n\n========================================\n\nComments:\n- I read the documentation, but I don't know how to implement it using the jwt token. If you have any resources to with me, I would appreciate it. Thanks\n- Man, you saved my life. I thought it was a problem which this guy described, but it's even simpler! Thanks that you left answer here!","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":309,"estimatedTokens":1727}}720{"id":"stack-51334907","source":"stackoverflow","questionId":51334907,"title":"Prisma Deploy Docker error \"Could not connect to server\"","tags":["docker","graphql","prisma"],"text":"Title: Prisma Deploy Docker error \"Could not connect to server\"\nTags: docker, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nThis is steps I have done\n\n```\nprisma init\n```\n\nI set postgresql for database in my local(not exist).\n\nIt created 3 files, datamodel.graphql, docker-compose.yml, prisma.yml\n\n```\ndocker-compose up -d\n```\n\nI confirmed it running successfully \nhttps://i.sstatic.net/NajDB.png\nBut if I call `prisma deploy`, it shows me error\n\n```\nCould not connect to server at http://localhost:4466. Please check if your server is running.\n```\n\nAll I have done is standard operation described in manual and there is no customization in\nhttps://www.prisma.io/docs/tutorials/deploy-prisma-servers/local-(docker)-meemaesh3k\n\nAnd this is docker-compose.yml\n\n```\nversion: '3'\nservices:\n prisma:\n image: prismagraphql/prisma:1.11\n restart: always\n ports:\n - \"4466:4466\"\n environment:\n PRISMA_CONFIG: |\n port: 4466\n # uncomment the next line and provide the env var PRISMA_MANAGEMENT_API_SECRET=my-secret to activate cluster security\n # managementApiSecret: my-secret\n databases:\n default:\n connector: postgres\n host: localhost\n port: '5432'\n database: databasename\n schema: public\n user: postgres\n password: root\n migrations: true\n```\n\nWhat am I missing?\n\n========================================\n\nTop Answer:\nI found this solution to the same problem i was facing\n\n```\ndocker-machine ip default\n```\n\nUse this address and replace the \"localhost\" with the IP with the above command to look something like this in prisma.yml file\n\n```\nendpoint: http://1xx.1xx.xx.xxx:4466\n```\n\nThe answer is referred from this Github Link\n\n========================================\n\nCode:\n```text\nprisma init\n```\n\n```text\ndocker-compose up -d\n```\n\n```text\nCould not connect to server at http://localhost:4466. Please check if your server is running.\n```\n\n```text\nversion: '3'\nservices:\n prisma:\n image: prismagraphql/prisma:1.11\n restart: always\n ports:\n - \"4466:4466\"\n environment:\n PRISMA_CONFIG: |\n port: 4466\n # uncomment the next line and provide the env var PRISMA_MANAGEMENT_API_SECRET=my-secret to activate cluster security\n # managementApiSecret: my-secret\n databases:\n default:\n connector: postgres\n host: localhost\n port: '5432'\n database: databasename\n schema: public\n user: postgres\n password: root\n migrations: true\n```\n\n```text\nprisma deploy\n```\n\n```text\ndocker ps\n```\n\n```text\n$ docker ps\nCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES\n2b799c529e73 prismagraphql/prisma:1.7 \"/bin/sh -c /app/staβ¦\" 17 hours ago Up 7 hours 0.0.0.0:4466->4466/tcp myapp_prisma_1\n757dfba212f7 mysql:5.7 \"docker-entrypoint.sβ¦\" 17 hours ago\n```\n\n```text\ndocker-compose logs\n```\n\n```text\ndocker-machine ip default\n```\n\n```text\nendpoint: http://1xx.1xx.xx.xxx:4466\n```\n\n```text\ndocker-compose up\n```\n\n```text\ndocker run --name <ENTER_NAME> -e POSTGRES_PASSWORD=<ENTER_PASSWORD> -d -p 5433:5432 postgres\n```\n\n========================================\n\nComments:\n- Thanks, I am running postgresql in my local, in this case how to set prisma to use hosted server's local database?\n- @NomuraNori Considering prisma is isolated in container, I am not sure it would be able to access a service (like postgresql) running on the local host.\n- I get this output: \"Docker machine \"default\" does not exist. Use \"docker-machine ls\" to list machines. Use \"docker-machine create\" to add a new one.\" How to create a docker-machine?\n- @kwoxer try this command: `docker-machine create default`. You can read more here: docs.docker.com/machine/get-started\n- I'm now using mongo as docker service. So my issue is now gone.\n- Said process worked for me. The only difference was I had to run `docker-machine ls` to get the ip.","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":160,"estimatedTokens":1001}}721{"id":"stack-54459947","source":"stackoverflow","questionId":54459947,"title":"Are mutation methods required to be on the top level?","tags":["graphql","apollo","apollo-server"],"text":"Title: Are mutation methods required to be on the top level?\nTags: graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nAll docs and tutorials usually show simple examples of mutations that look like this:\n\n```\nextend type Mutation {\n edit(postId: String): String\n}\n```\n\nBut this way the `edit` method has to be unique across all entities, which to me seems like not a very robust way to write things. I would like to describe mutation similar to how we describe Queries, something like this:\n\n```\ntype PostMutation {\n edit(postId: String): String\n}\n\nextend type Mutation {\n post: PostMutation\n}\n```\n\nThis seems to be a valid schema (it compiles and I can see it reflected in the generated graph-i-ql docs). But I can't find a way to make resolvers work with this schema.\n\nIs this a supported case for GraphQL?\n\n========================================\n\nTop Answer:\nAbsolutely disagree with Daniel!\n\nThis is an amazing approach which helps to frontenders fastly understand what operations have one or another resource/model. And do not list loooong lists of mutations.\n\nCalling multiple mutations in one request is common antipattern. For such cases better to create one complex mutation.\n\nBut even if you need to do such operation with several mutations you may use aliases:\n\n```\nawait graphql({\n schema,\n source: `\n mutation {\n op1: article { like(id: 1) }\n op2: article { like(id: 2) }\n op3: article { unlike(id: 3) }\n op4: article { like(id: 4) }\n }\n`,\n});\n\nexpect(serialResults).toEqual([\n 'like 1 executed with timeout 100ms',\n 'like 2 executed with timeout 100ms',\n 'unlike 3 executed with timeout 5ms',\n 'like 4 executed with timeout 100ms',\n]);\n```\n\nSee the following test case: https://github.com/nodkz/conf-talks/blob/master/articles/graphql/schema-design/**tests**/mutations-test.js\n\nMethods like/unlike are async with timeouts and works sequentially\n\n========================================\n\nCode:\n```text\nextend type Mutation {\n edit(postId: String): String\n}\n```\n\n```text\ntype PostMutation {\n edit(postId: String): String\n}\n\nextend type Mutation {\n post: PostMutation\n}\n```\n\n```text\nedit\n```\n\n```text\nmutation SomeOperationName {\n createUser\n editUser\n deleteUser\n}\n```\n\n```text\nmutation SomeOperationName {\n user {\n create\n edit\n delete\n }\n}\n```\n\n```text\nconst resolvers = {\n Mutation: {\n post: () => ({}), // return an empty object,\n },\n PostMutation: {\n edit: () => editPost(),\n },\n // Other types here\n}\n```\n\n```text\nmutation {\n post\n}\n```\n\n```text\nuser\n```\n\n```text\nposts\n```\n\n```text\ncomments\n```\n\n```text\nfirstName\n```\n\n```text\nlastName\n```\n\n```text\nUser\n```\n\n```text\nmutation\n```\n\n```text\nmutation\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nPostMutation\n```\n\n```text\npost\n```\n\n```text\nPostMutation\n```\n\n```js\nawait graphql({\n schema,\n source: `\n mutation {\n op1: article { like(id: 1) }\n op2: article { like(id: 2) }\n op3: article { unlike(id: 3) }\n op4: article { like(id: 4) }\n }\n`,\n});\n\nexpect(serialResults).toEqual([\n 'like 1 executed with timeout 100ms',\n 'like 2 executed with timeout 100ms',\n 'unlike 3 executed with timeout 5ms',\n 'like 4 executed with timeout 100ms',\n]);\n```\n\n========================================\n\nComments:\n- but you basically created the same top level Mutation. Moreover, could you explain the reason to make it robust? you have a function which will make a post. How do you think to use it again?\n- This is not a matter of opinion, but specification. GraphQL specification defines mutations as top level operations exclusively. All levels below are regular queries. The fact that they're actually mutating things is highly problematic as queries and mutations have different execution semantics and guarantees. It's equivalent to exposing a GET endpoint that writes things to the database in REST. Possible, but horribly unsafe and semantically wrong.","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":198,"estimatedTokens":969}}722{"id":"stack-63938943","source":"stackoverflow","questionId":63938943,"title":"Gradle plugin 'com.apollographql.apollo' not syncing in Android Studio","tags":["android","android-studio","kotlin","graphql"],"text":"Title: Gradle plugin 'com.apollographql.apollo' not syncing in Android Studio\nTags: android, android-studio, kotlin, graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to install apollo graphql plugin in my Android project for Kotlin.\n\nAs per the instruction from Apollographql installation for Kotlin, I am trying the installation process using the legacy syntax.\n\nMy build.gradle(app) file:\n\n```\napply plugin: 'com.android.application'\napply plugin: 'kotlin-android'\napply plugin: 'kotlin-android-extensions'\napply plugin: 'com.apollographql.apollo'\n\nandroid {\n compileSdkVersion 29\n\n defaultConfig {\n applicationId \"com.example.goonlinepackagescanner\"\n minSdkVersion 26\n targetSdkVersion 29\n versionCode 1\n versionName \"1.0\"\n\n testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n }\n\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n }\n }\n}\n\ndependencies {\n implementation fileTree(dir: \"libs\", include: [\"*.jar\"])\n implementation \"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version\"\n implementation 'androidx.core:core-ktx:1.3.1'\n implementation 'androidx.appcompat:appcompat:1.2.0'\n implementation 'androidx.constraintlayout:constraintlayout:2.0.1'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'androidx.test.ext:junit:1.1.2'\n androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'\n\n implementation \"com.apollographql.apollo:apollo-gradle-plugin:2.3.1\"\n implementation \"com.apollographql.apollo:apollo-runtime:2.3.1\"\n implementation \"com.apollographql.apollo:apollo-coroutines-support:2.3.1\"\n}\n```\n\nMy build.gradle(project) file:\n\n```\n// Top-level build file where you can add configuration options common to all sub-projects/modules.\nbuildscript {\n ext.kotlin_version = '1.4.10'\n repositories {\n google()\n jcenter()\n }\n dependencies {\n classpath \"com.android.tools.build:gradle:4.0.0\"\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n\n // NOTE: Do not place your application dependencies here; they belong\n // in the individual module build.gradle files\n }\n}\n\nallprojects {\n repositories {\n google()\n jcenter()\n }\n}\n\ntask clean(type: Delete) {\n delete rootProject.buildDir\n}\n```\n\nIt gives the following error when I try to sync the gradle file:\n\n```\nPlugin with id 'com.apollographql.apollo' not found.\n```\n\nI have been trying to figure out what has went wrong but couldn't do so. Any help on this will be appreciated.\n\n========================================\n\nCode:\n```text\napply plugin: 'com.android.application'\napply plugin: 'kotlin-android'\napply plugin: 'kotlin-android-extensions'\napply plugin: 'com.apollographql.apollo'\n\nandroid {\n compileSdkVersion 29\n\n defaultConfig {\n applicationId \"com.example.goonlinepackagescanner\"\n minSdkVersion 26\n targetSdkVersion 29\n versionCode 1\n versionName \"1.0\"\n\n testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n }\n\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n }\n }\n}\n\ndependencies {\n implementation fileTree(dir: \"libs\", include: [\"*.jar\"])\n implementation \"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version\"\n implementation 'androidx.core:core-ktx:1.3.1'\n implementation 'androidx.appcompat:appcompat:1.2.0'\n implementation 'androidx.constraintlayout:constraintlayout:2.0.1'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'androidx.test.ext:junit:1.1.2'\n androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'\n\n implementation \"com.apollographql.apollo:apollo-gradle-plugin:2.3.1\"\n implementation \"com.apollographql.apollo:apollo-runtime:2.3.1\"\n implementation \"com.apollographql.apollo:apollo-coroutines-support:2.3.1\"\n}\n```\n\n```text\n// Top-level build file where you can add configuration options common to all sub-projects/modules.\nbuildscript {\n ext.kotlin_version = '1.4.10'\n repositories {\n google()\n jcenter()\n }\n dependencies {\n classpath \"com.android.tools.build:gradle:4.0.0\"\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n\n // NOTE: Do not place your application dependencies here; they belong\n // in the individual module build.gradle files\n }\n}\n\nallprojects {\n repositories {\n google()\n jcenter()\n }\n}\n\ntask clean(type: Delete) {\n delete rootProject.buildDir\n}\n```\n\n```text\nPlugin with id 'com.apollographql.apollo' not found.\n```\n\n```text\nclasspath \"com.apollographql.apollo:apollo-gradle-plugin:2.3.1\"\n```\n\n```text\nbuildscript {\n ext.kotlin_version = '1.4.10'\n repositories {\n google()\n jcenter()\n }\n dependencies {\n classpath \"com.android.tools.build:gradle:4.0.0\"\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n classpath \"com.apollographql.apollo:apollo-gradle-plugin:2.3.1\"\n // NOTE: Do not place your application dependencies here; they belong\n // in the individual module build.gradle files\n }\n}\n\nallprojects {\n repositories {\n google()\n jcenter()\n }\n}\n\ntask clean(type: Delete) {\n delete rootProject.buildDir\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":203,"estimatedTokens":1337}}723{"id":"stack-47491992","source":"stackoverflow","questionId":47491992,"title":"set GrapqQL date format","tags":["node.js","mongodb","date","graphql"],"text":"Title: set GrapqQL date format\nTags: node.js, mongodb, date, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a mongoDB database in which one field is an ISO date.\nWhen i query the table using a graphql (node) query i receive my objects back all right but the date format i see in graphiql is in this weird format:\n\n```\n\"created\": \"Sun Nov 26 2017 00:55:35 GMT+0100 (CET)\"\n```\n\nif i write the field out in my resolver is shows:\n\n```\n2017-11-25T23:55:35.116Z\n```\n\nHow do i change the date format so it will show ISO dates in graphiql?\n\nthe field is just declared as a string in my data type.\n\n**EDIT**\nMy simple type is defined as:\n\n```\ntype MyString {\n _id: String\n myString: String\n created: String\n}\n```\n\nWhen I insert a value into the base created is set automatically by MongoDB. \n\nWhen I run the query it returns an array of obejcts. In my resolver (for checking) I do the following:\n\n```\ngetStrings: async (_, args) => {\n let myStrings = await MyString.find({});\n for (var i = 0; i all objects created date in the returned array have the form:\n\n```\n2017-11-25T23:55:35.116Z\n```\n\nbut when i see it in GraphIql it shows as:\n\n```\n\"created\": \"Sun Nov 26 2017 00:55:35 GMT+0100 (CET)\"\n```\n\nmy question is: Why does it change format?\n\nSince my model defines this as a String it should not be manipulated but just retain the format. But it doesn't. It puzzels me.\n\nKim\n\n========================================\n\nTop Answer:\nYou just need to do step by step:\n\n- Set type of your field is Object\n\n- Insert line `scalar Object` into your .graphql file\n\n- Add dependence `graphql-java-extended-scalars` into pom.xml file\n\n- Add syntax `.scalar(ExtendedScalars.Object)` in buildRuntimeWiring function\n\nLet try it.\nI try it and successful!\n\n========================================\n\nCode:\n```text\n\"created\": \"Sun Nov 26 2017 00:55:35 GMT+0100 (CET)\"\n```\n\n```text\n2017-11-25T23:55:35.116Z\n```\n\n```text\ntype MyString {\n _id: String\n myString: String\n created: String\n}\n```\n\n```text\ngetStrings: async (_, args) => {\n let myStrings = await MyString.find({});\n for (var i = 0; i < myStrings.length; i++) {\n console.log(myStrings[i][\"created\"]);\n }\n\n return myStrings;\n}\n```\n\n```text\n2017-11-25T23:55:35.116Z\n```\n\n```text\n\"created\": \"Sun Nov 26 2017 00:55:35 GMT+0100 (CET)\"\n```\n\n```text\nconst date1 = new Date('2017-11-25T23:45:35.116Z').toISOString();\nconsole.log({date1});\n// => { date1: '2017-11-25T23:45:35.116Z' }\n\nconst date2 = new Date('Sun Nov 26 2017 00:55:35 GMT+0100 (CET)').toISOString();\nconsole.log({date2})\n// => { date2: '2017-11-25T23:55:35.000Z' }\n```\n\n```text\nconst date1 = new Date('2017-11-25T23:45:35.116Z').toString();\nconsole.log({date1})\n// => { date1: 'Sat Nov 25 2017 15:45:35 GMT-0800 (PST)' }\n```\n\n```text\ntoISOString()\n```\n\n```text\ntoString()\n```\n\n```text\ncreated\n```\n\n```text\nDate\n```\n\n```text\nscalar Object\n```\n\n```text\ngraphql-java-extended-scalars\n```\n\n```text\n.scalar(ExtendedScalars.Object)\n```\n\n========================================\n\nComments:\n- Thanks for taking your time to help me. I have edited my question a little bit.","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":160,"estimatedTokens":773}}724{"id":"stack-43846889","source":"stackoverflow","questionId":43846889,"title":"Is is possible to skip part of a query with apollo-client","tags":["graphql","react-apollo","apollo-client"],"text":"Title: Is is possible to skip part of a query with apollo-client\nTags: graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm trying to perform 3 unique searches inside one query. The problem is that my search \"filter\" type is mandatory in the schema but in the front-end it's optional. If a null value is provided inside my filter then I'll get a graphql error.\n\nI want to skip searching for mainSearchData, firstComparisonSearchData or secondComparisonSearchData depending on whether the search filters contain data.\n\nI know that I can use the `skip` function to ignore the *whole* query but how can I achieve the same for part of the query? Or alternatively, how can I compose these as separate queries but perform just *one* request?\n\n```\nconst GROWTH_QUERY = gql`query aggregateQuery($mainFilter: filter!, $firstComparisonFilter: filter!, $secondComparisonFilter: filter! $interval: interval!) {\n mainSearchData: groupBy(filter: $mainFilter, first: 20, after: 0) {\n items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {\n date\n count\n }\n }\n firstComparisonSearchData: groupBy(filter: $firstComparisonFilter, first: 20, after: 0) {\n items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {\n date\n count\n }\n }\n secondComparisonSearchData: groupBy(filter: $secondComparisonFilter, first: 20, after: 0) {\n items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {\n date\n count\n }\n }\n}`;\n```\n\n========================================\n\nCode:\n```text\nconst GROWTH_QUERY = gql`query aggregateQuery($mainFilter: filter!, $firstComparisonFilter: filter!, $secondComparisonFilter: filter! $interval: interval!) {\n mainSearchData: groupBy(filter: $mainFilter, first: 20, after: 0) {\n items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {\n date\n count\n }\n }\n firstComparisonSearchData: groupBy(filter: $firstComparisonFilter, first: 20, after: 0) {\n items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {\n date\n count\n }\n }\n secondComparisonSearchData: groupBy(filter: $secondComparisonFilter, first: 20, after: 0) {\n items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {\n date\n count\n }\n }\n}`;\n```\n\n```text\nskip\n```\n\n```text\nconst GROWTH_QUERY = gql`query aggregateQuery($mainFilter: filter!, $firstComparisonFilter: filter!, $secondComparisonFilter: filter! $interval: interval!) @skip(if: ...) {\n mainSearchData: groupBy(filter: $mainFilter, first: 20, after: 0) {\n items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {\n date\n count\n }\n }\n firstComparisonSearchData: groupBy(filter: $firstComparisonFilter, first: 20, after: 0) @skip(if: ...) {\n items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {\n date\n count\n }\n }\n secondComparisonSearchData: groupBy(filter: $secondComparisonFilter, first: 20, after: 0) @skip(if: ...) {\n items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {\n date\n count\n }\n }\n}`;\n```\n\n```text\nskip\n```\n\n```text\n@skip(if: ...)\n```\n\n```text\nmainSearchData\n```\n\n```text\nfirstComparisonSearchData\n```\n\n```text\nsecondComparisonSearchData\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":106,"estimatedTokens":814}}725{"id":"stack-56049480","source":"stackoverflow","questionId":56049480,"title":"Error: \"user\" defined in resolvers, but not in schema","tags":["node.js","graphql","apollo-server"],"text":"Title: Error: \"user\" defined in resolvers, but not in schema\nTags: node.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm trying to set up my schema for Apollo Server, and I'm running into an error.\n\nWhat I'm trying is actually an attempt to fix a common and even more unhelpful message, using advice found here:\n\nhttps://github.com/apollographql/apollo-server/issues/1998\n\nI'm not really sure how to reduce the code here, since I haven't been able to isolate the error more than this.\n\nschema.js\n\n```\nimport { makeExecutableSchema } from 'apollo-server-express'\nimport ApplicationSchema from './types'\nimport Resolvers from './resolvers'\n\nexport default makeExecutableSchema({\n typeDefs: ApplicationSchema,\n resolvers: Resolvers\n})\n```\n\nresolvers/index.js\n\n```\nimport user from './user'\n\nexport default {\n user\n}\n```\n\nresolvers/user.js\n\n```\nimport Joi from 'joi'\nimport mongoose from 'mongoose'\nimport { UserInputError } from 'apollo-server-express'\nimport { signUp, signIn } from '../validators'\nimport { User } from '../schemata' // mongoose schema\nimport * as Authentication from '../authentication'\n\nexport default {\n Query: {\n me: (root, args, { request }, info) => {\n Authentication.checkSignedIn(request)\n\n return User.findbyId(request.session.userId)\n },\n\n users: (root, args, { request }, info) => {\n Authentication.checkSignedIn(request)\n User.find({})\n },\n\n user: (root, args, { request }, info) => {\n const { id } = args\n\n Authentication.checkSignedIn(request)\n\n if (!mongoose.Types.ObjectId.isValid(id)) {\n throw new UserInputError(`${id} is not a valid user ID.`)\n }\n\n return User.findById(id)\n }\n },\n\n Mutation: {\n signup: async (root, args, { request }, info) => {\n Authentication.checkSignedOut(request)\n await Joi.validate(args, signUp, { abortEarly: false })\n return User.create(args)\n },\n\n signIn: async (root, args, { request }, info) => {\n const { userId } = request.session\n\n if (userId) return User.findById(userId)\n\n await Joi.validate(args, signIn, { abortEarly: false })\n\n const user = await Authentication.attemptSignIn(args)\n\n request.session.userId = user.id\n\n return user\n },\n\n signOut: async (root, args, { request, response }, info) => {\n Authentication.checkSignedIn(request)\n\n return Authentication.signOut(request, response)\n }\n }\n}\n```\n\ntypes/index.js\n\n```\nimport root from './root'\nimport user from './user'\n\nexport default [\n root, \n user\n]\n```\n\ntypes/root,js\n\n```\nimport { gql } from 'apollo-server-express'\n\nexport default gql`\n type Query {\n _: String\n }\n\n type Mutation {\n _: String\n }\n\n type Subscription {\n _: String\n }\n```\n\ntypes/user.js\n\n```\nimport { gql } from 'apollo-server-express'\n\nexport default gql`\n type User {\n id: ID!\n email: String!\n username: String!\n name: String!\n password: String!\n createdAt: String!\n }\n\n extend type Query {\n me: User\n user(id: ID!): User\n users: [User!]!\n }\n\n extend type Mutation {\n signUp(email: String!, username: String!, name: String!): User\n signIn(email: String!, password: String!): User\n signOut: Boolean\n }\n```\n\nHopefully, schema.js should run without errors and the resulting executable schema will work well with Apollo Server.\n\n========================================\n\nCode:\n```text\nimport { makeExecutableSchema } from 'apollo-server-express'\nimport ApplicationSchema from './types'\nimport Resolvers from './resolvers'\n\nexport default makeExecutableSchema({\n typeDefs: ApplicationSchema,\n resolvers: Resolvers\n})\n```\n\n```text\nimport user from './user'\n\nexport default {\n user\n}\n```\n\n```text\nimport Joi from 'joi'\nimport mongoose from 'mongoose'\nimport { UserInputError } from 'apollo-server-express'\nimport { signUp, signIn } from '../validators'\nimport { User } from '../schemata' // mongoose schema\nimport * as Authentication from '../authentication'\n\nexport default {\n Query: {\n me: (root, args, { request }, info) => {\n Authentication.checkSignedIn(request)\n\n return User.findbyId(request.session.userId)\n },\n\n users: (root, args, { request }, info) => {\n Authentication.checkSignedIn(request)\n User.find({})\n },\n\n user: (root, args, { request }, info) => {\n const { id } = args\n\n Authentication.checkSignedIn(request)\n\n if (!mongoose.Types.ObjectId.isValid(id)) {\n throw new UserInputError(`${id} is not a valid user ID.`)\n }\n\n return User.findById(id)\n }\n },\n\n Mutation: {\n signup: async (root, args, { request }, info) => {\n Authentication.checkSignedOut(request)\n await Joi.validate(args, signUp, { abortEarly: false })\n return User.create(args)\n },\n\n signIn: async (root, args, { request }, info) => {\n const { userId } = request.session\n\n if (userId) return User.findById(userId)\n\n await Joi.validate(args, signIn, { abortEarly: false })\n\n const user = await Authentication.attemptSignIn(args)\n\n request.session.userId = user.id\n\n return user\n },\n\n signOut: async (root, args, { request, response }, info) => {\n Authentication.checkSignedIn(request)\n\n return Authentication.signOut(request, response)\n }\n }\n}\n```\n\n```text\nimport root from './root'\nimport user from './user'\n\nexport default [\n root, \n user\n]\n```\n\n```text\nimport { gql } from 'apollo-server-express'\n\nexport default gql`\n type Query {\n _: String\n }\n\n type Mutation {\n _: String\n }\n\n type Subscription {\n _: String\n }\n```\n\n```text\nimport { gql } from 'apollo-server-express'\n\nexport default gql`\n type User {\n id: ID!\n email: String!\n username: String!\n name: String!\n password: String!\n createdAt: String!\n }\n\n extend type Query {\n me: User\n user(id: ID!): User\n users: [User!]!\n }\n\n extend type Mutation {\n signUp(email: String!, username: String!, name: String!): User\n signIn(email: String!, password: String!): User\n signOut: Boolean\n }\n```\n\n```text\n{\n Query: {\n // Query fields\n },\n Mutation: {\n // Mutation fields\n },\n // etc.\n}\n```\n\n```text\n{\n user: {\n Query: {\n // Query fields\n },\n Mutation: {\n // Mutation fields\n },\n // etc.\n }\n}\n```\n\n```text\nimport user from './user'\nimport foo from './foo'\nimport _ from 'lodash'\n\nexport default _.merge(\n user,\n foo\n)\n```\n\n```text\nresolvers\n```\n\n```text\ntypes/user.js\n```\n\n```text\nresolvers\n```\n\n```text\nresolvers\n```\n\n```text\nuser\n```\n\n```text\nlodash\n```\n\n========================================\n\nComments:\n- daniel, it doest fix issue\n- It did for the OP. There could be any number of other issues with your code. Please post a new question with a reproducable example.\n- Much better to use `mergeResolvers` from `graphql-tools/merge`: graphql-tools.com/docs/merge-resolvers","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":369,"estimatedTokens":1665}}726{"id":"stack-55268731","source":"stackoverflow","questionId":55268731,"title":"Why are there \"two names\" for each GraphQL query/mutation?","tags":["graphql","apollo","apollo-server"],"text":"Title: Why are there \"two names\" for each GraphQL query/mutation?\nTags: graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am learning GraphQL and one basic point has me puzzled. I know there is an easy explanation, but I can't find it. Specifically, from the Apollo documentation (https://www.apollographql.com/docs/apollo-server/essentials/data.html#operation):\n\n ...it makes sense to name the operation in order to quickly identify\n operations during debugging or to aggregate similar operations\n together...Operations can be named by placing an identifier after the\n query or mutation keyword, as weβve done with HomeBookListing here:\n\n```\nquery HomeBookListing { \n getBooks {\n title \n } \n }\n```\n\nIf `HomeBookListing` is the name of the query, what, then, is `getBooks`? The name of the resolver?\n\nSimilarly, when you pass variables to a query, why are there \"two levels\" of parameters, like this\n\n```\nmutation HomeQuickAddBook($title: String, $author: String = \"Anonymous\") {\n addBook(title: $title, author: $author) {\n title\n }\n}\n```\n\nSo, would `$title: String, $author: String = \"Anonymous\"` be the variables passed to the query, and `title: $title, author: $author` variables passed to the resolver? \n\nOf course I can memorise the pattern, but I'm keen to understand, conceptually, what the different pieces are doing here. Any insights much appreciated!\n\n========================================\n\nCode:\n```text\nquery HomeBookListing { \n getBooks {\n title \n } \n }\n```\n\n```text\nmutation HomeQuickAddBook($title: String, $author: String = \"Anonymous\") {\n addBook(title: $title, author: $author) {\n title\n }\n}\n```\n\n```text\nHomeBookListing\n```\n\n```text\ngetBooks\n```\n\n```text\n$title: String, $author: String = \"Anonymous\"\n```\n\n```text\ntitle: $title, author: $author\n```\n\n```text\nquery\n```\n\n```text\nmutation\n```\n\n```text\nsubscription\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nSubscription\n```\n\n```text\nname\n```\n\n```text\ndescription\n```\n\n```text\nfields\n```\n\n```text\nquery\n```\n\n```text\ngetBooks\n```\n\n```text\nString\n```\n\n```text\nInt\n```\n\n```text\nquery\n```\n\n```text\nQuery\n```\n\n```text\nQuery\n```\n\n```text\ngetBooks\n```\n\n```text\nMutation\n```\n\n```text\nquery\n```\n\n```text\nmutation\n```\n\n========================================\n\nComments:\n- It's been a while since I touched graphql, but if memory serves me: \"what is getBooks\" - name of the resolver, yes. It's not a \"second name for the query\". You can have `getProducts` next to it. It's simply a \"field\" in the query.\n- Same for mutation: you declare parameter list for the whole operation, then different parts of the operation (addBook / addReview) will use different subsets of the argument list.\n- @SergioTulentsev -- Thanks. I think that's more for the separate 'fields' in the resolvers themselves, on the server, so that you can have `const resolvers= { Query: { getBooks: async() => {....}, getProducts: async() => {...} } }`, for instance. I think that's what you might be referring to?\n- Yep, that indeed.\n- I'd also like to add that the real world TRPC applications I see don't use `Query` at all. They are only using `Mutation` for everything. A few different implementations made by various companies.","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":159,"estimatedTokens":803}}727{"id":"stack-53715260","source":"stackoverflow","questionId":53715260,"title":"How to get GraphQL schema with Python?","tags":["python","python-3.x","python-requests","graphql"],"text":"Title: How to get GraphQL schema with Python?\nTags: python, python-3.x, python-requests, graphql\nSource: Stack Overflow\n\nQuestion:\nThere's lots of GUI clients like GraphQL Playground, GraphiQl, etc. with ability of getting GraphQL schema from the URL. How can I get the schema with Python?\n\n========================================\n\nTop Answer:\nThe `graphql-core` has utilities to get you the query, and convert the query result. Here is an example snippet that print the resulting schema in sdl: \n\n```\nfrom graphqlclient import GraphQLClient\nfrom pprint import PrettyPrinter\nfrom graphql import get_introspection_query, build_client_schema, print_schema\n\ndef main():\n pp = PrettyPrinter(indent=4)\n client = GraphQLClient('http://swapi.graph.cool/')\n query_intros = get_introspection_query(descriptions=True)\n intros_result = client.execute(query_intros, variables=None, operationName=None)\n client_schema = build_client_schema(intros_result.get('data', None))\n sdl = print_schema(client_schema)\n print(sdl)\n pp.pprint(sdl)\n```\n\nI was looking for the same and found the above in the end.\n\n========================================\n\nCode:\n```text\nintrospection_query = \"\"\"\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n description\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n fragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n fragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n }\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n\"\"\"\n```\n\n```text\nrequests\n```\n\n```text\ngraphql-core\n```\n\n```text\nfrom graphqlclient import GraphQLClient\nfrom pprint import PrettyPrinter\nfrom graphql import get_introspection_query, build_client_schema, print_schema\n\ndef main():\n pp = PrettyPrinter(indent=4)\n client = GraphQLClient('http://swapi.graph.cool/')\n query_intros = get_introspection_query(descriptions=True)\n intros_result = client.execute(query_intros, variables=None, operationName=None)\n client_schema = build_client_schema(intros_result.get('data', None))\n sdl = print_schema(client_schema)\n print(sdl)\n pp.pprint(sdl)\n```\n\n```text\ngraphql-core\n```\n\n```text\nimport json\n\nintrospection_dict = your_schema_object.introspect()\n\n# Or save the schema into some file\nwith open(\"schema.json\", \"w\") as fp:\n json.dump(introspection_dict, fp)\n```\n\n```text\npython3 -m sgqlc.introspection --exclude-deprecated --include-description ****-H \"Authorization: Bearer {TOKEN}\" http://yourgrapqlservice.com schema.json\n```\n\n```text\nsgqlc-codegen schema schema1.json schema.py\n```\n\n```text\nasync def get_graphql_schema(endpoint, api_key):\n headers = {\"X-API-KEY\": api_key}\n transport = AIOHTTPTransport(url=endpoint, headers=headers)\n async with Client(transport=transport, fetch_schema_from_transport=True) as session:\n query_intros = get_introspection_query(descriptions=True)\n query = gql(query_intros)\n intros_result = await session.execute(query)\n schema = build_client_schema(intros_result)\n return schema\n\ndef save_schema_to_json(schema):\n schema_dict = introspection_from_schema(schema)\n output_file = 'schema.json'\n with open(output_file, 'w') as json_file:\n dump(schema_dict, json_file, indent=2)\n\nschema = asyncio.run(get_graphql_schema(env_dev['url'], env_dev['key']))\nsave_schema_to_json(schema)\n```\n\n```text\nintrospection_from_schema()\n```\n\n========================================\n\nComments:\n- thanks a lot, this query works and returns all the fields!\n- This gives me the following error: `TypeError: execute() got an unexpected keyword argument 'operationName'`\n- Ok. Just take out the \"operationName=None\" from the call. It works on \"graphql.org/swapi-graphql\". It works with the intro_result. But the next line creating schema will fail, need to replace \"data\" element with a valid one. The environment: python 3.8, graphql-core 3.0.3, graphqlclient 0.2.4, urllib3 1.25.8. You can pick a public api from github.com/APIs-guru/graphql-apis\n- Got method not allowed. Tried a few other links, each gives a different error. Not sure.","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":204,"estimatedTokens":1299}}728{"id":"stack-45506535","source":"stackoverflow","questionId":45506535,"title":"Graphcool / GraphQL create mutation with relation","tags":["graphql","graphcool"],"text":"Title: Graphcool / GraphQL create mutation with relation\nTags: graphql, graphcool\nSource: Stack Overflow\n\nQuestion:\nI have the following GraphQL schema. It has `Books` and `Authors` with a many to many relationship. How do I create a new Book mutation for an existing Author?\n\nschema\n\n```\ntype Author implements Node {\n books: [Book!]! @relation(name: \"BookAuthors\")\n createdAt: DateTime!\n id: ID! @isUnique\n name: String!\n updatedAt: DateTime!\n}\n\ntype Book implements Node {\n authors: [Author!]! @relation(name: \"BookAuthors\")\n createdAt: DateTime!\n id: ID! @isUnique\n title: String!\n updatedAt: DateTime!\n}\n```\n\nmutation\n\n```\nmutation CreateBook($title: String!, $authors: [Author!]) {\n createBook(\n title: $title,\n authors: $authors,\n ) {\n id\n title\n }\n }\n```\n\nvariables\n\n```\n{\n \"title\": \"Ryans Book\",\n \"authors\": [\"cj5xti3kk0v080160yhwrbdw1\"]\n}\n```\n\n========================================\n\nCode:\n```text\ntype Author implements Node {\n books: [Book!]! @relation(name: \"BookAuthors\")\n createdAt: DateTime!\n id: ID! @isUnique\n name: String!\n updatedAt: DateTime!\n}\n\ntype Book implements Node {\n authors: [Author!]! @relation(name: \"BookAuthors\")\n createdAt: DateTime!\n id: ID! @isUnique\n title: String!\n updatedAt: DateTime!\n}\n```\n\n```text\nmutation CreateBook($title: String!, $authors: [Author!]) {\n createBook(\n title: $title,\n authors: $authors,\n ) {\n id\n title\n }\n }\n```\n\n```text\n{\n \"title\": \"Ryans Book\",\n \"authors\": [\"cj5xti3kk0v080160yhwrbdw1\"]\n}\n```\n\n```text\nBooks\n```\n\n```text\nAuthors\n```\n\n```text\nmutation CreateBook($title: String!, $authorIds: [ID!]) {\n createBook(\n title: $title,\n authorIds: $authorIds,\n ) {\n id\n title\n }\n }\n```\n\n========================================\n\nComments:\n- This is apparently called a connect mutation. Answer can be found here: graph.cool/docs/reference/simple-api/…\n- Note that this is specific to the Graphcool API :) Also, feel free to answer your own question.\n- Welp, that link is dead and the web archive doesn't have it archived. :\\","metadata":{"transformedAt":"2026-08-18T18:32:36.078Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":116,"estimatedTokens":516}}729{"id":"stack-64119033","source":"stackoverflow","questionId":64119033,"title":"graphene-django: 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated since 0.15.0 and is now disallowed","tags":["django","graphql","django-filter"],"text":"Title: graphene-django: 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated since 0.15.0 and is now disallowed\nTags: django, graphql, django-filter\nSource: Stack Overflow\n\nQuestion:\nI'm trying to return filtered results using django-graphene but it gives an error about error-message\n\n```\nclass PatientType(DjangoObjectType):\n class Meta:\n model = Patients\n exclude = ('active',)\n interfaces = (relay.Node,)\n\nclass PatientsQuery(ObjectType):\n get_patient = graphene.Field(PatientType, id=graphene.Int())\n all_patients = graphene.List(\n PatientType, first=graphene.Int(), skip=graphene.Int(), phone_no=graphene.Int()\n )\n upcoming_appointments = DjangoFilterConnectionField(PatientType)\n\n@permissions_checker([IsAuthenticated, CheckIsOrganizationActive])\ndef resolve_upcoming_appointments(self, info, **kwargs) -> List:\n d = datetime.today() - timedelta(hours=1)\n settings.TIME_ZONE # 'Asia/Karachi'\n aware_datetime = make_aware(d)\n res = Patients.objects.filter(appointments__booking_date__gte=aware_datetime,\n appointments__booking_date__day=aware_datetime.day,\n appointments__status=True)\n if res:\n return res\n return []\n\nclass Query(\n organization_schema.OrganizationQuery,\n inventory_schema.MedicineQuery,\n patient_schema.PatientsQuery,\n graphene.ObjectType,\n):\n pass\n```\n\n========================================\n\nCode:\n```text\nclass PatientType(DjangoObjectType):\n class Meta:\n model = Patients\n exclude = ('active',)\n interfaces = (relay.Node,)\n\n\nclass PatientsQuery(ObjectType):\n get_patient = graphene.Field(PatientType, id=graphene.Int())\n all_patients = graphene.List(\n PatientType, first=graphene.Int(), skip=graphene.Int(), phone_no=graphene.Int()\n )\n upcoming_appointments = DjangoFilterConnectionField(PatientType)\n\n\n@permissions_checker([IsAuthenticated, CheckIsOrganizationActive])\ndef resolve_upcoming_appointments(self, info, **kwargs) -> List:\n d = datetime.today() - timedelta(hours=1)\n settings.TIME_ZONE # 'Asia/Karachi'\n aware_datetime = make_aware(d)\n res = Patients.objects.filter(appointments__booking_date__gte=aware_datetime,\n appointments__booking_date__day=aware_datetime.day,\n appointments__status=True)\n if res:\n return res\n return []\n\n\nclass Query(\n organization_schema.OrganizationQuery,\n inventory_schema.MedicineQuery,\n patient_schema.PatientsQuery,\n graphene.ObjectType,\n):\n pass\n```\n\n```text\nclass PatientType(DjangoObjectType):\n class Meta:\n model = Patients\n exclude = ('active',)\n interfaces = (relay.Node,)\n filter_fields = [\"field_1\", \"field_2\"]\n```\n\n```text\nfilter_fields\n```\n\n```text\nPatientType.Meta\n```\n\n```text\nfilter_fields=[]\n```\n\n```text\nfilterset_class\n```\n\n```text\nMeta\n```\n\n```text\nGraphenePython- Filtering\n```\n\n========================================\n\nComments:\n- If this is really the answer, then they need to fix their documentation because their examples do not make mention of `filter_fields`.\n- I hope so :) btw, setting `filter_fields=[]` is also a valid one\n- Yup that's what I ended up doing.","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":122,"estimatedTokens":792}}730{"id":"stack-51525305","source":"stackoverflow","questionId":51525305,"title":"Getting \"error: GraphQL schema file should contain a valid GraphQL introspection query result\" after apollo schema:download","tags":["graphql","apollo-android"],"text":"Title: Getting \"error: GraphQL schema file should contain a valid GraphQL introspection query result\" after apollo schema:download\nTags: graphql, apollo-android\nSource: Stack Overflow\n\nQuestion:\nSo I set up the graphql server described here\n\nNow, I want to generate android queries against this server using apollo android as per these instructions.\n\nI've tried different folder configurations for the location of the generated schema against this sample server and no matter what I do I get an error at compile time saying \"**GraphQL schema file should contain a valid GraphQL introspection query result**\"\n\nAny advice?\n\n========================================\n\nComments:\n- I am having the same issue. How do you use `apollo-codegen`?\n- I found an example of how to use it: `apollo-codegen download-schema http://localhost:8080/v1alpha1/graphql --output schema.json`","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":18,"estimatedTokens":221}}731{"id":"stack-50069352","source":"stackoverflow","questionId":50069352,"title":"Use AppSync and Amazon RDS with serverless-graphql","tags":["node.js","graphql","amazon-rds","serverless-framework","aws-appsync"],"text":"Title: Use AppSync and Amazon RDS with serverless-graphql\nTags: node.js, graphql, amazon-rds, serverless-framework, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nThere is this great repository with example implementations of different serverless scenarios.\n\nRight now I'm struggling with the combination of AppSync and Amazon RDS. I tried the implementation of the standalone rds, and the appsync examples provided in the repository. These are working like a charm.\nBut obviously there are many differences and difficulties if you'd like to combine these technologies. I used the schema, resolver and handler functions from the rds directory and combined it with the appsync lambda implementation. I adjusted the mapping templates and updated the serverless.yml file.\n\nI could successfully deploy the whole appsync service and all resources without any errors. I'm able to access the graphql endpoint from graphiql and do my queries. But when I try it from the appsync console I get null as a response. I guess it has something to do with the mapping templates, but I'm not quite sure.\n\nHas anybody got any suggestions or maybe a working example of this specific combination?\n\n========================================\n\nComments:\n- hey!, how did you combined app sync with rds+lambda could you help me out in how to get data in realtime. Thanks\n- @SahajRana I'll create a sample git repository of my implementation in a few days\n- that would be great! and I have actually successfully added appSync+awsLambda+RDS with Android app with real-time integration. So if you need any help, please let me know!\n- @SahajRana Feel free to check out my sample implementation in my answer","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":21,"estimatedTokens":419}}732{"id":"stack-41688883","source":"stackoverflow","questionId":41688883,"title":"How to update all records in a collection using graphql","tags":["graphql","graphcool"],"text":"Title: How to update all records in a collection using graphql\nTags: graphql, graphcool\nSource: Stack Overflow\n\nQuestion:\nI'm using Graph.cool graphql as a service and am wondering how to do a mass update to the collection, similar to a SQL update.\n\nIn my case I need to update the suffix of a url, in the imageUrl column of my database. I need to swap out a {someid}_sm.jpg to {someid}_lg.jpg\n\nHow do I do that with a graphql mutation? I don't want to reload the entire dataset again and am looking for a way to do it that doesn't involve manually interating through the entire list with a graphql client.\n\n```\nmutation {\n updatePost() // what goes here?\n}\n```\n\n========================================\n\nCode:\n```text\nmutation {\n updatePost() // what goes here?\n}\n```\n\n```js\ntype Image {\n id: ID!\n name: String!\n}\n```\n\n```js\nmutation {\n first: updateImage(id: \"first-id\", name: \"01_lg.jpg\") {\n id\n name\n }\n\n second: updateImage(id: \"second-id\", name: \"02_lg.jpg\") {\n id\n name\n }\n}\n```\n\n```js\nconst queryImages = async() => {\n const result = await client.query(`{\n images: allImages {\n id\n name\n }\n }`)\n\n return result.images\n}\n```\n\n```js\nconst migrateImages = async(images) => {\n // beware! if your ids contain the string 'sm', adjust the string replacement accordingly!\n const updateMutations = _.chain(images)\n .map(image => ({ id: image.id, name: image.name.replace('sm', 'lg')}))\n .map(image => `\n ${image.id}: updateImage(id: \"${image.id}\", name: \"${image.name}\") {\n id\n name\n }`)\n .value()\n .join('\\n')\n\n const result = await client.mutate(`{\n ${updateMutations}\n }`)\n\n console.log(`Updated ${Object.keys(result).length} images`)\n console.log(result)\n}\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\nupdateImage\n```\n\n```text\nsm\n```\n\n```text\n{someid}\n```\n\n========================================\n\nComments:\n- `interating through the entire list` - that's pretty much the way to go for now. I added a feature request for what you had in mind instead: github.com/graphcool/feature-requests/issues/67 I can help with setting up the script as well.","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":106,"estimatedTokens":534}}733{"id":"stack-54525442","source":"stackoverflow","questionId":54525442,"title":"can't write unknown attribute `client_mutation_id`","tags":["ruby-on-rails","ruby","graphql"],"text":"Title: can't write unknown attribute `client_mutation_id`\nTags: ruby-on-rails, ruby, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to write my first mutation in Graphql with RoR. It seems like this:\n\napp/graphql/mutations/create_post.rb\n\n```\nmodule Mutations\n class CreatePost But every time I make request using Graphiql (like this:)\n\n```\nmutation createPost {\n createPost(input:{\n title:\"dupa\",\n body:\"dupa\"\n }) {\n id\n }\n}\n```\n\nThe post gets saved in database, but I recive an error\n\n```\n\"error\": {\n \"message\": \"can't write unknown attribute `client_mutation_id`\" [...]\n```\n\ninstead of requested id\nHow can I solve this problem?\nthis is my\n\napp/graphql/mutations/base_mutation.rb\n\n```\nmodule Mutations\n class BaseMutation app/graphql/types/mutation_type.rb\n\n```\nmodule Types\n class MutationType github link if it can help: https://github.com/giraffecms/GiraffeCMS-backend-rails/tree/blog/app/graphql\n\n========================================\n\nCode:\n```text\nmodule Mutations\n class CreatePost < Mutations::BaseMutation\n argument :title, String, required: true\n argument :body, String, required: true\n\n type Types::PostType\n\n def resolve(title: nil, body: nil)\n Post.create!(title: title, body: body)\n end\n end\nend\n```\n\n```text\nmutation createPost {\n createPost(input:{\n title:\"dupa\",\n body:\"dupa\"\n }) {\n id\n }\n}\n```\n\n```text\n\"error\": {\n \"message\": \"can't write unknown attribute `client_mutation_id`\" [...]\n```\n\n```text\nmodule Mutations\n class BaseMutation < GraphQL::Schema::RelayClassicMutation\n end\nend\n```\n\n```text\nmodule Types\n class MutationType < Types::BaseObject\n field :create_post, mutation: Mutations::CreatePost\n end\nend\n```\n\n```rb\nclass Mutations::CreatePost < Mutations::BaseMutation\n argument :title, String, required: true\n argument :body, String, required: true\n\n field :post, Types::PostType, null: false\n\n def resolve(title: nil, body: nil)\n post = Post.create!(title: title, body: body)\n { post: post }\n end\nend\n```\n\n```text\ntype\n```\n\n```text\nfield\n```\n\n```text\nclientMutationId\n```\n\n```text\n#client_mutation_id\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":123,"estimatedTokens":538}}734{"id":"stack-41440026","source":"stackoverflow","questionId":41440026,"title":"Inject bean into DataFetcher of GraphQL","tags":["java","spring","graphql","graphql-java"],"text":"Title: Inject bean into DataFetcher of GraphQL\nTags: java, spring, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI'm using **Spring** & graphql-java (**graphql-java-annotation**) in my project.\nFor retrieving data part, i'm using a DataFetcher to get data from a service (from database).\n\nThe weird thing is that: `myService` is always *null*. Anyone know the reason?\n\n*DataFetcher*\n\n```\n@Component\npublic class MyDataFetcher implements DataFetcher {\n\n // get data from database\n @Autowired\n private MyService myService;\n\n @Override\n public Object get(DataFetchingEnvironment environment) {\n return myService.getData();\n }\n}\n```\n\n*Schema*\n\n```\n@Component\n@GraphQLName(\"Query\")\npublic class MyGraphSchema {\n\n @GraphQLField\n @GraphQLDataFetcher(MyDataFetcher.class)\n public Data getData() {\n return null;\n }\n}\n```\n\n*MyService*\n\n```\n@Service\npublic class MyService {\n\n @Autowired\n private MyRepository myRepo;\n\n @Transactional(readOnly = true)\n public Data getData() {\n return myRepo.getData();\n }\n}\n```\n\n*Main test*\n\n```\n@Bean\npublic String testGraphql(){\n GraphQLObjectType object = GraphQLAnnotations.object(MyGraphSchema.class);\n GraphQLSchema schema = newSchema().query(object).build();\n GraphQL graphql = new GraphQL(schema);\n\n ExecutionResult result = graphql.execute(\"{getData {id name desc}}\");;\n Map v = (Map) result.getData();\n System.out.println(v);\n return v.toString();\n}\n```\n\n========================================\n\nTop Answer:\nThough @Nir's approach works (and I often use it inside JPA Event Listeners), the DataFetcher objects are Singletons, so injecting via static properties is a little hacky. \n\nHowever, GraphQL's `execute` method allows you to pass in an object as a context, which will then be available in your `DataFetchingEnvironment` object inside of your `DataFetcher` (see the graphql.execute() line below):\n\n```\n@Component\npublic class GraphQLService {\n\n @Autowired\n MyService myService;\n\n public Object getGraphQLResult() {\n GraphQLObjectType object = GraphQLAnnotations.object(MyGraphSchema.class);\n GraphQLSchema schema = newSchema().query(object).build();\n GraphQL graphql = new GraphQL(schema);\n\n ExecutionResult result = graphql.execute(\"{getData {id name desc}}\", myService);\n\n return result.getData();\n }\n}\n\npublic class MyDataFetcher implements DataFetcher {\n\n @Override\n public Object get(DataFetchingEnvironment environment) {\n MyService myService = (MyService) environment.getContext();\n\n return myService.getData();\n }\n}\n```\n\n========================================\n\nCode:\n```text\n@Component\npublic class MyDataFetcher implements DataFetcher {\n\n // get data from database\n @Autowired\n private MyService myService;\n\n @Override\n public Object get(DataFetchingEnvironment environment) {\n return myService.getData();\n }\n}\n```\n\n```text\n@Component\n@GraphQLName(\"Query\")\npublic class MyGraphSchema {\n\n @GraphQLField\n @GraphQLDataFetcher(MyDataFetcher.class)\n public Data getData() {\n return null;\n }\n}\n```\n\n```text\n@Service\npublic class MyService {\n\n @Autowired\n private MyRepository myRepo;\n\n @Transactional(readOnly = true)\n public Data getData() {\n return myRepo.getData();\n }\n}\n```\n\n```text\n@Bean\npublic String testGraphql(){\n GraphQLObjectType object = GraphQLAnnotations.object(MyGraphSchema.class);\n GraphQLSchema schema = newSchema().query(object).build();\n GraphQL graphql = new GraphQL(schema);\n\n ExecutionResult result = graphql.execute(\"{getData {id name desc}}\");;\n Map<String, Object> v = (Map<String, Object>) result.getData();\n System.out.println(v);\n return v.toString();\n}\n```\n\n```text\nmyService\n```\n\n```text\n@Component\npublic class MyDataFetcher implements DataFetcher, ApplicationContextAware {\n\n private static MyService myService;\n private static ApplicationContext context;\n\n @Override\n public Object get(DataFetchingEnvironment environment) {\n return myService.getData();\n }\n\n @override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansExcepion {\n context = applicationContext;\n myService = context.getBean(MyService.class);\n }\n}\n```\n\n```text\nApplicationContextAware\n```\n\n```text\nmyService\n```\n\n```text\npublic abstract class SpringContextAwareDataFetcher implements DataFetcher, ApplicationContextAware {\n\n private static ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n }\n\n @Override\n public final Object get(DataFetchingEnvironment environment) {\n return applicationContext.getBean(this.getClass()).fetch(environment);\n }\n\n protected abstract Object fetch(DataFetchingEnvironment environment);\n}\n```\n\n```text\n@Component\npublic class UserDataFetcher extends SpringContextAwareDataFetcher {\n\n @Autowired\n private UserService userService;\n\n @Override\n public String fetch(DataFetchingEnvironment environment) {\n User user = (User) environment.getSource();\n return userService.getUser(user.getId()).getName();\n }\n}\n```\n\n```text\n@Component\npublic class GraphQLService {\n\n @Autowired\n MyService myService;\n\n public Object getGraphQLResult() {\n GraphQLObjectType object = GraphQLAnnotations.object(MyGraphSchema.class);\n GraphQLSchema schema = newSchema().query(object).build();\n GraphQL graphql = new GraphQL(schema);\n\n ExecutionResult result = graphql.execute(\"{getData {id name desc}}\", myService);\n\n return result.getData();\n }\n}\n\npublic class MyDataFetcher implements DataFetcher {\n\n @Override\n public Object get(DataFetchingEnvironment environment) {\n MyService myService = (MyService) environment.getContext();\n\n return myService.getData();\n }\n}\n```\n\n```text\nexecute\n```\n\n```text\nDataFetchingEnvironment\n```\n\n```text\nDataFetcher\n```\n\n========================================\n\nComments:\n- can you post MyService.java as well?\n- i've posted MyService.java @jobin\n- is there any error while starting the app?\n- I don't think that's a good solution. MyDataFetcher is a singleton and setApplicationContext is called once. Why myService must be static?","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":283,"estimatedTokens":1569}}735{"id":"stack-55854430","source":"stackoverflow","questionId":55854430,"title":"Explanation for different implementations of resolver function in graphql","tags":["graphql","graphql-js","express-graphql"],"text":"Title: Explanation for different implementations of resolver function in graphql\nTags: graphql, graphql-js, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI've been reading through the graphQL docs and found that they've explained the implementation of the graphql server in 2 ways: one using graphql-yoga which is a fully featured graphql server and another one is using graphql, express-graphql and express. In both cases, we pass the schema and resolver functions while creating the server instance.\n\nBut the implementation of resolver function differs. While using graphql-yoga, the resolver function is provided with 4 arguments which contains information about the parent object, arguments received, context, info. whereas in the other case (using graphql), the resolver function only gets the arguments object. \n\nWhy is that so ? If I want the info, context objects, how do I get it ?\n\nUsing graphql-yoga example: https://graphql.org/learn/execution/\n\nUsing graphql example: https://graphql.github.io/graphql-js/mutations-and-input-types/\n\n// Code example using graphql\n\n```\nvar express = require('express');\nvar graphqlHTTP = require('express-graphql');\nvar { buildSchema } = require('graphql');\n\nvar schema = buildSchema(`\ntype Query {\n rollDice(numDice: Int!, numSides: Int): [Int]\n}\ntype Mutation {\n addDice(numDice: Int): String\n}\n`);\n\nvar root = {\n rollDice({numDice, numSides}) {\n return [1, 2];\n },\n addDice({numDice}) {\n console.log(\"Adding something\");\n return \"Added\";\n }\n};\n\nvar app = express();\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n rootValue: root,\n graphiql: true,\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at localhost:4000/graphql');\n```\n\n// Code example using graphql-yoga\n\n```\nlet graphqlServer = require(\"graphql-yoga\");\n\nconst typeDefs = `\n type Query {\n rollDice(numDice: Int!, numSides: Int): [Int]\n }\n type Mutation {\n addDice(numDice: Int): String\n }\n `;\n\nconst resolvers = {\n Query: {\n rollDice(parent, args, context, info) {\n console.log(args.numDice);\n console.log(args.numSides);\n return [1, 2];\n }\n },\n Mutation: {\n addDice(parent, args, context, info) {\n console.log(args.numDice);\n return \"Added\";\n }\n }\n};\n\nconst server = new graphqlServer.GraphQLServer({\n typeDefs,\n resolvers\n});\n\nserver.start(() => {\n console.log(\"server started on localhost:4000\");\n});\n```\n\nDifference between these 2 code snippets:\n\nThe resolver functions are present inside appropriate types (i.e. Query, Mutation) in one case. In the other case, they are present inside one root object. This means that I can have methods with same name in Query and Mutation in the first case, whereas in the second case that's not possible since they are keys of a single object and keys should be unique.\n\nWhy is this so ? Am I basically missing something ? How can the implementation details differ from one package to another ?\n\n========================================\n\nCode:\n```text\nvar express = require('express');\nvar graphqlHTTP = require('express-graphql');\nvar { buildSchema } = require('graphql');\n\nvar schema = buildSchema(`\ntype Query {\n rollDice(numDice: Int!, numSides: Int): [Int]\n}\ntype Mutation {\n addDice(numDice: Int): String\n}\n`);\n\nvar root = {\n rollDice({numDice, numSides}) {\n return [1, 2];\n },\n addDice({numDice}) {\n console.log(\"Adding something\");\n return \"Added\";\n }\n};\n\nvar app = express();\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n rootValue: root,\n graphiql: true,\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at localhost:4000/graphql');\n```\n\n```text\nlet graphqlServer = require(\"graphql-yoga\");\n\nconst typeDefs = `\n type Query {\n rollDice(numDice: Int!, numSides: Int): [Int]\n }\n type Mutation {\n addDice(numDice: Int): String\n }\n `;\n\nconst resolvers = {\n Query: {\n rollDice(parent, args, context, info) {\n console.log(args.numDice);\n console.log(args.numSides);\n return [1, 2];\n }\n },\n Mutation: {\n addDice(parent, args, context, info) {\n console.log(args.numDice);\n return \"Added\";\n }\n }\n};\n\nconst server = new graphqlServer.GraphQLServer({\n typeDefs,\n resolvers\n});\n\nserver.start(() => {\n console.log(\"server started on localhost:4000\");\n});\n```\n\n```text\nconst userType = new GraphQLObjectType({\n name: 'User',\n fields: {\n id: {\n type: GraphQLID,\n },\n email: {\n type: GraphQLString,\n },\n },\n});\nconst queryType = new GraphQLObjectType({\n name: 'Query',\n fields: {\n user: {\n type: userType,\n resolve: () => ({ id: 1, email: 'john.doe@example.com' }),\n },\n },\n});\nconst schema = new GraphQLSchema({\n query: queryType,\n})\n```\n\n```text\ntype Query {\n user: User\n}\n\ntype User {\n id: ID\n email: String\n}\n```\n\n```text\nexport const defaultFieldResolver: GraphQLFieldResolver<any, *> = function(\n source,\n args,\n contextValue,\n info,\n) {\n if (typeof source === 'object' || typeof source === 'function') {\n const property = source[info.fieldName];\n if (typeof property === 'function') {\n return source[info.fieldName](args, contextValue, info);\n }\n return property;\n }\n};\n```\n\n```text\nconst root = {\n user: () => ({id: 1, email: 'john.doe@example.com'})\n}\n```\n\n```text\nbuildSchema\n```\n\n```text\ngraphql\n```\n\n```text\nGraphQLSchema\n```\n\n```text\nbuildSchema\n```\n\n```text\ngraphql-tools\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\napollo-server\n```\n\n```text\ngraphql-yoga\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nbuildSchema\n```\n\n```text\nresolve\n```\n\n```text\nGraphQLResolveInfo\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nuserType\n```\n\n```text\ngraphql-yoga\n```\n\n```text\nbuildSchema\n```\n\n```text\nuser\n```\n\n```text\n{id: 1, email: 'john.doe@example.com'}\n```\n\n```text\nUser\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\n1\n```\n\n```text\nid\n```\n\n```text\nuser\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nQuery\n```\n\n```text\nQuery\n```\n\n```text\nuser\n```\n\n```text\nUser\n```\n\n```text\nresolveType\n```\n\n========================================\n\nComments:\n- Thanks @daniel-rearden That gave me some clarity. Hope they update the docs soon xD\n- I have been looking for this exact information for over a full day now. This is an excellent summary that addresses all these points of confusion about default resolvers, buildSchema vs makeExecutableSchema, etc. Thank you very much Daniel. I completely agree that much of this should be in the docs.\n- If I read default resolver correctly the missing parent or source object is available as βthisβ. For example if you pass root object like { user:()=> ({ id:1, comments:()=>([..])}) it will use βcommmentsβ function to resolve comments. While resolving comments source object will be available as this, args, context and info come as arguments to the function.","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":37,"totalLines":362,"estimatedTokens":1712}}736{"id":"stack-65127544","source":"stackoverflow","questionId":65127544,"title":"ApolloClient v3 fetchMore with nested query results","tags":["reactjs","graphql","apollo","apollo-client","github-graphql"],"text":"Title: ApolloClient v3 fetchMore with nested query results\nTags: reactjs, graphql, apollo, apollo-client, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm using ApolloClient 3 the GitHub GraphQL API to retrieve all releases from a repo.\n\nThis is what the query looks like:\n\n```\nquery ($owner: String!, $name: String!, $first: Int, $after: String, $before: String) {\n repository(owner: $owner, name: $name) {\n id\n releases(orderBy: {field: CREATED_AT, direction: DESC}, first: $first, after: $after, before: $before) {\n nodes {\n name\n publishedAt\n resourcePath\n tagName\n url\n id\n isPrerelease\n description\n descriptionHTML\n }\n totalCount\n pageInfo {\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n }\n }\n}\n```\n\nThis is what the result payload looks like:\n\nhttps://i.sstatic.net/v3VFH.png\n\nThis returns me the first x entries (`nodes`). So far, all good.\n\nI need to implement pagination and I make use of the `fetchMore` function provided by ApolloClient `useQuery`. Calling `fetchMore` fetches the next x entries successfully but these are not displayed in my component list.\n\nAccording to the ApolloClient Pagination documentation, it seems necessary to handle the `merging` of the `fetchMore` results with the ApolloClient caching mechanism. The documentation is understandable for simple situations but I am struggling to implement a solution for the situation where the actual array of results that needs to be merged togeher is deeply nested in the query result (`repository -> releases -> nodes`).\n\nThis is my implementation of the InMemoryCache options merge:\n\n```\nconst inMemoryCacheOptions = {\n addTypename: true,\n typePolicies: {\n ReleaseConnection: {\n fields: {\n nodes: {\n merge(existing, incoming, options) {\n const previous = existing || []\n const results = [...previous, ...incoming]\n return results\n }\n }\n }\n },\n }\n}\n```\n\nThe `results` array here contains the full list, including the existing entries and the new x entries. This is essentially the correct result. However, my component list which is using the `useQuery` and `fetchMore` functionality does not get the new entries after the `fetchMore` is called.\n\nI have tried various combinations in the `inMemoryCacheOptions` code above but so far I have been unsuccessful.\n\nTo add more context, this is the related component code:\n\n```\nexport default function Releases() {\n const { loading, error, data, fetchMore } = useQuery(releasesQuery, {\n variables: {\n owner: \"theowner\",\n name: \"myrepo\",\n first: 15\n }\n });\n\n if (loading) return null;\n\n if (error) {\n console.error(error);\n return null;\n }\n\n if (data) {\n console.log(data?.repository?.releases?.pageInfo?.endCursor);\n }\n\n const handleFetchMore = () => {\n fetchMore({\n variables: {\n first: 15,\n after: data?.repository?.releases?.pageInfo?.endCursor\n }\n });\n };\n\n return (\n \n \n {data?.repository?.releases?.nodes?.map(release => (\n \n- {release.name}\n ))}\n \n Fetch More\n \n );\n}\n```\n\nAfter `fetchMore` the component doesn't rerender with the new data.\n\nIf anyone has any other ideas that I could try, I'd be grateful.\n\n========================================\n\nCode:\n```text\nquery ($owner: String!, $name: String!, $first: Int, $after: String, $before: String) {\n repository(owner: $owner, name: $name) {\n id\n releases(orderBy: {field: CREATED_AT, direction: DESC}, first: $first, after: $after, before: $before) {\n nodes {\n name\n publishedAt\n resourcePath\n tagName\n url\n id\n isPrerelease\n description\n descriptionHTML\n }\n totalCount\n pageInfo {\n endCursor\n hasNextPage\n hasPreviousPage\n startCursor\n }\n }\n }\n}\n```\n\n```text\nconst inMemoryCacheOptions = {\n addTypename: true,\n typePolicies: {\n ReleaseConnection: {\n fields: {\n nodes: {\n merge(existing, incoming, options) {\n const previous = existing || []\n const results = [...previous, ...incoming]\n return results\n }\n }\n }\n },\n }\n}\n```\n\n```text\nexport default function Releases() {\n const { loading, error, data, fetchMore } = useQuery(releasesQuery, {\n variables: {\n owner: \"theowner\",\n name: \"myrepo\",\n first: 15\n }\n });\n\n if (loading) return null;\n\n if (error) {\n console.error(error);\n return null;\n }\n\n if (data) {\n console.log(data?.repository?.releases?.pageInfo?.endCursor);\n }\n\n const handleFetchMore = () => {\n fetchMore({\n variables: {\n first: 15,\n after: data?.repository?.releases?.pageInfo?.endCursor\n }\n });\n };\n\n return (\n <div>\n <ul>\n {data?.repository?.releases?.nodes?.map(release => (\n <li key={release.id}>{release.name}</li>\n ))}\n </ul>\n <button onClick={handleFetchMore}>Fetch More</button>\n </div>\n );\n}\n```\n\n```text\nnodes\n```\n\n```text\nfetchMore\n```\n\n```text\nuseQuery\n```\n\n```text\nfetchMore\n```\n\n```text\nmerging\n```\n\n```text\nfetchMore\n```\n\n```text\nrepository -> releases -> nodes\n```\n\n```text\nresults\n```\n\n```text\nuseQuery\n```\n\n```text\nfetchMore\n```\n\n```text\nfetchMore\n```\n\n```text\ninMemoryCacheOptions\n```\n\n```text\nfetchMore\n```\n\n```text\nconst inMemoryCacheOptions = {\n addTypename: true,\n typePolicies: {\n Repository: {\n fields: {\n releases: {\n keyArgs: false,\n merge(existing, incoming) {\n if (!incoming) return existing;\n if (!existing) return incoming;\n\n const { nodes, ...rest } = incoming;\n // We only need to merge the nodes array.\n // The rest of the fields (pagination) should always be overwritten by incoming\n let result = rest;\n result.nodes = [...existing.nodes, ...nodes];\n return result;\n }\n }\n }\n }\n }\n};\n```\n\n```text\nInMemoryCacheOptions\n```\n\n```text\nreleases\n```\n\n```text\nRepository\n```\n\n```text\nnodes\n```\n\n```text\nRelease\n```\n\n```text\nRepository\n```\n\n```text\nQuery\n```\n\n```text\nreleases\n```\n\n```text\nQuery -> repository -> releases\n```\n\n========================================\n\nComments:\n- eh....show not working parts ... rendering/component code\n- I added the relevant component code. I think the component is working fine, I just think the issue is with the data being returned from the ApolloClient cache. It isn't \"changing\" and the component doesn't have new data and therefore doesn't rerender.\n- eh ... still no rendering code here ... Iguess list wrapped into not changing elements? render **only** list elements in this component ... `if(data) console.log(data.repository.releases.pageInfo.endCursor);` ... you can inspect apollo cache store/entries using normal react dev tools\n- Added the whole component code. Inspecting apollo cache initially shows no entries, the after one fetchMore it shows 30 entries (initial 15 + new 15) but for further fetchMore requests it still only shows the 30 entries. The component always only shows the first 15 entries. In the network tab, the graphql request continues to fetch all the new entries when fetchMore is fired. I logged the `endCursor` but it is only shown once, the first time the component renders because it doesn't rerender.\n- no `if(data)` needed if loading/error checked earlier ... destructure/alias and resuse ... `const { repository:{ releases }} = data;` ... try to force rerender ... `return ( .... releases.nodes.map(...`","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":337,"estimatedTokens":1850}}737{"id":"stack-59153464","source":"stackoverflow","questionId":59153464,"title":"Does Azure APIM support GraphQL?","tags":["azure","graphql","azure-web-app-service","azure-api-management"],"text":"Title: Does Azure APIM support GraphQL?\nTags: azure, graphql, azure-web-app-service, azure-api-management\nSource: Stack Overflow\n\nQuestion:\nWe have microservices setup with Azure APIM as gateway and routers to all the services in the back. Is there anyway I can introduce GrpahQl before APIM or within APIM ?\n\n========================================\n\nTop Answer:\nAssuming your backend APIs are written to support GraphQL, importing GraphQL APIs is now available (in preview, at the time of writing this response) by Azure API Management: https://learn.microsoft.com/en-us/azure/api-management/graphql-api\n\nGraphQL validation policies are also available (in preview): https://learn.microsoft.com/en-us/azure/api-management/graphql-validation-policies\n\n========================================\n\nComments:\n- With limitations, you can serve it over HTTP with Azure API Management. However, the full support isn't on the roadmap.\n- It's supported as of Nov 2021. See answer below\n- what is the issue if we define a post graphql endpoint in APIM ? We can manually configure this in APIM as a workaround. What do we loose in this approach ?\n- I tried doing this and at startup gateway failed with auth error . I believe the reason behind this is that at startup gateway tries load services/subgraphs which is apparently deployed behind APIM and APIM send auth error because gateway cannot send JWT tokens at startup\n- GraphQL support in APIM is in public preview now: azure.microsoft.com/en-us/updates/…\n- GraphQL support has recently been added to APIM.\n- does it support GraphQL subscriptions as well?","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":24,"estimatedTokens":401}}738{"id":"stack-53074038","source":"stackoverflow","questionId":53074038,"title":"How granular should Relay/Apollo fragments be?","tags":["reactjs","graphql","apollo","relayjs","relay"],"text":"Title: How granular should Relay/Apollo fragments be?\nTags: reactjs, graphql, apollo, relayjs, relay\nSource: Stack Overflow\n\nQuestion:\nI'm using GraphQL + Relay in my app and find myself wrapping almost every component with `createFragmentContainer`, including those very low in the DOM hierarchy (usually functional components). \n\nIs that the right way to use fragments? I'm wondering what are the guidelines for when to wrap components in fragment containers? Seems redundant to wrap a component when it only needs one field and I can pass that data from the parent via props.\n\nI'm using Relay but I think the concepts are similar to Apollo as well.\n\n========================================\n\nTop Answer:\nThis is the answer from my co-worker Jan Kassens who works on the Relay team:\n\n If splitting out components makes sense to you, you should go for it. I find smaller modules generally help making code more understandable.\n Now, a Button component probably doesn't have to have a fragment attached to it, but if it's a \"Like Page\" button with a mutation and maybe label specific to the page, I think it makes total sense to make that it's own fragment container.\n\n \n As with so many things in engineering, there's probably trade offs in splitting out too much, but we've spent a lot of thought on making fragment containers as lightweight and efficient as we can so you shouldn't think too hard about introducing overhead.\n\n========================================\n\nCode:\n```text\ncreateFragmentContainer\n```\n\n```text\nData Masking\n```\n\n========================================\n\nComments:\n- Thanks, the article you linked gave a very good reason in favor of fragments (:","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":37,"estimatedTokens":419}}739{"id":"stack-68758848","source":"stackoverflow","questionId":68758848,"title":"Apollo Client relayStylePagination doesn't fetchMore","tags":["graphql","apollo-client"],"text":"Title: Apollo Client relayStylePagination doesn't fetchMore\nTags: graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have implemented `relayStylePagination()` according to the apollo docs(https://www.apollographql.com/docs/react/pagination/cursor-based/#relay-style-cursor-pagination) in the following way:\n\nindex.js:\n\n```\nconst httpLink=new HttpLink({\n uri:'https://api.github.com/graphql',\n headers:{\n authorization: 'Bearer -'\n }\n})\n\nconst cache = new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n repositories:relayStylePagination()\n },\n },\n },\n});\n\nconst client=new ApolloClient({\n link:httpLink,\n cache\n})\n\nReactDOM.render(\n \n \n \n \n ,\n document.getElementById('root')\n);\n```\n\nApp.js:\n\n```\nconst App=()=> {\n\n const {loading,error,data,fetchMore}=useQuery(GET_REPOSITORIES_OF_CURRENT_USER,{\n variables:{login:\"rwieruch\"}\n })\n\n if (loading) return \n\n### Loading...\n\n if (error) return Error...\n\n console.log(data.user.repositories.edges)\n console.log(data)\n\n const pageInfo=data.user.repositories.pageInfo\n console.log(pageInfo)\n return(\n \n \n {return fetchMore({\n variables:{\n after: data.user.repositories.pageInfo.endCursor,\n }\n })}\n }\n />\n \n )\n}\n```\n\nHow the button is rendered in the Child component:\n\n`Hey`\n\nAnd, finally the gql query:\n\n```\nconst GET_REPOSITORIES_OF_CURRENT_USER = gql`\n query getUser($login:String!,$after:String){\n user (login:$login){\n repositories(\n first: 10,\n after:$after\n ) {\n edges {\n node {\n id\n name\n url\n descriptionHTML\n primaryLanguage {\n name\n }\n owner {\n login\n url\n }\n stargazers {\n totalCount\n }\n viewerHasStarred\n watchers {\n totalCount\n }\n viewerSubscription\n }\n }\n pageInfo{\n endCursor\n hasNextPage\n }\n }\n }\n}\n`;\n```\n\nThe problem is that when I press the button with the onClick prop corresponding to fetchMore , nothing is fetched. Also, there are no errors in my console- it just doesn't do anything. Can you please let me know why? I have been trying to figure it out for hours now. Thank you!\n\n========================================\n\nCode:\n```js\nconst httpLink=new HttpLink({\n uri:'https://api.github.com/graphql',\n headers:{\n authorization: 'Bearer -'\n }\n})\n\nconst cache = new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n repositories:relayStylePagination()\n },\n },\n },\n});\n\nconst client=new ApolloClient({\n link:httpLink,\n cache\n})\n\nReactDOM.render(\n <ApolloProvider client={client}>\n <React.StrictMode>\n <App />\n </React.StrictMode>\n </ApolloProvider>,\n document.getElementById('root')\n);\n```\n\n```js\nconst App=()=> {\n\n const {loading,error,data,fetchMore}=useQuery(GET_REPOSITORIES_OF_CURRENT_USER,{\n variables:{login:\"rwieruch\"}\n })\n\n if (loading) return <h1>Loading...</h1>\n if (error) return <p>Error...</p>\n console.log(data.user.repositories.edges)\n console.log(data)\n\n const pageInfo=data.user.repositories.pageInfo\n console.log(pageInfo)\n return(\n <div>\n <RepositoryList repositories={data.user.repositories} onLoadMore={()=>\n {return fetchMore({\n variables:{\n after: data.user.repositories.pageInfo.endCursor,\n }\n })}\n }\n />\n </div>\n )\n}\n```\n\n```js\nconst GET_REPOSITORIES_OF_CURRENT_USER = gql`\n query getUser($login:String!,$after:String){\n user (login:$login){\n repositories(\n first: 10,\n after:$after\n ) {\n edges {\n node {\n id\n name\n url\n descriptionHTML\n primaryLanguage {\n name\n }\n owner {\n login\n url\n }\n stargazers {\n totalCount\n }\n viewerHasStarred\n watchers {\n totalCount\n }\n viewerSubscription\n }\n }\n pageInfo{\n endCursor\n hasNextPage\n }\n }\n }\n}\n`;\n```\n\n```text\nrelayStylePagination()\n```\n\n```text\n<button onClick={onLoadMore}>Hey</button>\n```\n\n```text\nconst cache = new InMemoryCache({\n typePolicies: {\n User: { // <- (!)\n fields: {\n repositories:relayStylePagination()\n },\n },\n },\n});\n```\n\n```text\nQuery.repositories\n```\n\n```text\nUser.repositories\n```\n\n========================================\n\nComments:\n- Can you check if the function that you are passing `onLoadMore` is actually called? You could do that by logging before the return statement.\n- @Herku Hello ! Yes , it is being called , I tried loggin the endCursor within the function and everything is fine...\n- @Herku Apollo gives the following warning in the console , yet it isnt marked as an error `Cache data may be lost when replacing the user field of a Query object. To address this problem (which is not a bug in Apollo Client), either ensure all objects of type User have an ID or a custom merge function, or define a custom merge function for the Query.user field, so InMemoryCache can safely merge these objects:` I have added an id to the user query and the warning dissapeared , yet it still didnt fetchMore..\n- Okay, I will write an answer now, I think I see your problem\n- What a lifesaver! The documentation seems a bit misleading in this case , because they give the following query `const COMMENTS_QUERY = gql query Comments($cursor: String) { comments(first: 10, after: $cursor) { edges { node { author text } } pageInfo { endCursor hasNextPage } } } ;` , but in the typePolicies : `const cache = new InMemoryCache({ typePolicies: { Query: { fields: { comments: relayStylePagination(), }, }, }, });` . Thank you so much !\n- Yes, in the documentation the field `Query.comments` is paginated. This requires some understanding of how the type policies are specified in general.\n- Thank you very much, I have been sitting on this for ages!\n- Happy I could help!","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":271,"estimatedTokens":1440}}740{"id":"stack-62202051","source":"stackoverflow","questionId":62202051,"title":"Is there a way to expose 2 graphql endpoints using spring boot starter app graphql-spring-boot-starter?","tags":["graphql","graphql-java"],"text":"Title: Is there a way to expose 2 graphql endpoints using spring boot starter app graphql-spring-boot-starter?\nTags: graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nCurrently we are using \n\n```\n\n com.graphql-java-kickstart\n graphql-spring-boot-starter\n ${graphql-spring-starter.version}\n \n```\n\nWith this, we are exposing our graphql API using /graphql endpoint. I want to have multiple endpoints like this, /graphql1 and /graphql2 so that I can define different response formats based on the endpoints. what is the best way to do it? Any inputs is highly appreciated.\n\n========================================\n\nCode:\n```text\n<dependency>\n <groupId>com.graphql-java-kickstart</groupId>\n <artifactId>graphql-spring-boot-starter</artifactId>\n <version>${graphql-spring-starter.version}</version>\n </dependency>\n```\n\n```java\n@Bean\npublic ServletRegistrationBean<AbstractGraphQLHttpServlet> fooGraphQLServlet() {\n //Create and configure the GraphQL Schema.\n GraphQLSchema schema = xxxxxxx;\n\n GraphQLHttpServlet graphQLHttpServlet = GraphQLHttpServlet.with(schema);\n ServletRegistrationBean<AbstractGraphQLHttpServlet> registration = new ServletRegistrationBean<>(\n graphQLHttpServlet, \"/graphql2/*\");\n\n registration.setName(\"Another GraphQL Endpoint\");\n return registration;\n}\n```\n\n```text\nGraphQLHttpServlet\n```\n\n```text\nGraphQLWebAutoConfiguration\n```\n\n```text\nGraphQLHttpServlet\n```\n\n```text\n/graphql\n```\n\n```text\nGraphQLWebAutoConfiguration\n```\n\n```text\nGraphQLHttpServlet\n```\n\n```text\nServlet\n```\n\n```text\nServletRegistrationBean\n```\n\n```text\nHttpServlet\n```\n\n========================================\n\nComments:\n- how about cors setup?","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":83,"estimatedTokens":426}}741{"id":"stack-70170480","source":"stackoverflow","questionId":70170480,"title":"how to scrape product data from website pages that uses graphql","tags":["python","web-scraping","graphql"],"text":"Title: how to scrape product data from website pages that uses graphql\nTags: python, web-scraping, graphql\nSource: Stack Overflow\n\nQuestion:\nI previously used the code below to scrape the search result for a word search, for example book, on https://www.walmart.com/. They have currently changed their request and response parameters and this code does not get any response again.\n\n```\nparams = {\n 'query': 'book',\n 'cat_id': 0,\n 'ps': 24,\n 'offset': 0,\n\n 'prg': 'desktop',\n 'stores': re.search(r'store/(\\d+)', url).group(1)\n }\n\n try:\n data1 = requests.get(api_url, params=params).json()\n\n except Exception as e:\n print(\"Sleeping for 10 seconds\", e)\n time.sleep(10)\n\n try:\n data1 = requests.get(api_url, params=params).json()\n except Exception as e:\n print(\"sleeping for 60 seconds\", e)\n time.sleep(60)\n\n try:\n data1 = requests.get(api_url, params=params).json()\n except Exception as e:\n print(\"sleeping for 360 seconds\")\n time.sleep(360)\n\n data1 = requests.get(api_url, params=params).json()\n```\n\nI want to get the json response for a product page for example the product the in this url\n\n```\nhttps://www.walmart.com/ip/SKIPPY-Natural-Creamy-Peanut-Butter-Spread-15-oz/37447671\n```\n\nHow could i rewrite the code with their current parameters to get the json response?\n\n========================================\n\nTop Answer:\nWhile this question specifically relates to Python, consider using Puppeteer or Playwright for browser automation. This allows you to initiate requests as the user from a high-level, and you can use `page.on('response')` to intercept API server responses. This could remove the low-level schema requirements that are more likely to change compared to the public UI. You could also parse the web page results seen by users, which avoids the low-level data abstractions.\n\n========================================\n\nCode:\n```text\nparams = {\n 'query': 'book',\n 'cat_id': 0,\n 'ps': 24,\n 'offset': 0,\n\n 'prg': 'desktop',\n 'stores': re.search(r'store/(\\d+)', url).group(1)\n }\n\n try:\n data1 = requests.get(api_url, params=params).json()\n\n except Exception as e:\n print(\"Sleeping for 10 seconds\", e)\n time.sleep(10)\n\n try:\n data1 = requests.get(api_url, params=params).json()\n except Exception as e:\n print(\"sleeping for 60 seconds\", e)\n time.sleep(60)\n\n try:\n data1 = requests.get(api_url, params=params).json()\n except Exception as e:\n print(\"sleeping for 360 seconds\")\n time.sleep(360)\n\n data1 = requests.get(api_url, params=params).json()\n```\n\n```text\nhttps://www.walmart.com/ip/SKIPPY-Natural-Creamy-Peanut-Butter-Spread-15-oz/37447671\n```\n\n```text\nimport requests\nimport json\ndata= {\n \n \"query\":\"query Browse( $query:String $page:Int $prg:Prg! $facet:String $sort:Sort $catId:String! $max_price:String $min_price:String $module_search:String $affinityOverride:AffinityOverride $ps:Int $ptss:String $beShelfId:String $fitmentFieldParams:JSON ={}$fitmentSearchParams:JSON ={}$rawFacet:String $seoPath:String $trsp:String $fetchMarquee:Boolean! $fetchSkyline:Boolean! $additionalQueryParams:JSON ={}){search( query:$query page:$page prg:$prg facet:$facet sort:$sort cat_id:$catId max_price:$max_price min_price:$min_price module_search:$module_search affinityOverride:$affinityOverride additionalQueryParams:$additionalQueryParams ps:$ps ptss:$ptss trsp:$trsp _be_shelf_id:$beShelfId ){query searchResult{...BrowseResultFragment}}contentLayout( channel:\\\"WWW\\\" pageType:\\\"BrowsePage\\\" tenant:\\\"WM_GLASS\\\" version:\\\"v1\\\" searchArgs:{query:$query cat_id:$catId _be_shelf_id:$beShelfId prg:$prg}){modules{...ModuleFragment configs{...on EnricherModuleConfigsV1{zoneV1}__typename...on _TempoWM_GLASSWWWSearchSortFilterModuleConfigs{facetsV1{...FacetFragment}}...on TempoWM_GLASSWWWPillsModuleConfigs{moduleSource pillsV2{...PillsModuleFragment}}...on TempoWM_GLASSWWWSearchFitmentModuleConfigs{fitments( fitmentSearchParams:$fitmentSearchParams fitmentFieldParams:$fitmentFieldParams ){...FitmentFragment sisFitmentResponse{...BrowseResultFragment}}}...on TempoWM_GLASSWWWStoreSelectionHeaderConfigs{fulfillmentMethodLabel storeDislayName}...on TempoWM_GLASSWWWBreadcrumbConfigs{_rawConfigs}...on TempoWM_GLASSWWWSponsoredProductCarouselConfigs{_rawConfigs}...PopularInModuleFragment...CopyBlockModuleFragment...BannerModuleFragment...HeroPOVModuleFragment...InlineSearchModuleFragment...MarqueeDisplayAdConfigsFragment @include(if:$fetchMarquee)...SkylineDisplayAdConfigsFragment @include(if:$fetchSkyline)...HorizontalChipModuleConfigsFragment}}...LayoutFragment pageMetadata{location{postalCode stateOrProvinceCode city storeId}pageContext}}seoBrowseMetaData( id:$catId facets:$rawFacet path:$seoPath facet_query_param:$facet _be_shelf_id:$beShelfId ){metaTitle metaDesc metaCanon h1}}fragment BrowseResultFragment on SearchInterface{title aggregatedCount...BreadCrumbFragment...DebugFragment...ItemStacksFragment...PageMetaDataFragment...PaginationFragment...RequestContextFragment...ErrorResponse modules{facetsV1{...FacetFragment}pills{...PillsModuleFragment}}}fragment ModuleFragment on TempoModule{name version type moduleId schedule{priority}matchedTrigger{zone}}fragment LayoutFragment on ContentLayout{layouts{id layout}}fragment BreadCrumbFragment on SearchInterface{breadCrumb{id name url}}fragment DebugFragment on SearchInterface{debug{sisUrl}}fragment ItemStacksFragment on SearchInterface{itemStacks{displayMessage meta{adsBeacon{adUuid moduleInfo max_ads}query stackId stackType title layoutEnum totalItemCount totalItemCountDisplay viewAllParams{query cat_id sort facet affinityOverride recall_set min_price max_price}}itemsV2{...ItemFragment...InGridMarqueeAdFragment}}}fragment ItemFragment on Product{__typename id usItemId fitmentLabel name checkStoreAvailabilityATC seeShippingEligibility brand type shortDescription imageInfo{...ProductImageInfoFragment}canonicalUrl externalInfo{url}category{path{name url}}badges{flags{...on BaseBadge{key text type id}}tags{...on BaseBadge{key text type}}}classType averageRating numberOfReviews esrb mediaRating salesUnitType sellerId sellerName hasSellerBadge availabilityStatusV2{display value}productLocation{displayValue aisle{zone aisle}}badge{type dynamicDisplayName}fulfillmentSpeed offerId preOrder{...PreorderFragment}priceInfo{...ProductPriceInfoFragment}variantCriteria{...VariantCriteriaFragment}fulfillmentBadge fulfillmentTitle fulfillmentType brand manufacturerName showAtc sponsoredProduct{spQs clickBeacon spTags}showOptions}fragment ProductImageInfoFragment on ProductImageInfo{thumbnailUrl}fragment ProductPriceInfoFragment on ProductPriceInfo{priceRange{minPrice maxPrice}currentPrice{...ProductPriceFragment}wasPrice{...ProductPriceFragment}unitPrice{...ProductPriceFragment}listPrice{...ProductPriceFragment}shipPrice{...ProductPriceFragment}subscriptionPrice{priceString subscriptionString}priceDisplayCodes{priceDisplayCondition finalCostByWeight}}fragment PreorderFragment on PreOrder{isPreOrder preOrderMessage preOrderStreetDateMessage}fragment ProductPriceFragment on ProductPrice{price priceString}fragment VariantCriteriaFragment on VariantCriterion{name type id isVariantTypeSwatch variantList{id images name rank swatchImageUrl availabilityStatus products selectedProduct{canonicalUrl usItemId}}}fragment InGridMarqueeAdFragment on MarqueePlaceholder{__typename type moduleLocation lazy}fragment PageMetaDataFragment on SearchInterface{pageMetadata{storeSelectionHeader{fulfillmentMethodLabel storeDislayName}title canonical description location{addressId}}}fragment PaginationFragment on SearchInterface{paginationV2{maxPage pageProperties}}fragment RequestContextFragment on SearchInterface{requestContext{vertical isFitmentFilterQueryApplied searchMatchType categories{id name}}}fragment ErrorResponse on SearchInterface{errorResponse{correlationId source errors{errorType statusCode statusMsg source}}}fragment PillsModuleFragment on PillsSearchInterface{title url image:imageV1{src alt}baseSeoURL}fragment BannerModuleFragment on TempoWM_GLASSWWWSearchBannerConfigs{moduleType viewConfig{title image imageAlt displayName description url urlAlt appStoreLink appStoreLinkAlt playStoreLink playStoreLinkAlt}}fragment PopularInModuleFragment on TempoWM_GLASSWWWPopularInBrowseConfigs{seoBrowseRelmData(id:$catId){relm{id name url}}}fragment CopyBlockModuleFragment on TempoWM_GLASSWWWCopyBlockConfigs{copyBlock(id:$catId){cwc}}fragment FacetFragment on Facet{name type layout min max selectedMin selectedMax unboundedMax stepSize values{id name description type itemCount isSelected baseSeoURL}}fragment FitmentFragment on Fitments{partTypeIDs result{status formId position quantityTitle extendedAttributes{...FitmentFieldFragment}labels{...LabelFragment}resultSubTitle}labels{...LabelFragment}savedVehicle{vehicleYear{...VehicleFieldFragment}vehicleMake{...VehicleFieldFragment}vehicleModel{...VehicleFieldFragment}additionalAttributes{...VehicleFieldFragment}}fitmentFields{...VehicleFieldFragment}fitmentForms{id fields{...FitmentFieldFragment}title labels{...LabelFragment}}}fragment LabelFragment on FitmentLabels{ctas{...FitmentLabelEntityFragment}messages{...FitmentLabelEntityFragment}links{...FitmentLabelEntityFragment}images{...FitmentLabelEntityFragment}}fragment FitmentLabelEntityFragment on FitmentLabelEntity{id label}fragment VehicleFieldFragment on FitmentVehicleField{id label value}fragment FitmentFieldFragment on FitmentField{id displayName value extended data{value label}dependsOn}fragment HeroPOVModuleFragment on TempoWM_GLASSWWWHeroPovConfigsV1{povCards{card{povStyle image{mobileImage{...TempoCommonImageFragment}desktopImage{...TempoCommonImageFragment}}heading{text textColor textSize}subheading{text textColor}detailsView{backgroundColor isTransparent}ctaButton{button{linkText clickThrough{value}}}logo{...TempoCommonImageFragment}links{link{linkText}}}}}fragment TempoCommonImageFragment on TempoCommonImage{src alt assetId uid clickThrough{value}}fragment InlineSearchModuleFragment on TempoWM_GLASSWWWInlineSearchConfigs{headingText placeholderText}fragment MarqueeDisplayAdConfigsFragment on TempoWM_GLASSWWWMarqueeDisplayAdConfigs{_rawConfigs ad{...DisplayAdFragment}}fragment DisplayAdFragment on Ad{...AdFragment adContent{type data{__typename...AdDataDisplayAdFragment}}}fragment AdFragment on Ad{status moduleType platform pageId pageType storeId stateCode zipCode pageContext moduleConfigs adsContext adRequestComposite}fragment AdDataDisplayAdFragment on AdData{...on DisplayAd{json status}}fragment SkylineDisplayAdConfigsFragment on TempoWM_GLASSWWWSkylineDisplayAdConfigs{_rawConfigs ad{...SkylineDisplayAdFragment}}fragment SkylineDisplayAdFragment on Ad{...SkylineAdFragment adContent{type data{__typename...SkylineAdDataDisplayAdFragment}}}fragment SkylineAdFragment on Ad{status moduleType platform pageId pageType storeId stateCode zipCode pageContext moduleConfigs adsContext adRequestComposite}fragment SkylineAdDataDisplayAdFragment on AdData{...on DisplayAd{json status}}fragment HorizontalChipModuleConfigsFragment on TempoWM_GLASSWWWHorizontalChipModuleConfigs{chipModuleSource:moduleSource chipModule{title url{linkText title clickThrough{type value}}}chipModuleWithImages{title url{linkText title clickThrough{type value}}image{alt clickThrough{type value}height src title width}}}\",\n \"variables\":{\n \"id\":\"\",\n \"affinityOverride\":\"default\",\n \"dealsId\":\"\",\n \"query\":\"\",\n \"page\":1,\n \"prg\":\"desktop\",\n \"catId\":\"3920\",\n \"facet\":\"\",\n \"sort\":\"best_seller\",\n \"rawFacet\":\"\",\n \"seoPath\":\"\",\n \"ps\":40,\n \"ptss\":\"\",\n \"trsp\":\"\",\n \"beShelfId\":\"\",\n \"recall_set\":\"\",\n \"module_search\":\"\",\n \"min_price\":\"\",\n \"max_price\":\"\",\n \"storeSlotBooked\":\"\",\n \"additionalQueryParams\":None,\n \"fitmentFieldParams\":None,\n \"fitmentSearchParams\":{\n \"id\":\"\",\n \"affinityOverride\":\"default\",\n \"dealsId\":\"\",\n \"query\":\"\",\n \"page\":1,\n \"prg\":\"desktop\",\n \"catId\":\"3920\",\n \"facet\":\"\",\n \"sort\":\"best_seller\",\n \"rawFacet\":\"\",\n \"seoPath\":\"\",\n \"ps\":40,\n \"ptss\":\"\",\n \"trsp\":\"\",\n \"beShelfId\":\"\",\n \"recall_set\":\"\",\n \"module_search\":\"\",\n \"min_price\":\"\",\n \"max_price\":\"\",\n \"storeSlotBooked\":\"\",\n \"additionalQueryParams\":None,\n \"cat_id\":\"3920\",\n \"_be_shelf_id\":\"\"\n },\n \"fetchMarquee\":True,\n \"fetchSkyline\":True,\n \"fetchSbaTop\":False\n }\n\n}\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',\n 'content-type':'application/json',\n 'wm_mp': 'true',\n 'wm_page_url': 'https://www.walmart.com/browse/books/3920?sort=best_seller&affinityOverride=default',\n 'wm_qos.correlation_id': 'FWpup9KEKUrLFOY68gppqfprABL16K6qE76g',\n 'x-apollo-operation-name': 'Browse',\n 'x-enable-server-timing': '1',\n 'x-latency-trace': '1',\n 'x-o-ccm': 'server',\n 'x-o-correlation-id': 'FWpup9KEKUrLFOY68gppqfprABL16K6qE76g',\n 'x-o-gql-query': 'query Browse',\n 'x-o-market': 'us',\n 'x-o-platform': 'rweb',\n 'x-o-platform-version': 'main-176-e8acb5',\n 'x-o-segment': 'oaoh'\n }\n\n\nparams= {\n \"affinityOverride\": \"default\",\n \"page\": \"1\",\n \"prg\": \"desktop\",\n \"catId\": \"3920\",\n \"sort\": \"best_seller\",\n \"ps\": \"40\",\n \"fetchMarquee\": \"true\",\n \"fetchSkyline\": \"true\",\n \"fetchSbaTop\": \"false\"}\n\n\n\n\n\nfor i in range(1,25,1):\n params['maxPage']=i\n api_url='https://www.walmart.com/orchestra/home/graphql/browse'\n resp = requests.post(api_url, data=json.dumps(data), headers=headers,params=params)\n r=resp.json()\n print(r)\n # items = r['data']['search']['searchResult']['itemStacks'][0]['itemsV2']\n # for item in items:\n # price = item['priceInfo']['currentPrice']['price']\n # print(price)\n```\n\n```text\n'https://i5.walmartimages.com/asr/deaaef8d-ca7f-4fc1-b556-1209c4c9000c.c6df15d971f1b9cddde27f80f17ae80b.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff'}, 'canonicalUrl': '/ip/Sonic-The-Hedgehog-Coloring-Book-For-Kids-Girls-Adults-Toddlers-Kids-ages-2-8-Unofficial-25-high-quality-illustrations-Pages-8-5-x-11-Paperback-9781677024223/614029660?athbdg=L1600', 'externalInfo': None, 'category': {'path': None}, 'badges': {'flags': [{'key': 'BESTSELLER', 'text': 'Best seller', 'type': 'LABEL', 'id': 'L1600'}], 'tags': [{'key': 'THREE_PLUS_DAY_SHIPPING', 'text': '3+ day shipping', 'type': 'LABEL'}, {'key': 'SAVE_WITH_W_PLUS', 'text': 'Save with', 'type': 'ICON'}]}, 'classType': 'REGULAR', 'averageRating': 3.9, 'numberOfReviews': 8, 'esrb': None, 'mediaRating': None, 'salesUnitType': 'EACH', 'sellerId': 'F55CDC31AB754BB68FE0B39041159D63', 'sellerName': 'Walmart.com', 'hasSellerBadge': None, 'availabilityStatusV2': {'display': 'In stock', \n'value': 'IN_STOCK'}, 'productLocation': None, 'badge': [{'type': 'bestSeller', 'dynamicDisplayName': None}], 'fulfillmentSpeed': None, 'offerId': '27E4BA43A8704A1DABF0B37693611D16', 'preOrder': {'isPreOrder': False, 'preOrderMessage': None, 'preOrderStreetDateMessage': None}, 'priceInfo': {'priceRange': None, 'currentPrice': {'price': 6.99, \n'priceString': '$6.99'}, 'wasPrice': None, 'unitPrice': None, 'listPrice': None, 'shipPrice': None, 'subscriptionPrice': None, 'priceDisplayCodes': {'priceDisplayCondition': None, 'finalCostByWeight': None}}, 'variantCriteria': [], 'fulfillmentBadge': None, \n'fulfillmentTitle': 'title_shipToHome_not_available', 'fulfillmentType': 'FC', 'manufacturerName': None, 'showAtc': True, 'sponsoredProduct': None, 'showOptions': False}, {'__typename': 'Product', 'id': '16FA2JT4ZT52', 'usItemId': '491355610', 'fitmentLabel': None, 'name': 'Bible Word Search Books: Word Search Bible Puzzle Book - Extra Large \nPrint: Bible Word Search Large Print Puzzles for Seniors and Adults - Beginners Edition (Large Print) (Paperback)', 'checkStoreAvailabilityATC': False, 'seeShippingEligibility': False, 'brand': None, 'type': 'REGULAR', 'shortDescription': '<li>Format:Paperback</li><li>Publication Date: 2019-11-22</li>', 'imageInfo': {'thumbnailUrl': 'https://i5.walmartimages.com/asr/46269778-a1bc-4a7a-aff2-75a825e35cf9.62e71231ecd42f6cda6d3701a3281b53.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff'}, 'canonicalUrl': '/ip/Bible-Word-Search-Books-Puzzle-Book-Extra-Large-Print-Print-Puzzles-Seniors-Adults-Beginners-Edition-Large-Print-Paperback-9781710478792/491355610', 'externalInfo': None, 'category': {'path': None}, 'badges': {'flags': None, 'tags': [{'key': 'THREE_PLUS_DAY_SHIPPING', 'text': '3+ day shipping', 'type': 'LABEL'}, {'key': 'SAVE_WITH_W_PLUS', 'text': 'Save with', 'type': 'ICON'}]}, 'classType': 'REGULAR', 'averageRating': 4.7, 'numberOfReviews': 13, 'esrb': None, 'mediaRating': None, 'salesUnitType': 'EACH', 'sellerId': 'F55CDC31AB754BB68FE0B39041159D63', 'sellerName': 'Walmart.com', 'hasSellerBadge': None, 'availabilityStatusV2': {'display': 'In stock', 'value': 'IN_STOCK'}, 'productLocation': None, 'badge': None, 'fulfillmentSpeed': None, 'offerId': '0E3D37D69AE14435A4E83D3AE2789B7F', 'preOrder': {'isPreOrder': False, 'preOrderMessage': None, 'preOrderStreetDateMessage': None}, 'priceInfo': {'priceRange': None, 'currentPrice': {'price': 6.99, 'priceString': '$6.99'}, 'wasPrice': None, 'unitPrice': None, 'listPrice': None, 'shipPrice': None, 'subscriptionPrice': None, 'priceDisplayCodes': {'priceDisplayCondition': None, 'finalCostByWeight': None}}, 'variantCriteria': [], 'fulfillmentBadge': None, 'fulfillmentTitle': 'title_shipToHome_not_available', 'fulfillmentType': 'FC', 'manufacturerName': None, 'showAtc': True, 'sponsoredProduct': None, 'showOptions': False}, {'__typename': 'Product', 'id': '72BDRK2VT8QQ', 'usItemId': '599380007', 'fitmentLabel': None, 'name': 'Trace Letters and Numbers Workbook: Learn How to Write Alphabet Upper and Lower Case and Numbers (Series #2) (Paperback)', 'checkStoreAvailabilityATC': False, 'seeShippingEligibility': False, 'brand': None, 'type': 'REGULAR', 'shortDescription': '9781794540767', 'imageInfo': {'thumbnailUrl': 'https://i5.walmartimages.com/asr/535dff68-7946-4e20-899b-20d05015b05a_1.22a1f229111edd3725505c0db3fe1371.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff'}, 'canonicalUrl': '/ip/Trace-Letters-and-Numbers-Workbook-Learn-How-to-Write-Alphabet-Upper-and-Lower-Case-and-Numbers-Series-2-Paperback/599380007?athbdg=L1600', 'externalInfo': None, 'category': {'path': None}, 'badges': {'flags': [{'key': 'BESTSELLER', 'text': 'Best seller', 'type': 'LABEL', 'id': 'L1600'}], 'tags': [{'key': 'THREE_PLUS_DAY_SHIPPING', 'text': '3+ day shipping', 'type': 'LABEL'}, {'key': 'SAVE_WITH_W_PLUS', 'text': 'Save with', 'type': 'ICON'}]}, 'classType': 'REGULAR', 'averageRating': 4.7, 'numberOfReviews': 37, 'esrb': None, 'mediaRating': \nNone, 'salesUnitType': 'EACH', 'sellerId': 'F55CDC31AB754BB68FE0B39041159D63', 'sellerName': 'Walmart.com', 'hasSellerBadge': None, 'availabilityStatusV2': {'display': 'In \nstock', 'value': 'IN_STOCK'}, 'productLocation': None, 'badge': [{'type': 'bestSeller', 'dynamicDisplayName': None}], 'fulfillmentSpeed': None, 'offerId': 'B701DAA6361D4A97A599815F29FA450D', 'preOrder': {'isPreOrder': False, 'preOrderMessage': None, 'preOrderStreetDateMessage': None}, 'priceInfo': {'priceRange': None, 'currentPrice': {'price': 6.95, 'priceString': '$6.95'}, 'wasPrice': None, 'unitPrice': None, 'listPrice': None, 'shipPrice': None, 'subscriptionPrice': None, 'priceDisplayCodes': {'priceDisplayCondition': None, 'finalCostByWeight': None}}, 'variantCriteria': [], 'fulfillmentBadge': None, 'fulfillmentTitle': 'title_shipToHome_not_available', 'fulfillmentType': 'FC', 'manufacturerName': None, 'showAtc': True, 'sponsoredProduct': None, 'showOptions': False}, {'__typename': 'Product', 'id': '72DZILK2NY05', 'usItemId': '817841366', 'fitmentLabel': None, 'name': 'Toddler Coloring Book for Kids Age 1-3 : aby Activity Book Boys or Girls, Preschool coloring for Their Fun Early Learning of First Easy Number Shape and Color (Paperback)', 'checkStoreAvailabilityATC': False, 'seeShippingEligibility': False, 'brand': None, 'type': 'REGULAR', 'shortDescription': '<li>Format:Paperback</li><li>Publication Date: 2019-08-02</li>', 'imageInfo': {'thumbnailUrl': 'https://i5.walmartimages.com/asr/d2f8e8be-7fa1-4a25-a80c-e1741c6b2f6f.6392f3a67fccf0b396e1fb6ee2848b4b.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff'}, 'canonicalUrl': '/ip/Toddler-Coloring-Book-Kids-Age-1-3-aby-Activity-Boys-Girls-Preschool-coloring-Their-Fun-Early-Learning-First-Easy-Number-Shape-Color-Paperback-9781086986501/817841366?athbdg=L1600', 'externalInfo': None, 'category': {'path': None}, 'badges': {'flags': [{'key': 'BESTSELLER', 'text': 'Best seller', 'type': 'LABEL', 'id': 'L1600'}], 'tags': [{'key': 'THREE_PLUS_DAY_SHIPPING', 'text': '3+ day shipping', 'type': 'LABEL'}, {'key': 'SAVE_WITH_W_PLUS', 'text': 'Save with', 'type': 'ICON'}]}, 'classType': 'REGULAR', 'averageRating': 5, 'numberOfReviews': 2, 'esrb': None, 'mediaRating': None, 'salesUnitType': 'EACH', 'sellerId': 'F55CDC31AB754BB68FE0B39041159D63', 'sellerName': 'Walmart.com', 'hasSellerBadge': None, 'availabilityStatusV2': {'display': 'In stock', 'value': 'IN_STOCK'}, \n'productLocation': None, 'badge': [{'type': 'bestSeller', 'dynamicDisplayName': None}], 'fulfillmentSpeed': None, 'offerId': 'D3D88022487D4BF19D540BED3742A75D', 'preOrder': {'isPreOrder': False, 'preOrderMessage': None, 'preOrderStreetDateMessage': None}, 'priceInfo': {'priceRange': None, 'currentPrice': {'price': 6.95, 'priceString': '$6.95'}, 'wasPrice': None, 'unitPrice': None, 'listPrice': None, 'shipPrice': None, 'subscriptionPrice': None, 'priceDisplayCodes': {'priceDisplayCondition': None, 'finalCostByWeight': None}}, 'variantCriteria': [], 'fulfillmentBadge': None, 'fulfillmentTitle': 'title_shipToHome_not_available', 'fulfillmentType': 'FC', 'manufacturerName': None, 'showAtc': True, 'sponsoredProduct': None, 'showOptions': False}, {'__typename': 'Product', 'id': '46CGMFA2PY1Y', 'usItemId': '56172624', 'fitmentLabel': None, 'name': 'Crystals for Beginners : The Guide to Get Started with the Healing Power of Crystals (Paperback)', 'checkStoreAvailabilityATC': False, 'seeShippingEligibility': False, 'brand': None, 'type': 'VARIANT', 'shortDescription': '<li>Format:Paperback</li><li>Publication \nDate: 2017-10-17</li>', 'imageInfo': {'thumbnailUrl': 'https://i5.walmartimages.com/asr/d2954574-c30c-48af-8297-900867a2458e_1.03867d2efc65af18a6fdbff418a68afa.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff'}, 'canonicalUrl': '/ip/Crystals-for-Beginners-The-Guide-to-Get-Started-with-the-Healing-Power-of-Crystals-Paperback-9781623159917/56172624?athbdg=L1600', 'externalInfo': None, 'category': {'path': None}, 'badges': {'flags': \n[{'key': 'BESTSELLER', 'text': 'Best seller', 'type': 'LABEL', 'id': 'L1600'}], 'tags': [{'key': 'THREE_PLUS_DAY_SHIPPING', 'text': '3+ day shipping', 'type': 'LABEL'}, {'key': 'SAVE_WITH_W_PLUS', 'text': 'Save with', 'type': 'ICON'}]}, 'classType': 'VARIANT', 'averageRating': 5, 'numberOfReviews': 13, 'esrb': None, 'mediaRating': None, 'salesUnitType': 'EACH', 'sellerId': 'F55CDC31AB754BB68FE0B39041159D63', 'sellerName': 'Walmart.com', 'hasSellerBadge': None, 'availabilityStatusV2': {'display': 'In stock', 'value': 'IN_STOCK'}, 'productLocation': None, 'badge': [{'type': 'bestSeller', 'dynamicDisplayName': None}], 'fulfillmentSpeed': None, 'offerId': '5F59F4B1DE6945728E7F2EC9A3005472', 'preOrder': {'isPreOrder': False, 'preOrderMessage': None, 'preOrderStreetDateMessage': None}, 'priceInfo': {'priceRange': None, 'currentPrice': {'price': 8.99, 'priceString': '$8.99'}, 'wasPrice': None, 'unitPrice': None, 'listPrice': {'price': 14.99, 'priceString': '$14.99'}, 'shipPrice': None, 'subscriptionPrice': None, 'priceDisplayCodes': {'priceDisplayCondition': None, 'finalCostByWeight': None}}, 'variantCriteria': [], 'fulfillmentBadge': None, 'fulfillmentTitle': 'title_shipToHome_not_available', 'fulfillmentType': 'FC', 'manufacturerName': None, 'showAtc': True, 'sponsoredProduct': None, 'showOptions': False}, {'__typename': 'Product', 'id': '7FF8DA7PEPDT', 'usItemId': '136868031', 'fitmentLabel': None, 'name': 'Hack Learning: Hacking School Discipline : 9 Ways to Create a Culture of Empathy and Responsibility Using Restorative Justice (Series #22) (Paperback)', 'checkStoreAvailabilityATC': False, 'seeShippingEligibility': False, 'brand': None, 'type': 'REGULAR', 'shortDescription': '<li>Format:Paperback</li><li>Publication Date: 2019-03-12</li>', 'imageInfo': {'thumbnailUrl': 'https://i5.walmartimages.com/asr/4c639aa7-2580-4782-84ce-33a428cae000.571d547af78d39ffc35bdd28f988023f.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff'}, 'canonicalUrl': '/ip/Hack-Learning-Hacking-School-Discipline-9-Ways-Create-Culture-Empathy-Responsibility-Using-Restorative-Justice-Series-22-Paperback-9781948212137/136868031?athbdg=L1600', 'externalInfo': None, 'category': {'path': None}, 'badges': {'flags': [{'key': 'BESTSELLER', 'text': 'Best seller', 'type': 'LABEL', 'id': 'L1600'}], 'tags': [{'key': 'THREE_PLUS_DAY_SHIPPING', 'text': '3+ day shipping', 'type': 'LABEL'}, {'key': 'SAVE_WITH_W_PLUS', 'text': 'Save with', 'type': 'ICON'}]}, 'classType':\n```\n\n```text\n22.99\n1.22\n6.99\n9.95\n5.95\n9.81\n5.99\n13.17\n4.52\n6.99\n4.99\n7.99\n6.79\n5.99\n6.5\n6.95\n6.99\n5.99\n4.99\n5\n4.99\n11.93\n5.99\n4.99\n6.99\n6.99\n6.95\n6.95\n8.99\n14.81\n5.13\n7.29\n3.95\n5.99\n5.5\n5.99\n16.88\n6.99\n6.99\n1.99\n22.99\n1.22\n6.99\n9.95\n5.95\n9.81\n5.99\n13.17\n4.52\n6.99\n4.99\n7.99\n6.7\n```\n\n```text\npage.on('response')\n```\n\n========================================\n\nComments:\n- Bummer you aren't trying to use JS, this would be a perfect job for headless chrome.\n- @AdamF can you please provide a js solution?\n- Oh wow, amazing. This is the response I am getting back for r {'redirectUrl': '/blocked?url=Lw==&uuid=912ce32e-5603-11ec-92c4-454758524a73‌​&vid=&g=b', 'appId': 'PXu6b0qd2S', 'jsClientSrc': '/px/PXu6b0qd2S/init.js', 'firstPartyEnabled': True, 'vid': '', 'uuid': '912ce32e-5603-11ec-92c4-454758524a73', 'hostUrl': '/px/PXu6b0qd2S/xhr', 'blockScript': '/px/PXu6b0qd2S/captcha/captcha.js?a=c&m=0&u=912ce32e-5603-1‌​1ec-92c4-454758524a7‌​3&v=&g=b'}\n- The data of that particular site is `cloudflare` protected and which is why you are getting such result @e.iluf. Try this library `cloudscraper` which is meant to bypass that protection. Fyi, `requests` library and `cloudscraper` work in the same way, so you can use this library interchangeably. This is how the modified portion of the above script looks like.\n- I have tried this but it is working sometime and rest of the time giving {'redirectUrl': '/blocked?url=Lw==&uuid=912ce32e-5603-11ec-92c4-454758524a73‌​&vid=&g=b', 'appId': 'PXu6b0qd2S', 'jsClientSrc': '/px/PXu6b0qd2S/init.js', 'firstPartyEnabled': True, 'vid': '', 'uuid': '912ce32e-5603-11ec-92c4-454758524a73', 'hostUrl': '/px/PXu6b0qd2S/xhr', 'blockScript': '/px/PXu6b0qd2S/captcha/captcha.js?a=c&m=0&u=912ce32e-5603-1‌​1ec-92c4-454758524a7‌​3&v=&g=b'}, response. implemented this using httparty.","metadata":{"transformedAt":"2026-08-18T18:32:36.079Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":280,"estimatedTokens":6849}}742{"id":"stack-65238655","source":"stackoverflow","questionId":65238655,"title":"Is good to use TypeORM entity models classes in conjuction with NestJS-GraphQL schema type?","tags":["typescript","graphql","nestjs","dry","typeorm"],"text":"Title: Is good to use TypeORM entity models classes in conjuction with NestJS-GraphQL schema type?\nTags: typescript, graphql, nestjs, dry, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm creating a GraphQL API using NestJS and TypeORM. Starting with the classic User entity I've created both the `user.type.ts` and the `user.entity.ts` as described by the Nestjs documentation.\n\nThis is an example of the content:\n\n- `user.entity.ts`\n\n```\n@Entity({ schema: 'mydb', name: 'userList' })\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n guid: string;\n\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n\n // ...\n```\n\n- `user.type.ts`\n\n```\n@ObjectType()\nexport class UserType {\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n firstName: string;\n\n @Field()\n lastName: string;\n\n // ...\n```\n\nThe question is: since they use the same fields, can I create a single class that combines the decorators of both classes?\n\nFor instance:\n\n```\n@Entity({ schema: 'mydb', name: 'userList' })\n@ObjectType()\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Field()\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n```\n\nIs it an antipattern? are there any limitations or downsides in doing it?\n\nThanks in advance\n\n========================================\n\nTop Answer:\nI have the case where the Entities don't match the objects precisely.\nI have orders with products, but I only store the productId and resolve the product data fresh from a different system.\n\nHere I think it makes more sense to separate the two for type safety.\nI don't get the real product {} object back, only the productId, but typescript thinks I have both there.\n\n========================================\n\nCode:\n```js\n@Entity({ schema: 'mydb', name: 'userList' })\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n guid: string;\n\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n\n // ...\n```\n\n```js\n@ObjectType()\nexport class UserType {\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n firstName: string;\n\n @Field()\n lastName: string;\n\n // ...\n```\n\n```js\n@Entity({ schema: 'mydb', name: 'userList' })\n@ObjectType()\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Field()\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n```\n\n```text\nuser.type.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.type.ts\n```\n\n========================================\n\nComments:\n- Hi! Thanks for the reply!\n- I've been using the DTO with REST, but in graphql I think they are useless since the field mapping and the validations are done by graphql. Moreover, for the arguments of the queries/mutations I'm using a separated class. The mixed class I'm referring above would be used only for the gql payload and I can easily hide/transform/extends fields with the graphl decorators. For now I really don't see the point of keeping them separated. Could you give me a real-world example?\n- @Joseph - One great example I can name is when your API field name should be different than your database's field name. If you build the entity and GraphQL object together, you are stuck with the api name and entity field names having to be the same. Might not seem like an issue, but it can be.\n- Thanks! Yes I was thinking the same but actually with the @Field decorator on Nestjs you can define the mapping of a field name. For instance: `@Field({name: ID}) guid: string;` it means that your db field is called guid but it's exposed as ID. Also you can @HideField and stuff like that. For now I don't see limitation but I'll try to spot them as well","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":166,"estimatedTokens":1109}}743{"id":"stack-63702570","source":"stackoverflow","questionId":63702570,"title":"What is the $condition input parameter for in a GraphQL mutation generated by AWS Amplify CLI?","tags":["graphql","aws-appsync","graphql-mutation","graphql-codegen"],"text":"Title: What is the $condition input parameter for in a GraphQL mutation generated by AWS Amplify CLI?\nTags: graphql, aws-appsync, graphql-mutation, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nI have generated a simple GraphQL API on AWS AppSync (using CLI) from this model:\n\n```\ntype WalletProperty @model {\n id: ID!\n title: String!\n}\n```\n\nThis generated a CreateWalletProperty, UpdateWalletProperty and DeleteWalletProperty mutations all similar to this:\n\n```\nmutation CreateWalletProperty(\n $input: CreateWalletPropertyInput!\n $condition: ModelWalletPropertyConditionInput and the schema for the condition being:\n\n```\ninput ModelWalletPropertyConditionInput {\n title: ModelStringInput\n and: [ModelWalletPropertyConditionInput]\n or: [ModelWalletPropertyConditionInput]\n not: ModelWalletPropertyConditionInput\n}\n```\n\nGiven that I always have to supply the mandatory $input, what is the $condition parameter for?\n\n========================================\n\nCode:\n```text\ntype WalletProperty @model {\n id: ID!\n title: String!\n}\n```\n\n```text\nmutation CreateWalletProperty(\n $input: CreateWalletPropertyInput!\n $condition: ModelWalletPropertyConditionInput <<<<<<<<<<<< what is this for?\n ) {\n createWalletProperty(input: $input, condition: $condition) {\n id\n title\n createdAt\n updatedAt\n }\n }\n```\n\n```text\ninput ModelWalletPropertyConditionInput {\n title: ModelStringInput\n and: [ModelWalletPropertyConditionInput]\n or: [ModelWalletPropertyConditionInput]\n not: ModelWalletPropertyConditionInput\n}\n```\n\n```text\n\"errors\": [\n {\n \"path\": [\n \"deleteWalletProperty\"\n ],\n \"data\": null,\n \"errorType\": \"DynamoDB:ConditionalCheckFailedException\",\n \"errorInfo\": null,\n \"locations\": [\n {\n \"line\": 12,\n \"column\": 3,\n \"sourceName\": null\n }\n ],\n \"message\": \"The conditional request failed (Service: DynamoDb, Status Code: 400, Request ID: E3PR9OM6M5J1QBHKNT8E4SM1DJVV4KQNSO5AEMVJF66Q9ASUAAJG, Extended Request ID: null)\"\n }\n ]\n```\n\n========================================\n\nComments:\n- not marked wit `!` then not mandatory/not required ... optional parameter to filter affected rows/items\n- @xadm, thanks. I've just tested it and it appears it gets applied together with the input parameter. Given the $input is already mandatory I cannot think of a use-case where this actually makes sense or could be applied?\n- for create not, but for update ...","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":92,"estimatedTokens":620}}744{"id":"stack-58303788","source":"stackoverflow","questionId":58303788,"title":"Hasura GraphQL Endpoint behind Apollo Federated Gateway","tags":["graphql","hasura","federation","apollo-federation"],"text":"Title: Hasura GraphQL Endpoint behind Apollo Federated Gateway\nTags: graphql, hasura, federation, apollo-federation\nSource: Stack Overflow\n\nQuestion:\nHas anyone successfully placed a Hasura GraphQL endpoint, behind an Apollo Federated Gateway? I know Hasura wants to act as the point of federation but I would rather not do that...current thought is to create an apollo server with a remote schema to connect Hasura, and then but **that** beind the gateway...looking for any thoughts or guidance on whether this is possible? \n\nI'm tempted to say it's not because I can't see anyone who has attempted it. I'm not sure if the Hasura endpoint will allow. \"itself\" to be federated in this way. \n\nI've started the process but intially haven't been able to get an Express Apollo Server with a remote schemea to connect to the Hasura endpoint so a smaller question is whether or not that is even possible.\n\nCheers.\n\n========================================\n\nTop Answer:\nSince v2.10, you can now add Hasura behind an Apollo Federation gateway natively. See the docs here: https://hasura.io/docs/latest/data-federation/apollo-federation/\n\n========================================\n\nCode:\n```text\nconst { ApolloServer } = require('apollo-server');\nconst gql = require('graphql-tag');\nconst hasuraSchema = require('./schema.js');\n\nconst typeDefs = gql`\n\n schema {\n query: query_root\n }\n\n type _Service {\n sdl: String\n }\n\n type query_root {\n _service: _Service!\n }\n\n`;\n\nconst resolvers = {\n query_root: {\n _service: () => { return {sdl: hasuraSchema} },\n },\n};\n\nconst schema = new ApolloServer({ typeDefs, resolvers });\n\nschema.listen({ port: process.env.PORT}).then(({ url }) => {\n console.log(`schema ready at ${url}`);\n});\n```\n\n```text\n// schema.js\n\nconst hasuraSchema = `\n\n# NOTE: does not have subscription field\nschema {\n query: query_root\n mutation: mutation_root\n}\n\ntype articles {\n id: Int!\n title: String!\n}\n\ntype query_root {\n ...\n}\n\ntype mutation_root {\n ...\n}\n`\n\nmodule.exports = hasuraSchema;\n```\n\n```text\n_service\n```\n\n```text\n_service\n```\n\n```text\nSchema Definition Language\n```\n\n```text\nquery\n```\n\n```text\nconst hasuraSchema\n```\n\n```text\nsubscriptions\n```\n\n```text\nsubscription\n```\n\n```text\nschema root\n```\n\n========================================\n\nComments:\n- This is so helpful, thank you so much. I will try this soon. Theorectically, could you use this apollo server to then create a remote schema, that could then be used behind an apollo federated server?\n- `could you use this apollo server to then create a remote schema, that could then be used behind an apollo federated server?` I am not 100% sure what you mean here. In the solution above, you add the apollo-server that is shown as a remote schema in Hasura. And then mount Hasura in apollo-gateway.\n- I understand yep, apologies, maybe I should explain myself better. I want to achieve: Hasura -> Apollo Server -> Apollo Federated Gateway -> Client ...I think that's now possible based on what you shared?","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":121,"estimatedTokens":753}}745{"id":"stack-57720083","source":"stackoverflow","questionId":57720083,"title":"Query DynamoDB with multiple begins_with clause in AppSync","tags":["amazon-dynamodb","graphql","velocity","aws-appsync","apache-velocity"],"text":"Title: Query DynamoDB with multiple begins_with clause in AppSync\nTags: amazon-dynamodb, graphql, velocity, aws-appsync, apache-velocity\nSource: Stack Overflow\n\nQuestion:\nI'm currently trying to create a dynamic query using AppSync and Apache Velocity Template Language (VTL).\n\nI want to evaluate series of begins_with with \"OR\"\n\nSuch as:\n\n```\n{\n \"operation\": \"Query\",\n \"query\": {\n \"expression\": \"pk = :pk and (begins_with(sk,:sk) or begins_with(sk, :sk1)\",\n \"expressionValues\": {\n \":pk\": { \"S\": \"tenant:${context.args.tenantId}\",\n \":sk\": {\"S\": \"my-sort-key-${context.args.evidenceId[0]}\"},\n \":sk1\": {\"S\": \"my-sort-key-${context.args.evidenceId[1]}\"}\n\n }\n\n }\n```\n\nBut that isn't working. I've also tried using `|` instead of `or` but it hasn't worked either. I get:\n\n Invalid KeyConditionExpression: Syntax error; token: \"|\", near: \") | begins_with\" (Service: AmazonDynamoDBv2;\n\nHow can I achieve this using VTL?\n\n========================================\n\nTop Answer:\nReading this answer seems that this isn't possible, as DynamoDB only accepts a single Sort key value and a single operation. \n\nThere's also no \"OR\" condition in the operation: \nhttps://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#DDB-Query-request-KeyConditionExpression\n\n If you also want to provide a condition for the sort key, it must be combined using AND with the condition for the sort key. Following is an example, using the = comparison operator for the sort key:\n\nI am going to be restructuring the access pattern to better match my request.\n\n========================================\n\nCode:\n```text\n{\n \"operation\": \"Query\",\n \"query\": {\n \"expression\": \"pk = :pk and (begins_with(sk,:sk) or begins_with(sk, :sk1)\",\n \"expressionValues\": {\n \":pk\": { \"S\": \"tenant:${context.args.tenantId}\",\n \":sk\": {\"S\": \"my-sort-key-${context.args.evidenceId[0]}\"},\n \":sk1\": {\"S\": \"my-sort-key-${context.args.evidenceId[1]}\"}\n\n }\n\n }\n```\n\n```text\n|\n```\n\n```text\nor\n```\n\n```text\n\"expression\": \"pk = :pk and (begins_with(sk,:sk) or begins_with(sk, :sk1))\"\n```\n\n```text\nbegins_with(sk, :sk1)\n```\n\n```text\nor\n```\n\n```text\na = :v1 and (b = :v2 or b = :v3)\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n```text\na\n```\n\n```text\nb\n```\n\n========================================\n\nComments:\n- Thanks, Itay for the answer π... did you run in using a text context or did you try running it against GraphQL? I have been checking and I think this is indeed not possible.\n- I missed the fact the `pk` and `sk` in your table are the partition and sort key of the table. please see my revised answer.\n- That's exactly what I found! π Thanks for corroborating.","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":108,"estimatedTokens":664}}746{"id":"stack-54251284","source":"stackoverflow","questionId":54251284,"title":"Which graphql-spring-boot-starter should I choose?","tags":["spring-boot","graphql","graphql-java"],"text":"Title: Which graphql-spring-boot-starter should I choose?\nTags: spring-boot, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI'm thinking about adding GraphQL functionalities to my Spring Boot application.\n\nI found there are two artifacts for that.\n\nOne is `com.graphql-java-kickstart:graphql-spring-boot-starter` and the other is `com.graphql-java:graphql-spring-boot-starter`.\n\nWhich one should I choose?\n\n========================================\n\nCode:\n```text\ncom.graphql-java-kickstart:graphql-spring-boot-starter\n```\n\n```text\ncom.graphql-java:graphql-spring-boot-starter\n```\n\n```text\ncom.graphql-java:graphql-spring-boot-starter\n```\n\n```text\norg.springframework.boot:spring-boot-starter-web\n```\n\n```text\norg.springframework.boot:spring-boot-starter-webflux\n```\n\n```text\ncom.netflix.graphql.dgs:graphql-dgs-spring-boot-starter\n```\n\n```text\ngraphql-spqr-spring-boot-starter\n```\n\n```text\ngraphql-java-tools\n```\n\n```text\ncom.graphql-java-kickstart:graphql-spring-boot-starter\n```\n\n========================================\n\nComments:\n- I've used your project before and found it quite easy to use. I wasn't aware of the other projects. I will likely check them out for self-edification. Thanks.\n- Also should mention that Netflix offers the DGS framework, which is an abstraction built on top of graphql-java. It was built specifically to be incorporated into Spring :) netflix.github.io/dgs\n- Great library. Really waiting for Spring Boot 3 support. Also proposing out-of-the-box support for protobuf classes. That will be something\n- @LewisMunene Upgrading to Spring Boot3 is actually trivial, but I'm trying to rebase the starter onto Spring GraphQL, to avoid maintaining the features already implemented there. As for Protobuf, I've never used it... would you be interested in contributing a module?","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":59,"estimatedTokens":453}}747{"id":"stack-60635101","source":"stackoverflow","questionId":60635101,"title":"Using ID in GraphQL parametrized query","tags":["graphql","apollo","grandstack"],"text":"Title: Using ID in GraphQL parametrized query\nTags: graphql, apollo, grandstack\nSource: Stack Overflow\n\nQuestion:\nI have the following schema:\n\n```\ntype Post {\n id: ID!\n text: String\n}\n```\n\nI am using autogenerated mutations from `neo4j-graphql.js`, so I have access to the following mutation:\n\n```\nUpdatePost(\nid: ID!\ntext: String\n): Post\n```\n\n**The issue:**\n\nWhen I'm using the following query:\n\n```\nmutation update($id: String, $text: String) {\n UpdatePost(id: $id, text: $text) {\n id\n text\n }\n}\n```\n\nWith the following parameters:\n\n```\n{\n \"id\": \"a19289b3-a191-46e2-9912-5a3d1b067cb2\",\n \"text\": \"text\"\n}\n```\n\nI get the following error:\n\n```\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Variable \\\"$id\\\" of type \\\"String\\\" used in position expecting type \\\"ID!\\\".\",\n \"locations\": [\n {\n \"line\": 1,\n \"column\": 17\n },\n {\n \"line\": 2,\n \"column\": 18\n }\n ],\n \"extensions\": {\n \"code\": \"GRAPHQL_VALIDATION_FAILED\"\n }\n }\n ]\n }\n}\n```\n\n**Is there a way to convert my string ID to the actual ID type? Or circumvent this error altogether?**\n\n========================================\n\nTop Answer:\nFor anyone else encountering this issue, in the mutation definition you have:\n\n```\nmutation update($id: String, $text: String) {\n UpdatePost(id: $id, text: $text) {\n id\n text\n }\n}\n```\n\nwhere you're explicitly saying the $id is a String, you need to change it to ID like so:\n\n```\nmutation update($id: ID, $text: String) {\n UpdatePost(id: $id, text: $text) {\n id\n text\n }\n}\n```\n\nThis is why you're seeing the error, because your query to update it's saying explicitly that ID is a type String hence the error.\n\n========================================\n\nCode:\n```text\ntype Post {\n id: ID!\n text: String\n}\n```\n\n```text\nUpdatePost(\nid: ID!\ntext: String\n): Post\n```\n\n```text\nmutation update($id: String, $text: String) {\n UpdatePost(id: $id, text: $text) {\n id\n text\n }\n}\n```\n\n```text\n{\n \"id\": \"a19289b3-a191-46e2-9912-5a3d1b067cb2\",\n \"text\": \"text\"\n}\n```\n\n```text\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Variable \\\"$id\\\" of type \\\"String\\\" used in position expecting type \\\"ID!\\\".\",\n \"locations\": [\n {\n \"line\": 1,\n \"column\": 17\n },\n {\n \"line\": 2,\n \"column\": 18\n }\n ],\n \"extensions\": {\n \"code\": \"GRAPHQL_VALIDATION_FAILED\"\n }\n }\n ]\n }\n}\n```\n\n```text\nneo4j-graphql.js\n```\n\n```text\n$id\n```\n\n```text\nString\n```\n\n```text\nID\n```\n\n```text\nid\n```\n\n```text\n$id\n```\n\n```text\nID!\n```\n\n```text\nID\n```\n\n```text\nID!\n```\n\n```text\n!\n```\n\n```text\nid\n```\n\n```text\nnull\n```\n\n```text\nID\n```\n\n```text\nID!\n```\n\n```text\nnull\n```\n\n```text\nID\n```\n\n```text\nID\n```\n\n```text\nID!\n```\n\n```csharp\nvar request = new GraphQLRequest\n {\n Query = @\"\n query getToken($tokenId: ID!){{\n tokens(where: {{ id: $tokenId}} orderBy: decimals, orderDirection: desc) {{\n id\n symbol\n name\n }}\n }}\", Variables = new\n {\n tokenId = \"<stringValue>\"\n }\n };\n```\n\n```csharp\nquery getToken($tokenIds: [ID!]){{\n tokens(where: {{ id_in: $tokenIds}} orderBy: decimals, orderDirection: desc) {{\n id\n symbol\n name\n }}\n }}\", Variables = new \n {\n tokenIds = new ArrayList(<yourStringArrayListValue>)\n }\n```\n\n```text\nmutation update($id: String, $text: String) {\n UpdatePost(id: $id, text: $text) {\n id\n text\n }\n}\n```\n\n```text\nmutation update($id: ID, $text: String) {\n UpdatePost(id: $id, text: $text) {\n id\n text\n }\n}\n```\n\n========================================\n\nComments:\n- adjust mutation definition to `mutation update($id: ID!` <<<\n- I understand that, but how do you make such string an ID then? I use the exact value returned when querying for the field.\n- You don't \"convert\" a string to an ID. An ID scalar simply accepts strings (and integers) as valid values as outlined in the spec.\n- If you are still seeing an error after fixing your variable definitions, recheck that it is in fact the same error. The error you pasted doesn't match up to the query you pasted.\n- The error message does. I've purged irrelevant fields from my schema. > If you are still seeing an error after fixing your variable definitions That is exactly the point of my question... How do I fix my variable definition? The value in my question is exactly what is returned when querying for object I want to modify.\n- And when I'm not using a parametrized query, this works without issue\n- Like I said, it needs to be `$id: ID!` instead of `$id: ID`. But that's not relevant to the error you're seeing. The error implies that whatever query is actually hitting your server has this as a definition: `$id: String`.\n- Let us continue this discussion in chat.\n- yup just convert String -> ID!","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":27,"totalLines":291,"estimatedTokens":1265}}748{"id":"stack-41051523","source":"stackoverflow","questionId":41051523,"title":"How to mutate a list of custom objects in GraphQL for .NET","tags":["c#",".net","graphql","mutation"],"text":"Title: How to mutate a list of custom objects in GraphQL for .NET\nTags: c#, .net, graphql, mutation\nSource: Stack Overflow\n\nQuestion:\nUsing GraphQL for .NET, I would like to replace the collection of Foo with a new collection.\n\nGiven this server-side code:\n\n```\npublic class Foo\n{\n public Foo(string name)\n {\n Name = name;\n }\n\n public string Name { get; set; }\n}\n\npublic class Root\n{\n public Foo[] Foos { get; private set; }\n\n public Foo[] UpdateFoos(Foo[] foos)\n {\n Foos = foos;\n return Foos;\n }\n}\n\npublic class MutationSchema : Schema\n{\n public MutationSchema()\n {\n Query = new MutationQuery();\n Mutation = new MutationChange();\n }\n}\n\npublic class FooType : ObjectGraphType\n{\n public FooType()\n {\n Name = \"IndividualFoo\";\n Field(\"name\");\n }\n}\n\npublic class FoosType : ObjectGraphType>\n{\n public FoosType()\n {\n Name = \"ListOfFoo\";\n Field>(\"foos\");\n }\n}\n\npublic class FoosInput : InputObjectGraphType\n{\n public FoosInput()\n {\n Name = \"InputForManyFoo\";\n Field>(\"foos\");\n Field>(\"foosResult\");\n }\n}\n\npublic class FooInput : InputObjectGraphType\n{\n public FooInput()\n {\n Name = \"InputForSingleFoo\";\n Field(\"name\");\n }\n}\n\npublic class MutationQuery : ObjectGraphType\n{\n public MutationQuery()\n {\n Name = \"Query\";\n Field(\"queryAllFoos\");\n }\n}\n\npublic class MutationChange : ObjectGraphType\n{\n public MutationChange()\n {\n Name = \"Mutation\";\n\n Field(\n \"updateAllFoos\",\n arguments: new QueryArguments(\n new QueryArgument\n {\n Name = \"updateFoosQueryArgument\"\n }\n ),\n resolve: context =>\n {\n var root = context.Source as Root;\n var change = context.GetArgument(\"updateFoosQueryArgument\");\n // TODO: update collection e.g. return root.UpdateFoos(change);\n return change;\n }\n );\n }\n}\n```\n\nWhen I run the mutation query:\n\n```\nmutation M {\n fooCollection: updateAllFoos(updateFoosQueryArgument: {\n foos: [\n {name: \"First Foo\"},\n {name: \"Second Foo\"}\n ]}) {\n foosResult\n }\n}\n```\n\nThen I get the following error:\n\n```\n{GraphQL.Validation.ValidationError: Cannot query field \"foosResult\" on type \"InputForManyFoo\". Did you mean \"foosResult\"?}\n```\n\nI'm using the latest version of GraphQL for .NET at the time of writing.\n\nWhat am I missing?\n\n**Working Example:** How to mutate a list of custom objects in GraphQL for .NET\n\n========================================\n\nCode:\n```text\npublic class Foo\n{\n public Foo(string name)\n {\n Name = name;\n }\n\n public string Name { get; set; }\n}\n\npublic class Root\n{\n public Foo[] Foos { get; private set; }\n\n public Foo[] UpdateFoos(Foo[] foos)\n {\n Foos = foos;\n return Foos;\n }\n}\n\npublic class MutationSchema : Schema\n{\n public MutationSchema()\n {\n Query = new MutationQuery();\n Mutation = new MutationChange();\n }\n}\n\npublic class FooType : ObjectGraphType\n{\n public FooType()\n {\n Name = \"IndividualFoo\";\n Field<StringGraphType>(\"name\");\n }\n}\n\npublic class FoosType : ObjectGraphType<ListGraphType<FooType>>\n{\n public FoosType()\n {\n Name = \"ListOfFoo\";\n Field<ListGraphType<FooType>>(\"foos\");\n }\n}\n\npublic class FoosInput : InputObjectGraphType\n{\n public FoosInput()\n {\n Name = \"InputForManyFoo\";\n Field<ListGraphType<FooInput>>(\"foos\");\n Field<ListGraphType<FooType>>(\"foosResult\");\n }\n}\n\npublic class FooInput : InputObjectGraphType\n{\n public FooInput()\n {\n Name = \"InputForSingleFoo\";\n Field<StringGraphType>(\"name\");\n }\n}\n\npublic class MutationQuery : ObjectGraphType\n{\n public MutationQuery()\n {\n Name = \"Query\";\n Field<FoosType>(\"queryAllFoos\");\n }\n}\n\npublic class MutationChange : ObjectGraphType\n{\n public MutationChange()\n {\n Name = \"Mutation\";\n\n Field<FoosInput>(\n \"updateAllFoos\",\n arguments: new QueryArguments(\n new QueryArgument<FoosInput>\n {\n Name = \"updateFoosQueryArgument\"\n }\n ),\n resolve: context =>\n {\n var root = context.Source as Root;\n var change = context.GetArgument<Foo[]>(\"updateFoosQueryArgument\");\n // TODO: update collection e.g. return root.UpdateFoos(change);\n return change;\n }\n );\n }\n}\n```\n\n```text\nmutation M {\n fooCollection: updateAllFoos(updateFoosQueryArgument: {\n foos: [\n {name: \"First Foo\"},\n {name: \"Second Foo\"}\n ]}) {\n foosResult\n }\n}\n```\n\n```text\n{GraphQL.Validation.ValidationError: Cannot query field \"foosResult\" on type \"InputForManyFoo\". Did you mean \"foosResult\"?}\n```\n\n```text\npublic class FoosResultType : ObjectGraphType\n{\n public FoosResultType()\n {\n Field<ListGraphType<FooType>>(\"foosResult\");\n }\n}\n\npublic class FoosResult\n{\n public IEnumerable<Foo> FoosResult { get;set; }\n}\n\npublic class MutationChange : ObjectGraphType\n{\n public MutationChange()\n {\n Name = \"Mutation\";\n\n Field<FoosResultType>(\n \"updateAllFoos\",\n arguments: new QueryArguments(\n new QueryArgument<ListGraphType<FooInput>>\n {\n Name = \"updateFoosQueryArgument\"\n }\n ),\n resolve: context =>\n {\n var root = context.Source as Root;\n var change = context.GetArgument<List<Foo>>(\"updateFoosQueryArgument\");\n // TODO: update collection e.g. return root.UpdateFoos(change);\n return new FoosResult { FoosResult = change };\n }\n );\n }\n}\n```\n\n```text\nmutation M {\n fooCollection: updateAllFoos(updateFoosQueryArgument: [\n {name: \"First Foo\"},\n {name: \"Second Foo\"}\n ]) {\n foosResult {\n name\n }\n }\n}\n```\n\n```text\nObjectGraphType\n```\n\n========================================\n\nComments:\n- Thanks very much for all your help Joe! I will revisit on Monday morning and make sure it works. It's past validation now but it falls over during execution on the GetArgument line. {GraphQL.Validation.ValidationError: Argument \"updateFoosQueryArgument\" has invalid value {foos: [{name: \"First Foo\"}, {name: \"Second Foo\"}]}. In field \"foos\": Unknown field.}\n- I'll try alternatives to Foo[] (IEnumerable etc)\n- I updated the mutation - I had forgotten to change `updateFoosQueryArgument` in the mutation to just be a list.\n- An array doesn't work - changed context.GetArgument(\"updateFoosQueryArgument\"); to context.GetArgument>(\"updateFoosQueryArgument\");","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":324,"estimatedTokens":1633}}749{"id":"stack-35067685","source":"stackoverflow","questionId":35067685,"title":"getFragment from a dynamic component in Relay","tags":["reactjs","relayjs","graphql"],"text":"Title: getFragment from a dynamic component in Relay\nTags: reactjs, relayjs, graphql\nSource: Stack Overflow\n\nQuestion:\nMy use case is that I have a Node application that consumes data from a CMS, and in that CMS I give the users the ability to select a React Component as a \"Layout\". I'd like for Relay to be able to get a GraphQL Fragment from that dynamically select component. When the Layout's parent component mounts, it goes through its query and gets the layout component it needs and sets a Relay variable - it then needs to get a fragment from that component. Is there a way to do that? \n\nHere is the parent level query:\n\n```\nexport default Relay.createContainer(WordpressPage, {\n\ninitialVariables:{\n Component: null,\n page: null,\n showPosts: false,\n limit: 5\n},\n\nprepareVariables(prevVars){\n return{\n ...prevVars,\n showPosts: true\n }\n},\n\nfragments: {\n viewer: ({Component, showPosts, limit}) => Relay.QL`\n fragment on User {\n ${PostList.getFragment(\"viewer\", {limit:limit}).if(showPosts)},\n page(post_name:$page){\n id,\n post_title,\n post_type,\n post_content,\n thumbnail,\n layout{\n meta_value\n }\n }\n }\n `,\n },\n});\n```\n\nAs you can see, it queries and gets a layout field. When it mounts, it sets the Relay Component variable to be a React Component. Instead of \"PostList.getFragment\", I'd really like to be able to do a Component.getFragment.\n\n========================================\n\nCode:\n```js\nexport default Relay.createContainer(WordpressPage, {\n\ninitialVariables:{\n Component: null,\n page: null,\n showPosts: false,\n limit: 5\n},\n\nprepareVariables(prevVars){\n return{\n ...prevVars,\n showPosts: true\n }\n},\n\nfragments: {\n viewer: ({Component, showPosts, limit}) => Relay.QL`\n fragment on User {\n ${PostList.getFragment(\"viewer\", {limit:limit}).if(showPosts)},\n page(post_name:$page){\n id,\n post_title,\n post_type,\n post_content,\n thumbnail,\n layout{\n meta_value\n }\n }\n }\n `,\n },\n});\n```\n\n```js\nconst COMPONENTS = [\n [PostList, 'showPosts'],\n [OtherKindOfList, 'showOthers'],\n /* ... */\n];\n\nstatic initialVariables = {\n showPosts: false,\n showOthers: false,\n /* ... */\n};\n\nfragments: {\n viewer: variables => Relay.QL`\n fragment on User {\n ${COMPONENTS.map(([Component, variableName]) => {\n const condition = variables[variableName];\n return Component\n .getFragment('viewer', {limit: variables.limit})\n .if(condition);\n })},\n # ...\n `,\n },\n});\n```\n\n```text\n${Foo.getFragment('viewer')}\n```\n\n```text\n${COMPONENTS.map(c => c.getFragment('viewer'))}\n```\n\n```text\n${(route) => COMPONENTS[route].getFragment('viewer')}\n```\n\n========================================\n\nComments:\n- Thanks! Any idea when 0.7.1 will be released?\n- I released v0.7.1 a moment ago, just for you. :)\n- Will the condition only work for boolean variables? I couldn't set a 'Layout' variable and check that it equals a string?\n- I don't think so, because `condition` here represents a βvariableβ data type, and not actually a raw boolean. This lets Relay evaluate the variable over time to see if the `if()` condition passes or fails.\n- I'm still getting a \"Expected prop `viewer` supplied to `PostList` to be data fetched by Relay.\" The query runs, gets the layout, then reruns, but before it reruns I think PostList gets rendered. I need to only render PostList after it's gotten the fragment from PostList. Thoughts?\n- What happens if you check to see if `viewer` is null before rendering `PostList`? `render() { return this.props.viewer == null ? null : ; }`\n- No dice - it just doesn't render anything and I still get the \"expected prop viewer\" error\n- Strange. Are you able to more of the code, particularly the implementations of `PostList` and `WordpressPage`?\n- Here is page Here is PostList\n- Thank you for doing that. I was able to spot the problem right away. I'll update the answer in a bit, but in the meantime take a look at this fix. Basically you have to move all of your variable wrangling into `prepareVariables()`; a Relay variable is not a boolean, so you can't do things like `if(variables.foo) { β¦ }` in your interpolation. gist.github.com/steveluscher/3681d7795fbd2f13141b\n- Still nope. The mapping only runs before the component mounts. When the variables update the map doesnt rerun. Verrified that the variables are getting update properly though - I feel like this is sooooo close.\n- The mapping shouldn't need to re-run, since now you've primed the `if(β¦)` calls with the right variable for each fragment. When the variables change, the `if(β¦)` should be reevaluated with the new variable value. Despite the `map(β¦)` not re-running, what behavior are you seeing or not seeing now?\n- I'm still getting the same error that PostList is expecting viewer to be Relay data. Same error as before.\n- Also, if I console.log(this.props.viewer) from Page render, I don't even see a RelayFragmentPointer. If, for example, I set showPosts to true in initial variables, everything runs fine and I see the RelayFragmentPointer.\n- Sorry, one last thing - if I remove the map and try to us PostList by itself with the condition - it still doesn't work unless I initially set showPosts to true.\n- I'm stumped! I drummed up a Relay Playground that tries to get as close to your implementation as possible. Can you take a look at this, and see if you can get it into a state where it repros the problem? tinyurl.com/zvq3a3z\n- Will do. In the meantime my solution has to remove the condition from the map function and pass a boolean to the child component, then adding a condition to each child component query. It works but I end up with empty fragments.","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":148,"estimatedTokens":1435}}750{"id":"stack-49384737","source":"stackoverflow","questionId":49384737,"title":"GraphQL Spring-boot Query filtering","tags":["java","spring-boot","graphql"],"text":"Title: GraphQL Spring-boot Query filtering\nTags: java, spring-boot, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm using the GraphQL Spring-boot library to build a GraphQL API\nhttps://github.com/graphql-java/graphql-spring-boot\n\nI have a schema\n\n```\ntype Car {\n id: ID!\n model: String\n brand: String\n}\n\ntype Query {\n allCars: [Car]!\n}\n```\n\nAnd my query is implemented in a Query class in my Spring Boot project\n\n```\n@Component\npublic class Query implements GraphQLQueryResolver {\n\npublic List allCars() {}\n\n}\n```\n\nMy question is:\n\nHow do I use filters and sorting when returning lists:\n\n```\nallCars(first:3){id model}\n\nallCars(filter: {....}){}\n```\n\nI guess this is something that has to be implemented in the Java method, but i'm unsure how to inject the filters etc. in the method.\n\n========================================\n\nTop Answer:\nGraphQL allows for the client to specify exactly what data is desired but it doesn't has any inbuilt way of filtering and sorting the data. You will have write code for that yourself. Regarding injecting the filters, one possible way of doing it can be following:\n\n```\ntype Query {\n allCars(filter: String, range: String, sort: String): [Car]!\n}\n```\n\nFor above Query, sample request would be like:\n\n```\n{\n allCars(filter: \"{brand: 'Abc'}\", range: \"[0, 100]\", sort: \"[id, ASC]\") { # Fetch first 100 cars of brand 'Abc' sorted by id\n id\n model\n brand\n }\n}\n```\n\nThen your getAllCars method would be like following:\n\n```\npublic List getAllCars(String filter, String range, String sort) {\n // Implement parser and filter by using JPA specifications\n}\n```\n\nTo see a sample implementation of parser and its conversion it to JPA specifications, please refer to following project: https://github.com/jaskaransingh156/spring-boot-graphql-with-custom-rql\n\n========================================\n\nCode:\n```text\ntype Car {\n id: ID!\n model: String\n brand: String\n}\n\ntype Query {\n allCars: [Car]!\n}\n```\n\n```text\n@Component\npublic class Query implements GraphQLQueryResolver {\n\npublic List<Machine> allCars() {}\n\n}\n```\n\n```text\nallCars(first:3){id model}\n\nallCars(filter: {....}){}\n```\n\n```graphql\ntype Query {\n allCars(filter: CarsFilter!): [Car]\n}\n\n\ninput CarsFilter {\n color: String!\n brand: String!\n}\n```\n\n```java\npublic class CarsFilter {\n private String color;\n private String brand;\n\n // Getters + Setters\n}\n```\n\n```text\npublic List<Car> allCars(CarsFilter filter) {\n // Filter by using JPA specifications, custom queries, ...\n}\n```\n\n```text\nCarsFilter\n```\n\n```text\nCarsFilter\n```\n\n```text\ntype Query {\n allCars(filter: String, range: String, sort: String): [Car]!\n}\n```\n\n```text\n{\n allCars(filter: \"{brand: 'Abc'}\", range: \"[0, 100]\", sort: \"[id, ASC]\") { # Fetch first 100 cars of brand 'Abc' sorted by id\n id\n model\n brand\n }\n}\n```\n\n```text\npublic List<Car> getAllCars(String filter, String range, String sort) {\n // Implement parser and filter by using JPA specifications\n}\n```\n\n========================================\n\nComments:\n- Have you been able to find something that auto-generates the filters for every model?\n- Ok - that would make sense. I was wondering if there were some filtering and sorting available as part of the GraphQL Java library. Since we can restrict return parameters from our \"types/models\"\n- Hi Jaskaran, I was looking at your blog and tried to implement with Spring boot 3.1.x and Spring boot data jpa 3.1.x. But I was getting an error for FilterService required a single bean, but 2(my no. of repos extending base repo) were found so do you have any workaround for this for newer version of Spring boot.","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":171,"estimatedTokens":909}}751{"id":"stack-64675181","source":"stackoverflow","questionId":64675181,"title":"JavaScript/GraphQL add fragments conditionally","tags":["javascript","graphql"],"text":"Title: JavaScript/GraphQL add fragments conditionally\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a JavaScript function that sends a fetch request to a graphQL endpoint. My goal is to add a fragment to my graphQL query based a parameter passed into the JavaScript function, for example, my function looks like this:\n\n```\nconst getEvent = async (id, lang) => {\n const data = await fetchAPI(`\n fragment EventFields on Event {\n title\n slug\n date\n }\n fragment BnFields on Event {\n bn {\n content\n subtitle\n }\n }\n query fetchEvent($id: ID!, $idType: EventIdType!) {\n event(id: $id, idType: $idType) {\n ...EventFields\n content\n }\n }\n }\n}\n```\n\nI would like to add the `BnFields` fragment if the lang parameter to the `getEvent` function equals `bn`. I know I can achieve this by declaring two separate queries depending on the `lang` parameter, but I was wondering if there's a more optimum way inside the graphQL itself to add a fragment based on a variable. Any help would be really appreciated.\n\n========================================\n\nCode:\n```text\nconst getEvent = async (id, lang) => {\n const data = await fetchAPI(`\n fragment EventFields on Event {\n title\n slug\n date\n }\n fragment BnFields on Event {\n bn {\n content\n subtitle\n }\n }\n query fetchEvent($id: ID!, $idType: EventIdType!) {\n event(id: $id, idType: $idType) {\n ...EventFields\n content\n }\n }\n }\n}\n```\n\n```text\nBnFields\n```\n\n```text\ngetEvent\n```\n\n```text\nbn\n```\n\n```text\nlang\n```\n\n```text\nquery fetchEvent($id: ID!, $idType: EventIdType!, $isBn: Boolean!) {\n event(id: $id, idType: $idType) {\n ...EventFields\n ...BnFields @include(if: $isBn)\n content\n }\n}\n```\n\n```text\n@include\n```\n\n```text\nisBn: lang === 'bn'\n```\n\n========================================\n\nComments:\n- The `getEvent` function you posted appears incomplete. Can you please edit it to include the actual code?\n- @xadm please do not make unnecessary edits.\n- meta.stackexchange.com/questions/2950/…","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":100,"estimatedTokens":541}}752{"id":"stack-62432519","source":"stackoverflow","questionId":62432519,"title":"GraphQL order of mutation operations","tags":["graphql","graphql-mutation"],"text":"Title: GraphQL order of mutation operations\nTags: graphql, graphql-mutation\nSource: Stack Overflow\n\nQuestion:\nI am creating a mutation which works but I am not sure if it is working the way that I think it is. However, I would like to know what is the order of execution?\n\n- Async\n\n- Sync Top to Bottom\n\n- Sync random order\n\n- Something else\n\nI want to make sure that certain items are deleted from a table before the insert/upsert is executed. Using the following mutation query string, will this always do what I want or will it not work from time-to-time because I assume it is Synchronous but in reality it is Asynchronous?\n\n```\nmutation MyMutation(...) {\n update_my_table_1(...) { }\n\n delete_my_table_2(...) { }\n\n insert_my_table_2(...) { }\n}\n```\n\n========================================\n\nCode:\n```text\nmutation MyMutation(...) {\n update_my_table_1(...) { }\n\n delete_my_table_2(...) { }\n\n insert_my_table_2(...) { }\n}\n```\n\n```text\ninsert_my_table_2\n```\n\n```text\ndelete_my_table_2\n```\n\n```text\ndelete_my_table_2\n```\n\n```text\nupdate_my_table_1\n```\n\n========================================\n\nComments:\n- Perfect! That is what I was thinking but had no idea where to find the information on that.","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":60,"estimatedTokens":301}}753{"id":"stack-50300936","source":"stackoverflow","questionId":50300936,"title":"How to declare strings in enum","tags":["graphql","graphql-js"],"text":"Title: How to declare strings in enum\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nWith graphql, `enum` can make a predefined list of elements but strings don't work.\n\nFor example:\n\n```\nenum Dias {\n lunes\n martes\n miΓ©rcoles\n jueves\n viernes\n sΓ‘bado\n domingo\n}\n```\n\nThis returns an error `GraphQLError: Syntax Error: Cannot parse the unexpected character \"\\u00E9\".`\n\n**how is it possible to make a predefined list of strings?**\n\n**Edit**: to give more context, I want to reflect the database schema, which is like this (with mongoose):\n\n```\ndias: {\n type: String,\n enum: ['lunes', 'martes', 'miΓ©rcoles', 'jueves', 'viernes', 'sΓ‘bado', 'domingo'],\n lowercase: true,\n required: true\n}\n```\n\n========================================\n\nTop Answer:\nJust extending @Daniel-Rearden's answer :\n\nAll works like a charm (thank you!), just would like to note, that for me makeCustomEnumScalar required some different small tweaks (maybe lib version affects) :\n\n1)The name \"Day Of Week\" should correspond to regex /^[_a-zA-Z][_a-zA-Z0-9]*$/\n\n```\nconst DayOfWeek = makeCustomEnumScalar('Day of Week', 'day of week enum', [\n```\n\nso should be for example :\n\n```\nconst DayOfWeek = makeCustomEnumScalar('DayofWeek', 'day of week enum', [\n```\n\n2)Just had a minimal changes relating types, so my variant is :\n\n```\nconst makeCustomEnumScalar = (name:string, description:string, validValues:string[]) => {\n const checkValue = (value:ValueNode) => {\n const coerced = String(value)\n if (!validValues.includes(coerced)) {\n throw new TypeError(`${coerced} is not a valid value for scalar ${name}`)\n }\n return coerced \n }\n return new GraphQLScalarType({\n name,\n description,\n serialize: checkValue,\n parseValue: checkValue,\n parseLiteral: (ast) => checkValue(ast),\n })\n}\n```\n\nSo providing full code listing :\n\n```\nimport { GraphQLScalarType, ValueNode } from 'graphql';\n\nconst makeCustomEnumScalar = (name:string, description:string, validValues:string[]) => {\n const checkValue = (value:ValueNode) => {\n const coerced = String(value)\n if (!validValues.includes(coerced)) {\n throw new TypeError(`${coerced} is not a valid value for scalar ${name}`)\n }\n return coerced \n }\n return new GraphQLScalarType({\n name,\n description,\n serialize: checkValue,\n parseValue: checkValue,\n parseLiteral: (ast) => checkValue(ast),\n })\n}\n\nexport const DayOfWeek = makeCustomEnumScalar('DayOfWeek', 'day of week enum', [\n \"My enum value 1\",\n \"My enum value 2\"\n ])\n\nexport const typeDefs = gql`\n scalar DayOfWeek\n\n type StrEntity {\n id: ID!\n dayOfWeek: DayOfWeek!\n }\n \n extend type Mutation {\n getStrById(id: String!): StrEntity\n }\n`;\n```\n\n========================================\n\nCode:\n```text\nenum Dias {\n lunes\n martes\n miΓ©rcoles\n jueves\n viernes\n sΓ‘bado\n domingo\n}\n```\n\n```text\ndias: {\n type: String,\n enum: ['lunes', 'martes', 'miΓ©rcoles', 'jueves', 'viernes', 'sΓ‘bado', 'domingo'],\n lowercase: true,\n required: true\n}\n```\n\n```text\nenum\n```\n\n```text\nGraphQLError: Syntax Error: Cannot parse the unexpected character \"\\u00E9\".\n```\n\n```text\n/[_A-Za-z][_0-9A-Za-z]*/\n```\n\n```text\nconst makeCustomEnumScalar = (name, description, validValues) => {\n const checkValue = (value) => {\n const coerced = String(value)\n if (!validValues.includes(coerced)) {\n throw new TypeError(`${coerced} is not a valid value for scalar ${name}`)\n }\n return coerced \n }\n return new GraphQLScalarType({\n name,\n description,\n serialize: checkValue,\n parseValue: checkValue,\n parseLiteral: (ast) => checkValue(ast.value),\n })\n}\n```\n\n```text\nconst DayOfWeek = makeCustomEnumScalar('Day of Week', 'day of week enum', [\n 'lunes',\n 'martes',\n 'miΓ©rcoles',\n 'jueves',\n 'viernes',\n 'sΓ‘bado',\n 'domingo'\n])\n```\n\n```text\nconst resolvers = {\n DayOfWeek,\n // Query, Mutation, etc.\n}\n```\n\n```text\nscalar DayOfWeek\n```\n\n```text\nconst DayOfWeek = makeCustomEnumScalar('Day of Week', 'day of week enum', [\n```\n\n```text\nconst DayOfWeek = makeCustomEnumScalar('DayofWeek', 'day of week enum', [\n```\n\n```text\nconst makeCustomEnumScalar = (name:string, description:string, validValues:string[]) => {\n const checkValue = (value:ValueNode) => {\n const coerced = String(value)\n if (!validValues.includes(coerced)) {\n throw new TypeError(`${coerced} is not a valid value for scalar ${name}`)\n }\n return coerced \n }\n return new GraphQLScalarType({\n name,\n description,\n serialize: checkValue,\n parseValue: checkValue,\n parseLiteral: (ast) => checkValue(ast),\n })\n}\n```\n\n```text\nimport { GraphQLScalarType, ValueNode } from 'graphql';\n\n\nconst makeCustomEnumScalar = (name:string, description:string, validValues:string[]) => {\n const checkValue = (value:ValueNode) => {\n const coerced = String(value)\n if (!validValues.includes(coerced)) {\n throw new TypeError(`${coerced} is not a valid value for scalar ${name}`)\n }\n return coerced \n }\n return new GraphQLScalarType({\n name,\n description,\n serialize: checkValue,\n parseValue: checkValue,\n parseLiteral: (ast) => checkValue(ast),\n })\n}\n\nexport const DayOfWeek = makeCustomEnumScalar('DayOfWeek', 'day of week enum', [\n \"My enum value 1\",\n \"My enum value 2\"\n ])\n\nexport const typeDefs = gql`\n scalar DayOfWeek\n\n type StrEntity {\n id: ID!\n dayOfWeek: DayOfWeek!\n }\n \n extend type Mutation {\n getStrById(id: String!): StrEntity\n }\n`;\n```\n\n========================================\n\nComments:\n- thank you for your answer. Like I explained in the question I already noted it is not working out-of-the box with `enum`. Your explanation is interesting, but this does not answer the question. I edited the question to add a bit more context\n- @FrançoisRomain please see my edited answer for an alternative approach\n- thank you very much, this works! One last thing: in graphiql, is it possible to have auto-complete on those value like a standard `enum`?\n- No, as far as I'm aware there's no way to do that since the valid values themselves will not be available via introspection. If you adopt this approach, it may be helpful to include the values in the description to at least document them that way","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":269,"estimatedTokens":1532}}754{"id":"stack-38688907","source":"stackoverflow","questionId":38688907,"title":"GraphQL/Relay Schema Cannot query field \"store\" on type \"CreateLinkPayload\"","tags":["javascript","reactjs","graphql","relayjs"],"text":"Title: GraphQL/Relay Schema Cannot query field \"store\" on type \"CreateLinkPayload\"\nTags: javascript, reactjs, graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nI can successfully do graphql/relay queries and mutations with CURL and GraphiQL tool:\n\nhttps://i.sstatic.net/gY8a2.png\n\nHowever, in my react/relay app I can query and get the data into the app, but \nevery time I try to mutate something in my app, I get this error in the console:\n\n```\nbundle.js:51511 Uncaught Error: GraphQL validation error ``Cannot query field \"store\" on type \"CreateLinkPayload\".`` in file \n`/Users/johndoe/react-relay-project/src/mutations/CreateLinkMutation.js`. Try updating your GraphQL schema if an argument/field/type was recently added.\n(anonymous function) @ bundle.js:51511\ngetFatQuery @ bundle.js:51512\ngetFatQuery @ bundle.js:35664\ngetQuery @ bundle.js:35791\n_handleCommit @ bundle.js:35539\ncommit @ bundle.js:35453\ncommit @ bundle.js:35894\n(anonymous function) @ bundle.js:28526\n```\n\nand every time I do `npm start` I get this error:\n\n```\n-- GraphQL Validation Error -- CreateLinkMutation --\n\nFile: /Users/johndoe/react-relay-project/src/mutations/CreateLinkMutation.js\nError: Cannot query field \"store\" on type \"CreateLinkPayload\".\nSource:\n> \n> store { linkConnection }\n> ^^^\n```\n\n`CreateLinkMutation.js`\n\n```\nimport Relay from 'react-relay'\n\nclass CreateLinkMutation extends Relay.Mutation {\n getMutation() {\n return Relay.QL`\n mutation { createLink }\n `\n }\n\n getVariables() {\n return {\n title: this.props.title,\n url: this.props.url\n }\n }\n\n getFatQuery() {\n return Relay.QL`\n fragment on CreateLinkPayload {\n linkEdge,\n store { linkConnection }\n }\n `\n }\n\n getConfigs() {\n return [{\n type: 'RANGE_ADD',\n parentName: 'store',\n parentID: this.props.store.id,\n connectionName: 'linkConnection',\n edgeName: 'linkEdge',\n rangeBehaviors: {\n '': 'append'\n }\n }]\n\n }\n}\n\nexport default CreateLinkMutation\n```\n\nparts of `Link.js`\n\n```\nLink = Relay.createContainer(Link, {\n fragments: {\n link: () => Relay.QL`\n fragment on Link {\n url,\n title\n }\n `\n }\n})\n```\n\nparts of `App.js`\n\n```\nhandleSubmit(e) {\n e.preventDefault()\n Relay.Store.update(\n new CreateLinkMutation({\n title: this.refs.newTitle.value,\n url: this.refs.newUrl.value,\n store: this.props.store\n })\n )\n this.refs.newTitle.value = ''\n this.refs.newUrl.value = ''\n }\n\nApp = Relay.createContainer(App, {\n initialVariables: {\n limit: 10\n },\n fragments: {\n store: () => Relay.QL`\n fragment on Store {\n id,\n linkConnection(first: $limit) {\n edges {\n node {\n id,\n ${Link.getFragment('link')}\n }\n }\n }\n }\n `\n\n }\n})\n```\n\nparts of `main.js`\n\n```\nclass LinkStoreRoute extends Relay.Route {\n static routeName = 'LinkStoreRoute'\n static queries = {\n store: () => Relay.QL`query { store }`\n }\n}\n```\n\nMy `schema.js`:\n\n```\nconst store = {}\n\nconst Store = new GraphQLObjectType({\n name: 'Store',\n fields: () => ({\n id: globalIdField('Store'),\n linkConnection: {\n type: linkConnection.connectionType,\n args: connectionArgs,\n resolve: (_, args) => {\n return docClient.scan(\n Object.assign(\n {},\n {TableName: linksTable},\n paginationToParams(args)\n )\n ).promise().then(dataToConnection)\n }\n }\n })\n})\n\nconst Link = new GraphQLObjectType({\n name: 'Link',\n fields: () => ({\n id: {\n type: new GraphQLNonNull(GraphQLID),\n resolve: (obj) => obj.id\n },\n title: { type: GraphQLString },\n url: { type: GraphQLString }\n })\n})\n\nconst linkConnection = connectionDefinitions({\n name: 'Link',\n nodeType: Link\n})\n\nlet createLinkMutation = mutationWithClientMutationId({\n\n name: 'CreateLink',\n\n inputFields: {\n title: { type: new GraphQLNonNull(GraphQLString) },\n url: { type: new GraphQLNonNull(GraphQLString) }\n },\n\n outputFields: {\n linkEdge: {\n type: linkConnection.edgeType,\n resolve: (obj) => ({node: obj, cursor: obj.id})\n }\n },\n\n store: {\n type: Store,\n resolve: () => store\n },\n\n mutateAndGetPayload: (inputFields) => {\n\n let link = {\n id: uuid.v4(),\n title: inputFields.title,\n url: inputFields.url\n }\n\n return new Promise((resolve, reject) => {\n docClient.put(\n Object.assign(\n {},\n {TableName: linksTable},\n {Item: link}\n ),\n (err, data) => {\n if (err) return reject(err)\n return resolve(link)\n }\n )\n })\n }\n})\n\nconst schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n store: {\n type: Store,\n resolve: () => store\n }\n })\n }),\n\n mutation: new GraphQLObjectType({\n name: 'Mutation',\n fields: () => ({\n createLink: createLinkMutation\n })\n })\n})\n\nmodule.exports = schema\n```\n\nNote that I excluded 40 lines of `require` statements at the top.\n\nHow is this even possible? And how can I fix it?\nCould it be a bug of relay/react?\n\n========================================\n\nTop Answer:\nTurns out store\n\n```\nstore: {\n type: Store,\n resolve: () => store\n }\n```\n\nhas to go inside outputFields like so:\n\n```\noutputFields: {\n linkEdge: {\n type: linkConnection.edgeType,\n resolve: (obj) => ({node: obj, cursor: obj.id})\n }\n store: {\n type: Store,\n resolve: () => store\n }\n }\n```\n\n========================================\n\nCode:\n```text\nbundle.js:51511 Uncaught Error: GraphQL validation error ``Cannot query field \"store\" on type \"CreateLinkPayload\".`` in file \n`/Users/johndoe/react-relay-project/src/mutations/CreateLinkMutation.js`. Try updating your GraphQL schema if an argument/field/type was recently added.\n(anonymous function) @ bundle.js:51511\ngetFatQuery @ bundle.js:51512\ngetFatQuery @ bundle.js:35664\ngetQuery @ bundle.js:35791\n_handleCommit @ bundle.js:35539\ncommit @ bundle.js:35453\ncommit @ bundle.js:35894\n(anonymous function) @ bundle.js:28526\n```\n\n```text\n-- GraphQL Validation Error -- CreateLinkMutation --\n\nFile: /Users/johndoe/react-relay-project/src/mutations/CreateLinkMutation.js\nError: Cannot query field \"store\" on type \"CreateLinkPayload\".\nSource:\n> \n> store { linkConnection }\n> ^^^\n```\n\n```text\nimport Relay from 'react-relay'\n\nclass CreateLinkMutation extends Relay.Mutation {\n getMutation() {\n return Relay.QL`\n mutation { createLink }\n `\n }\n\n getVariables() {\n return {\n title: this.props.title,\n url: this.props.url\n }\n }\n\n getFatQuery() {\n return Relay.QL`\n fragment on CreateLinkPayload {\n linkEdge,\n store { linkConnection }\n }\n `\n }\n\n getConfigs() {\n return [{\n type: 'RANGE_ADD',\n parentName: 'store',\n parentID: this.props.store.id,\n connectionName: 'linkConnection',\n edgeName: 'linkEdge',\n rangeBehaviors: {\n '': 'append'\n }\n }]\n\n }\n}\n\nexport default CreateLinkMutation\n```\n\n```text\nLink = Relay.createContainer(Link, {\n fragments: {\n link: () => Relay.QL`\n fragment on Link {\n url,\n title\n }\n `\n }\n})\n```\n\n```text\nhandleSubmit(e) {\n e.preventDefault()\n Relay.Store.update(\n new CreateLinkMutation({\n title: this.refs.newTitle.value,\n url: this.refs.newUrl.value,\n store: this.props.store\n })\n )\n this.refs.newTitle.value = ''\n this.refs.newUrl.value = ''\n }\n\n\n\nApp = Relay.createContainer(App, {\n initialVariables: {\n limit: 10\n },\n fragments: {\n store: () => Relay.QL`\n fragment on Store {\n id,\n linkConnection(first: $limit) {\n edges {\n node {\n id,\n ${Link.getFragment('link')}\n }\n }\n }\n }\n `\n\n }\n})\n```\n\n```text\nclass LinkStoreRoute extends Relay.Route {\n static routeName = 'LinkStoreRoute'\n static queries = {\n store: () => Relay.QL`query { store }`\n }\n}\n```\n\n```text\nconst store = {}\n\nconst Store = new GraphQLObjectType({\n name: 'Store',\n fields: () => ({\n id: globalIdField('Store'),\n linkConnection: {\n type: linkConnection.connectionType,\n args: connectionArgs,\n resolve: (_, args) => {\n return docClient.scan(\n Object.assign(\n {},\n {TableName: linksTable},\n paginationToParams(args)\n )\n ).promise().then(dataToConnection)\n }\n }\n })\n})\n\nconst Link = new GraphQLObjectType({\n name: 'Link',\n fields: () => ({\n id: {\n type: new GraphQLNonNull(GraphQLID),\n resolve: (obj) => obj.id\n },\n title: { type: GraphQLString },\n url: { type: GraphQLString }\n })\n})\n\nconst linkConnection = connectionDefinitions({\n name: 'Link',\n nodeType: Link\n})\n\nlet createLinkMutation = mutationWithClientMutationId({\n\n name: 'CreateLink',\n\n inputFields: {\n title: { type: new GraphQLNonNull(GraphQLString) },\n url: { type: new GraphQLNonNull(GraphQLString) }\n },\n\n outputFields: {\n linkEdge: {\n type: linkConnection.edgeType,\n resolve: (obj) => ({node: obj, cursor: obj.id})\n }\n },\n\n store: {\n type: Store,\n resolve: () => store\n },\n\n mutateAndGetPayload: (inputFields) => {\n\n let link = {\n id: uuid.v4(),\n title: inputFields.title,\n url: inputFields.url\n }\n\n return new Promise((resolve, reject) => {\n docClient.put(\n Object.assign(\n {},\n {TableName: linksTable},\n {Item: link}\n ),\n (err, data) => {\n if (err) return reject(err)\n return resolve(link)\n }\n )\n })\n }\n})\n\nconst schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n store: {\n type: Store,\n resolve: () => store\n }\n })\n }),\n\n mutation: new GraphQLObjectType({\n name: 'Mutation',\n fields: () => ({\n createLink: createLinkMutation\n })\n })\n})\n\nmodule.exports = schema\n```\n\n```text\nnpm start\n```\n\n```text\nCreateLinkMutation.js\n```\n\n```text\nLink.js\n```\n\n```text\nApp.js\n```\n\n```text\nmain.js\n```\n\n```text\nschema.js\n```\n\n```text\nrequire\n```\n\n```text\noutputFields: {\n linkEdge: {\n type: linkConnection.edgeType,\n resolve: (obj) => ({node: obj, cursor: obj.id})\n },\n store: {\n type: Store,\n resolve: () => store\n },\n},\n```\n\n```text\nCreateLinkMutation\n```\n\n```text\ngetFatQuery()\n```\n\n```text\nlinkEdge\n```\n\n```text\nstore\n```\n\n```text\nlinkEdge\n```\n\n```text\ncreateLinkMutation\n```\n\n```text\nstore\n```\n\n```text\nstore: {\n type: Store,\n resolve: () => store\n }\n```\n\n```text\noutputFields: {\n linkEdge: {\n type: linkConnection.edgeType,\n resolve: (obj) => ({node: obj, cursor: obj.id})\n }\n store: {\n type: Store,\n resolve: () => store\n }\n }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":617,"estimatedTokens":2578}}755{"id":"stack-53597024","source":"stackoverflow","questionId":53597024,"title":"Best way to do a delete operation with GraphQL + graphene","tags":["graphql","graphene-python"],"text":"Title: Best way to do a delete operation with GraphQL + graphene\nTags: graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI'm struggling to get my Delete operation working.\nMy Create, Read and Update are working fine, but a Delete has nothing to return.\n\n```\nclass DeleteEmployeeInput(graphene.InputObjectType):\n \"\"\"Arguments to delete an employee.\"\"\"\n id = graphene.ID(required=True, description=\"Global Id of the employee.\")\n\nclass DeleteEmployee(graphene.Mutation):\n \"\"\"Delete an employee.\"\"\"\n employee = graphene.Field(\n lambda: Employee, description=\"Employee deleted by this mutation.\")\n\n class Arguments:\n input = DeleteEmployeeInput(required=True)\n\n def mutate(self, info, input):\n data = utils.input_to_dictionary(input)\n #data['edited'] = datetime.utcnow()\n\n employee = db_session.query(\n EmployeeModel).filter_by(id=data['id'])\n employee.delete(data['id'])\n db_session.commit()\n #employee = db_session.query(\n #EmployeeModel).filter_by(id=data['id']).first()\n\n #return DeleteEmployee(employee=employee)\n```\n\nWhat is the best way to delete an entry?\nI assume I have to return an OK or an Error.\n\nWhen I run my mutation:\n\n```\nmutation {\n deleteEmployee (input: {\n id: \"RW1wbG95ZWU6MQ==\"\n }) \n}\n```\n\nI get the error `Field \\\"deleteEmployee\\\" of type \\\"DeleteEmployee\\\" must have a sub selection.\"`\n\nNote the commented out lines\n\n========================================\n\nCode:\n```text\nclass DeleteEmployeeInput(graphene.InputObjectType):\n \"\"\"Arguments to delete an employee.\"\"\"\n id = graphene.ID(required=True, description=\"Global Id of the employee.\")\n\n\nclass DeleteEmployee(graphene.Mutation):\n \"\"\"Delete an employee.\"\"\"\n employee = graphene.Field(\n lambda: Employee, description=\"Employee deleted by this mutation.\")\n\n class Arguments:\n input = DeleteEmployeeInput(required=True)\n\n def mutate(self, info, input):\n data = utils.input_to_dictionary(input)\n #data['edited'] = datetime.utcnow()\n\n employee = db_session.query(\n EmployeeModel).filter_by(id=data['id'])\n employee.delete(data['id'])\n db_session.commit()\n #employee = db_session.query(\n #EmployeeModel).filter_by(id=data['id']).first()\n\n #return DeleteEmployee(employee=employee)\n```\n\n```text\nmutation {\n deleteEmployee (input: {\n id: \"RW1wbG95ZWU6MQ==\"\n }) \n}\n```\n\n```text\nField \\\"deleteEmployee\\\" of type \\\"DeleteEmployee\\\" must have a sub selection.\"\n```\n\n```text\ndef mutate(self, info, input):\n ... skipping deletion code ...\n db_session.commit()\n return DeleteEmployee(ok=True)\n```\n\n```text\nemployee = graphene.Field...\n```\n\n```text\nok = graphene.Boolean()\n```\n\n```text\nreturn DeleteEmployee(ok=True)\n```\n\n========================================\n\nComments:\n- That worked perfectly. I'm relatively new to python as you may have noticed. What exactly happens in the return line `return DeleteEmployee(ok=True)`? It returns an new instance of the same class DeleteEmployee? The ok=True is an kwarg that is passed to the constructor of the graphene.Mutation class?\n- The last line of the mutate method creates an object that is the output of the mutation. It would make more sense in the documentation if the `mutate` method was consistently shown a classmethod.\n- I'm still a bit confused, but I guess I have to grab some 101 udemy courses. For example the line `input = DeleteEmployeeInput(required=True)` The class `DeleteEmployeeInput` itself doesn't have a (visible) variable `required`. It is placed in the super() class `graphene.InputObjectType`?\n- `DeleteEmployeeInput` is defining the shape of the inputs, whereas inside `class Arguments` you are defining the relationship between `DeleteEmployee` and its inputs, which is why `required` goes there.\n- So `required` is a python convention and not a graphene variable? Because I don't see where the variable `required` is created\n- `required` is an argument to method that is creating the graphene field\n- `DeleteEmployeeInput` is an instance of `graphene.InputObjectType` with an additional attribute `id` right? So to my understanding the class attribute `required` has to be created inside `graphene.InputObjectType` but I don't see one in there. I'm coming from PHP btw, maybe I'm missing something crucial here.","metadata":{"transformedAt":"2026-08-18T18:32:36.080Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":124,"estimatedTokens":1072}}756{"id":"stack-61996475","source":"stackoverflow","questionId":61996475,"title":"GraphQL - how to specify maximum String lengths in schema","tags":["graphql"],"text":"Title: GraphQL - how to specify maximum String lengths in schema\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI want to tell GraphQL that my 'serialNumber' field is a String with a length of between 1 and 20 characters. I know to use the ! in the schema to make a field Required, but can I tell GraphQL that there is also a maximum field length?\n\nIf I pass a null value in for a required String field, GraphQL will not accept it. I want it to behave the same way when it is passed a string that is longer than the maximum allowed length.\n\nI have looked at doing this two ways: 1) Add a 'maxlength' attribute to the field definition in the schema.graphql file. or 2) Create a new type and assign it a maximum length.\n\nI can't find any information on how to do it. Is is possible?\n\n========================================\n\nTop Answer:\nYou can use directives:\n\n```\ndirective @length(max: Int!) on FIELD_DEFINITION\n\ninput Payload {\n name: String! @length(max: 50)\n}\n```\n\n========================================\n\nCode:\n```js\nconst logToConsoleToHelpMeUnderstand = false;\nconst { GraphQLScalarType, Kind } = require('graphql');\nconst parseStringMaxLenType = (value,maxLength) => {\n logToConsoleToHelpMeUnderstand && console.log('Checking variable passed to a query is a string and max ' + maxLength + 'chars',value)\n if (typeof value === 'string') {\n if (value.length <= maxLength) {\n return value;\n } else {\n throw new Error('parseCi' + maxLength + 'Type: String must not be more that ' + maxLength + ' characters. It is ' + value.length + ' characters');\n }\n } else {\n throw new Error('parseCi' + maxLength + 'Type: value must be of type String. It is of type \\'' + typeof value + '\\'');\n }\n}\nconst parseStringMaxLen20Type = value => { return parseStringMaxLenType(value, 20) };\nconst parseStringMaxLen25Type = value => { return parseStringMaxLenType(value, 25) };\nconst parseStringMaxLen50Type = value => { return parseStringMaxLentype(value, 50) };\nconst parseStringMaxLen255Type = value => { return parseStringMaxLentype(value, 255) };\nconst parseStringMaxLen500Type = value => { return parseStringMaxLentype(value, 500) };\n\n\nconst serializeStringMaxLenType = (value, maxLength) => {\n /** the serialize methods are called when data is going to be sent to the client. This can return anything\n * of any type, as it will end up as JSON, but we check what is coming back from the database is a string \n * and not too long.\n */\n logToConsoleToHelpMeUnderstand && console.log(`Checking value '${value}' is at most ${maxLength} chars before serialising for output from graphQL to a client (the OCCP gateway is the client)`);\n if (typeof value === 'string') {\n if (value.length <= maxLength) {\n return value;\n } else {\n throw new Error('serializeCi' + maxLength + 'Type: String must not be more that ' + maxLength + ' characters. It is ' + value.length + ' characters');\n }\n } else {\n throw new Error('serializeCi' + maxLength + 'Type: value must be of type String. It is of type \\'' + typeof value + '\\'');\n }\n};\nconst serializeStringMaxLen20Type = (value) => { return serializeStringMaxLenType(value,20) };\nconst serializeStringMaxLen25Type = (value) => { return serializeStringMaxLenType(value,25) };\nconst serializeStringMaxLen50Type = (value) => { return serializeStringMaxLenType(value,50) };\nconst serializeStringMaxLen255Type = (value) => { return serializeStringMaxLenType(value,255) };\nconst serializeStringMaxLen500Type = (value) => { return serializeStringMaxLenType(value,500) };\n\nconst parseLiteralStringMaxLenType = (ast, maxLength) => {\n logToConsoleToHelpMeUnderstand && console.log('checking Abstract Syntax Tree value (these come from parameters in GraphQL queries) is not more than ' + maxLength + ' chars long',ast);\n // For input payload i.e. for mutation. ast stands for abstract syntax tree, which is the type of \n if (ast.kind === Kind.STRING) {\n // Note the parseStringMaxLenType function throws errors, or returns a valid value, so there is no need to throw errors here.\n return parseStringMaxLenType(ast.value, maxLength)\n } else {\n throw new Error()\n }\n};\n\nconst parseLiteralStringMaxLen20Type = (ast) => { return parseLiteralStringMaxLenType(ast, 20) }\nconst parseLiteralStringMaxLen25Type = (ast) => { return parseLiteralStringMaxLenType(ast, 25) }\nconst parseLiteralStringMaxLen50Type = (ast) => { return parseLiteralStringMaxLenType(ast, 50) }\nconst parseLiteralStringMaxLen255Type = (ast) => { return parseLiteralStringMaxLenType(ast, 255) }\nconst parseLiteralStringMaxLen500Type = (ast) => { return parseLiteralStringMaxLenType(ast, 500) }\n\nconst StringMaxLen20Type = new GraphQLScalarType({\n name: 'StringMaxLen20Type',\n description: 'String up to 20 Chars',\n serialize: serializeStringMaxLen20Type,\n parseValue: parseStringMaxLen20Type,\n parseLiteral: parseLiteralStringMaxLen20Type,\n});\n\nconst StringMaxLen25Type = new GraphQLScalarType({\n name: 'StringMaxLen25Type',\n description: 'String up to 25 Chars',\n serialize: serializeStringMaxLen25Type,\n parseValue: parseStringMaxLen25Type,\n parseLiteral: parseLiteralStringMaxLen25Type,\n});\n\nconst StringMaxLen50Type = new GraphQLScalarType({\n name: 'StringMaxLen50Type',\n description: 'String up to 50 Chars',\n serialize: serializeStringMaxLen50Type,\n parseValue: parseStringMaxLen50Type,\n parseLiteral: parseLiteralStringMaxLen50Type,\n});\n\nconst StringMaxLen255Type = new GraphQLScalarType({\n name: 'StringMaxLen255Type',\n description: 'String up to 255 Chars',\n serialize: serializeStringMaxLen255Type,\n parseValue: parseStringMaxLen255Type,\n parseLiteral: parseLiteralStringMaxLen255Type,\n});\n\nconst StringMaxLen500Type = new GraphQLScalarType({\n name: 'StringMaxLen500Type',\n description: 'String up to 500 Chars',\n serialize: serializeStringMaxLen500Type,\n parseValue: parseStringMaxLen500Type,\n parseLiteral: parseLiteralStringMaxLen500Type,\n});\n\nmodule.exports = {StringMaxLen20Type, StringMaxLen25Type, StringMaxLen50Type, StringMaxLen255Type, StringMaxLen500Type };\n```\n\n```text\nscalar StringMaxLen20Type\nscalar StringMaxLen25Type\nscalar StringMaxLen50Type\nscalar StringMaxLen255Type\nscalar StringMaxLen500Type\ntype YourOtherTypes {\n id: ID!\n canUseAboveTypesLikeThis: StringMaxLen50Type\n}\n```\n\n```text\n...\n...\nconst {StringMaxLen20Type, StringMaxLen25Type, StringMaxLen50Type, StringMaxLen255Type, StringMaxLen500Type } = require('StringMaxLenTypes.js');```\n...\nmodule.exports = {\nQuery: {...},\nMutation: {...},\nStringMaxLen20Type,\nStringMaxLen25Type,\nStringMaxLen50Type,\nStringMaxLen255Type,\nStringMaxLen500Type\n```\n\n```text\ndirective @length(max: Int!) on FIELD_DEFINITION\n\ninput Payload {\n name: String! @length(max: 50)\n}\n```\n\n========================================\n\nComments:\n- I think it's worth mentioning that `@length` only supported by Apollo.\n- with directives you can use any/dynamic length\n- thanks @xadm but I chose not to use directives cause I read they are not part of the GraphQL standard, and hence are implementation dependant. Is that your understanding?\n- apply a few directives to one field vs define thousands possible types? types looks ugly for api consumer? your solution is equally implementation based - needs recreation when moved to other server\n- ... and directives are in graphql specs\n- @xadm you are right, directives are mentioned the current release of the spec: spec.graphql.org/June2018/#sec-Language.Directives . The working draft elaborates a little: \"GraphQL implementations should provide the `@skip` and `@include` directives.\", and \"must provide the `@deprecated`..\". It says we \"may provide additional directives\" but I don't take that to mean `@length` will be implemented in all compliant servers.\n- implementing this as directives makes api much more universal - implementing as hardcoded types is rather naive/basic solution - what if you'll need length 200 (180, 30, whatever not already defined) and server doesn't have this? supporting this (requests) would be a pain - solution for a few use cases instead of the whole class\n- In my use case I am validating validating requests that must meet the specs defined in an RFC. It defines these 5 string types only (and uses integer and boolean and some ENUMS). These types allow the graphql.schema types to be called the same as it is called in the RFC, makes reading it consistent and precise to read. I see what you are saying, but this will be reusable across all compliant GraphQL servers, whereas the length(20) directive may not be. Horses for courses I guess.","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":179,"estimatedTokens":2140}}757{"id":"stack-55473302","source":"stackoverflow","questionId":55473302,"title":"What's the difference between Operation Arguments and GraphQL variables?","tags":["graphql","graphql-js"],"text":"Title: What's the difference between Operation Arguments and GraphQL variables?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am in the process of learning GraphQL and have stumbled upon understanding the difference between **Operation Arguments** and **GraphQL variables**. Because IMO, **both provide**, client, the facility to **pass in dynamic data** to either mutations or queries etc.\n\nCan someone enlighten me ?\n\nCheers!\n\n========================================\n\nCode:\n```text\nquery FilmQuery {\n film (id: \"ZmlsbXM6MQ==\") {\n id\n title\n }\n}\n```\n\n```text\nquery FilmQuery($myId: ID!) {\n film (id: $myId) {\n id\n title\n }\n}\n```\n\n```text\nfilm\n```\n\n```text\nid\n```\n\n```text\nFilm\n```\n\n```text\nid\n```\n\n```text\n\"ZmlsbXM6MQ==\"\n```\n\n```text\n$myId\n```\n\n```text\nID!\n```\n\n========================================\n\nComments:\n- This was the exact kind of answer I was looking for. Thanks a ton man!!! Cheers!","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":64,"estimatedTokens":233}}758{"id":"stack-53792064","source":"stackoverflow","questionId":53792064,"title":"CORS blocks mutation in GraphQL Yoga","tags":["javascript","express","graphql","react-apollo","prisma-graphql"],"text":"Title: CORS blocks mutation in GraphQL Yoga\nTags: javascript, express, graphql, react-apollo, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI am working here with a graphql prisma backend and a graphql yoga express server on top of that. In the frontend, I am trying to call a signout mutation but its blocked by the CORS policy. Though I have added cors settings in my graphql yoga server, I keep getting this error. GraphQL Queries are working fine but Mutations are being blocked. My frontend URL is 'http://localhost:7777' and yoga server is running at 'http://localhost:4444/'. The Error was: \n\n```\nAccess to fetch at 'http://localhost:4444/' from origin 'http://localhost:7777' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.\n\n[Network error]: TypeError: Failed to fetch\n```\n\nGraphQL Yoga Server Cors Config:\n\n```\nserver.start(\n{\n cors: {\n credentials: true,\n origin: [process.env.FRONTEND_URL],\n },\n},\ndeets => {\n console.log(\n `Server is now running on port http://localhost:${deets.port}`\n );\n}\n);\n```\n\nMutation:\n\n```\n// import React, { Component } from 'react';\nimport { Mutation } from 'react-apollo';\nimport styled from 'styled-components';\nimport gql from 'graphql-tag';\nimport { CURRENT_USER_QUERY } from './User';\nimport { log } from 'util';\n\nconst SIGN_OUT_MUTATION = gql`\nmutation SIGN_OUT_MUTATION {\n signout {\n message\n }\n}\n`;\n\nconst SignOutBtn = styled.button`\ncolor: ${props => props.theme.textMedium};\npadding: 10px;\nmargin-right: 20px;\ntext-align: center;\nfont-family: garamond-light;\nborder: 1px solid ${props => props.theme.textMedium};\nborder-radius: 5px;\ntransition: background-color 0.5s ease;\ntransition: color 0.5s ease;\n:hover {\n background: ${props => props.theme.textMedium};\n color: ${props => props.theme.white};\n}\n`;\n\nconst Signout = props => (\n\n {signout => (\n {\n console.log(\"comes here\")\n signout();\n }}\n >\n Sign Out\n \n )}\n\n);\nexport default Signout;\n```\n\nPlease tell me what I am doing wrong here. Thanks in Advance.\n\n========================================\n\nTop Answer:\nWhat I had to do was pass the origin an array of string values. As well as set the new origin PAST_FRONTEND_URL in heroku\n\n\r\n\r\n\n```\nserver.start(\r\n {\r\n cors: {\r\n credentials: true,\r\n origin: [process.env.FRONTEND_URL, process.env.PAST_FRONTEND_URL],\r\n },\r\n },\r\n deets => {\r\n console.log(`Server is now running on port http://localhost:${deets.port}`);\r\n }\r\n);\n```\n\n========================================\n\nCode:\n```text\nAccess to fetch at 'http://localhost:4444/' from origin 'http://localhost:7777' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.\n\n[Network error]: TypeError: Failed to fetch\n```\n\n```text\nserver.start(\n{\n cors: {\n credentials: true,\n origin: [process.env.FRONTEND_URL],\n },\n},\ndeets => {\n console.log(\n `Server is now running on port http://localhost:${deets.port}`\n );\n}\n);\n```\n\n```text\n// import React, { Component } from 'react';\nimport { Mutation } from 'react-apollo';\nimport styled from 'styled-components';\nimport gql from 'graphql-tag';\nimport { CURRENT_USER_QUERY } from './User';\nimport { log } from 'util';\n\nconst SIGN_OUT_MUTATION = gql`\nmutation SIGN_OUT_MUTATION {\n signout {\n message\n }\n}\n`;\n\nconst SignOutBtn = styled.button`\ncolor: ${props => props.theme.textMedium};\npadding: 10px;\nmargin-right: 20px;\ntext-align: center;\nfont-family: garamond-light;\nborder: 1px solid ${props => props.theme.textMedium};\nborder-radius: 5px;\ntransition: background-color 0.5s ease;\ntransition: color 0.5s ease;\n:hover {\n background: ${props => props.theme.textMedium};\n color: ${props => props.theme.white};\n}\n`;\n\nconst Signout = props => (\n<Mutation\n mutation={SIGN_OUT_MUTATION}\n refetchQueries={[{ query: CURRENT_USER_QUERY }]}\n>\n {signout => (\n <SignOutBtn\n onClick={() => {\n console.log(\"comes here\")\n signout();\n }}\n >\n Sign Out\n </SignOutBtn>\n )}\n</Mutation>\n);\nexport default Signout;\n```\n\n```text\nserver.express.use(function(req, res, next) {\n res.header('Access-Control-Allow-Origin', 'http://localhost:7777');\n res.header(\n 'Access-Control-Allow-Headers',\n 'Origin, X-Requested-With, Content-Type, Accept'\n );\n next();\n});\n```\n\n```js\nserver.start(\n {\n cors: {\n credentials: true,\n origin: [process.env.FRONTEND_URL, process.env.PAST_FRONTEND_URL],\n },\n },\n deets => {\n console.log(`Server is now running on port http://localhost:${deets.port}`);\n }\n);\n```\n\n```js\nserver.start(\n {\n cors: {\n credentials: true,\n origin: [process.env.FRONTEND_URL],\n methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',\n preflightContinue: false,\n optionsSuccessStatus: 204\n }\n },\n server => {\n console.log(`Server is running on http://localhost/${server.port}`);\n }\n);\n```\n\n```text\nserver.express.use((req, res, next) => {\n res.header('Access-Control-Allow-Credentials', true)\n next()\n})\n```\n\n```text\napp.use(function(req, res, next) {\n res.header(\"Access-Control-Allow-Origin\", \"YOUR-DOMAIN\"); // update to match the domain you will make the request from\n res.header(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\");\n next();\n});\n```\n\n```text\nconst cors = require('cors')\nconst corsOptions = {\n origin: [\n \n \"http://YOUR-DOMAIN\"\n ],\n credentials: true\n}\napp.use(cors(corsOptions))\n```\n\n```text\nAccess-Control-Allow-Origin: YOUR_DOMAIN\n```\n\n========================================\n\nComments:\n- I don't see what's wrong with the code you shared. Could you provide a minimum reproduciable repository for us to investigate more?\n- @Errorname Thanks for trying to help and you can find the repo here. The repo won't be having environment files. If you are in need of those, please let me know.\n- Thank you for the link, but there is too much files to analyse. Could you create a repository with only the files necessary to reproduce the issue?\n- Did you keep the `cors: {credentials: true,origin: process.env.FRONTEND_URL,},` on the server?\n- @ChanceSmith Yes I tried that, but it wasn't working for me. I have posted the same config in the question as well. Let me know if I have done something wrong.\n- Sorry, I'm having the same issue, but now wondering if you left that object in or not. π€·ββοΈ\n- Can you more of the code above this block? I've found several implementations of this, but none that really explain how the `.express.use` part is set up. This CodePen is what I have so far.","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":265,"estimatedTokens":1745}}759{"id":"stack-50334328","source":"stackoverflow","questionId":50334328,"title":"Can an enum return description (string) in GraphQL?","tags":["graphql","graphql-js"],"text":"Title: Can an enum return description (string) in GraphQL?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm struggling with my GraphQL API because I need to take advantage of Enums while keeping their full description in the frontend.\n\nIn short:\nI have different states for a product: `\"Has been sent\"`, `\"Not sent yet\"`, `\"Received\"`.\nSo this is the right place to use Enums:\n\n```\nenum ProductState {\n HAS_BEEN_SENT\n NOT_SENT_YET\n RECEIVED\n}\n```\n\nBut I need to display the **proper strings** on the frontend (\"`Has been sent`\", and not \"`HAS_BEEN_SENT`\").\n\nI can't use a simple solution as \"replace underscores with spaces and lowercase the string\" because my API is not in English but in French (so I have accents and special characters).\n\n**Can't an Enum return a string? Or an object?**\nI tried with directives but impossible to get it work...\n\nActually I don't care how it is written in the database (the uppercase or lowercase form) nor in the GraphQL API. I just need my client to access to the different product states in their \"French\" form.\n\n========================================\n\nCode:\n```text\nenum ProductState {\n HAS_BEEN_SENT\n NOT_SENT_YET\n RECEIVED\n}\n```\n\n```text\n\"Has been sent\"\n```\n\n```text\n\"Not sent yet\"\n```\n\n```text\n\"Received\"\n```\n\n```text\nHas been sent\n```\n\n```text\nHAS_BEEN_SENT\n```\n\n```text\n#NOTE: I would probably use a more descriptive name as opposed to ProductState\nenum AllowedProductStatus { \n HAS_BEEN_SENT\n NOT_SENT_YET\n RECEIVED\n}\n```\n\n```text\nconst resolvers = {\n AllowedProductStatus: {\n HAS_BEEN_SENT: \"Has been sent\", \n NOT_SENT_YET: \"Not sent yet\", \n RECEIVED: \"Received\"\n }\n};\n```\n\n```text\ntype Product {\n status: String! @unique\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":83,"estimatedTokens":428}}760{"id":"stack-59024939","source":"stackoverflow","questionId":59024939,"title":"Upgrade GraphQL from .NET core 2.2 to 3.0","tags":["c#","asp.net-core","graphql","asp.net-core-3.0","graphiql"],"text":"Title: Upgrade GraphQL from .NET core 2.2 to 3.0\nTags: c#, asp.net-core, graphql, asp.net-core-3.0, graphiql\nSource: Stack Overflow\n\nQuestion:\nI am new to GraphQL, when I try to upgrade .net core version from 2.2 to 3.0\n\nI got problem about UI display on /graphql page when using UseGraphiQl\n\nhttps://i.sstatic.net/BiJtk.png\n\nAPI is working normally but the UI is display incorrect.\nI googled for find out solutions, but nothing really helpful.\n\nHere is my config for graphql:\n\n```\nservices.AddRazorPages().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);\n\napp.UseGraphiQLServer(new GraphiQLOptions());\napp.UseGraphiQl(\"/graphiql\", \"/graphql\");\napp.UseEndpoints(x =>\n{\n x.MapControllers();\n});\n```\n\nAny help is greatly appreciated, thanks.\n\n========================================\n\nTop Answer:\nI'm not sure if they are changing anything in .net core version 3.0 but you can view my blog here\n\nI'm using `GraphQL.Server.Ui.Playground`\n\nBelow is minial config you can see\n\n```\npublic void ConfigureServices(IServiceCollection services)\n{\n services\n .AddMvc()\n .AddJsonOptions(\n options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore\n )\n .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);\n\n services.AddGraphQL(x =>\n {\n x.ExposeExceptions = true; //set true only in development mode. make it switchable.\n })\n .AddGraphTypes(ServiceLifetime.Scoped);\n}\n\n// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.\npublic void Configure(IApplicationBuilder app, IHostingEnvironment env, Seeder seeder)\n{\n app.UseGraphQL();\n app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());\n\n app.UseMvc(routes =>\n {\n routes.MapRoute(\n name: \"default\",\n template: \"{controller}/{action=Index}/{id?}\");\n });\n}\n```\n\nThe result is the same with GraphiQl\n\nhttps://i.sstatic.net/bWCX7.png\n\nEdit: This is because Newtonsoft.Json is change in .Net Core 3. You can view my answer here\n\nASP.NET Core 3.0 [FromBody] string content returns \"The JSON value could not be converted to System.String.\"\n\n========================================\n\nCode:\n```text\nservices.AddRazorPages().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);\n\napp.UseGraphiQLServer(new GraphiQLOptions());\napp.UseGraphiQl(\"/graphiql\", \"/graphql\");\napp.UseEndpoints(x =>\n{\n x.MapControllers();\n});\n```\n\n```text\nservices.AddRazorPages().AddNewtonsoftJson();\n```\n\n```text\npublic void ConfigureServices(IServiceCollection services)\n{\n services\n .AddMvc()\n .AddJsonOptions(\n options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore\n )\n .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);\n\n services.AddGraphQL(x =>\n {\n x.ExposeExceptions = true; //set true only in development mode. make it switchable.\n })\n .AddGraphTypes(ServiceLifetime.Scoped);\n}\n\n// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.\npublic void Configure(IApplicationBuilder app, IHostingEnvironment env, Seeder seeder)\n{\n app.UseGraphQL<DataSchema>();\n app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());\n\n app.UseMvc(routes =>\n {\n routes.MapRoute(\n name: \"default\",\n template: \"{controller}/{action=Index}/{id?}\");\n });\n}\n```\n\n```text\nGraphQL.Server.Ui.Playground\n```\n\n========================================\n\nComments:\n- Thanks for your response but my application is totally ok in v2.2.\n- I am in latest version already 1.2 for graphiql and 3.4.0 for GraphQL.Server.Ui.GraphiQL","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":137,"estimatedTokens":908}}761{"id":"stack-58421858","source":"stackoverflow","questionId":58421858,"title":"java.lang.NoClassDefFoundError: graphql/execution/instrumentation/SimpleInstrumentation (GraphQL and Spring Boot)","tags":["java","spring-boot","graphql"],"text":"Title: java.lang.NoClassDefFoundError: graphql/execution/instrumentation/SimpleInstrumentation (GraphQL and Spring Boot)\nTags: java, spring-boot, graphql\nSource: Stack Overflow\n\nQuestion:\nI am experimenting with GraphQL and Spring Boot, when i try to run one of my GraphQL queries i get the next error: (Graphiql loads fine btw) \n\njava.lang.NoClassDefFoundError: graphql/execution/instrumentation/SimpleInstrumentation\n\nPOM dependencies: \n\n```\n\n com.graphql-java\n graphql-spring-boot-starter\n 5.0.2\n \n \n com.graphql-java\n graphql-java-tools\n 4.3.0\n \n \n com.graphql-java\n graphiql-spring-boot-starter\n 4.0.0\n\n```\n\nand this is the exception:\n\n```\njava.lang.NoClassDefFoundError: graphql/execution/instrumentation/SimpleInstrumentation\nat graphql.servlet.GraphQLQueryInvoker$Builder.lambda$new$0(GraphQLQueryInvoker.java:101) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.getInstrumentation(GraphQLQueryInvoker.java:72) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.newGraphQL(GraphQLQueryInvoker.java:57) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.query(GraphQLQueryInvoker.java:92) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.query(GraphQLQueryInvoker.java:88) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.query(GraphQLQueryInvoker.java:39) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.query(AbstractGraphQLHttpServlet.java:265) [graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.lambda$new$2(AbstractGraphQLHttpServlet.java:183) [graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.doRequest(AbstractGraphQLHttpServlet.java:236) [graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.doRequestAsync(AbstractGraphQLHttpServlet.java:227) [graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.doPost(AbstractGraphQLHttpServlet.java:257) [graphql-java-servlet-6.1.2.jar:na]\nat javax.servlet.http.HttpServlet.service(HttpServlet.java:660) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat javax.servlet.http.HttpServlet.service(HttpServlet.java:741) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:97) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ....\nat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135) [na:na]\nat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) [na:na]\nat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat java.base/java.lang.Thread.run(Thread.java:844) [na:na]\nCaused by: java.lang.ClassNotFoundException: graphql.execution.instrumentation.SimpleInstrumentation\nat java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582) ~[na:na]\nat java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190) ~[na:na]\nat java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499) ~[na:na]\n... 54 common frames omitted\n```\n\n========================================\n\nCode:\n```text\n<dependency>\n <groupId>com.graphql-java</groupId>\n <artifactId>graphql-spring-boot-starter</artifactId>\n <version>5.0.2</version>\n </dependency>\n <dependency>\n <groupId>com.graphql-java</groupId>\n <artifactId>graphql-java-tools</artifactId>\n <version>4.3.0</version>\n </dependency>\n <dependency>\n <groupId>com.graphql-java</groupId>\n <artifactId>graphiql-spring-boot-starter</artifactId>\n <version>4.0.0</version>\n</dependency>\n```\n\n```text\njava.lang.NoClassDefFoundError: graphql/execution/instrumentation/SimpleInstrumentation\nat graphql.servlet.GraphQLQueryInvoker$Builder.lambda$new$0(GraphQLQueryInvoker.java:101) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.getInstrumentation(GraphQLQueryInvoker.java:72) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.newGraphQL(GraphQLQueryInvoker.java:57) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.query(GraphQLQueryInvoker.java:92) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.query(GraphQLQueryInvoker.java:88) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.GraphQLQueryInvoker.query(GraphQLQueryInvoker.java:39) ~[graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.query(AbstractGraphQLHttpServlet.java:265) [graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.lambda$new$2(AbstractGraphQLHttpServlet.java:183) [graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.doRequest(AbstractGraphQLHttpServlet.java:236) [graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.doRequestAsync(AbstractGraphQLHttpServlet.java:227) [graphql-java-servlet-6.1.2.jar:na]\nat graphql.servlet.AbstractGraphQLHttpServlet.doPost(AbstractGraphQLHttpServlet.java:257) [graphql-java-servlet-6.1.2.jar:na]\nat javax.servlet.http.HttpServlet.service(HttpServlet.java:660) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat javax.servlet.http.HttpServlet.service(HttpServlet.java:741) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:97) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]\nat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ....\nat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135) [na:na]\nat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) [na:na]\nat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.26.jar:9.0.26]\nat java.base/java.lang.Thread.run(Thread.java:844) [na:na]\nCaused by: java.lang.ClassNotFoundException: graphql.execution.instrumentation.SimpleInstrumentation\nat java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582) ~[na:na]\nat java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190) ~[na:na]\nat java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499) ~[na:na]\n... 54 common frames omitted\n```\n\n```text\ngraphql-spring-boot-starter\n```\n\n```text\ngraphql-java-tools\n```\n\n```text\ngraphql-java\n```\n\n```text\nSimpleInstrumentation\n```\n\n```text\nNoClassDefFoundError\n```\n\n```text\ngraphql-spring-boot-starter\n```\n\n```text\ngraphql-java-tools\n```\n\n```text\ngraphql-java\n```\n\n```text\nmvn dependency:tree\n```\n\n```text\ngraphql-java\n```\n\n========================================\n\nComments:\n- Have you checked if the SimpleInstrumentation class is in one the dependencies and that all dependencies are on the build path?\n- Yes i checked, and it was not there. Seems the problem i have is the dependencies are not compatible between them. Need to check if the version are correct. Thanks a lot for commenting, that gave me the clue i needed.\n- I think that if you go with the latest versions you should not have compatibility. You should also check that graphql-spring-boot-starter does not include graphql-java-tools, in which case you could face dependency conflicts that you would need to solve by excluding one of the dependencies.\n- Hi! this solved my problem. I upgraded graphiql-spring-boot-starter to version 5.0.2 to match graphql-spring-boot-starter and that fixed the issue. Thanks.","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":201,"estimatedTokens":3525}}762{"id":"stack-50872538","source":"stackoverflow","questionId":50872538,"title":"React Apollo dynamically create query from state","tags":["reactjs","graphql","apollo","react-apollo"],"text":"Title: React Apollo dynamically create query from state\nTags: reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nHeres a model situation\nI have some fields in my DB lets say color,size,height ...\n\nI can fetch and display these fields to user who can choose these fields and they are afterwards set to components state\n\nWhat i want to achieve is to dynamically create GQL query **(not query variables)** from these fields stored in state\n\nExample\n\n```\n//import react gql ....\nclass MyComponent extends Component {\n\nconstructor(props){\n super(props)\n this.state = {\n fields : []\n }\n}\n\nrender(){\n...\n}\n\ncomponentWillMount(){\n fetch(...)\n .then(fields => this.setState({fields}))\n }\n\n}\n\nexport default graphql( --->state => CREATE_QUERY_DYNAMICALLY_FROM_FIELDS(state.fields)**Is there a way to access components state during query creation ?**\n\n**Or some other approach ?**\n\n**Any ideas appreciated**\n\n========================================\n\nTop Answer:\n```\nclass MyComponent extends Component {\n\n constructor(props){\n super(props)\n this.state = {\n fields : []\n }\n }\n\n render(){\n ...\n }\n\n componentWillMount(){\n const query = gql`\n query myDynamicQuery {\n viewer {\n endpoint {\n ${this.state.fields.join('\\n')}\n }\n }\n }\n `\n this.props.client.query({ query }).then((res) => ...)\n }\n}\nexport default withApollo(MyComponent)\n```\n\nHope this is working :)\n\n========================================\n\nCode:\n```text\n//import react gql ....\nclass MyComponent extends Component {\n\nconstructor(props){\n super(props)\n this.state = {\n fields : []\n }\n}\n\nrender(){\n...\n}\n\ncomponentWillMount(){\n fetch(...)\n .then(fields => this.setState({fields}))\n }\n\n}\n\nexport default graphql( --->state => CREATE_QUERY_DYNAMICALLY_FROM_FIELDS(state.fields)<----,{..some options})\n```\n\n```text\n<Query .../>\n```\n\n```text\nclass MyComponent extends Component {\n\n constructor(props){\n super(props)\n this.state = {\n fields : []\n }\n }\n\n render(){\n ...\n }\n\n componentWillMount(){\n const query = gql`\n query myDynamicQuery {\n viewer {\n endpoint {\n ${this.state.fields.join('\\n')}\n }\n }\n }\n `\n this.props.client.query({ query }).then((res) => ...)\n }\n}\nexport default withApollo(MyComponent)\n```\n\n========================================\n\nComments:\n- I don't think there is any built-in function for dynamically creating queries, but since the query is just a string you could format that string by yourself. Eg: ``query{ topLevelField { ${ fields.join(',') } }}`` Also you should declare the list of fields outside of your react component, if you are going to declare the `graphql` query outside of your component.\n- Since `graphql` doesn't support dynamic queries, try to use the apollo client and inject the query conditionally or even the declarative https://www.apollographql.com/docs/react/why-apollo.html#declarative-data Component.\n- @LefiTarik great comment i have upgraded to react-apollo 2.1 and with works like a charm if you write it as an answer i would definitely accept :)\n- great @Ziker :).\n- actually graphql **does** support dynamic queries (the query is simply sent as a json payload in the post). I am going to try what @a-moynet suggested working\n- Your suggestion works! In fact, the entire query can be dynamic. I do not know what downstream impact there might be (related to offline or subscriptions).","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":148,"estimatedTokens":873}}763{"id":"stack-50887793","source":"stackoverflow","questionId":50887793,"title":"check for internet connectivity using WebSocketLink from apollo-link-ws","tags":["websocket","graphql","apollo","apollo-client","apollo-server"],"text":"Title: check for internet connectivity using WebSocketLink from apollo-link-ws\nTags: websocket, graphql, apollo, apollo-client, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm trying to check for internet connectivity using apollo websockets, the purpose of this is to show a \"you're disconnected\" message when there is no connection to prevent the user from typing and assuming the changes are saved (the changes are supposedly saved on type), here's part of the setup of apollo-link-ws\n\n```\nconst wsLink = new WebSocketLink({\nuri: `ws://${hostname}${port ? `:${port}` : ''}/subscriptions`,\noptions: {\n reconnect: true,\n connectionParams: () => ({\n authorization: localStorage.getItem('accelerator-token')\n })\n}\n});\n```\n\nand \n\n```\nconst hasSubscriptionOperation = ({ query: { definitions } }) =>\n definitions.some(\n ({ kind, operation }) =>\n kind === 'OperationDefinition' && operation === 'subscription'\n );\n```\n\nand here's the client config:\n\n```\nconst client = new ApolloClient({\nlink: ApolloLink.split(\n hasSubscriptionOperation,\n wsLink,\n ApolloLink.from([\n cleanTypenameLink,\n authMiddleware,\n errorLink,\n stateLink,\n createUploadLink()\n ])\n ),\n cache\n});\n```\n\n========================================\n\nTop Answer:\nIf you are working with React I found this nice community package react-apollo-network-status\n\n========================================\n\nCode:\n```text\nconst wsLink = new WebSocketLink({\nuri: `ws://${hostname}${port ? `:${port}` : ''}/subscriptions`,\noptions: {\n reconnect: true,\n connectionParams: () => ({\n authorization: localStorage.getItem('accelerator-token')\n })\n}\n});\n```\n\n```text\nconst hasSubscriptionOperation = ({ query: { definitions } }) =>\n definitions.some(\n ({ kind, operation }) =>\n kind === 'OperationDefinition' && operation === 'subscription'\n );\n```\n\n```text\nconst client = new ApolloClient({\nlink: ApolloLink.split(\n hasSubscriptionOperation,\n wsLink,\n ApolloLink.from([\n cleanTypenameLink,\n authMiddleware,\n errorLink,\n stateLink,\n createUploadLink()\n ])\n ),\n cache\n});\n```\n\n```text\nexport const myClient = new SubscriptionClient(`ws://${hostname}${port ? \n`:${port}` : ''}/subscriptions`, {\n reconnect: true,\n connectionParams: () => ({\n authorization: localStorage.getItem('accelerator-token')\n })\n});\nmyClient.onConnected(()=>{console.log(\"connected f client f onConnected\")})\n myClient.onReconnected(()=>{console.log(\"connected f client f \nreconnected\")})\nmyClient.onReconnecting(()=>{console.log(\"connected f client f \nreconnecting\")})\nmyClient.onDisconnected(()=>{console.log(\"connected f client f \nonDisconnected\")})\nmyClient.onError(()=>{console.log(\"connected f client f onError\")})\nexport const wsLink = new WebSocketLink(myClient);\n```\n\n========================================\n\nComments:\n- is there any other way to achieve this? (without using ws)\n- `onConnected` never fires for me. Does it for you?","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":117,"estimatedTokens":730}}764{"id":"stack-41862789","source":"stackoverflow","questionId":41862789,"title":"GraphQL - how to filter a hierarchy? (\"customers who ordered gizmos last month\")","tags":["graphql"],"text":"Title: GraphQL - how to filter a hierarchy? (\"customers who ordered gizmos last month\")\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nLet's assume a type hierarchy of `Customer -(hasMany)-> Orders -(hasMany)-> OrderLines`\n\nSomething like this:\n\n```\nCustomer {\n Name\n Orders [\n {\n OrderId\n Date\n OrderLines [\n { \n ItemCount\n ItemName\n }\n ]\n }\n ]\n}\n```\n\nI want to query for this whole tree, and *filter* on properties at *any level* in the tree. \n\nFor instance: Get all customers who ordered 'gizmos'.\n\nThis is what I tried: at each level of the hierarchy, I specify optional arguments that would filter based on the properties available at that level:\n\n```\nCustomer (Name) {\n Name\n Orders (OrderId, Date) [\n {\n OrderId\n Date\n OrderLines (ItemCount, ItemName) [\n { \n ItemCount\n ItemName\n }\n ]\n }\n ]\n}\n```\n\nGraphQL needs me to define *how to resolve* each type in the hierarchy, so when resolving, I filter based on the arguments in the query.\n\n*But what if I only specify a filter at a deep level?* e.g. `ItemName : 'gizmo'`\n\nAssuming there's only one order line in the system containing a gizmo, I would expect to get a response like this:\n\n```\n[{\n Name: \"cust12\",\n Orders [{\n OrderId: \"ade32f\",\n OrderLines: [{\n ItemCount: 50000, //customer really likes gizmos\n ItemName: \"gizmo\"\n }]\n }]\n}]\n```\n\nBut what I actually get is **all** customers (no filter there), **all** their orders (no filter there) and **all** order items, mostly empty (the items inside are filtered).\n\n```\n[{\n Name: \"cust12\",\n Orders [\n {\n OrderId: \"aaaaaa\",\n OrderLines: [ ]\n },\n {\n OrderId: \"ade32f\",\n OrderLines: [{\n ItemCount: 50000,\n ItemName: \"gizmo\"\n }]\n },\n {\n OrderId: \"bbbbbb\",\n OrderLines: [ ]\n },\n {\n OrderId: \"cccccc\",\n OrderLines: [ ]\n }\n ]\n},\n{\n Name: \"cust345\",\n Orders [\n {\n OrderId: \"eeeeee\",\n OrderLines: [ ]\n },\n {\n OrderId: \"ffffff\",\n OrderLines: [ ]\n }\n ]\n}]\n```\n\nGraphQL calls the resolvers *top-down*:\n- get all (filtered) clients\n- for each of these get all (filtered) orders\n- for each of those get all (filtered) order lines \n\nBecause of the top-down nature of calling the resolvers, I get a lot more data than I bargained for. \n\nHow should I approach this?\n\n========================================\n\nCode:\n```text\nCustomer {\n Name\n Orders [\n {\n OrderId\n Date\n OrderLines [\n { \n ItemCount\n ItemName\n }\n ]\n }\n ]\n}\n```\n\n```text\nCustomer (Name) {\n Name\n Orders (OrderId, Date) [\n {\n OrderId\n Date\n OrderLines (ItemCount, ItemName) [\n { \n ItemCount\n ItemName\n }\n ]\n }\n ]\n}\n```\n\n```text\n[{\n Name: \"cust12\",\n Orders [{\n OrderId: \"ade32f\",\n OrderLines: [{\n ItemCount: 50000, //customer really likes gizmos\n ItemName: \"gizmo\"\n }]\n }]\n}]\n```\n\n```text\n[{\n Name: \"cust12\",\n Orders [\n {\n OrderId: \"aaaaaa\",\n OrderLines: [ ]\n },\n {\n OrderId: \"ade32f\",\n OrderLines: [{\n ItemCount: 50000,\n ItemName: \"gizmo\"\n }]\n },\n {\n OrderId: \"bbbbbb\",\n OrderLines: [ ]\n },\n {\n OrderId: \"cccccc\",\n OrderLines: [ ]\n }\n ]\n},\n{\n Name: \"cust345\",\n Orders [\n {\n OrderId: \"eeeeee\",\n OrderLines: [ ]\n },\n {\n OrderId: \"ffffff\",\n OrderLines: [ ]\n }\n ]\n}]\n```\n\n```text\nCustomer -(hasMany)-> Orders -(hasMany)-> OrderLines\n```\n\n```text\nItemName : 'gizmo'\n```\n\n```text\nquery {\n Customer(filter: {\n orders_some: {\n orderLines_some: {\n item: {\n itemName: \"gizmo\"\n }\n }\n }\n }) {\n Name\n Orders {\n OrderId\n Date\n OrderLines { \n ItemCount\n ItemName\n }\n }\n }\n}\n```\n\n```text\norders_some: {\n orderLines_some: {\n item: {\n itemName: \"gizmo\"\n }\n }\n}\n```\n\n```text\nquery {\n Customer(filter: {\n orders_none: {\n orderLines_some: {\n item: {\n itemName: \"gizmo\"\n }\n }\n }\n }) {\n Name\n Orders {\n OrderId\n Date\n OrderLines { \n ItemCount\n ItemName\n }\n }\n }\n}\n```\n\n```text\nquery {\n Customer(filter: {\n orders_every: {\n orderLines_some: {\n item: {\n itemName: \"gizmo\"\n }\n }\n }\n }) {\n Name\n Orders {\n OrderId\n Date\n OrderLines { \n ItemCount\n ItemName\n }\n }\n }\n}\n```\n\n```text\nevery\n```\n\n```text\nsome\n```\n\n```text\nnone\n```\n\n========================================\n\nComments:\n- I actually thought about *hierarchical* filters at the top level (or at all levels), in order to have the full context when resolving types - but was afraid this may be abusing it. Your explanation and link are awesome!","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":319,"estimatedTokens":1221}}765{"id":"stack-41201405","source":"stackoverflow","questionId":41201405,"title":"How to build a GraphQL API on top of a Django/Elasticsearch/MySQL backend?","tags":["python","django","elasticsearch","graphql","graphene-python"],"text":"Title: How to build a GraphQL API on top of a Django/Elasticsearch/MySQL backend?\nTags: python, django, elasticsearch, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI'm looking into develop a GraphQL API. I have a django/elasticsearch/mysql backend and I'm figuring out how GraphQL fits into this picture. \n\nI reading about the graphene-django project but it seems tightly coupled with the Django ORM, so I'm wondering if elasticsearch can fits in this recipe.\n\nI'm just starting this research so there is a chance that even this question is making no sense.\n\nAny clue about how to do this?\n\n========================================\n\nTop Answer:\nSome attempts are started at https://pypi.org/project/graphene-elastic/\n\nYet, still alpha.\n\n========================================\n\nComments:\n- Can you tell how to set the schema for elasticsearch so I can query using graphql.","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":24,"estimatedTokens":222}}766{"id":"stack-46155137","source":"stackoverflow","questionId":46155137,"title":"How do I represent Neo4j relationship properties in my Graphql Schema?","tags":["neo4j","graphql","apollo-server"],"text":"Title: How do I represent Neo4j relationship properties in my Graphql Schema?\nTags: neo4j, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI have a Neo4j DB with relationships that have properties such as [:FRIENDS {since: \"11/2015\"}]. I need to represent the \"since\" property in the GraphQl Schema. RELAY has something call \"edges\" an apparently this is how they implement this feature but I am not using RELAY.....I didn't see anything in Apollo (maybe I missed it). Can someone show me how to do this?\n\n========================================\n\nCode:\n```text\n... memberOf : [Group]\n groupStatus : [MemberProfile]\n attended : [Meeting]\n submittedReport : [Report]\n post : [Post]\n\n}\n\ntype MemberProfile {\n name : String\n location : String\n created : String\n since : String\n role : String\n financial : Boolean\n active : Boolean\n }\n```\n\n```text\ngroupStatus(voter) {\n let session = driver.session(),\n params = { voterid: voter.voterid },\n query = `\n MATCH (v:Voter)-[r:MEMBER_OF]->(g:Group)\n WHERE v.voterid = $voterid\n RETURN g AS group,r AS rel;\n `\n return session\n .run(query, params)\n .then(result => {\n return result.records.map(record => {\n return Object.assign(record.get(\"group\").properties, record.get(\"rel\").properties)\n })\n })\n },\n```\n\n========================================\n\nComments:\n- I found the following well written blog that may lead to my answer....dev-blog.apollodata.com/…","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":53,"estimatedTokens":436}}767{"id":"stack-40547164","source":"stackoverflow","questionId":40547164,"title":"File Upload with Relay and graphql-dotnet","tags":["asp.net","asp.net-mvc","graphql","relayjs","graphql-dotnet"],"text":"Title: File Upload with Relay and graphql-dotnet\nTags: asp.net, asp.net-mvc, graphql, relayjs, graphql-dotnet\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a mutation within relay that includes a file. As soon as I implement the `getFiles()` method referenced here: https://facebook.github.io/relay/docs/api-reference-relay-mutation.html#getfiles\n\nRelay sends a multipart request causing a 415 error from ASP.NET Core MVC.\n\nI'm looking for a working example, similar to \"How would you do file uploads in a React-Relay app?\" with the graphql-dotnet library.\n\n========================================\n\nTop Answer:\nAre you just having trouble figuring out how to access the files in your resolver on the server? You can pass the files as your `rootObject` or `userContext`.\n\n```\n// GraphQLController\nvar files = Request.Form.Files;\nvar userContext = files;\n\nvar result = await executer.ExecuteAsync(\n schema,\n rootObject,\n query,\n operationName,\n inputs,\n userContext).ConfigureAwait(false);\n\n// Mutation type\nField(\n \"uploadFile\",\n arguments: new QueryArguments(new QueryArgument> {Name = \"fileName\"}),\n resolve: context =>\n {\n var userContext = context.UserContext.As();\n\n // process files\n\n // return data\n return \"success\";\n });\n```\n\n========================================\n\nCode:\n```text\ngetFiles()\n```\n\n```text\npublic class RelayResourceFilter : IResourceFilter\n{\n private readonly string jsonMediaType = \"application/json\";\n\n public void OnResourceExecuted(ResourceExecutedContext context)\n {\n }\n\n public void OnResourceExecuting(ResourceExecutingContext context)\n {\n\n\n if (!string.Equals(MediaTypeHeaderValue.Parse(context.HttpContext.Request.ContentType).MediaType,\n this.jsonMediaType, StringComparison.OrdinalIgnoreCase))\n {\n var encoder = JavaScriptEncoder.Create();\n var variables = encoder.Encode(context.HttpContext.Request.Form[\"variables\"]);\n var query = encoder.Encode(context.HttpContext.Request.Form[\"query\"]);\n var body = $\"{{\\\"query\\\":\\\"{query}\\\", \\\"variables\\\":\\\"{variables}\\\"}}\";\n\n byte[] requestData = Encoding.UTF8.GetBytes(body);\n context.HttpContext.Request.Body = new MemoryStream(requestData);\n context.HttpContext.Request.ContentType = this.jsonMediaType;\n }\n }\n}\n```\n\n```text\nservices.AddScoped<RelayResourceFilter>();\n```\n\n```text\n[ServiceFilter(typeof(RelayResourceFilter))]\n public async Task<ExecutionResult> Post([FromBody]GraphQLQuery query, bool? useErrorCode)\n{\nvar files = this.Request.HasFormContentType ? this.Request.Form.Files : null;\n// ... assignment to Root Object\n}\n```\n\n```text\n// GraphQLController\nvar files = Request.Form.Files;\nvar userContext = files;\n\nvar result = await executer.ExecuteAsync(\n schema,\n rootObject,\n query,\n operationName,\n inputs,\n userContext).ConfigureAwait(false);\n\n// Mutation type\nField<StringGraphType>(\n \"uploadFile\",\n arguments: new QueryArguments(new QueryArgument<NonNullGraphType<StringGraphType>> {Name = \"fileName\"}),\n resolve: context =>\n {\n var userContext = context.UserContext.As<IFormFileCollection>();\n\n // process files\n\n // return data\n return \"success\";\n });\n```\n\n```text\nrootObject\n```\n\n```text\nuserContext\n```\n\n========================================\n\nComments:\n- Thanks for the response Joe. I actually ended up writing a small ResourceFilter for the GraphQL endpoint:\n- How I can read query from his? In general I am reading like this `var request = JsonConvert.DeserializeObject(body);`. Then `request` is object which contains query. If I am uploading file content is not `application/json`.\n- @kat1330 I would look at the accepted answer. You need to check the media type. See also github.com/graphql-dotnet/relay/blob/master/src/GraphQL.Rela‌​y/…\n- @JoeMcBride Thanks. I prefer to use is middleware. Do you know which type is most suitable for mutation `QueryArgument` for file upload?\n- @kat1330 I'm not sure I fully understand your question (perhaps add an issue on the GraphQL .NET project with more info?) - but I think you're asking how you pass files as Query Arguments. Short answer is you can't. You'll have to access them via the User Context.","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":137,"estimatedTokens":1065}}768{"id":"stack-60561282","source":"stackoverflow","questionId":60561282,"title":"In GraphQL, can you change the structure of the output in an alias?","tags":["graphql"],"text":"Title: In GraphQL, can you change the structure of the output in an alias?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nLet's say I've got a GraphQL query that looks like this:\n\n```\nquery {\n Todo {\n label\n is_completed\n id\n }\n}\n```\n\nBut the client that consumes the data from this query needs a data structure that's a bit different- e.g. a TypeScript interface like:\n\n```\ninterface Todo {\n title: string // \"title\" is just a different name for \"label\"\n data: {\n is_completed: boolean\n id: number\n }\n}\n```\n\nIt's easy enough to just use an alias to return `label` as `title`. But is there any way to make it return both `is_completed` and `id` under an alias called `data`?\n\n========================================\n\nCode:\n```text\nquery {\n Todo {\n label\n is_completed\n id\n }\n}\n```\n\n```text\ninterface Todo {\n title: string // \"title\" is just a different name for \"label\"\n data: {\n is_completed: boolean\n id: number\n }\n}\n```\n\n```text\nlabel\n```\n\n```text\ntitle\n```\n\n```text\nis_completed\n```\n\n```text\nid\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- what client? apollo? data fetched by apollo can be easily converted to [react component] desired format f.e. using some wrapper/HOC\n- Related: stackoverflow.com/questions/56444837/…","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":79,"estimatedTokens":322}}769{"id":"stack-45390076","source":"stackoverflow","questionId":45390076,"title":"valid GitHub api v4 query keeps returning error \"Problems parsing JSON\"","tags":["curl","graphql","github-api","github-graphql"],"text":"Title: valid GitHub api v4 query keeps returning error \"Problems parsing JSON\"\nTags: curl, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nHere is an example of a cURL query to the GitHub api v4 that keeps returning an error:\n\n```\ncurl -H \"Authorization: bearer token\" -X POST -d \" \\\n { \\\n \\\"query\\\": \\\"query { repositoryOwner(login: \\\"brianzelip\\\") { id } }\\\" \\\n } \\\n\" https:\\/\\/api.github.com\\/graphql\n```\n\nThe error that is returned:\n\n```\n{\n \"message\": \"Problems parsing JSON\",\n \"documentation_url\": \"https://developer.github.com/v3\"\n}\n```\n\n**Why do I keep getting this error?**\n\nAccording to the GH api v4 docs about forming query calls, the above cURL command is valid. Here's what the docs say that backs up my claim that the above cURL command is valid:\n\n```\ncurl -H \"Authorization: bearer token\" -X POST -d \" \\\n { \\\n \\\"query\\\": \\\"query { viewer { login }}\\\" \\\n } \\\n\" https://api.github.com/graphql\n```\n\n Note: The string value of \"query\" must escape newline characters or\n the schema will not parse it correctly. For the POST body, use outer\n double quotes and escaped inner double quotes.\n\nWhen I enter the above query into the GitHub GraphQL API Explorer, I get the expected result. The format of the above cURL command looks like this for the GH GraphQL Explorer:\n\n```\n{\n repositoryOwner(login: \"brianzelip\") {\n id\n }\n}\n```\n\n========================================\n\nCode:\n```sh\ncurl -H \"Authorization: bearer token\" -X POST -d \" \\\n { \\\n \\\"query\\\": \\\"query { repositoryOwner(login: \\\"brianzelip\\\") { id } }\\\" \\\n } \\\n\" https:\\/\\/api.github.com\\/graphql\n```\n\n```text\n{\n \"message\": \"Problems parsing JSON\",\n \"documentation_url\": \"https://developer.github.com/v3\"\n}\n```\n\n```sh\ncurl -H \"Authorization: bearer token\" -X POST -d \" \\\n { \\\n \\\"query\\\": \\\"query { viewer { login }}\\\" \\\n } \\\n\" https://api.github.com/graphql\n```\n\n```text\n{\n repositoryOwner(login: \"brianzelip\") {\n id\n }\n}\n```\n\n```text\n{\n \"query\": \"query { repositoryOwner(login: \\\"brianzelip\\\") { id } }\"\n}\n```\n\n```sh\ncurl -H \"Authorization: bearer token\" -d \" \\\n { \\\n \\\"query\\\": \\\"query { repositoryOwner(login: \\\\\\\"brianzelip\\\\\\\") { id } }\\\" \\\n } \\\n\" https://api.github.com/graphql\n```\n\n```sh\ncurl -H \"Authorization: bearer token\" -d '\n {\n \"query\": \"query { repositoryOwner(login: \\\"brianzelip\\\") { id } }\"\n }\n' https://api.github.com/graphql\n```\n\n```sh\ncurl -H \"Authorization: bearer token\" -d @- https://api.github.com/graphql <<EOF\n{\n \"query\": \"query { repositoryOwner(login: \\\"brianzelip\\\") { id } }\"\n}\nEOF\n```\n\n```text\nquery\n```\n\n```text\n\\\"brianzelip\\\"\n```\n\n```text\n\\\\\\\"brianzelip\\\\\\\"\n```\n\n========================================\n\nComments:\n- Isn't it awesome how GraphQL Explore parses the JSON correctly, but when using the API using the exact same query it's problematic.\n- How to support multiple Query schema ?. My query schema as { viewer { login } codesOfConduct { body id key name resourcePath url }","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":131,"estimatedTokens":731}}770{"id":"stack-48155693","source":"stackoverflow","questionId":48155693,"title":"How to query pull request by number, using Github's v4 GraphQL API?","tags":["github","graphql","github-api","github-graphql"],"text":"Title: How to query pull request by number, using Github's v4 GraphQL API?\nTags: github, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI can query the *first* pull request like this:\n\n```\nquery {\n repository(owner: \"test_owner\", name: \"test_name\") {\n pullRequests(first: 1) {\n nodes {\n id\n number\n title\n }\n }\n }\n}\n```\n\nBut how do I query a certain pull request based on its `number`?\n\nThe following doesn't work:\n\n```\nquery {\n repository(owner: \"test_owner\", name: \"test_name\") {\n pullRequests(first: 1, number: 50) { Thanks for any help!\n\n========================================\n\nCode:\n```text\nquery {\n repository(owner: \"test_owner\", name: \"test_name\") {\n pullRequests(first: 1) {\n nodes {\n id\n number\n title\n }\n }\n }\n}\n```\n\n```text\nquery {\n repository(owner: \"test_owner\", name: \"test_name\") {\n pullRequests(first: 1, number: 50) { <-- CANNOT FILTER BY `number`\n nodes {\n id\n number\n title\n }\n }\n }\n}\n```\n\n```text\nnumber\n```\n\n```graphql\n{\n repository(owner: \"nodejs\", name: \"node\") {\n pullRequest(number: 2) {\n id\n number\n title\n }\n }\n}\n```\n\n```text\npullRequest\n```\n\n```text\npullRequests\n```\n\n========================================\n\nComments:\n- Compared to a `pullRequests` (with an s at the end) query, you just need to remove the `edges` and `node` outer clauses, all the `node` fields apply.","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":89,"estimatedTokens":357}}771{"id":"stack-65661743","source":"stackoverflow","questionId":65661743,"title":"Apollo client queries and data store when connected to multiple components","tags":["javascript","react-native","graphql","apollo-client"],"text":"Title: Apollo client queries and data store when connected to multiple components\nTags: javascript, react-native, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have 3 different components that use the same graphql query. This example would be `GET_USERS` query. This is used when looking for users to message in the messaging respective tab and also when inviting users for actions and tagging them when creating posts.\n\nthe problem I'm having and trying to figure out how to handle is that its not always the case that only one is rendered at a time. A user might click the message tab and then go to tag a user in the post tab. **Problem**: when he comes back to the message tab it now has re-rendered with the state of the query that was called from the tagging.\n\nAny suggestions on how to set up the state with Apollo and the queries in general to avoid this issue. At the end of the day my backend is one \"route\" or `resolve` function for the specific action.\n\n**EDIT**\nFor further information. The way I know I could solve it is to use axios request to the graphql endpoint and store the response in local `useState` for that component. If I did this for each of the different places in the app that use the information they would remain decoupled and not the exact same state.\n\nBut to be clear I am trying to solve this while using Apollo if possible.\n\n========================================\n\nCode:\n```text\nGET_USERS\n```\n\n```text\nresolve\n```\n\n```text\nuseState\n```\n\n```text\nexport const useLazyGetUsers = () => {\n const [users, setUsers] = useState()\n\n const [queryGetUsers] = useLazyQuery(GET_USERS, {\n onCompleted: (data) => setUsers(data.users),\n onError: (error) => console.log('onError', { error }), // handle errors as you wish\n fetchPolicy: \"cache-and-network\", // or whatever you want\n })\n\n return {queryGetUsers, users}\n}\n```\n\n```text\nconst ScreenA = () => {\n const {queryGetUsers, users} = useLazyGetUsers()\n \n return (\n <TouchableOpacity onPress={() => queryGetUsers()}>\n <Text>Get users</Text>\n </TouchableOpacity>\n )\n}\n```\n\n```text\nconst ScreenB = () => {\n const {queryGetUsers, users} = useLazyGetUsers()\n \n useEffect(() => {\n queryGetUsers()\n }, [])\n\n return (\n ...\n )\n}\n```\n\n```text\nqueryGetUsers\n```\n\n```text\nusers\n```\n\n```text\nqueryGetUsers\n```\n\n```text\nusers\n```\n\n```text\nuseLazyQuery\n```\n\n========================================\n\nComments:\n- simply use `cache-only` fetchPolicy in queries/components you want to not affect 'main source of truth' ?\n- Do you know how to resolve the same issue when we have not separated but the map of the same reusable component? screens.map(screen => )\n- @Julia not sure what you are talking about. Maybe post a question with more details and tag it here, then I can take a look.","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":97,"estimatedTokens":699}}772{"id":"stack-56223625","source":"stackoverflow","questionId":56223625,"title":"Passing argument to react-apollo-hooks useQuery","tags":["reactjs","graphql","react-hooks"],"text":"Title: Passing argument to react-apollo-hooks useQuery\nTags: reactjs, graphql, react-hooks\nSource: Stack Overflow\n\nQuestion:\nHow can I pass an argument to useQuery when using react-apollo-hook?\n\nThis does not work: \n\n```\nconst { data, loading, error } = useQuery(GET_DATA,\n{ variables: { id: 'testId' }});\n```\n\nAnd the query itself:\n\n```\nexport const GET_DATA = gql`\n{ query ($id: String) {\n document(id: $uid) {\n uid\n } \n }\n}\n`;\n```\n\n========================================\n\nCode:\n```text\nconst { data, loading, error } = useQuery(GET_DATA,\n{ variables: { id: 'testId' }});\n```\n\n```text\nexport const GET_DATA = gql`\n{ query ($id: String) {\n document(id: $uid) {\n uid\n } \n }\n}\n`;\n```\n\n```text\nquery ($id: String) {\n document(id: $id) {\n uid\n }\n}\n```\n\n```text\nuid\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- What is the error? Please provide a stacktrace.\n- You can see the actual response from your server in the network tab of your browser's dev tools. If your query is not valid, this will show the validation errors, which will help you troubleshoot your issue. You can search SO for the same error messages, but if you need to open a new question, you should include these errors in your question to help both answerers and future searchers.","metadata":{"transformedAt":"2026-08-18T18:32:36.081Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":67,"estimatedTokens":322}}773{"id":"stack-75864886","source":"stackoverflow","questionId":75864886,"title":"How to resolve type from another subgraph in a Apollo GraphQL federated schema?","tags":["javascript","node.js","graphql","apollo","apollo-federation"],"text":"Title: How to resolve type from another subgraph in a Apollo GraphQL federated schema?\nTags: javascript, node.js, graphql, apollo, apollo-federation\nSource: Stack Overflow\n\nQuestion:\nI have an Order subgraph and a Menu subgraph. The order subgraph returns customers orders and the Menu subgraph return information about menu's and the menu items.\n\nWhen I fetch an order, I want the order data returned from the Order subgraph but then any correlated item information such as price and name etc needs to be resolved from the Menu subgraph.\n\nMy schema's are as follows:\n\n```\n// Order subgraph\ntype Order @key(fields: \"id\") {\n id: ID!\n item: MenuItem! // MenuItem type exists in the Menu subgraph\n}\n```\n\n```\n// Menu subgraph\ntype MenuItem @key(fields: \"id\") {\n id: ID!\n name: String!\n price Float!\n}\n```\n\nWhen I start my Order subgraph, I get the error: `Error: Unknown type: \"MenuItem\".`.\n\nSounds like I might be able to use `@external` or `@provides` directives in order to tell my subgraph that the types exist in another subgraph but I can't seem to get it to work.\n\nHow can I types across subgraphs and how does the data resolve from one to another?\n\n========================================\n\nCode:\n```text\n// Order subgraph\ntype Order @key(fields: \"id\") {\n id: ID!\n item: MenuItem! // MenuItem type exists in the Menu subgraph\n}\n```\n\n```text\n// Menu subgraph\ntype MenuItem @key(fields: \"id\") {\n id: ID!\n name: String!\n price Float!\n}\n```\n\n```text\nError: Unknown type: \"MenuItem\".\n```\n\n```text\n@external\n```\n\n```text\n@provides\n```\n\n```text\ntype Order @key(fields: \"id\") {\n id: ID!\n item: MenuItem! // MenuItem type exists in the Menu subgraph\n}\n\ntype MenuItem @key(fields: \"id\", resolvable: false) {\n id: ID!\n}\n```\n\n```js\nfunction orderById(orderId) {\n // ...content...\n returns {\n // ...order information...\n menuItem: {\n id: menuItemID\n }\n }\n}\n```\n\n```js\n// Order resolvers\nconst resolvers = {\n Query: {\n orderById: ...\n }\n Order: {\n menuItem: ({menuItem}: Order) => {\n return {id: menuItem.id}\n }\n }\n}\n```\n\n```text\ntype MenuItem @key(fields: \"id\") @shareable {\n id: ID!\n name: String!\n price Float!\n}\n```\n\n```js\n// Menu resolvers\nconst resolvers = {\n Query: {\n menuItemByID: ...\n }\n MenuItem: {\n __resolveReference: ({id}: MenuItem,{dataSources}: ServerContext) => {\n return dataSources.menuItemAPI.menuItemByID(id)\n }\n }\n}\n```\n\n```text\nMenuItems\n```\n\n```text\nMenu\n```\n\n```text\nOrders\n```\n\n```text\nOrder\n```\n\n```text\nMenuItem\n```\n\n```text\n@provides\n```\n\n```text\n@external\n```\n\n```text\nMenuItem\n```\n\n```text\nOrder\n```\n\n```text\nOrder\n```\n\n```text\norderById\n```\n\n```text\nMenu\n```\n\n```text\nOrder\n```\n\n```text\nmenuItem\n```\n\n```text\nMenu\n```\n\n```text\nOrder\n```\n\n```text\nMenu\n```\n\n```text\n__resolveReference\n```\n\n```text\nMenu\n```\n\n```text\nOrder\n```\n\n```text\nmenuItem\n```\n\n```text\nOrder\n```\n\n```text\nMenu\n```\n\n```text\nmenuItem\n```\n\n========================================\n\nComments:\n- @shareable entity is not required for this case","metadata":{"transformedAt":"2026-08-18T18:32:36.082Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":34,"totalLines":225,"estimatedTokens":759}}774{"id":"stack-52710372","source":"stackoverflow","questionId":52710372,"title":"Include relationship when querying node using Prisma generated wrapper","tags":["graphql","prisma","plumatic-schema","prisma-graphql"],"text":"Title: Include relationship when querying node using Prisma generated wrapper\nTags: graphql, prisma, plumatic-schema, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI am following the GraphQL Prisma Typescript example provided by Prisma and created a simple data model, generated the code for the Prisma client and resolvers, etc.\n\nMy data model includes the following nodes:\n\n```\ntype User {\n id: ID! @unique\n displayName: String!\n}\n\ntype SystemUserLogin {\n id: ID! @unique\n username: String! @unique\n passwordEnvironmentVariable: String!\n user: User!\n}\n```\n\nI've seeded with a system user and user.\n\n```\nmutation {\n systemUserLogin: createSystemUserLogin({\n data: {\n username: \"SYSTEM\",\n passwordEnvironmentVariable: \"SYSTEM_PASSWORD\",\n user: {\n create: {\n displayName: \"System User\"\n }\n }\n }\n })\n}\n```\n\nI've created a sample mutation `login`:\n\n```\nlogin: async (_parent, { username, password }, ctx) => {\n let user\n const systemUser = await ctx.db.systemUserLogin({ username })\n const valid = systemUser && systemUser.passwordEnvironmentVariable && process.env[systemUser.passwordEnvironmentVariable] &&(process.env[systemUser.passwordEnvironmentVariable] === password)\n\n if (valid) {\n user = systemUser.user // this is always undefined!\n }\n\n if (!valid || !user) {\n throw new Error('Invalid Credentials')\n }\n\n const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)\n\n return {\n token,\n user: ctx.db.user({ id: user.id }),\n }\n },\n```\n\nBut no matter what I do, `systemUser.user` is ALWAYS undefined!\n\nThis makes sense - how would the client wrapper know how \"deep\" to recurse into the graph without me telling it?\n\nBut how can I tell it that I want to include the `User` relationship?\n\n### Edit: I tried the suggestion below to use `prisma-client`.\n\nBut none of my resolvers ever seem to get called...\n\n```\nexport const SystemUserLogin: SystemUserLoginResolvers.Type = {\n id: parent => parent.id,\n user: (parent, args, ctx: any) => {\n console.log('resolving')\n return ctx.db.systemUserLogin({id: parent.id}).user()\n },\n environmentVariable: parent => parent.environmentVariable,\n systemUsername: parent => parent.systemUsername,\n createdAt: parent => parent.createdAt,\n updatedAt: parent => parent.updatedAt\n};\n```\n\nAnd...\n\n```\nlet identity: UserParent;\n\n const systemUserLogins = await context.db.systemUserLogins({\n where: {\n systemUsername: user,\n }\n });\n const systemUserLogin = (systemUserLogins) ? systemUserLogins[0] : null ;\n\n if (systemUserLogin && systemUserLogin.environmentVariable && process.env[systemUserLogin.environmentVariable] && process.env[systemUserLogin.environmentVariable] === password) {\n console.log('should login!')\n\n identity = systemUserLogin.user; // still null\n }\n```\n\n### Edit 2: Here is the repository\n\nhttps://github.com/jshin47/annotorious/tree/master/server\n\n========================================\n\nTop Answer:\nSecond parameter of prisma binding functions accept GraphQL query string. Changing following line from\n\n```\nconst systemUser = await ctx.db.query.systemUserLogin({ username })\n```\n\nto\n\n```\nconst systemUser = await ctx.db.query.systemUserLogin({ username }, `{id username user {id displayName}}`)\n```\n\nwill give you the data of user.\n\nPrisma binding will return only direct properties of model in case second parameter is not passed to it.\n\n========================================\n\nCode:\n```text\ntype User {\n id: ID! @unique\n displayName: String!\n}\n\ntype SystemUserLogin {\n id: ID! @unique\n username: String! @unique\n passwordEnvironmentVariable: String!\n user: User!\n}\n```\n\n```text\nmutation {\n systemUserLogin: createSystemUserLogin({\n data: {\n username: \"SYSTEM\",\n passwordEnvironmentVariable: \"SYSTEM_PASSWORD\",\n user: {\n create: {\n displayName: \"System User\"\n }\n }\n }\n })\n}\n```\n\n```text\nlogin: async (_parent, { username, password }, ctx) => {\n let user\n const systemUser = await ctx.db.systemUserLogin({ username })\n const valid = systemUser && systemUser.passwordEnvironmentVariable && process.env[systemUser.passwordEnvironmentVariable] &&(process.env[systemUser.passwordEnvironmentVariable] === password)\n\n if (valid) {\n user = systemUser.user // this is always undefined!\n }\n\n if (!valid || !user) {\n throw new Error('Invalid Credentials')\n }\n\n const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)\n\n return {\n token,\n user: ctx.db.user({ id: user.id }),\n }\n },\n```\n\n```text\nexport const SystemUserLogin: SystemUserLoginResolvers.Type<TypeMap> = {\n id: parent => parent.id,\n user: (parent, args, ctx: any) => {\n console.log('resolving')\n return ctx.db.systemUserLogin({id: parent.id}).user()\n },\n environmentVariable: parent => parent.environmentVariable,\n systemUsername: parent => parent.systemUsername,\n createdAt: parent => parent.createdAt,\n updatedAt: parent => parent.updatedAt\n};\n```\n\n```text\nlet identity: UserParent;\n\n const systemUserLogins = await context.db.systemUserLogins({\n where: {\n systemUsername: user,\n }\n });\n const systemUserLogin = (systemUserLogins) ? systemUserLogins[0] : null ;\n\n if (systemUserLogin && systemUserLogin.environmentVariable && process.env[systemUserLogin.environmentVariable] && process.env[systemUserLogin.environmentVariable] === password) {\n console.log('should login!')\n\n identity = systemUserLogin.user; // still null\n }\n```\n\n```text\nlogin\n```\n\n```text\nsystemUser.user\n```\n\n```text\nUser\n```\n\n```text\nprisma-client\n```\n\n```text\ntype SystemUserLogin {\n id: ID! @unique\n username: String! @unique\n passwordEnvironmentVariable: String!\n user: User! # GraphQL doesn't know how to resolve this\n}\n```\n\n```text\nconst resolvers = {\n SystemUserLogin: {\n user(parent, args, ctx) {\n return ctx.db.systemUserLogin({id: parent.id}).user()\n }\n } \n}\n```\n\n```text\n$fragment\n```\n\n```text\nuser\n```\n\n```text\nSystemUserLogin\n```\n\n```text\nauthor\n```\n\n```text\nposts\n```\n\n```text\nconst systemUser = await ctx.db.query.systemUserLogin({ username })\n```\n\n```text\nconst systemUser = await ctx.db.query.systemUserLogin({ username }, `{id username user {id displayName}}`)\n```\n\n========================================\n\nComments:\n- I was really hoping this sort of thing would work, but I tried and it doesn't, and the method's interface suggests that it only accepts one parameter anyway: `systemUserLogin: (where: SystemUserLoginWhereUniqueInput) => SystemUserLogin;`\n- And `ctx.db.query` is `undefined`\n- Are you setting `db` in context while initialising your server?\n- Yes, but I was importing the wrong `Prisma`, I guess... `import {Prisma} from \"./generated/prisma\";` works, `import {Prisma} from \"./generated/prisma-client\";` doesnt\n- There are two ways to query data from Prisma. You can either use `prisma-binding` or `prisma-client`. My answer uses `prisma-binding`. For `prisma-client`, this is how relationships are queried: prisma.io/docs/prisma-client/basic-data-access/…\n- Sorry for the confusion around Prisma client and Prisma bindings. Hope my answer helps π\n- Thank you for the detailed answer. I was wondering what the difference was! I have found the documentation to be wanting, so this really helps.\n- I tried your suggestion using `prisma-client` and it seems like my resolver is never actually called, so I am still unable to get it to work with `prisma-client`\n- Hmm this is strange! Did you double check that the resolvers are actually passed to your GraphQL server? Normally when a query is resolved, the resolvers for *all* fields inside the query should be called! So if you're sending a query that uses the `user` of `SystemUserLogin` the `user` resolver should get called. If no, there might be an issue somewhere else!\n- Were you able to resolve the issue in the meantime @tacos_tacos_tacos? Is the resolver still not called?\n- The resolver is still not called... tonight when I get home I will copy and paste the code from the entry point on down... Any ideas?\n- Do you maybe have a link to a GitHub repo so I can reproduce the issue? Currently it's difficult for me to tell where the error is since my understanding is that the resolver *should* be called. So I believe the point we need to investigate is why it is not called.\n- any idea about what's going wrong with my example? I provided a link to repo","metadata":{"transformedAt":"2026-08-18T18:32:36.082Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":298,"estimatedTokens":2084}}775{"id":"stack-41434241","source":"stackoverflow","questionId":41434241,"title":"How to design the following resolver for GraphQL server?","tags":["javascript","graphql","graphql-js","apollo-server"],"text":"Title: How to design the following resolver for GraphQL server?\nTags: javascript, graphql, graphql-js, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am using react-apollo on meteor with mysql and sequelize, I am still a beginner in JS.\nLets assume I have the following resolver function on my apollo-server:\n\n```\nexport default resolvers = {\n Query: {\n posts(_, args){\n return Post.findAndCountAll({ where: args });\n },\n numberOfPosts(){\n return /// the number of selected posts\n }\n }\n```\n\nI would like to select some data from the database where some conditions are met and then count the amount of selected rows and return them in the field \"numberOfPosts\".\n`findAndCountAll()` returns an object, which contains the selected rows and the count. I would like to get my `post()` to return only the selected rows, and my numberOfPosts() to return only the count of the selected posts. Right now, both is returned by posts().\n\n**My schema is:**\n\n```\ntype Post {\n id: Int\n date: Float\n text: String\n}\n\n type NumberOfPosts{\n total: Int\n filtered: Int\n}\n\ntype Query {\n posts(\n id: Ind,\n offset: Int,\n limit: Int,\n filter: String): [Post]\n numberOfPosts:[NumberOfPosts] \n}\n\nschema {\n query: Query\n}\n```\n\n**The Goal is to receive data in the following format:**\n\n```\n{\n \"data\": {\n \"numberOfPosts\": [\n {\n \"total\": 1000,\n \"filtered\": 21\n }\n ],\n \"posts\": [\n {\n \"id\": 4,\n \"date\": 5105626122,\n \"text\": \"jzybiwutudi\"\n },\n ...\n ]\n }\n}\n```\n\nMy work so far:\nTry 1:\n\n```\nlet selectedCount;\nexport default resolvers = {\n Query: {\n posts(_, args){\n return Post.findAndCountAll({where: args}).then(\n function (results) {\n selectedCount = results.count;\n return results.rows\n });\n },\n numberOfPosts(){\n return selectedCount\n }\n }}\n```\n\nSo I am defining a helping variable outside of resolvers, and set it to the number of selected rows, then the count is returned in `numberOfPosts()`, which works, but the problem with this is, `return results.rows` causes an error, and I do not understand why.\n\nanother issue is, that `selectedCount` is always the previous number of rows\n\n**Try 2**\n\nAnother solution that seems to work is to Pass the arguments twice into the GraphQL query, like so:\n\n```\n{\n numberOfPosts(filter: \"example\") {\n total\n filtered\n }\n posts(filter: \"example\") {\n id\n date\n text\n }\n}\n```\n\nThen both resolver functions know the same arguments, so I can select and count the same posts. But this looks not right to me, since I have to pass the same args twice, they will also be transmitted twice...\n\n========================================\n\nCode:\n```text\nexport default resolvers = {\n Query: {\n posts(_, args){\n return Post.findAndCountAll({ where: args });\n },\n numberOfPosts(){\n return /// the number of selected posts\n }\n }\n```\n\n```text\ntype Post {\n id: Int\n date: Float\n text: String\n}\n\n type NumberOfPosts{\n total: Int\n filtered: Int\n}\n\ntype Query {\n posts(\n id: Ind,\n offset: Int,\n limit: Int,\n filter: String): [Post]\n numberOfPosts:[NumberOfPosts] \n}\n\nschema {\n query: Query\n}\n```\n\n```text\n{\n \"data\": {\n \"numberOfPosts\": [\n {\n \"total\": 1000,\n \"filtered\": 21\n }\n ],\n \"posts\": [\n {\n \"id\": 4,\n \"date\": 5105626122,\n \"text\": \"jzybiwutudi\"\n },\n ...\n ]\n }\n}\n```\n\n```text\nlet selectedCount;\nexport default resolvers = {\n Query: {\n posts(_, args){\n return Post.findAndCountAll({where: args}).then(\n function (results) {\n selectedCount = results.count;\n return results.rows\n });\n },\n numberOfPosts(){\n return selectedCount\n }\n }}\n```\n\n```text\n{\n numberOfPosts(filter: \"example\") {\n total\n filtered\n }\n posts(filter: \"example\") {\n id\n date\n text\n }\n}\n```\n\n```text\nfindAndCountAll()\n```\n\n```text\npost()\n```\n\n```text\nnumberOfPosts()\n```\n\n```text\nreturn results.rows\n```\n\n```text\nselectedCount\n```\n\n```text\ntype Post {\n id: Int\n date: Float\n text: String\n}\n\ntype PostList {\n total: Int\n filtered: Int\n posts: [Post]\n}\n\ntype Query {\n posts(\n id: Ind,\n offset: Int,\n limit: Int,\n filter: String): PostList\n}\n\nschema {\n query: Query\n}\n```\n\n```text\nposts(_, args) {\n return Post.findAndCountAll({ where: args }).then(result => {\n return {\n total: 1000,\n filtered: result.count,\n posts: result.rows\n }\n })\n}\n```\n\n```text\nposts(_, args) {\n return Promise.all([\n Post.count(),\n Post.findAndCountAll({ where: args })\n ]).then(data => {\n return {\n total: data[0],\n filtered: data[1].count,\n posts: data[1].rows\n }\n })\n}\n```\n\n```text\nposts(_, args) {\n return Promise.all([\n Post.count(),\n Post.findAndCountAll({ where: args })\n ]).then(([totalCount, filteredData]) => {\n return {\n total: totalCount,\n filtered: filteredData.count,\n posts: filteredData.rows\n }\n })\n}\n```\n\n```text\nquery {\n posts(filter:\"example\") {\n total\n filtered\n posts {\n id\n date\n text\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"posts\": {\n \"total\": 1000,\n \"filtered\": 21,\n \"posts\": [\n {\n \"id\": 4,\n \"date\": 5105626122,\n \"text\": \"jzybiwutudi\"\n },\n ...\n ]\n }\n }\n}\n```\n\n```text\ntotal\n```\n\n```text\nfiltered\n```\n\n```text\nNumberOfPosts\n```\n\n```text\nposts\n```\n\n```text\nfindAndCountAll\n```\n\n```text\nPromise.all\n```\n\n========================================\n\nComments:\n- i don't know anything about `react-apollo`, but I would highly recommend NOT creating a `selectedCount` variable where one query would assign the result for another query\n- thank you, do you have any tips how to pass the result to the other query?\n- i'm taking it that these are two independent queries and not two related fields on one query?\n- it seems like these resolver methods correspond directly with your schema. can you update your question and post an example of what that looks like? If your `rootValue` has a field name `numberOfPosts` being returned already, then you don't need to add this resolver. Would it make more sense to design the db to always have a field that contains that value instead?\n- Maybe, but I don't know how to do that yet. I have edited my Question, please take a look at it again.\n- Thank you, very good answer. I would like to add that Post.findAndCountAll already returns the count of rows, so instead of filteredData.rows.length one could simply use filteredData.count.\n- Oh I meant to do that as well. Updated answer for future references :) I'm glad it helped.\n- Btw. ist this the same as your solution with promise all?: posts(_, args) { return Post.findAndCountAll({ where: args }).then(data => { return { total: Post.count(), filtered: data[1].count, posts: data[1].rows } }) } I mean will the return wait till Post.count() returns the value? Or is it more safe to use a Promise.all? Because it works like this too...\n- @henk if you chain those promises, the second one would wait for the first one to be resolved first. As those two are independent, we can parallelize them, and use `Promise.all` to wait for both to be finished. Yours works too I believe, it is just more performant in this case to parallelize them.\n- @henk and I believe, in your code, you don't need to use it like `data[1].`. just `data.` should be right.\n- `posts(_, args) {` here `posts` should be matched with graphql request param name as like here `query { posts(filter:\"example\") {` right ?\n- @AjayS yeah that function is the function that is passed to graphql as a `posts` resolver. The name of the function could be anything as long as it's tied to the `posts` in ` query { posts(filter:\"example\") }`.\n- Thank you so much! Was trying to figure out how to make the resolvers talk to each other for the count... then saw your solution. Turns out I just have to improve my schema. :)","metadata":{"transformedAt":"2026-08-18T18:32:36.082Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":372,"estimatedTokens":1980}}776{"id":"stack-62441400","source":"stackoverflow","questionId":62441400,"title":"Trouble migrating from graphql-import to just graphql-tools with ApolloServer, directives cease to work","tags":["node.js","graphql","apollo-server","graphql-tools","graphql-schema"],"text":"Title: Trouble migrating from graphql-import to just graphql-tools with ApolloServer, directives cease to work\nTags: node.js, graphql, apollo-server, graphql-tools, graphql-schema\nSource: Stack Overflow\n\nQuestion:\nMy plight began as a simple desire to expand my graphql schema from a single .graphql file to multiple files so i can better organize the schema and so it wouldn;t grow to one huge file out of control. \n\nMy original layout was very straight forward and i had a working schema in a `schema.graphql` file. I would be able to parse it into a string using `importSchema('server/schema.graphql')` from the graphql-import library, which is now deprecated https://github.com/ardatan/graphql-import\n\nThey mention that it has been merged into `graphql-tools` in the newest version and provide a migration tutorial here https://www.graphql-tools.com/docs/migration-from-import The tutorial seems very straight forward since their first example pretty much illustrate exactly what my code looks like (except i dont use es6 import but old fashoined require):\n\n```\nimport { importSchema } from 'graphql-import';\nimport { makeExecutableSchema } from 'graphql-tools';\n\nconst typeDefs = importSchema(join(__dirname, 'schema.graphql'));\nconst resolvers = {\n Query: {...}\n};\nconst schema = makeExecutableSchema({ typeDefs, resolvers });\n```\n\nAnd then they say to modify it, simply make these changes\n\n```\nimport { loadSchemaSync } from '@graphql-tools/load';\nimport { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';\nimport { addResolversToSchema } from '@graphql-tools/schema';\n\nconst schema = loadSchemaSync(join(__dirname, 'schema.graphql'), { loaders: [new GraphQLFileLoader()] });\nconst resolvers = { Query: {...} };\n\nconst schemaWithResolvers = addResolversToSchema({\n schema,\n resolvers,\n});\n```\n\nI made those changes but the vital difference is that they no longer use `makeExecutableSchema()` in their example, which is pretty important for me since i need to include the directives. What do i do now with the schema? How do i declare the directives? their documentation for directives still uses `makeExecutableSchema` but i cant use it anymore since the new `loadSchemaSync` function returns an object instead of a string literal which i would need to pass to `typeDefs` in `makeExecutableSchema`\n\nI am using apollo-server, so it seemed a possible workaround was to just declare the directives in the apollo-server constructor and just pass in this new `schemaWithResolvers` as a schema as such\n\n```\nconst server = new ApolloServer({\n schema, //this includes now the returned value of using addResolversToSchema()\n schemaDirectives : {\n auth:AuthDirective,\n authRole: AuthRoleDirective\n }\n context : ({req}) => //dostuff,\n\n});\n```\n\nThis allows my server to run, and i can perform queries and mutations, however, my directives are no longer working, and i no longer have authentication on protected queries. \n\nI would like a way to import my .graphql file and parse it into a string so i can use it inside `typeDefs` as i used to with importSchema() or a way to declase my directies without using makeExecutableSchema() so that they continue working again!\n\nI have gone up and down the documentation and seen other libraries and so far i keep coming up short, any tips or guidance is greatly appreciated\n\n========================================\n\nTop Answer:\nI tried this way but I couldn't solve the problem. A unique solution that managed to take the following approach:\n\n```\nconst { ApolloServer, makeExecutableSchema, gql} = require('apollo-server-express')\nconst { loadTypedefsSync } = require('@graphql-tools/load')\nconst { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader')\nconst path = require('path')\n\nconst sources = loadTypedefsSync(\n path.resolve(__dirname, '../schema/root.graphql'),\n { loaders: [new GraphQLFileLoader()] }\n)\nconst typeDefs = sources.map(source => source.document)\n```\n\n```\nconst schema = makeExecutableSchema({\n typeDefs: gql`${typeDefs[0]}`,\n resolvers,\n})\n```\n\n========================================\n\nCode:\n```text\nimport { importSchema } from 'graphql-import';\nimport { makeExecutableSchema } from 'graphql-tools';\n\nconst typeDefs = importSchema(join(__dirname, 'schema.graphql'));\nconst resolvers = {\n Query: {...}\n};\nconst schema = makeExecutableSchema({ typeDefs, resolvers });\n```\n\n```text\nimport { loadSchemaSync } from '@graphql-tools/load';\nimport { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';\nimport { addResolversToSchema } from '@graphql-tools/schema';\n\nconst schema = loadSchemaSync(join(__dirname, 'schema.graphql'), { loaders: [new GraphQLFileLoader()] });\nconst resolvers = { Query: {...} };\n\nconst schemaWithResolvers = addResolversToSchema({\n schema,\n resolvers,\n});\n```\n\n```text\nconst server = new ApolloServer({\n schema, //this includes now the returned value of using addResolversToSchema()\n schemaDirectives : {\n auth:AuthDirective,\n authRole: AuthRoleDirective\n }\n context : ({req}) => //dostuff,\n\n});\n```\n\n```text\nschema.graphql\n```\n\n```text\nimportSchema('server/schema.graphql')\n```\n\n```text\ngraphql-tools\n```\n\n```text\nmakeExecutableSchema()\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nloadSchemaSync\n```\n\n```text\ntypeDefs\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nschemaWithResolvers\n```\n\n```text\ntypeDefs\n```\n\n```text\nimport { loadTypedefsSync } from '@graphql-tools/load';\nimport { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';\nimport { addResolversToSchema } from '@graphql-tools/schema';\n\nconst sources = loadTypedefsSync(join(__dirname, 'schema.graphql'), { loaders: [new GraphQLFileLoader()] });\nconst documentNodes = sources.map(source => source.document);\nconst resolvers = { Query: {...} };\n\nconst schema = makeExecutableSchema({ typeDefs, resolvers });\n```\n\n```text\nimport { SchemaDirectiveVisitor } from \"@graphql-tools/utils\";\nimport { loadSchemaSync } from '@graphql-tools/load';\nimport { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';\nimport { addResolversToSchema } from '@graphql-tools/schema';\n\nconst schema = loadSchemaSync(join(__dirname, 'schema.graphql'), { loaders: [new GraphQLFileLoader()] });\nconst resolvers = { Query: {...} };\n\nconst schemaWithResolvers = addResolversToSchema({\n schema,\n resolvers,\n});\n\nSchemaDirectiveVisitor.visitSchemaDirectives(schemaWithResolvers, schemaDirectives);\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\ngraphql-tools\n```\n\n```text\nloadTypedefsSync\n```\n\n```text\nloadSchema\n```\n\n```text\nconst { ApolloServer, makeExecutableSchema, gql} = require('apollo-server-express')\nconst { loadTypedefsSync } = require('@graphql-tools/load')\nconst { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader')\nconst path = require('path')\n\nconst sources = loadTypedefsSync(\n path.resolve(__dirname, '../schema/root.graphql'),\n { loaders: [new GraphQLFileLoader()] }\n)\nconst typeDefs = sources.map(source => source.document)\n```\n\n```text\nconst schema = makeExecutableSchema({\n typeDefs: gql`${typeDefs[0]}`,\n resolvers,\n})\n```\n\n```text\nimport { addResolversToSchema, wrapSchema } from 'graphql-tools';\nimport { GraphQLSchema } from 'graphql';\nimport resolvers from './resolver';\n\nschema = loadSchemaSync('./**/*.graphql', {\n loaders: [new GraphQLFileLoader()],\n});\n\nconst schemaWithResolver = addResolversToSchema({\n schema,\n resolvers\n });\n\nconst { constraintDirective } = require('graphql-constraint-directive')\n \nconst schemaConstrain = wrapSchema({\n schema: schemaWithResolver,\n transforms: [constraintDirective()]\n})\n```\n\n```text\n.graphql\n```\n\n```text\nloadSchemaSync\n```\n\n```text\nwrapSchema\n```\n\n```text\n.graphql\n```\n\n========================================\n\nComments:\n- i cannot find loadTypedefsSync in the documentation anywhere, so not sure how you know about it but thanks! this solution worked for me!\n- So both solutions worked for me, so thanks, however, the first solution using loadTypedefsSync did not allow me to import multiple .graphql files and use the #import feature within the files, but the second approach did. Do you have an approach for using your first solution but still being able to import multiple `.graphql` files and use the #import feature within the files?\n- `loadSchema` uses `loadTypedefs` under the hood, so I would expect the behavior to be same with regard to the import syntax. You may want to open an issue against the repo with that question\n- how do you find out about these functions? loadTypedefs i cannot find in the documentation for graphql-tools and the repo for graphql-tools/load gave me a 404, do you straight up look at the source code?\n- If anyone tripped up trying solution #1 going from documentNodes to typeDefs, you need to import { concatAST } from \"graphql\" and then typeDefs = concatAST(documentNodes)\n- So far I haven't used *makeExcecutableSchema* since it seems I could avoid it. Here's my tweak to get Apollo running: **typeDefs = sources.map(source => source.document); new ApolloServer({ typeDefs, resolvers, ... })**\n- `documentNodes` in the first solution should be `typeDefs`\n- When using the second approach, how do I create schemaDirectives var from a DocumentNode object containing the directive declarations?\n- In the first example you aren't even including the schema directives.\n- You don't need to use wrapSchema. It is not ideal. It adds an additional delegation step which might have performance implications please graphql-constraint-directive docs for this. We don't use wrapSchema in any of examples about directives in GraphQL Tools documentation.","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":281,"estimatedTokens":2400}}777{"id":"stack-32588021","source":"stackoverflow","questionId":32588021,"title":"How do you define a relay connection for pagination against an ORM?","tags":["javascript","node.js","graphql","relayjs","graphql-js"],"text":"Title: How do you define a relay connection for pagination against an ORM?\nTags: javascript, node.js, graphql, relayjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI've looked through all of Relay's documentation and there doesn't seem to be a straightforward explanation on how to build a Relay connection with an ORM. All the examples seem to use the `connectionFromArray` method which is fine if you're storing your data in memory but when you're storing the data in a database how would you go about providing the information necessary for a connection's pagination to work?\n\n========================================\n\nCode:\n```text\nconnectionFromArray\n```\n\n```text\nWHERE id > ?\n```\n\n========================================\n\nComments:\n- Thanks for the links, they helped a lot! If I can clean up this code I put together maybe I'll post it here for future reference.","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":22,"estimatedTokens":218}}778{"id":"stack-34406667","source":"stackoverflow","questionId":34406667,"title":"Relay Pagination: How to initialize \"after\" value?","tags":["pagination","reactjs","relayjs","graphql","graphql-js"],"text":"Title: Relay Pagination: How to initialize \"after\" value?\nTags: pagination, reactjs, relayjs, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nSo based on this comment here, I've been able to hack together a simple \"paginating\" component/container: https://github.com/facebook/graphql/issues/4#issuecomment-118162627\n\nI say \"hack\" because that's just what I did. \n\nI got it to work by taking a look at the edge cursors on the `/graphql` response in my browser. Problem is.. how do I make this work for the *first* \"page\" of items, when I have no \"prior query\" to work from?\n\nI tried leaving `after` as `undefined` in my query, but I only got the following error:\n\n Uncaught Invariant Violation: callsFromGraphQL(): Expected a declared value for variable, $curs.\n\nIt seems, if you define `first` and `after` in your container's fragment, then they're required parameters. But I have no value for `after`, so how in the world does one go about initializing this?\n\nThis example throws the error above:\n\n```\nexport default Relay.createContainer(Widgets2, {\n initialVariables: {\n pageSize: 2\n },\n fragments: {\n viewer: () => Relay.QL`\n fragment on User {\n widgets(\n first: $pageSize,\n after: $curs\n ) {\n edges {\n cursor,\n node {\n id,\n name,\n },\n },\n },\n }\n `,\n },\n});\n//And in the React component:\nnextPage () {\n let lastIndex = this.props.viewer.widgets.edges.length - 1\n this.props.relay.setVariables({\n curs: this.props.viewer.widgets.edges[lastIndex].cursor\n })\n }\n```\n\n========================================\n\nCode:\n```text\nexport default Relay.createContainer(Widgets2, {\n initialVariables: {\n pageSize: 2\n },\n fragments: {\n viewer: () => Relay.QL`\n fragment on User {\n widgets(\n first: $pageSize,\n after: $curs\n ) {\n edges {\n cursor,\n node {\n id,\n name,\n },\n },\n },\n }\n `,\n },\n});\n//And in the React component:\nnextPage () {\n let lastIndex = this.props.viewer.widgets.edges.length - 1\n this.props.relay.setVariables({\n curs: this.props.viewer.widgets.edges[lastIndex].cursor\n })\n }\n```\n\n```text\n/graphql\n```\n\n```text\nafter\n```\n\n```text\nundefined\n```\n\n```text\nfirst\n```\n\n```text\nafter\n```\n\n```text\nafter\n```\n\n```text\nnull\n```\n\n```text\ncurs: null\n```\n\n```text\ninitialVariables\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- Thanks @Joe Savona. I've created a PR for updating the documentation: github.com/facebook/relay/issues/700","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":132,"estimatedTokens":631}}779{"id":"stack-50745327","source":"stackoverflow","questionId":50745327,"title":"How to remove Cache-control header no-cache","tags":["php","laravel","nginx","graphql","apollo"],"text":"Title: How to remove Cache-control header no-cache\nTags: php, laravel, nginx, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nMy team and I are working on a Laravel API which communicates with a Vue.js frontend that uses the Apollo client to consume the GraphQL responses. \n\nWe have an issue with cache-control headers being added to the response. \n\nApollo cannot cache the contents because the response contains this header: \n\n```\nCache-Control: no-cache, private\n```\n\nIn php.ini, we have this to disable sending cache-control headers by PHP: \n\n```\n; Set to {nocache,private,public,} to determine HTTP caching aspects\n; or leave this empty to avoid sending anti-caching headers.\n; http://php.net/session.cache-limiter\nsession.cache_limiter =\n```\n\nIn the nginx config we cannot find anything that is setting those headers. I checked the global nginx.conf and config file we setup in sites/available.\n\nI can add this to the nginx config, but it will only add another header: \n\n```\nadd_header Cache-Control \"public\";\n\nCache-Control: no-cache, private\nCache-Control: public\n```\n\nIf this header is not coming from PHP or nginx, then where could it be coming from? \nAnd how can I remove or overwrite it? \n\n- Laravel 5.5\n\n- Folkloreatelier/laravel-graphql\n\n- PHP 7.1\n\n- nginx 1.14.0\n\n- Ubuntu 16.04\n\n========================================\n\nTop Answer:\nIn Laravel, the `Cache-Control: no-cache, private` header is set in the vendor package Symfony http-foundation by the following logic:\n\n```\n/**\n * Returns the calculated value of the cache-control header.\n *\n * This considers several other headers and calculates or modifies the\n * cache-control header to a sensible, conservative value.\n *\n * @return string\n */\n protected function computeCacheControlValue()\n {\n if (!$this->cacheControl) {\n if ($this->has('Last-Modified') || $this->has('Expires')) {\n return 'private, must-revalidate'; // allows for heuristic expiration (RFC 7234 Section 4.2.2) in the case of \"Last-Modified\"\n }\n\n // conservative by default\n return 'no-cache, private';\n }\n\n $header = $this->getCacheControlHeader();\n if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {\n return $header;\n }\n\n // public if s-maxage is defined, private otherwise\n if (!isset($this->cacheControl['s-maxage'])) {\n return $header.', private';\n }\n\n return $header;\n }\n```\n\n*Source: Laravel 5.6 `vendor/symfony/http-foundation/ResponseHeaderBag.php` lines 269-299*\n\nAs the OP stated in his comment to @the_hasanov's answer, the header can be overwritten by implementing a middleware.\n\n`php artisan make:middleware CachePolicy` \n\nedit the new `app/Http/Middleware/Cachepolicy.php` so that it reads:\n\n```\nheader('Cache-Control','no-cache, public');\n }\n}\n```\n\n- Modify `app/http/Kernel.php` to include the new middleware:\n\n```\n...\nprotected $middleware = [\n ...\n \\App\\Http\\Middleware\\CachePolicy::class,\n ];\n...\n```\n\n========================================\n\nCode:\n```text\nCache-Control: no-cache, private\n```\n\n```text\n; Set to {nocache,private,public,} to determine HTTP caching aspects\n; or leave this empty to avoid sending anti-caching headers.\n; http://php.net/session.cache-limiter\nsession.cache_limiter =\n```\n\n```text\nadd_header Cache-Control \"public\";\n\nCache-Control: no-cache, private\nCache-Control: public\n```\n\n```text\npublic function handle($request, Closure $next)\n {\n $response = $next($request);\n return $response instanceof \\Symfony\\Component\\HttpFoundation\\Response\n ? $response->header('pragma', 'no-cache')\n ->header('Cache-Control', 'no-store,no-cache, must-revalidate, post-check=0, pre-check=0')\n ->header('X-ANY-HEADER', 'any header value')\n : $response;\n }\n```\n\n```text\nHeader always set Cache-Control \"no-cache, public\"\n```\n\n```text\nCache-Control:no-cache , public\n```\n\n```php\n/**\n * Returns the calculated value of the cache-control header.\n *\n * This considers several other headers and calculates or modifies the\n * cache-control header to a sensible, conservative value.\n *\n * @return string\n */\n protected function computeCacheControlValue()\n {\n if (!$this->cacheControl) {\n if ($this->has('Last-Modified') || $this->has('Expires')) {\n return 'private, must-revalidate'; // allows for heuristic expiration (RFC 7234 Section 4.2.2) in the case of \"Last-Modified\"\n }\n\n // conservative by default\n return 'no-cache, private';\n }\n\n $header = $this->getCacheControlHeader();\n if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {\n return $header;\n }\n\n // public if s-maxage is defined, private otherwise\n if (!isset($this->cacheControl['s-maxage'])) {\n return $header.', private';\n }\n\n return $header;\n }\n```\n\n```php\n<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\n\nclass CachePolicy\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @return mixed\n */\n public function handle($request, Closure $next)\n {\n // return $next($request);\n $response= $next($request);\n return $response->header('Cache-Control','no-cache, public');\n }\n}\n```\n\n```php\n...\nprotected $middleware = [\n ...\n \\App\\Http\\Middleware\\CachePolicy::class,\n ];\n...\n```\n\n```text\nCache-Control: no-cache, private\n```\n\n```text\nvendor/symfony/http-foundation/ResponseHeaderBag.php\n```\n\n```text\nphp artisan make:middleware CachePolicy\n```\n\n```text\napp/Http/Middleware/Cachepolicy.php\n```\n\n```text\napp/http/Kernel.php\n```\n\n```text\nif (!$this->cacheControl) {\n if ($this->has('Last-Modified') || $this->has('Expires')) {\n return 'private, must-revalidate'; // allows for heuristic expiration (RFC 7234 Section 4.2.2) in the case of \"Last-Modified\"\n }\n\n // conservative by default\n return 'no-cache, private';\n }\n```\n\n```text\nno cache\n```\n\n```text\nno-store\n```\n\n```text\nno cache\n```\n\n```text\netag\n```\n\n```text\nLast-Modified\n```\n\n```text\nIf-Modified-Since\n```\n\n```text\nIf-None-Match\n```\n\n```text\nprivate\n```\n\n```text\nmust-revalidate\n```\n\n```text\nno-cache\n```\n\n```text\nmust-revalidate\n```\n\n```text\nETag\n```\n\n```text\nLast-Modified\n```\n\n```text\nno-cache\n```\n\n```text\nmust-revalidate\n```\n\n```text\nHeader always set Cache-Control \"no-cache, no-store, must-revalidate\"\n```\n\n========================================\n\nComments:\n- Try uploading a sample HTML and load it in browser & check the cache headers are present in it or not\n- Yes, with $response->header('Cache-Control','public') it changes the no-cache header. So it was either Laravel adding this header, or the laravel-graphql package.\n- In addition, use Illuminate\\Support\\Facades\\Response; use Illuminate\\Support\\Facades\\View; - and an example: $contents = View::make('index')->with([])); $response = Response::make($contents, 200); $response->header('Cache-Control','private'); return $response;\n- finally a solution after hours of search","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":323,"estimatedTokens":1775}}780{"id":"stack-72128141","source":"stackoverflow","questionId":72128141,"title":"Flutter graphql show actual request","tags":["flutter","graphql","flutter-graphql","graphql-flutter"],"text":"Title: Flutter graphql show actual request\nTags: flutter, graphql, flutter-graphql, graphql-flutter\nSource: Stack Overflow\n\nQuestion:\nI'm using flutter_graphql and keep getting exception ***OperationException(linkException: ResponseFormatException(originalException: FormatException: Unexpected end of input (at character 1), )^ graphqlErrors: []),***\n\nIs there a way to show the actual request sent?\nWant to see in console the actual request passed\n\n**Client**\n\n```\nclass GraphqlClient {\n static String _token;\n static final String serverUrl =\n GlobalConfiguration().getString(Config.GRAPHQL_URL);\n\n static final HttpLink httpLink = HttpLink(\n serverUrl,\n );\n\n static final AuthLink authLink = AuthLink(getToken: () async {\n final SharedPrefsRepository _sharedPrefsRepository =\n SharedPrefsRepository();\n String accountKey = await _sharedPrefsRepository.getAccountKey();\n String sessionKey= await _sharedPrefsRepository.getSessionKey();\n _token = 'Bearer $accountKey, Bearer $sessionKey';\n debugPrint('token '+_token);\n return _token ?? '';\n });\n\n static final Link link = authLink.concat(httpLink);\n\n static ValueNotifier initializeClient() {\n debugPrint('link '+link.toString());\n final policies = Policies(\n fetch: FetchPolicy.networkOnly,\n );\n \n final ValueNotifier client = ValueNotifier(\n GraphQLClient(\n cache: GraphQLCache(store: HiveStore()),\n link: link,\n defaultPolicies: DefaultPolicies(\n watchQuery: policies,\n query: policies,\n mutate: policies,\n ),\n ),\n );\n return client;\n }\n}\n```\n\n**Request**\n\n```\nQuery(\n options: QueryOptions(\n document: gql(DashboardGraphQL.accountDetailsQuery),\n operationName: 'AccountDetails',\n ),\n```\n\n**Query**\n\n```\nstatic const String accountDetailsQuery = \"\"\"\n query AccountDetails {\n accountDetails {\n ... on AccountDetails {\n ibanList {\n accountId\n bicCode\n iban\n }\n accountType\n accountNumber\n accountNumberShort\n accountId\n ruid\n companyId\n accountDataOpened\n email\n mobile\n baseCurrency\n balanceInBaseCurrency\n lastTransactionDate\n }\n\n ... on ResponseErrors {\n errors {\n message\n code\n displayMessage\n\n ... on InternalError {\n message\n code\n displayMessage\n context\n }\n }\n }\n }\n }\n \"\"\"\n```\n\n========================================\n\nCode:\n```text\nclass GraphqlClient {\n static String _token;\n static final String serverUrl =\n GlobalConfiguration().getString(Config.GRAPHQL_URL);\n\n static final HttpLink httpLink = HttpLink(\n serverUrl,\n );\n\n static final AuthLink authLink = AuthLink(getToken: () async {\n final SharedPrefsRepository _sharedPrefsRepository =\n SharedPrefsRepository();\n String accountKey = await _sharedPrefsRepository.getAccountKey();\n String sessionKey= await _sharedPrefsRepository.getSessionKey();\n _token = 'Bearer $accountKey, Bearer $sessionKey';\n debugPrint('token '+_token);\n return _token ?? '';\n });\n\n static final Link link = authLink.concat(httpLink);\n\n static ValueNotifier<GraphQLClient> initializeClient() {\n debugPrint('link '+link.toString());\n final policies = Policies(\n fetch: FetchPolicy.networkOnly,\n );\n \n final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(\n GraphQLClient(\n cache: GraphQLCache(store: HiveStore()),\n link: link,\n defaultPolicies: DefaultPolicies(\n watchQuery: policies,\n query: policies,\n mutate: policies,\n ),\n ),\n );\n return client;\n }\n}\n```\n\n```text\nQuery(\n options: QueryOptions(\n document: gql(DashboardGraphQL.accountDetailsQuery),\n operationName: 'AccountDetails',\n ),\n```\n\n```text\nstatic const String accountDetailsQuery = \"\"\"\n query AccountDetails {\n accountDetails {\n ... on AccountDetails {\n ibanList {\n accountId\n bicCode\n iban\n }\n accountType\n accountNumber\n accountNumberShort\n accountId\n ruid\n companyId\n accountDataOpened\n email\n mobile\n baseCurrency\n balanceInBaseCurrency\n lastTransactionDate\n }\n\n ... on ResponseErrors {\n errors {\n message\n code\n displayMessage\n\n ... on InternalError {\n message\n code\n displayMessage\n context\n }\n }\n }\n }\n }\n \"\"\"\n```\n\n```text\nclass LoggerLink extends Link {\n\n\n@override\n Stream<Response> request(\n Request request, [\n NextLink? forward,\n ]) {\n Stream<Response> response = forward!(request).map((Response fetchResult) {\n final ioStreamedResponse =\n fetchResult.context.entry<HttpLinkResponseContext>();\n if (kDebugMode) {\n print(\"Request: \" + request.toString());\n print(\"Response:\" + (ioStreamedResponse?.toString() ?? \"null\"));\n }\n return fetchResult;\n }).handleError((error) {\n // throw error;\n });\n\n return response;\n }\n\n LoggerLink();\n}\n```\n\n```text\nfinal _loggerLink = LoggerLink() ;\n```\n\n```text\nclient = ValueNotifier<GraphQLClient>(GraphQLClient(\n link: _loggerLink.concat(httpLink),\n cache: GraphQLCache(),\n defaultPolicies: DefaultPolicies(\n watchQuery: Policies(fetch: FetchPolicy.networkOnly),\n query: Policies(fetch: FetchPolicy.networkOnly),\n mutate: Policies(fetch: FetchPolicy.networkOnly),\n ),\n ));\n```\n\n```text\nhttpLink\n```\n\n========================================\n\nComments:\n- i think you need to\n- How can I read the HttpLink url from the LoggerLink","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":262,"estimatedTokens":1379}}781{"id":"stack-61550919","source":"stackoverflow","questionId":61550919,"title":"How do I represent a string enum (string literal union) in graphql?","tags":["types","enums","graphql"],"text":"Title: How do I represent a string enum (string literal union) in graphql?\nTags: types, enums, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a short list of string literals which I would like to have represented in my GraphQl definition. I tried using enum, but it's not for string literals.\n\nSay I had some list of string literals:\n\n```\nexport const DanceTypeList = [\n \"truffle-shuffle\",\n \"stanky-leg\",\n \"ghost-ride-the-whip\",\n] as const;\n\n// equivalent to (\"truffle-shuffle\" | \"stanky-leg\" | \"ghost-ride-the-whip\")\nexport type DanceType = typeof DanceTypeList[number];\n```\n\nHow could I take this and make a GraphQl type which was more descriptive than GraphQlString? Ideally it would be able to auto-suggest in the interactive UI.\n\n========================================\n\nCode:\n```text\nexport const DanceTypeList = [\n \"truffle-shuffle\",\n \"stanky-leg\",\n \"ghost-ride-the-whip\",\n] as const;\n\n// equivalent to (\"truffle-shuffle\" | \"stanky-leg\" | \"ghost-ride-the-whip\")\nexport type DanceType = typeof DanceTypeList[number];\n```\n\n```text\nenum DanceType {\n truffle_shuffle\n stanky_leg\n ghost_ride_the_whip\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":43,"estimatedTokens":281}}782{"id":"stack-66448489","source":"stackoverflow","questionId":66448489,"title":"How to update my gatsby and its dependences","tags":["node.js","reactjs","npm","graphql"],"text":"Title: How to update my gatsby and its dependences\nTags: node.js, reactjs, npm, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm new on React and I'm trying to update my gatsby and its dependences but is not working.\nOn the terminal I have put `npm outdated` and I got this below.\n\n```\nPackage Current Wanted Latest Location Depended by\ngatsby 2.32.4 2.32.9 3.0.0 node_modules/gatsby form-gatsby\ngatsby-plugin-sass 3.2.0 3.2.0 4.0.0 node_modules/gatsby-plugin-sass form-gatsby\ngatsby-source-filesystem 2.11.1 2.11.1 3.0.0 node_modules/gatsby-source-filesystem form-gatsby\ngatsby-transformer-remark 2.16.1 2.16.1 3.0.0 node_modules/gatsby-transformer-remark form-gatsby\nreact 16.13.1 16.14.0 17.0.1 node_modules/react form-gatsby\nreact-dom 16.13.1 16.14.0 17.0.1 node_modules/react-dom form-gatsby\n```\n\nWhen I tryind to run this: `npm update` I got this error below.\n\n```\nnpm WARN using --force Recommended protections disabled.\nnpm WARN ERESOLVE overriding peer dependency\nnpm WARN Found: graphql@15.5.0\nnpm WARN node_modules/graphql\nnpm WARN graphql@\"^15.4.0\" from gatsby@3.0.0\nnpm WARN node_modules/gatsby\nnpm WARN gatsby@\"3.0.0\" from the root project\nnpm WARN 6 more (gatsby-plugin-image, ...)\nnpm WARN \nnpm WARN Could not resolve dependency:\nnpm WARN peer graphql@\"^14.4.1\" from express-graphql@0.9.0\nnpm WARN node_modules/express-graphql\nnpm WARN express-graphql@\"^0.9.0\" from gatsby@3.0.0\nnpm WARN node_modules/gatsby\nnpm ERR! code ERESOLVE\nnpm ERR! ERESOLVE unable to resolve dependency tree\nnpm ERR! \nnpm ERR! Found: gatsby@3.0.0\nnpm ERR! node_modules/gatsby\nnpm ERR! gatsby@\"3.0.0\" from the root project\nnpm ERR! peer gatsby@\"^3.0.0-next.0\" from gatsby-plugin-image@1.0.0\nnpm ERR! node_modules/gatsby-plugin-image\nnpm ERR! gatsby-plugin-image@\"^1.0.0\" from gatsby-source-contentful@5.0.0\nnpm ERR! node_modules/gatsby-source-contentful\nnpm ERR! gatsby-source-contentful@\"^5.0.0\" from the root project\nnpm ERR! 5 more (babel-plugin-remove-graphql-queries, ...)\nnpm ERR! \nnpm ERR! Could not resolve dependency:\nnpm ERR! peer gatsby@\"^2.0.0\" from gatsby-plugin-sass@3.2.0\nnpm ERR! node_modules/gatsby-plugin-sass\nuser@Users-MacBook-Pro form-gatsby % npm update\nnpm ERR! code ERESOLVE\nnpm ERR! ERESOLVE unable to resolve dependency tree\nnpm ERR! \nnpm ERR! While resolving: gatsby-starter-hello-world@0.1.0\nnpm ERR! Found: gatsby@2.32.9\nnpm ERR! node_modules/gatsby\nnpm ERR! gatsby@\"^2.26.1\" from the root project\nnpm ERR! \nnpm ERR! Could not resolve dependency:\nnpm ERR! peer gatsby@\"^3.0.0-next.0\" from gatsby-plugin-sharp@3.0.0\nnpm ERR! node_modules/gatsby-plugin-sharp\nnpm ERR! gatsby-plugin-sharp@\"^3.0.0\" from the root project\nnpm ERR! \nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force, or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\nnpm ERR! \nnpm ERR! See /Users/user/.npm/eresolve-report.txt for a full report.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /Users/user/.npm/_logs/2021-03-02T23_15_17_390Z-debug.log\n```\n\nI have tried to run `npm install --force gatsby@3.0.0`, but the same didn't work.\n\nDo you guys any way I can update this?\n\nThanks so much.\n\n========================================\n\nTop Answer:\nIt means the version you are trying to update to has been found\n\n```\nnpm ERR! gatsby@\"3.0.0\" from the root project\n```\n\nRun gatsby -v to see if version is up to date\n\n========================================\n\nCode:\n```text\nPackage Current Wanted Latest Location Depended by\ngatsby 2.32.4 2.32.9 3.0.0 node_modules/gatsby form-gatsby\ngatsby-plugin-sass 3.2.0 3.2.0 4.0.0 node_modules/gatsby-plugin-sass form-gatsby\ngatsby-source-filesystem 2.11.1 2.11.1 3.0.0 node_modules/gatsby-source-filesystem form-gatsby\ngatsby-transformer-remark 2.16.1 2.16.1 3.0.0 node_modules/gatsby-transformer-remark form-gatsby\nreact 16.13.1 16.14.0 17.0.1 node_modules/react form-gatsby\nreact-dom 16.13.1 16.14.0 17.0.1 node_modules/react-dom form-gatsby\n```\n\n```text\nnpm WARN using --force Recommended protections disabled.\nnpm WARN ERESOLVE overriding peer dependency\nnpm WARN Found: graphql@15.5.0\nnpm WARN node_modules/graphql\nnpm WARN graphql@\"^15.4.0\" from gatsby@3.0.0\nnpm WARN node_modules/gatsby\nnpm WARN gatsby@\"3.0.0\" from the root project\nnpm WARN 6 more (gatsby-plugin-image, ...)\nnpm WARN \nnpm WARN Could not resolve dependency:\nnpm WARN peer graphql@\"^14.4.1\" from express-graphql@0.9.0\nnpm WARN node_modules/express-graphql\nnpm WARN express-graphql@\"^0.9.0\" from gatsby@3.0.0\nnpm WARN node_modules/gatsby\nnpm ERR! code ERESOLVE\nnpm ERR! ERESOLVE unable to resolve dependency tree\nnpm ERR! \nnpm ERR! Found: gatsby@3.0.0\nnpm ERR! node_modules/gatsby\nnpm ERR! gatsby@\"3.0.0\" from the root project\nnpm ERR! peer gatsby@\"^3.0.0-next.0\" from gatsby-plugin-image@1.0.0\nnpm ERR! node_modules/gatsby-plugin-image\nnpm ERR! gatsby-plugin-image@\"^1.0.0\" from gatsby-source-contentful@5.0.0\nnpm ERR! node_modules/gatsby-source-contentful\nnpm ERR! gatsby-source-contentful@\"^5.0.0\" from the root project\nnpm ERR! 5 more (babel-plugin-remove-graphql-queries, ...)\nnpm ERR! \nnpm ERR! Could not resolve dependency:\nnpm ERR! peer gatsby@\"^2.0.0\" from gatsby-plugin-sass@3.2.0\nnpm ERR! node_modules/gatsby-plugin-sass\nuser@Users-MacBook-Pro form-gatsby % npm update\nnpm ERR! code ERESOLVE\nnpm ERR! ERESOLVE unable to resolve dependency tree\nnpm ERR! \nnpm ERR! While resolving: gatsby-starter-hello-world@0.1.0\nnpm ERR! Found: gatsby@2.32.9\nnpm ERR! node_modules/gatsby\nnpm ERR! gatsby@\"^2.26.1\" from the root project\nnpm ERR! \nnpm ERR! Could not resolve dependency:\nnpm ERR! peer gatsby@\"^3.0.0-next.0\" from gatsby-plugin-sharp@3.0.0\nnpm ERR! node_modules/gatsby-plugin-sharp\nnpm ERR! gatsby-plugin-sharp@\"^3.0.0\" from the root project\nnpm ERR! \nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force, or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\nnpm ERR! \nnpm ERR! See /Users/user/.npm/eresolve-report.txt for a full report.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! /Users/user/.npm/_logs/2021-03-02T23_15_17_390Z-debug.log\n```\n\n```text\nnpm outdated\n```\n\n```text\nnpm update\n```\n\n```text\nnpm install --force gatsby@3.0.0\n```\n\n```text\nnpm install gatsby@latest\n```\n\n```text\nnpm outdated\n```\n\n```text\nnpm ERR! gatsby@\"3.0.0\" from the root project\n```\n\n```text\nyarn upgrade\n```\n\n========================================\n\nComments:\n- Thanks so much! actually jsut worked when I did `npm install gatsby@latest --legacy--peer-deps`","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":192,"estimatedTokens":1706}}783{"id":"stack-62632360","source":"stackoverflow","questionId":62632360,"title":"Apollo Client lazy refetch","tags":["reactjs","graphql","react-apollo","apollo-client"],"text":"Title: Apollo Client lazy refetch\nTags: reactjs, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nIn `Apollo Client v3` React implementation, I am using hooks to use subscription. When I receive data from subscription I would like to refetch query but only if query has been previously executed and is in cache. Is there a way to achieve this?\n\nI have started by having a lazy query and then checking the cache manually when subscription data received and then trying to execute lazy query and refetch. It works but it just feels clunky...\n\n```\nexport const useMyStuffLazyRefetch = () => {\n const [refetchNeeded, setRefetchNeeded] = useState(false);\n const client = useApolloClient();\n const [getMyStuff, { data, refetch }] = useLazyQuery(GET_MY_STUFF);\n\n useEffect(() => {\n if (refetchNeeded) {\n setRefetchNeeded(false);\n refetch();\n }\n }, [refetchNeeded]);\n\n const refetchIfNeeded = async () => {\n const stuffData = client.cache.readQuery({ query: GET_MY_STUFF });\n if (!stuffData?.myStuff?.length) return;\n getMyStuff();\n setRefetchNeeded(true);\n }\n\n return {\n refetchIfNeeded: refetchIfNeeded\n };\n}\n```\n\n========================================\n\nTop Answer:\n`useLazyQuery` has a prop called `called`, this is a boolean indicating if the query function has been called,\n\nso maybe you can try this:\n\n```\nexport const useMyStuffLazyRefetch = () => {\n const [refetchNeeded, setRefetchNeeded] = useState(false);\n const client = useApolloClient();\n const [getMyStuff, { data, refetch, called }] = useLazyQuery(GET_MY_STUFF);\n\n useEffect(() => {\n if (refetchNeeded) {\n setRefetchNeeded(false);\n\n if (called) {\n refetch();\n }\n else {\n getMyStuff()\n }\n }\n }, [refetchNeeded, called]);\n\n const refetchIfNeeded = async () => {\n const stuffData = client.cache.readQuery({ query: GET_MY_STUFF });\n if (!stuffData?.myStuff?.length) return;\n getMyStuff();\n setRefetchNeeded(true);\n }\n\n return {\n refetchIfNeeded: refetchIfNeeded\n };\n}\n```\n\n========================================\n\nCode:\n```text\nexport const useMyStuffLazyRefetch = () => {\n const [refetchNeeded, setRefetchNeeded] = useState<boolean>(false);\n const client = useApolloClient();\n const [getMyStuff, { data, refetch }] = useLazyQuery<IStuffData>(GET_MY_STUFF);\n\n useEffect(() => {\n if (refetchNeeded) {\n setRefetchNeeded(false);\n refetch();\n }\n }, [refetchNeeded]);\n\n const refetchIfNeeded = async () => {\n const stuffData = client.cache.readQuery<IStuffData>({ query: GET_MY_STUFF });\n if (!stuffData?.myStuff?.length) return;\n getMyStuff();\n setRefetchNeeded(true);\n }\n\n return {\n refetchIfNeeded: refetchIfNeeded\n };\n}\n```\n\n```text\nApollo Client v3\n```\n\n```text\nimport { useState, useEffect } from \"react\";\nimport { OperationVariables, DocumentNode, LazyQueryHookOptions, useApolloClient, useLazyQuery } from \"@apollo/client\";\n\nexport default function useLazyRefetch <TData = any, TVariables = OperationVariables>(query: DocumentNode, options?: LazyQueryHookOptions<TData, TVariables>) {\n const [refetchNeeded, setRefetchNeeded] = useState<boolean>(false);\n const [loadData, { refetch }] = useLazyQuery(query, options);\n const client = useApolloClient();\n\n useEffect(() => {\n if (refetchNeeded) {\n setRefetchNeeded(false);\n refetch();\n }\n }, [refetchNeeded]);\n\n const refetchIfNeeded = (variables: TVariables) => {\n try {\n const cachecData = client.cache.readQuery<\n TData,\n TVariables\n >({\n query: query,\n variables: variables\n });\n if (!cachecData) return;\n loadData({ variables: variables });\n setRefetchNeeded(true);\n }\n catch {}\n };\n\n return {\n refetchIfNeeded: refetchIfNeeded\n };\n}\n```\n\n```text\nconst { refetchIfNeeded } = useLazyRefetch<\n IStuffData,\n { dataId?: string }\n >(GET_MY_STUFF);\n\n//... And then you can just call it when you need to\n\nrefetchIfNeeded({ dataId: \"foo\" });\n```\n\n```text\nApollo Client\n```\n\n```text\nundefined\n```\n\n```text\nnull\n```\n\n```text\nexport const useMyStuffLazyRefetch = () => {\n const [refetchNeeded, setRefetchNeeded] = useState<boolean>(false);\n const client = useApolloClient();\n const [getMyStuff, { data, refetch, called }] = useLazyQuery<IStuffData>(GET_MY_STUFF);\n\n useEffect(() => {\n if (refetchNeeded) {\n setRefetchNeeded(false);\n\n if (called) {\n refetch();\n }\n else {\n getMyStuff()\n }\n }\n }, [refetchNeeded, called]);\n\n const refetchIfNeeded = async () => {\n const stuffData = client.cache.readQuery<IStuffData>({ query: GET_MY_STUFF });\n if (!stuffData?.myStuff?.length) return;\n getMyStuff();\n setRefetchNeeded(true);\n }\n\n return {\n refetchIfNeeded: refetchIfNeeded\n };\n}\n```\n\n```text\nuseLazyQuery\n```\n\n```text\ncalled\n```\n\n```text\nuseEffect(() => {\n if (refetchNeeded) {\n setRefetchNeeded(false);\n refetch();\n }\n}, [refetchNeeded]);\n\nrefetch() says - Cannot invoke an object which is possibly 'undefined'.ts(2722)\n\nconst refetch: ((variables?: Partial<TVariables> | undefined) => Promise<ApolloQueryResult<TData>>) | undefined\n\n and in [refetchNeeded] dependency -\n```\n\n========================================\n\nComments:\n- Thank you for your answer. Not sure if the change would have much effect, the refetch is only triggered on a state change and at that point, refetchIfNeeded function has already called the getMyStuff() so I think the called check would be redundant? Another component would have potentially populated the cache so useMyStuffLazyRefetch would only be responsible for calling refetch but should not try to call server if data is not in a cache.","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":227,"estimatedTokens":1476}}784{"id":"stack-57612167","source":"stackoverflow","questionId":57612167,"title":"GraphQL query works in Gatsby page but not inside class component","tags":["reactjs","graphql","gatsby","prismic.io"],"text":"Title: GraphQL query works in Gatsby page but not inside class component\nTags: reactjs, graphql, gatsby, prismic.io\nSource: Stack Overflow\n\nQuestion:\nThere have been a couple of similar questions, but none helped me really understand using a GraphQL inside a (class) component other than the ones in the pages folder.\n\nMy project structure looks like that:\n\n```\n-src\n--components\n---aboutBody\n----index.js\n--pages\n---about.js\n```\n\nI have a page component called `about` (Prismic single page type) and set up some components to \"fill\" this page (cleaned up for better readability).\n\n```\nclass AboutPage extends Component {\n\n render() {\n return (\n \n \n \n )\n }\n\n}\n\nexport default AboutPage\n```\n\nThis is what my query looks like (had it like this in both files):\n\n```\nexport const aboutQuery = graphql`\n query About {\n prismicAbout {\n data {\n\n # Intro Block\n intro_headline {\n text\n }\n intro_paragraph {\n text\n }\n }\n }\n }\n`\n```\n\n(In case I am missing a bracket at the bottom, it's due to cleaning up the query example for SO β as mentioned earlier, it's working in my page component).\n\nMy graphql query is at the bottom of the `AboutPage` page component. It works like a charm and as intended.\n\nBut to clean this page up a bit I wanted to create appropriate components and put my query inside each component (e.g. `aboutBody`, `aboutCarousel`), again cleaned up a bit:\n\n```\nclass AboutBody extends Component {\n\n render() {\n\n return (\n \n \n\n### About\n\n \n\n### {this.props.data.prismicAbout.data.intro_headline.text}\n\n \n )\n }\n\n}\n\nexport default AboutBody\n```\n\nAnd I deleted the query from my `about` page component and put it inside my `AboutBody` component (exactly the way as shown above).\n\nBut with this it always returns the error `Cannot read property 'prismicAbout' of undefined` (I can't even console log the data, it always returns the same error).\n\nI used `import { graphql } from \"gatsby\"` in both files.\n\nLong story short, how can I achieve putting a query inside my class component and render only the component without clarifying the props in my page component like this:\n\n```\nclass AboutPage extends Component {\n\n render() {\n return (\n \n \n \n )\n }\n\n}\n```\n\nSome blogs posts mention GraphQL Query Fragments, but not sure if this is the correct use case or if it's simply a stupid beginner mistake...\n\n========================================\n\nTop Answer:\nYou can only use a query like that in a page component. One option would be to just query it in the page and then pass the data in to your component as a prop. Another is to use a static query in the component.\n\nIf your query has variables in it then you can't use a static query. In that case you should either query it all in the page and then pass it in, or you can put the part of the query related to that component in a fragment within that component's file and then use that fragment in the page query.\n\nExample of using fragments in a component and then passing the data into the component:\n\n```\n// MyComponent.js\nimport React from \"react\"\nimport { graphql } from 'gatsby'\n\nconst MyComponent = (props) => {\n\n const { myProp: { someData } } = props\n\n return (\n \n my awesome component\n \n )\n}\n\nexport default MyComponent\n\nexport const query = graphql`\n fragment MyAwesomeFragment on Site {\n someData {\n item\n }\n }\n`\n```\n\n```\n// MyPage.js\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\n\nimport MyComponent from \"../components/MyComponent\"\n\nexport default ({ data }) => {\n return (\n \n {/*\n You can pass all the data from the fragment\n back to the component that defined it\n */}\n \n \n )\n}\nexport const query = graphql`\n query {\n site {\n ...MyAwesomeFragment\n }\n }\n`\n```\n\nRead more about using fragments in Gatsby docs.\n\n========================================\n\nCode:\n```text\n-src\n--components\n---aboutBody\n----index.js\n--pages\n---about.js\n```\n\n```text\nclass AboutPage extends Component {\n\n render() {\n return (\n <LayoutDefault>\n <AboutBody\n introHeadline={this.props.data.prismicAbout.data.intro_headline.text}\n introParagraph={this.props.data.prismicAbout.data.intro_paragraph.text}\n />\n </LayoutDefault>\n )\n }\n\n}\n\nexport default AboutPage\n```\n\n```text\nexport const aboutQuery = graphql`\n query About {\n prismicAbout {\n data {\n\n # Intro Block\n intro_headline {\n text\n }\n intro_paragraph {\n text\n }\n }\n }\n }\n`\n```\n\n```text\nclass AboutBody extends Component {\n\n render() {\n\n return (\n <StyledIntro>\n <h3>About</h3>\n <h1>{this.props.data.prismicAbout.data.intro_headline.text}</h1>\n </StyledIntro>\n )\n }\n\n}\n\nexport default AboutBody\n```\n\n```text\nclass AboutPage extends Component {\n\n render() {\n return (\n <LayoutDefault>\n <AboutBody />\n </LayoutDefault>\n )\n }\n\n}\n```\n\n```text\nabout\n```\n\n```text\nAboutPage\n```\n\n```text\naboutBody\n```\n\n```text\naboutCarousel\n```\n\n```text\nabout\n```\n\n```text\nAboutBody\n```\n\n```text\nCannot read property 'prismicAbout' of undefined\n```\n\n```text\nimport { graphql } from \"gatsby\"\n```\n\n```text\nimport React from \"react\"\nimport { useStaticQuery, graphql } from \"gatsby\"\n\nconst MyElement = () => {\n const data = useStaticQuery(graphql`\n query About {\n prismicAbout {\n data {\n intro_headline {\n text\n }\n intro_paragraph {\n text\n }\n }\n }\n }\n `)\n\n return (\n <StyledIntro>\n <h3>About</h3>\n <h1>{this.props.data.prismicAbout.data.intro_headline.text}</h1>\n </StyledIntro>\n )\n}\n\nexport default MyElement\n```\n\n```text\nimport React from 'react'\nimport { StaticQuery, graphql } from 'gatsby';\n\nconst MyElement = () => {\n return(\n <StaticQuery\n query About {\n prismicAbout {\n data {\n intro_headline {\n text\n }\n intro_paragraph {\n text\n }\n }\n }\n }\n `}\n render={data => (\n <StyledIntro>\n <h3>About</h3>\n <h1>{this.props.data.prismicAbout.data.intro_headline.text}</h1>\n </StyledIntro>\n )}\n />\n )\n}\n\nexport default MyElement\n```\n\n```text\nuseStaticQuery\n```\n\n```text\nStaticQuery\n```\n\n```text\nuseStaticQuery\n```\n\n```text\nstaticQuery\n```\n\n```text\n// MyComponent.js\nimport React from \"react\"\nimport { graphql } from 'gatsby'\n\nconst MyComponent = (props) => {\n\n const { myProp: { someData } } = props\n\n return (\n <div>\n my awesome component\n </div>\n )\n}\n\nexport default MyComponent\n\nexport const query = graphql`\n fragment MyAwesomeFragment on Site {\n someData {\n item\n }\n }\n`\n```\n\n```text\n// MyPage.js\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\n\nimport MyComponent from \"../components/MyComponent\"\n\nexport default ({ data }) => {\n return (\n <div>\n {/*\n You can pass all the data from the fragment\n back to the component that defined it\n */}\n <MyComponent myProp={data.site.someData} />\n </div>\n )\n}\nexport const query = graphql`\n query {\n site {\n ...MyAwesomeFragment\n }\n }\n`\n```\n\n```text\nimport React, { Component } from 'react';\nimport { StaticQuery, graphql } from 'gatsby';\n\nclass Layout extends Component {\n render() {\n return (\n <StaticQuery\n query={graphql`\n query SiteTitleQuery {\n site {\n siteMetadata {\n title\n }\n }\n }\n `}\n render={data => {\n return (\n <main>\n {!data && <p>Loading...</p>}\n {data && data.site.siteMetadata.title}\n </main>\n )\n }}\n />\n );\n }\n}\n```\n\n========================================\n\nComments:\n- Thank you Logan Blangenois and ksav. This works a like charm and perfectly explained it. Appreciated.\n- Thanks Caleb Barnes, great explanation. Really appreciated.","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":460,"estimatedTokens":2023}}785{"id":"stack-66183785","source":"stackoverflow","questionId":66183785,"title":"How to connect mg_client outside container in Docker?","tags":["database","docker","docker-compose","graphql","memgraphdb"],"text":"Title: How to connect mg_client outside container in Docker?\nTags: database, docker, docker-compose, graphql, memgraphdb\nSource: Stack Overflow\n\nQuestion:\nI am trying to access mg_client inside a docker container but unfortunately, I am unable to connect it. I have followed instructions from the docs here\n\ndocker-compose.yaml\n\n```\nversion: \"3\"\nservices:\n redis:\n image: redislabs/redisgraph\n container_name: redis\n restart: unless-stopped\n ports:\n - \"6379:6379\"\n\n memgraph:\n image: memgraph\n container_name: memgraph\n restart: unless-stopped\n ports:\n - \"7687:7687\"\n```\n\nCLI returns back an error -\n\nhttps://i.sstatic.net/ULUVj.png\n\nMemgraph is successfully initialized as shown.\n\nhttps://i.sstatic.net/oZCoz.png\n\nStrangely, if I execute it inside the container, I am able to connect.\n\nhttps://i.sstatic.net/WJC40.png\n\nWhat can be a possible mistake from my end?\n\nPS: I am trying to create a Project with Memgraph, Neo4j, and RedisGraph running simultaneously and accessing each datastore using Python libs/adapter. This is the very initial step towards it.\n\nFeedback would be appreciated.\n\n========================================\n\nCode:\n```text\nversion: \"3\"\nservices:\n redis:\n image: redislabs/redisgraph\n container_name: redis\n restart: unless-stopped\n ports:\n - \"6379:6379\"\n\n memgraph:\n image: memgraph\n container_name: memgraph\n restart: unless-stopped\n ports:\n - \"7687:7687\"\n```\n\n```text\ndocker run --rm -p 7687:7687 --name test memgraph\n```\n\n```text\nversion: \"3\"\nservices:\n memgraph:\n image: memgraph:1.3.0-community\n container_name: memgraph\n networks:\n - test_network\n container_name: memgraph\n restart: unless-stopped\n ports:\n - \"7687:7687\"\nnetworks:\n test_network:\n driver: bridge\n```\n\n```text\ndocker run\n```\n\n```text\ndocker-compose\n```\n\n```text\ndocker-compose\n```\n\n```text\n{{folder_name}}_{{network_name}}\n```\n\n```text\nstack_issue_test_network\n```\n\n```text\ndocker-compose\n```\n\n```text\n--log-level=TRACE --also-log-to-stderr\n```\n\n```text\nmg_client\n```\n\n```text\nmgconsole\n```\n\n```text\nmg_client\n```\n\n========================================\n\nComments:\n- Hi! It seems I understand the problem. When using `docker-compose`, things are not the same. I'm writing the full answer...\n- What are the images you've attached to this question? Do you have the actual code you're using to connect to the server, and the actual error messages you're getting back? Please include these details as text in the question, not as images.\n- This answer serves my question. However, moving forward I would like to ask you few things 1) What are the volumes necessary to be mounted to the host machine in order to visualize any Graph data? 2) Is there any official docker image for memgraph available on the docker hub? 3) Is there a way to install mg_console without building it from the source? @user:4888809\n- 1) Volumes are not required to visualize data. Once an instance is running, data should be fetched via Bolt protocol and visualized somehow. 2) Memgraph doesn't provide the DockerHub image yet, but there is a plan to offer that soon. 3) The only way to install mgconsole is to build it from the source. In a similar way to how we plan to offer DockerHub image, there is a plan to put mgconsole in the repo. Before doing that, we'll probably ship mgconsole together with Memgraph so. There won't be a need to install it manually.","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":134,"estimatedTokens":851}}786{"id":"stack-63603450","source":"stackoverflow","questionId":63603450,"title":"GraphQL - How do I use the return value as a variable for the next query?","tags":["graphql"],"text":"Title: GraphQL - How do I use the return value as a variable for the next query?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nHow do I take the return result from the first query and assign that result to a variable to use in the second query? I need the first value result before I can make the second call, but would like to make only 1 call to accomplish this. My query:\n\n```\nquery {\n test1(sku: \"12345\"){ \n price\n }\n test2(itemPrice: $price){ \n isSuccessful\n }\n}\n```\n\n========================================\n\nCode:\n```text\nquery {\n test1(sku: \"12345\"){ \n price\n }\n test2(itemPrice: $price){ \n isSuccessful\n }\n}\n```\n\n```text\nquery {\n test1(sku: \"12345\"){ \n price\n }\n test2(itemPrice: $price){ \n isSuccessful\n }\n}\n```\n\n```text\ntest1\n```\n\n```text\ntest2\n```\n\n```text\nprice\n```\n\n```text\nisSuccessful\n```\n\n========================================\n\nComments:\n- Hi, do you know if there is some kind of workaround? rearrange the queries in some way?","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":63,"estimatedTokens":262}}787{"id":"stack-48244950","source":"stackoverflow","questionId":48244950,"title":"Can I list Github's public repositories using GraphQL?","tags":["github","graphql","github-api","github-graphql"],"text":"Title: Can I list Github's public repositories using GraphQL?\nTags: github, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to list public repositories in Github using **GraphQL** as it allows me to choose exactly which information from an `Object` I want. \n\nUsing **REST** I could list public repositories simply by making requests to `https://api.github.com/repositories`. This is OK, but the response comes with a bunch of stuff I don't need. So, I was wondering if I could use **GraphQL** to do the same job.\n\nThe problem is, I couldn't find any high level repositories `Object` I could use to list public repositories using **GraphQL**. For me it seems I can only use **GraphQL** to list repositories from organizations or from users. For example, like doing so:\n\n```\nquery{\n user(login: \"someuser\"){\n repositories(first: 50){\n nodes{\n name\n }\n pageInfo{\n hasNextPage\n }\n }\n }\n}\n```\n\nSo, how can I use (if at all) Github's GraphQL endpoint to list Github's public repositories?\n\nI have also tried something on this line, using `search`, but I doubt Github has only 54260 repositories as the `repositoryCount` variable returned me.\n\n```\nquery{\n search(query:\"name:*\", type:REPOSITORY, first:50){\n repositoryCount\n pageInfo{\n endCursor\n startCursor\n }\n edges{\n node{\n ... on Repository{\n name\n }\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nThere is also an inPrivate attribute on the Repository object you can query\nhttps://docs.github.com/en/graphql/reference/objects#repository\n\n========================================\n\nCode:\n```text\nquery{\n user(login: \"someuser\"){\n repositories(first: 50){\n nodes{\n name\n }\n pageInfo{\n hasNextPage\n }\n }\n }\n}\n```\n\n```text\nquery{\n search(query:\"name:*\", type:REPOSITORY, first:50){\n repositoryCount\n pageInfo{\n endCursor\n startCursor\n }\n edges{\n node{\n ... on Repository{\n name\n }\n }\n }\n }\n}\n```\n\n```text\nObject\n```\n\n```text\nhttps://api.github.com/repositories\n```\n\n```text\nObject\n```\n\n```text\nsearch\n```\n\n```text\nrepositoryCount\n```\n\n```graphql\n{\n search(query: \"is:public\", type: REPOSITORY, first: 50) {\n repositoryCount\n pageInfo {\n endCursor\n startCursor\n }\n edges {\n node {\n ... on Repository {\n name\n }\n }\n }\n }\n}\n```\n\n```text\nis:public\n```\n\n========================================\n\nComments:\n- Learned so much in the last few days about GraphQL that I summarized my endeavor with a post on Medium: medium.com/@fabiomolinar/…\n- One more question, would it be possible to order the results by date it was created?\n- @FTM you can't sort by creation date in search query, check this post. You can only sort by creation date when requesting user repositories in the `repositories` connection, check this post\n- thank you once again. Final question, where can I find more information about what can I use to form my search query? I tried Github's documentation about its Repository object, but it says nothing about things like \"is:public\" or any other arguments I could use on the search query.\n- You can find it here for search options & here for sorting\n- Bertrand, if you were my neighbor I would definitely pay some beers for you! Thanks again!","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":144,"estimatedTokens":862}}788{"id":"stack-56567937","source":"stackoverflow","questionId":56567937,"title":"How to handle .gql file imports in Jest tests","tags":["graphql","jestjs","apollo","vue-apollo","graphql-tag"],"text":"Title: How to handle .gql file imports in Jest tests\nTags: graphql, jestjs, apollo, vue-apollo, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nI'm trying to test a component that imports a `.gql` file. When I try to build the component in a Jest file, I receive this error:\n\n```\n( object. anonymous function(module exports require __dirname __filename global jest) {\nquery getUser { \n ΛΛΛΛΛΛΛ\n\nimport GET_USER from 'PATH';\nΛ\n```\n\nDoes anyone have any idea of how to ignore the import? Because I don't need to test the GraphQL call.\n\n========================================\n\nCode:\n```text\n( object. anonymous function(module exports require __dirname __filename global jest) {\nquery getUser { \n ΛΛΛΛΛΛΛ\n<script>\nimport GET_USER from 'PATH';\nΛ\n```\n\n```text\n.gql\n```\n\n```text\n\"jest\": {\n \"transform\": {\n \"\\\\.(gql|graphql)$\": \"jest-transform-graphql\",\n \".*\": \"babel-jest\"\n }\n}\n```\n\n```text\n.gql\n```\n\n```text\ngraphql-tag\n```\n\n```text\ngraphql-tag\n```\n\n```text\nbabel-jest\n```\n\n```text\nmoduleNameMapper\n```\n\n========================================\n\nComments:\n- Can you please edit your question and replace the image with the actual error message? This will help other users find your question when they encounter the same error.\n- I had this issue on my `nuxt` project, the error disappeared after adding `jest-transform-graphql` as above and also adding `moduleFileExtensions: ['js', 'vue', 'json', 'gql'],`.\n- `jest-transform-graphql` doesn't work with newer jest versions (>= v28). There is an issue tracking it and a workaround is explained here.","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":69,"estimatedTokens":401}}789{"id":"stack-45992025","source":"stackoverflow","questionId":45992025,"title":"invoking Query of GraphQL of Apollo Client","tags":["reactjs","graphql","react-apollo"],"text":"Title: invoking Query of GraphQL of Apollo Client\nTags: reactjs, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nquery screenshot\n\n```\nconst allTeamApplicants = gql`\n query ($id: ID!) {\n allApplicants(filter: { user: { id: $id } }) {\n id\n firstName\n lastName\n appliedPosition\n applicationStage\n isFormFilled\n isContractSigned\n email\n phoneNumber\n}\n```\n\nI use Apollo Client for GraphQL in React web app. Anyone knows how to invoke a query with parameters in an event, for example, I want to trigger the query with a parameter when a user clicks a button.\n\n========================================\n\nCode:\n```text\nconst allTeamApplicants = gql`\n query ($id: ID!) {\n allApplicants(filter: { user: { id: $id } }) {\n id\n firstName\n lastName\n appliedPosition\n applicationStage\n isFormFilled\n isContractSigned\n email\n phoneNumber\n}\n```\n\n```text\nimport { withApollo } from 'react-apollo';\n```\n\n```text\nconst component = withApollo(Component)\n```\n\n```text\nfunction eventHandler(idParam) {\n client.query({\n query: gql`\n query ($id: ID!) {\n allApplicants(filter: { user: { id: $id } }) {\n id\n firstName\n lastName\n appliedPosition\n applicationStage\n isFormFilled\n isContractSigned\n email\n phoneNumber\n }\n }`,\n variables: {\n // set the variables defined in the query, in this case: query($id: ID!)\n id: idParam \n }\n }\n })\n .then(...)\n .catch(...)\n}\n```\n\n```text\nwithApollo\n```\n\n```text\nclient\n```\n\n========================================\n\nComments:\n- In the .then(response => response) I seem to be getting the response wrapped in another Promise which is proving a pain to resolve. Any ideas?\n- @Stefano the then function argument should just be an object containing query results. something like: `response.queryName`","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":93,"estimatedTokens":476}}790{"id":"stack-53465903","source":"stackoverflow","questionId":53465903,"title":"GraphQL API - any automation tool for testing it?","tags":["testing","graphql","soapui","postman"],"text":"Title: GraphQL API - any automation tool for testing it?\nTags: testing, graphql, soapui, postman\nSource: Stack Overflow\n\nQuestion:\nI want to test a GraphQL API. \nFor now, I'm using GraphiQL, but I'm looking for any automated tool...\nIt seems that SOAPUI does not support GraphQL testing.\n\nAny ideas?\n\nThanks.\n\n========================================\n\nTop Answer:\nI am using SoapUI 5.4.0 (community edition) and have no trouble testing GraphQL requests.\nTreat them as a Rest request and add a header, e.g. Content-Type: application/graphql\n\nsee image for all details.\n\n========================================\n\nCode:\n```text\ngraphql-js\n```\n\n```text\ngraphql-js\n```\n\n```text\nfindBreakingChanges\n```\n\n```text\ngraphql-js\n```\n\n========================================\n\nComments:\n- My team had a similar requirement as well, we have written our own tool based on cucumber-jvm, and we have open-sourced it to help others, we've included graphql testing in the latest version. if you are still searching, have a look at github.com/JakimLi/pandaria\n- Postman released GraphQL support on their canary channel - getpostman.com/downloads/canary\n- Thank you for your answer but I'm asking about automation tools for testing the server's response for a GraphQL query.\n- Can anyone have solve this problem with AI tools ?\n- This only works if the server side accepts application/graphql Many servers tend to remain standard and accept the json format","metadata":{"transformedAt":"2026-08-18T18:32:36.083Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":359}}791{"id":"stack-43665937","source":"stackoverflow","questionId":43665937,"title":"GraphQL Schema with Sangria","tags":["json","scala","graphql","sangria"],"text":"Title: GraphQL Schema with Sangria\nTags: json, scala, graphql, sangria\nSource: Stack Overflow\n\nQuestion:\nI'm looking at the Sangria library for coding a GraphQL server in Scala. It feels odd, however, that the same type system must be implemented twice: (1) as part of the GraphQL type declarations, and (2) also at the server side, as Scala case classes, with accompanying ObjectType, InterfaceType, etc. vals.\n\nHardcoding the type system in Scala is especially irksome, since my purpose is to be able to CRUD aggregates of arbitrary shape, where each shape is defined as a GraphQL collection of types. For example, say an instance of type Shape contains a GraphQL document as a field; and an instance of type Entity has a reference to its Shape and also contains a Json object of the shape defined in that Shape.\n\n```\ncase class Shape(id: String, name: String, doc: sangria.ast.Document)\ncase class Entity(id: String, name: String, shape: Shape, content: JsValue)\n```\n\nFor example, if the shape document is something like this:\n\n```\ntype Person {\n firstName: String!\n lastName: String!\n age: Int\n}\n```\n\nthen the Json content in the entity could be something like this:\n\n```\n{\n \"firstName\": \"John\",\n \"lastName\": \"Smith\",\n \"age\": 30\n}\n```\n\n(A real example would, of course, also have nested types, etc.)\n\nThus, I seek to be able to define instances of type Entity whose shape is defined in their corresponding Shape. I do NOT want to hardcode the corresponding sangria.schema.Schema but want to derive it directly from the shape document.\n\nIs there a ready way to generate a GraphQL schema programmatically from a GraphQL document containing type declarations?\n\n========================================\n\nCode:\n```text\ncase class Shape(id: String, name: String, doc: sangria.ast.Document)\ncase class Entity(id: String, name: String, shape: Shape, content: JsValue)\n```\n\n```text\ntype Person {\n firstName: String!\n lastName: String!\n age: Int\n}\n```\n\n```text\n{\n \"firstName\": \"John\",\n \"lastName\": \"Smith\",\n \"age\": 30\n}\n```\n\n```text\nimport sangria.ast._\nimport sangria.schema._\nimport sangria.macros._\nimport sangria.marshalling.sprayJson._\nimport sangria.execution.Executor\n\nimport scala.concurrent.ExecutionContext.Implicits.global\nimport spray.json._\n\nval schemaAst =\n gql\"\"\"\n type Person {\n firstName: String!\n lastName: String!\n age: Int\n }\n\n type Query {\n people: [Person!]\n }\n \"\"\"\n\nval schema = Schema.buildFromAst(schemaAst, builder)\n\nval query =\n gql\"\"\"\n {\n people {\n firstName\n age\n }\n }\n \"\"\"\n\nval data =\n \"\"\"\n {\n \"people\": [{\n \"firstName\": \"John\",\n \"lastName\": \"Smith\",\n \"age\": 30\n }]\n }\n \"\"\".parseJson\n\nval result = Executor.execute(schema, query, data)\n```\n\n```text\nval builder =\n new DefaultAstSchemaBuilder[JsValue] {\n override def resolveField(typeDefinition: TypeDefinition, definition: FieldDefinition) =\n typeDefinition.name match {\n case \"Query\" β\n c β c.ctx.asJsObject.fields get c.field.name map fromJson\n case _ β\n c β fromJson(c.value.asInstanceOf[JsObject].fields(c.field.name))\n }\n\n def fromJson(v: JsValue) = v match {\n case JsArray(l) β l\n case JsString(s) β s\n case JsNumber(n) β n.intValue()\n case other β other\n }\n }\n```\n\n```text\n{\n \"data\": {\n \"people\": [{\n \"firstName\": \"John\",\n \"age\": 30\n }]\n }\n}\n```\n\n```text\nShape\n```\n\n```text\nEntity\n```\n\n```text\nresolve\n```\n\n```text\nresolveField\n```\n\n```text\nresult\n```\n\n========================================\n\nComments:\n- Why is it such a pain, for example, to map sangria.ast.Type to sangria.schema.OutputType?\n- Many thanks, tenshi! This may be exactly what I'm looking for.\n- One problem, though. The case of JsNumber should return Int if c.field.fieldType is of the OutputType[Int] type, Long if OutputType[Long], etc. Unfortunately, we only get OutputType[_], with the TypeTag erased (so cannot compare typeOf[T] with =:=, either). This makes it very cumbersome to write a correct fromJson function, since it must account not only for ScalarLongType, but also for OptionType(ScalarLongType), as well as for enum and union types, etc. Still, this is a minor concern, which may hopefully be addressed in a future release of Sangria.\n- @silverberry the type information is available at runtime as well. Here is an example of function that can extract a correct scala type based on type info: github.com/OlegIlyenko/graphql-toolbox/blob/master/app/…","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":171,"estimatedTokens":1132}}792{"id":"stack-51830791","source":"stackoverflow","questionId":51830791,"title":"GraphQL.js - timestamp scalar type?","tags":["javascript","schema","graphql","graphql-js","scalar"],"text":"Title: GraphQL.js - timestamp scalar type?\nTags: javascript, schema, graphql, graphql-js, scalar\nSource: Stack Overflow\n\nQuestion:\nI am building a GraphQL schema programmatically and in need of a `Timestamp` scalar type; a *Unix Epoch timestamp* scalar type:\n\n```\nconst TimelineType = new GraphQLObjectType({\n name: 'TimelineType',\n fields: () => ({\n date: { type: new GraphQLNonNull(GraphQLTimestamp) },\n price: { type: new GraphQLNonNull(GraphQLFloat) },\n sold: { type: new GraphQLNonNull(GraphQLInt) }\n })\n});\n```\n\nUnfortunately, GraphQL.js **doesn't** have a `GraphQLTimestamp` nor a `GraphQLDate` type so the above doesn't work.\n\nI am expecting a `Date` input and I want to convert that to a timestamp. How would I go about creating my own GraphQL timestamp type?\n\n========================================\n\nCode:\n```js\nconst TimelineType = new GraphQLObjectType({\n name: 'TimelineType',\n fields: () => ({\n date: { type: new GraphQLNonNull(GraphQLTimestamp) },\n price: { type: new GraphQLNonNull(GraphQLFloat) },\n sold: { type: new GraphQLNonNull(GraphQLInt) }\n })\n});\n```\n\n```text\nTimestamp\n```\n\n```text\nGraphQLTimestamp\n```\n\n```text\nGraphQLDate\n```\n\n```text\nDate\n```\n\n```js\n/** Kind is an enum that describes the different kinds of AST nodes. */\nimport { Kind } from 'graphql/language';\nimport { GraphQLScalarType } from 'graphql';\n\nconst TimestampType = new GraphQLScalarType({\n name: 'Timestamp',\n serialize(date) {\n return (date instanceof Date) ? date.getTime() : null\n },\n parseValue(date) {\n try { return new Date(value); }\n catch (error) { return null; }\n },\n parseLiteral(ast) {\n if (ast.kind === Kind.INT) {\n return new Date(parseInt(ast.value, 10));\n }\n else if (ast.kind === Kind.STRING) {\n return this.parseValue(ast.value);\n }\n else {\n return null;\n }\n },\n});\n```\n\n```text\nGraphQLScalarType\n```\n\n```text\nTimestampType\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":87,"estimatedTokens":482}}793{"id":"stack-49283044","source":"stackoverflow","questionId":49283044,"title":"How do you validate a GraphQL mutation in Python","tags":["python","graphql"],"text":"Title: How do you validate a GraphQL mutation in Python\nTags: python, graphql\nSource: Stack Overflow\n\nQuestion:\nI am new to GraphQL. I am using Graphene-Django and have a mutation called `CreateUser`. It takes three arguments `username`, `email`, `password`. \n\nHow do I validate the data and return multiple errors back?\n\nI want something like this returned.\n\n```\n{ \n \"name\":[ \n \"Ensure this field has at least 2 characters.\"\n ],\n \"email\":[ \n \"This field may not be blank.\"\n ],\n \"password\":[ \n \"This field may not be blank.\"\n ]\n}\n```\n\nSo I can render the errors on the form like this:\n\nhttps://i.sstatic.net/PGZjh.png\n\nMy code so far:\n\n```\nfrom django.contrib.auth.models import User as UserModel\nfrom graphene_django import DjangoObjectType\nimport graphene\n\nclass User(DjangoObjectType):\n class Meta:\n model = UserModel\n only_fields = 'id', 'username', 'email'\n\nclass Query(graphene.ObjectType):\n users = graphene.List(User)\n user = graphene.Field(User, id=graphene.Int())\n\n def resolve_users(self, info):\n return UserModel.objects.all()\n\n def resolve_user(self, info, **kwargs):\n try:\n return UserModel.objects.get(id=kwargs['id'])\n except (UserModel.DoesNotExist, KeyError):\n return None\n\nclass CreateUser(graphene.Mutation):\n\n class Arguments:\n username = graphene.String()\n email = graphene.String()\n password = graphene.String()\n\n user = graphene.Field(User)\n\n def mutate(self, info, username, email, password):\n user = UserModel.objects.create_user(username=username, email=email, password=password)\n return CreateUser(user=user)\n\nclass Mutation(graphene.ObjectType):\n create_user = CreateUser.Field()\n\nschema = graphene.Schema(query=Query, mutation=Mutation)\n```\n\n========================================\n\nCode:\n```text\n{ \n \"name\":[ \n \"Ensure this field has at least 2 characters.\"\n ],\n \"email\":[ \n \"This field may not be blank.\"\n ],\n \"password\":[ \n \"This field may not be blank.\"\n ]\n}\n```\n\n```text\nfrom django.contrib.auth.models import User as UserModel\nfrom graphene_django import DjangoObjectType\nimport graphene\n\n\nclass User(DjangoObjectType):\n class Meta:\n model = UserModel\n only_fields = 'id', 'username', 'email'\n\n\nclass Query(graphene.ObjectType):\n users = graphene.List(User)\n user = graphene.Field(User, id=graphene.Int())\n\n def resolve_users(self, info):\n return UserModel.objects.all()\n\n def resolve_user(self, info, **kwargs):\n try:\n return UserModel.objects.get(id=kwargs['id'])\n except (UserModel.DoesNotExist, KeyError):\n return None\n\n\nclass CreateUser(graphene.Mutation):\n\n class Arguments:\n username = graphene.String()\n email = graphene.String()\n password = graphene.String()\n\n user = graphene.Field(User)\n\n def mutate(self, info, username, email, password):\n user = UserModel.objects.create_user(username=username, email=email, password=password)\n return CreateUser(user=user)\n\n\nclass Mutation(graphene.ObjectType):\n create_user = CreateUser.Field()\n\n\nschema = graphene.Schema(query=Query, mutation=Mutation)\n```\n\n```text\nCreateUser\n```\n\n```text\nusername\n```\n\n```text\nemail\n```\n\n```text\npassword\n```\n\n```text\ntype RegisterUserSuccess {\n user: User!\n}\n\ntype FieldError {\n fieldName: String!\n errors: [String!]!\n}\n\ntype RegisterUserError {\n fieldErrors: [FieldError!]!\n nonFieldErrors: [String!]!\n}\n\n\nunion RegisterUserPayload = RegisterUserSuccess | RegisterUserError\n\nmutation {\n registerUser(name: String, email: String, password: String): RegisterUserPayload!\n}\n```\n\n========================================\n\nComments:\n- Hi, I was looking for something similar too and came up with a small PoC to have Django Rest Framework like validation on Graphene: github.com/chpmrc/graphene-validator. Feel free to try it out, feedback is more than welcome! Not posting as an answer since it's not ready for release yet.\n- @MarcoChiappetta do you use this with GraphQL Code Generator / Formik / Yup? I'm new to this stack, but would your validator weave into that? Can you point to any articles/docs that use that full stack? There doesn't seem to be a lot of docs going from Graphene to the front end forms.","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":181,"estimatedTokens":1047}}794{"id":"stack-56341100","source":"stackoverflow","questionId":56341100,"title":"Complex query variables in GraphQL (via Gatsby)","tags":["graphql","gatsby"],"text":"Title: Complex query variables in GraphQL (via Gatsby)\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI am building a localized static website using Gatsby, with the help of `gatsby-plugin-intl`. This plugin adds a context variable named `intl` to pages (including template-based pages), which is an object: https://github.com/wiziple/gatsby-plugin-intl/blob/master/src/gatsby-node.js#L27-L34\n\nI would like to access the `intl.language` variable from the context within a page query. This is my (failing) code at this stage:\n\n```\nquery($slug: String!, $intl: String) {\n contentfulPerson(slug: {eq: $slug}, node_locale: {eq: $intl.language}) {\n name\n }\n}\n```\n\nContentful is the headless CMS I use and from which I would like to fetch data in the correct locale.\n\nObviously this code has two problems: `$intl` is not a string, and `$intl.language` is not syntactically correct. But I don't know how to fix either problem.\n\nI guess I could either fork the plugin or do something in my own `gatsby-node.js` to make the language available as a top-level variable in the context, but I'm interested to know if there is a way to do it directly.\nThe Gatsby docs say that query variables can be complex (https://www.gatsbyjs.org/docs/graphql-reference/#query-variables) but in the example they provide, they don't show how the types are defined or how to access a property within these variables.\n\nEDIT : I tried moving the language to a top-level context variable in my `gatsby-node.js` using this code:\n\n```\nexports.onCreatePage = ({page, actions}) => {\n const { createPage, deletePage } = actions\n deletePage(page)\n createPage({\n ...page,\n context: {\n ...page.context,\n language: page.context.intl.language\n }\n })\n}\n```\n\nbut the program runs out of memory (even when increasing `max_old_space_size`)\n\n========================================\n\nCode:\n```text\nquery($slug: String!, $intl: String) {\n contentfulPerson(slug: {eq: $slug}, node_locale: {eq: $intl.language}) {\n name\n }\n}\n```\n\n```js\nexports.onCreatePage = ({page, actions}) => {\n const { createPage, deletePage } = actions\n deletePage(page)\n createPage({\n ...page,\n context: {\n ...page.context,\n language: page.context.intl.language\n }\n })\n}\n```\n\n```text\ngatsby-plugin-intl\n```\n\n```text\nintl\n```\n\n```text\nintl.language\n```\n\n```text\n$intl\n```\n\n```text\n$intl.language\n```\n\n```text\ngatsby-node.js\n```\n\n```text\ngatsby-node.js\n```\n\n```text\nmax_old_space_size\n```\n\n```text\nexports.onCreatePage = ({ page, actions }) => {\n const { createPage, deletePage } = actions\n const oldPage = Object.assign({}, page)\n\n page.context.language = page.context.intl.language;\n if (page.context.language !== oldPage.context.language) {\n // Replace new page with old page\n deletePage(oldPage)\n createPage(page)\n }\n}\n```\n\n```text\nlanguage\n```\n\n========================================\n\nComments:\n- This is not a problem I have had to deal with yet personally, but I have done some research on it. I think looking at this repo might help you with your problem. You can look at `pages/index.jsx` afterwards to see how they have queried it.\n- Thanks for the reference @FranklinFarahani. I did come across it but unfortunately in this case the language is directly available as a top level variable, which makes it easy to query.\n- Well played! Thanks :)\n- Worked like a charm!","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":124,"estimatedTokens":839}}795{"id":"stack-43712128","source":"stackoverflow","questionId":43712128,"title":"How to modularize GraphQL schema when using `buildSchema`?","tags":["graphql"],"text":"Title: How to modularize GraphQL schema when using `buildSchema`?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nIt has been about a year since I updated my graphql-js dependency. I see now that there is a utility that simplifies schema generation: `buildSchema`. This function takes, as an arg, your entire schema, as a string, in the GraphQL language. That's awesome, but is there a way to modularize this? My schema is not super small, and would suck to cram into a single `.graphql` file. Is there some sort of utility or pattern for storing each type definition in its own file, for example?\n\n========================================\n\nTop Answer:\nYou can further improve your schema modularity by using `merge-graphql-schemas` package. \n\nHere is a modular graphql server seed - graphql-server-seed\n\nThe project structure allows you to separate your types and resolver to multiple files. Hope it helps!\n\n========================================\n\nCode:\n```text\nbuildSchema\n```\n\n```text\n.graphql\n```\n\n```text\nconst schema = makeExecutableSchema({\n typeDefs: [schema1, schema2, schema3, ...],\n resolvers: resolvers,\n});\n```\n\n```text\ngraphql-tools\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nmerge-graphql-schemas\n```\n\n```text\nconst { makeExecutableSchema } = require('graphql-tools')\nconst { glue } = require('schemaglue')\n\nconst { schema, resolver } = glue('src/graphql')\n\nconst executableSchema = makeExecutableSchema({\n typeDefs: schema,\n resolvers: resolver\n})\n```\n\n```text\n- src/\n |__ graphql/\n |__ product/\n | |__ schema.js\n | |__ resolver.js\n |\n |__ variant/\n |__ schema.js\n |__ resolver.js\n\n- index.js\n- package.json\n```\n\n========================================\n\nComments:\n- I wrote a library that can do this github.com/graphql-factory/graphql-factory\n- Here is an article on the best way to do this if you're using Apollo's graphql-tools: hackernoon.com/…\n- Here are the docs: dev.apollodata.com/tools/graphql-tools/…","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":79,"estimatedTokens":513}}796{"id":"stack-51637618","source":"stackoverflow","questionId":51637618,"title":"Cache GraphQL query with multiple ids using Apollo","tags":["caching","graphql","apollo","react-apollo","apollo-client"],"text":"Title: Cache GraphQL query with multiple ids using Apollo\nTags: caching, graphql, apollo, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nwe're using apollo client in a web application and are looking for ways to improve cache usage.\n\nWe have a query that takes an array of ids as parameter an example query with ids `foo` and `bar` would look like this:\n\n```\nquery routes {\n routes(routeNames: [\"foo\", \"bar\"]) {\n items {\n name\n route\n defaults\n }\n }\n}\n```\n\nThe cache setup looks like this:\n\n```\nexport const cacheRedirects = {\n Query: {\n routes: (_: any, args: RoutesArgs, { getCacheKey }: Resolver): Array =>\n args.routeNames.map(name => getCacheKey({ __typename: 'Route', name })),\n },\n};\n\nexport const dataIdFromObject = (object: QueryResult): ?string => {\n switch (object.__typename) {\n case 'Route':\n return `${object.__typename}:${object.name}`;\n default: return defaultDataIdFromObject(object);\n }\n};\n\nexport function newCache(): InMemoryCache {\n return new InMemoryCache({ dataIdFromObject, cacheRedirects });\n}\n```\n\nNow when using the query in several places in our client we'd like to fetch only data for routeNames not cached via network and retrieve the rest via cache.\n\nSo the problem boils down to this:\nWhen having one query that caches the results for `routeNames: [\"foo\", \"bar\"]` and later another query comes along asking for the routes for `routeNames: [\"bar\", \"baz\"]` we'd love to take the result corresponding to `\"bar\"` from cache and send a query for `routeNames: [\"baz\"]`.\n\nI'm uncertain whether and how this can be done with Apollo because in contrast to the cacheRedirect example here we deal with multiple ids rather than a single one.\n\nNow if we can't cache per array item the next best thing we could do would be to transform the ids into common cache keys so that `[\"foo\", \"bar\"]` and `[\"bar\", \"foo\"]` end up using the same cache key, but `[\"foo\", \"baz\"]` would use a different one.\n\nOf course the ideal thing would be to only fetch `\"baz\"` as the missing item in our scenario.\n\n========================================\n\nCode:\n```text\nquery routes {\n routes(routeNames: [\"foo\", \"bar\"]) {\n items {\n name\n route\n defaults\n }\n }\n}\n```\n\n```text\nexport const cacheRedirects = {\n Query: {\n routes: (_: any, args: RoutesArgs, { getCacheKey }: Resolver<'name'>): Array<CacheKey> =>\n args.routeNames.map(name => getCacheKey({ __typename: 'Route', name })),\n },\n};\n\nexport const dataIdFromObject = (object: QueryResult): ?string => {\n switch (object.__typename) {\n case 'Route':\n return `${object.__typename}:${object.name}`;\n default: return defaultDataIdFromObject(object);\n }\n};\n\nexport function newCache(): InMemoryCache {\n return new InMemoryCache({ dataIdFromObject, cacheRedirects });\n}\n```\n\n```text\nfoo\n```\n\n```text\nbar\n```\n\n```text\nrouteNames: [\"foo\", \"bar\"]\n```\n\n```text\nrouteNames: [\"bar\", \"baz\"]\n```\n\n```text\n\"bar\"\n```\n\n```text\nrouteNames: [\"baz\"]\n```\n\n```text\n[\"foo\", \"bar\"]\n```\n\n```text\n[\"bar\", \"foo\"]\n```\n\n```text\n[\"foo\", \"baz\"]\n```\n\n```text\n\"baz\"\n```\n\n```text\nreadQuery()\n```\n\n```text\nreadFragment()\n```\n\n```text\nfetchPolicy\n```\n\n```text\ncache-only\n```\n\n========================================\n\nComments:\n- Great question! What did you end up with?\n- Thanks :) - I did a project ~3y ago for an apollo-link to rewrite queries, but lost focus on it somewhen in August 2018. So something was started but never finished, and I believe Apollo substantially restructured their codebase since - so I don't expect any of my prior code to be in a useful state. For practical purposes I think it has become a combination of two things: some parts of the schema are now easier to cache/use, and for others we're not currently caring the same.\n- Hey thanks - we'll investigate the middleware approach. I'll accept accordingly ;)","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":153,"estimatedTokens":954}}797{"id":"stack-60289062","source":"stackoverflow","questionId":60289062,"title":"Allow optional GraphQL data in Gatsby","tags":["reactjs","graphql","gatsby","yaml-front-matter"],"text":"Title: Allow optional GraphQL data in Gatsby\nTags: reactjs, graphql, gatsby, yaml-front-matter\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a Type in my `gatsby-node.js` file that supports an optional value. Which I think is done with `[String!]!`.\n\n**How can I load the new Type that I've created inside `gatsby-node.js` on `home.js`?**\n\ngatsby-node.js:\n\n```\nconst path = require('path');\nexports.createSchemaCustomization = ({ actions }) => {\n const { createTypes } = actions;\n const typeDefs = `\n type markdownRemark implements Node {\n frontmatter: Features\n }\n type Features {\n title: [String!]!\n description: [String!]!\n }\n `;\n createTypes(typeDefs);\n};\n```\n\npages/home/home.js:\n\n```\nexport const query = graphql`\n query HomeQuery($path: String!) {\n markdownRemark(frontmatter: { path: { eq: $path } }) {\n html\n frontmatter {\n features {\n title\n description\n }\n }\n }\n }\n`;\n```\n\nhome.md:\n\n```\n---\npath: \"/\"\nfeatures:\n - title: Barns\n description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.\n - title: Private Events\n description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.\n - title: Food and Drinks\n description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.\n - title: Spa\n description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.\n---\n```\n\nThis needs to work so that if the `features` array inside `home.md`'s front matter is empty, then GraphQL doesn't throw an error.\n\nPlease don't tell me to always include at least one value in the array, because this isn't practical, my solution needs to support no values in my array.\n\nI've spent two hours going through documentation/issues in circles trying to find a working solution, please can someone save me!\n\n========================================\n\nCode:\n```text\nconst path = require('path');\nexports.createSchemaCustomization = ({ actions }) => {\n const { createTypes } = actions;\n const typeDefs = `\n type markdownRemark implements Node {\n frontmatter: Features\n }\n type Features {\n title: [String!]!\n description: [String!]!\n }\n `;\n createTypes(typeDefs);\n};\n```\n\n```text\nexport const query = graphql`\n query HomeQuery($path: String!) {\n markdownRemark(frontmatter: { path: { eq: $path } }) {\n html\n frontmatter {\n features {\n title\n description\n }\n }\n }\n }\n`;\n```\n\n```text\n---\npath: \"/\"\nfeatures:\n - title: Barns\n description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.\n - title: Private Events\n description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.\n - title: Food and Drinks\n description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.\n - title: Spa\n description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.\n---\n```\n\n```text\ngatsby-node.js\n```\n\n```text\n[String!]!\n```\n\n```text\ngatsby-node.js\n```\n\n```text\nhome.js\n```\n\n```text\nfeatures\n```\n\n```text\nhome.md\n```\n\n```text\nconst typeDefs = `\n type markdownRemark implements Node {\n // Use custom frontmatter type\n frontmatter: Frontmatter\n }\n // Define custom frontmatter type\n type FrontMatter {\n // Nullable array of Feature elements\n features: [Feature]\n }\n // Feature has nullable fields title and description\n type Feature {\n title: String\n description: String\n }\n`;\n```\n\n```text\nString!\n```\n\n```text\n[Episode!]!\n```\n\n```text\nEpisode\n```\n\n```text\nEpisode!\n```\n\n```text\nEpisode\n```\n\n```text\n!\n```\n\n```text\n[String!]!\n```\n\n```text\n!\n```\n\n```text\n[String]\n```\n\n```text\ntitle\n```\n\n```text\ndescription\n```\n\n```text\nfeatures\n```\n\n```text\nFeature\n```\n\n```text\nFeature\n```\n\n```text\nFeature\n```\n\n```text\ntitle\n```\n\n```text\ndescription\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":230,"estimatedTokens":1090}}798{"id":"stack-43603182","source":"stackoverflow","questionId":43603182,"title":"Passing complex arguments to GraphQL mutations","tags":["javascript","node.js","graphql"],"text":"Title: Passing complex arguments to GraphQL mutations\nTags: javascript, node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI've been using GraphQL in a Node server using graphql-js, and GraphQL has shown to be an extremely valuable abstraction, but I'm running into an issue.\n\nI often find myself needing to pass large structured objects as arguments to GraphQL mutations, using `GraphQLInputObjectType`. This would be fine, but GraphQL doesn't support the use of JSON notation :(. So I end up just sending a string containing the JSON, for the server to deal with.\n\n```\nconst objectStr = JSON.stringify(object).replace(new RegExp(\"\\\"\", \"g\"), \"'\")\n\ngraphQLClient(`{\n user: updateUser(someDataObject: \"${objectStr}\") {...}\n}`)\n```\n\nBut now I'm not benefiting at all from GraphQL!\n\nI have a feeling I'm doing something wrong here. What is the GraphQL way of sending, say, signup form data, to a mutation?\n\n========================================\n\nCode:\n```text\nconst objectStr = JSON.stringify(object).replace(new RegExp(\"\\\"\", \"g\"), \"'\")\n\ngraphQLClient(`{\n user: updateUser(someDataObject: \"${objectStr}\") {...}\n}`)\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\n/* Query */\nmutation Update($input: UpdateUserInput!) {\n updateUser(input: $input) {\n changedUser {\n id\n username\n }\n }\n}\n\n/* Variables (as JSON) */\n{\n \"input\": {\n \"username\": \"elon@spacex.com\",\n \"password\": \"SuperSecretPassword\"\n }\n}\n```\n\n```text\n{\n \"query\": <GraphQL query from above as a string>,\n \"variables\": <JSON object from above>\n}\n```\n\n========================================\n\nComments:\n- Missing part of this solution is where and how do you define UpdateUserInput.\n- the website is down, so the documentation can be found here github.com/scaphold-io/scaphold-docs/blob/master/docs/coreda‌​ta/…","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":68,"estimatedTokens":465}}799{"id":"stack-65491399","source":"stackoverflow","questionId":65491399,"title":"Gatsby doesn't render MD in component inside of mdx file","tags":["javascript","reactjs","graphql","gatsby","mdxjs"],"text":"Title: Gatsby doesn't render MD in component inside of mdx file\nTags: javascript, reactjs, graphql, gatsby, mdxjs\nSource: Stack Overflow\n\nQuestion:\nWhat is working:\n\n- The layout is correctly applied to each of my pages\n\n- The MDX file correctly gets the Hero and section component and renders the HTML/CSS of the container correctly\n\n- The data from MDX is loaded and displayed\n\nWhat is NOT working:\n\n- The MD within the Hero or the Section Shortcode is not being rendered! # is not transformed into H1 etc.\n\nWhat i have tried:\n\n- Using the MDXRender in Section & Hero => Error\n\n- Use the component directly in the MDX file instead of shortcode\n\nQuestion:\n\nIs it not possible to render the MD correctly within the shortcode?\nIn other words, is the MDX not rendered recurisvely?\n\ncontent/index.mdx:\n\n```\n---\ntitle: Main Content English\nslug: /main-content/\n---\n\n# This is a test, but never gets transformed\n\n# In Section Headline\n\n# ABC\n\nOfficia cillum _asdasd_ et duis dolor occaecat velit culpa. Cillum eu sint adipisicing labore incididunt nostrud tempor fugiat. Occaecat ex id fugiat laborum ullamco. Deserunt sint quis aliqua consequat ullamco Lorem dolor pariatur laboris. Laborum officia ut magna exercitation elit velit mollit do. Elit minim nostrud cillum reprehenderit deserunt consequat. Aliqua ex cillum sunt exercitation deserunt sit aliquip aliquip ea proident cillum quis.\n```\n\nMy layout.js looks like this:\n\n```\nimport React, {useEffect} from \"react\";\n\nimport \"./Layout.css\";\n\nimport { MDXProvider } from \"@mdx-js/react\";\nimport { MdxLink } from \"gatsby-theme-i18n\";\n...\n\nimport Hero from \"../Hero/HomepageHero/HomepageHero\"\nimport Section from \"../Section/Section\"\n\nconst components = {\n a: MdxLink,\n Hero, Section\n};\n\nexport default function Layout({ children }) {\n ...\n return (\n \n \n\n \n\n \n {children}\n \n\n \n\n \n \n );\n}\n```\n\nmy index.js page (loaded automatically) looks like this:\n\n```\nimport * as React from \"react\";\n\nimport { graphql } from \"gatsby\";\n\nimport Layout from \"../components/Layout/layout\";\nimport { MDXRenderer } from \"gatsby-plugin-mdx\";\n\nconst IndexPage = ({ data }) => {\n\n return (\n \n {data.allFile.nodes.map(({ childMdx: node }) => (\n \n {node ? (\n {node.body}\n ) : (\n This page has not been translated yet.\n )}\n \n ))}\n \n );\n};\n\nexport default IndexPage;\n\nexport const query = graphql`\n query($locale: String!) {\n allFile(\n filter: {\n sourceInstanceName: { eq: \"content\" }\n childMdx: { fields: { locale: { eq: $locale } } }\n }\n ) {\n nodes {\n childMdx {\n body\n }\n }\n }\n }\n`;\n```\n\nGatsby Config:\n\n```\nmodule.exports = {\n siteMetadata: {\n siteUrl: \"localhost:8000\",\n title: \"app\",\n },\n plugins: [\n {\n resolve: \"gatsby-plugin-google-analytics\",\n options: {\n trackingId: \"\",\n },\n },\n \"gatsby-plugin-sharp\",\n \"gatsby-plugin-react-helmet\",\n \"gatsby-plugin-sitemap\",\n \"gatsby-plugin-offline\",\n {\n resolve: \"gatsby-plugin-manifest\",\n options: {\n icon: \"src/images/icon.png\",\n },\n },\n \"gatsby-transformer-sharp\",\n {\n resolve: \"gatsby-source-filesystem\",\n options: {\n name: \"images\",\n path: \"./src/images/\",\n },\n __key: \"images\",\n },\n {\n resolve: `gatsby-theme-i18n`,\n options: {\n defaultLang: `en`,\n locales: `en el de`,\n configPath: require.resolve(`${__dirname}/i18n/config.json`),\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `pages`,\n path: `${__dirname}/src/pages/`,\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `content`,\n path: `${__dirname}/src/content/`,\n },\n },\n {\n resolve: `gatsby-plugin-mdx`,\n options: {\n defaultLayouts: {\n default: require.resolve(`./src/components/Layout/layout.js`),\n },\n },\n },\n ],\n};\n```\n\nSection.js Component\n\n```\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\nimport \"./Section.css\";\n\nexport default function Section(props) {\n let content = props.children\n if (props.centered) {\n content = (\n \n {props.children}\n \n );\n }\n return {content};\n}\n\nSection.propTypes = {\n centered: PropTypes.bool,\n children: PropTypes.element,\n};\n```\n\n========================================\n\nTop Answer:\nWith MDX you are rendering JSX inside a Markdown (**MD** + JS**X**) file so, `#` it's not recognized as a shortcode when it's wrapped by a JSX component when it's in the same declarative line:\n\nChange:\n\n```\n# This is a test, but never gets transformed\n```\n\nTo:\n\n```\n\n # This is a test, but never gets transformed\n\n```\n\nAlternatively, you can also change:\n\n```\n# This is a test, but never gets transformed\n```\n\nTo:\n\n```\n\n### This is a test, but never gets transformed\n\n```\n\nAnother thing that may work for you is using a Markdown parser (like markdown-to-jsx) and:\n\n```\n---\ntitle: Main Content English\nslug: /main-content/\n---\n\nimport Markdown from 'markdown-to-jsx';\n\n# This is a test, but never gets transformed\n\n# In Section Headline\n\n# ABC\n\nOfficia cillum _asdasd_ et duis dolor occaecat velit culpa. Cillum eu sint adipisicing labore incididunt nostrud tempor fugiat. Occaecat ex id fugiat laborum ullamco. Deserunt sint quis aliqua consequat ullamco Lorem dolor pariatur laboris. Laborum officia ut magna exercitation elit velit mollit do. Elit minim nostrud cillum reprehenderit deserunt consequat. Aliqua ex cillum sunt exercitation deserunt sit aliquip aliquip ea proident cillum quis.\n```\n\nAlternatively, you add a custom mapping component, as you do with `MdxLink` but using your own component to parse the `children` as `` dependency does.\n\n========================================\n\nCode:\n```text\n---\ntitle: Main Content English\nslug: /main-content/\n---\n\n<Hero># This is a test, but never gets transformed</Hero>\n\n<Section># In Section Headline</Section>\n\n# ABC\n\nOfficia cillum _asdasd_ et duis dolor occaecat velit culpa. Cillum eu sint adipisicing labore incididunt nostrud tempor fugiat. Occaecat ex id fugiat laborum ullamco. Deserunt sint quis aliqua consequat ullamco Lorem dolor pariatur laboris. Laborum officia ut magna exercitation elit velit mollit do. Elit minim nostrud cillum reprehenderit deserunt consequat. Aliqua ex cillum sunt exercitation deserunt sit aliquip aliquip ea proident cillum quis.\n```\n\n```text\nimport React, {useEffect} from \"react\";\n\nimport \"./Layout.css\";\n\nimport { MDXProvider } from \"@mdx-js/react\";\nimport { MdxLink } from \"gatsby-theme-i18n\";\n...\n\nimport Hero from \"../Hero/HomepageHero/HomepageHero\"\nimport Section from \"../Section/Section\"\n\n\nconst components = {\n a: MdxLink,\n Hero, Section\n};\n\n\nexport default function Layout({ children }) {\n ...\n return (\n <div className=\"appGrid\">\n <Header />\n\n <ScrollToTopButton />\n\n <div className=\"cell contentCell\">\n <MDXProvider components={components}>{children}</MDXProvider>\n </div>\n\n <Footer />\n\n <Copyright />\n </div>\n );\n}\n```\n\n```text\nimport * as React from \"react\";\n\nimport { graphql } from \"gatsby\";\n\nimport Layout from \"../components/Layout/layout\";\nimport { MDXRenderer } from \"gatsby-plugin-mdx\";\n\n\nconst IndexPage = ({ data }) => {\n\n return (\n <Layout>\n {data.allFile.nodes.map(({ childMdx: node }) => (\n <div>\n {node ? (\n <MDXRenderer>{node.body}</MDXRenderer>\n ) : (\n <div>This page has not been translated yet.</div>\n )}\n </div>\n ))}\n </Layout>\n );\n};\n\nexport default IndexPage;\n\nexport const query = graphql`\n query($locale: String!) {\n allFile(\n filter: {\n sourceInstanceName: { eq: \"content\" }\n childMdx: { fields: { locale: { eq: $locale } } }\n }\n ) {\n nodes {\n childMdx {\n body\n }\n }\n }\n }\n`;\n```\n\n```text\nmodule.exports = {\n siteMetadata: {\n siteUrl: \"localhost:8000\",\n title: \"app\",\n },\n plugins: [\n {\n resolve: \"gatsby-plugin-google-analytics\",\n options: {\n trackingId: \"\",\n },\n },\n \"gatsby-plugin-sharp\",\n \"gatsby-plugin-react-helmet\",\n \"gatsby-plugin-sitemap\",\n \"gatsby-plugin-offline\",\n {\n resolve: \"gatsby-plugin-manifest\",\n options: {\n icon: \"src/images/icon.png\",\n },\n },\n \"gatsby-transformer-sharp\",\n {\n resolve: \"gatsby-source-filesystem\",\n options: {\n name: \"images\",\n path: \"./src/images/\",\n },\n __key: \"images\",\n },\n {\n resolve: `gatsby-theme-i18n`,\n options: {\n defaultLang: `en`,\n locales: `en el de`,\n configPath: require.resolve(`${__dirname}/i18n/config.json`),\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `pages`,\n path: `${__dirname}/src/pages/`,\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `content`,\n path: `${__dirname}/src/content/`,\n },\n },\n {\n resolve: `gatsby-plugin-mdx`,\n options: {\n defaultLayouts: {\n default: require.resolve(`./src/components/Layout/layout.js`),\n },\n },\n },\n ],\n};\n```\n\n```text\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\nimport \"./Section.css\";\n\nexport default function Section(props) {\n let content = props.children\n if (props.centered) {\n content = (\n <div className=\"grid-container \">\n {props.children}\n </div>\n );\n }\n return <div className=\"section\">{content}</div>;\n}\n\nSection.propTypes = {\n centered: PropTypes.bool,\n children: PropTypes.element,\n};\n```\n\n```text\n---\ntitle: Main Content English\nslug: /main-content/\n---\n\n<Hero>\n\n# This is a test, but never gets transformed\n\n</Hero>\n\n<Section>\n\n# In Section Headline\n\n</Section>\n\n...\n```\n\n```text\n<Hero># This is a test, but never gets transformed</Hero>\n```\n\n```text\n<Hero>\n # This is a test, but never gets transformed\n</Hero>\n```\n\n```text\n<Hero># This is a test, but never gets transformed</Hero>\n```\n\n```text\n<Hero><h1> This is a test, but never gets transformed</h1></Hero>\n```\n\n```text\n---\ntitle: Main Content English\nslug: /main-content/\n---\n\nimport Markdown from 'markdown-to-jsx';\n\n\n<Hero><Markdown># This is a test, but never gets transformed</Markdown></Hero>\n\n<Section><Markdown># In Section Headline</Markdown></Section>\n\n# ABC\n\nOfficia cillum _asdasd_ et duis dolor occaecat velit culpa. Cillum eu sint adipisicing labore incididunt nostrud tempor fugiat. Occaecat ex id fugiat laborum ullamco. Deserunt sint quis aliqua consequat ullamco Lorem dolor pariatur laboris. Laborum officia ut magna exercitation elit velit mollit do. Elit minim nostrud cillum reprehenderit deserunt consequat. Aliqua ex cillum sunt exercitation deserunt sit aliquip aliquip ea proident cillum quis.\n```\n\n```text\n#\n```\n\n```text\nMdxLink\n```\n\n```text\nchildren\n```\n\n```text\n<Markdown>\n```\n\n========================================\n\nComments:\n- As weird of a solution as this is, It seems there is no other way of rendering `gatsby-image` components inside html currently other than the markdown `` approach and this is the only solution that works for me.","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":547,"estimatedTokens":2714}}800{"id":"stack-53960809","source":"stackoverflow","questionId":53960809,"title":"Get latest release without prerelease in GraphQL","tags":["github","graphql","github-api"],"text":"Title: Get latest release without prerelease in GraphQL\nTags: github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nI'm migrating my connection with GitHub REST API to GraphQL API and I'm confused about getting latest release.\n\nWhen I use this endpoint bellow to get latest release with REST API it will never return Draft releases or prereleases.\n\n```\n/repos/:owner/:repo/releases/latest\n```\n\nBut, when I do the same with GraphQL API I can't filter that, using the query bellow I get the latest release but if it is and prerelease I'll have to query again to find another one.\n\n```\n{\n InovaFarmaApi: repository(owner: \"precisaosistemas\", name: \"inovafarma-api\") {\n ...releaseData\n }\n}\n\nfragment releaseData on Repository {\n releases (last: 2) {\n nodes {\n isPrerelease\n }\n }\n}\n```\n\nCan I filter for only release and not Draft releases or prereleases?\n\n========================================\n\nCode:\n```text\n/repos/:owner/:repo/releases/latest\n```\n\n```text\n{\n InovaFarmaApi: repository(owner: \"precisaosistemas\", name: \"inovafarma-api\") {\n ...releaseData\n }\n}\n\nfragment releaseData on Repository {\n releases (last: 2) {\n nodes {\n isPrerelease\n }\n }\n}\n```\n\n```graphql\nquery GetRelease($owner: String!, $name: String!, $cursor: String) {\n repository(owner: $owner, name: $name) {\n releases(before: $cursor,\n last: 1,\n orderBy: {field: CREATED_AT, order: DESC}) {\n pageInfo { hasPreviousPage, startCursor }\n nodes {\n isPrerelease\n ...OtherReleaseData\n }\n }\n }\n}\n```\n\n```text\nCREATED_AT\n```\n\n```text\nNAME\n```\n\n```text\nisPrerelease\n```\n\n```text\nhasPreviousPage\n```\n\n```text\nstartCursor\n```\n\n```text\ncursor\n```\n\n========================================\n\nComments:\n- checkout docs.github.com/en/graphql/reference/objects#repository. There is a `latestRelease` field. You could probably find out how to use it with the explorer","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":100,"estimatedTokens":479}}801{"id":"stack-53838475","source":"stackoverflow","questionId":53838475,"title":"Apollo-server 2 validation middleware","tags":["javascript","graphql","apollo-server"],"text":"Title: Apollo-server 2 validation middleware\nTags: javascript, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI want to add a validation layer to the apollo server.\nIt should run after every graphql query / mutation but before the resolver function. The validation layer will need to know the graphql query / mutation being called and the passed parameters. It will throw an error if its invalid and prevent the resolver function from running.\n\nI'm unclear where to inject it without manually placing it in each resolver function.\n\n========================================\n\nTop Answer:\nyou can add your validation method inside `context` where you can also get request parameters, query, headers, etc\n\nYou can also consider implementing custom directive which can be applied on schema level.\n\nref https://www.apollographql.com/docs/apollo-server/features/authentication.html\n\n========================================\n\nCode:\n```text\nconst schema = makeExecutableSchema({ resolvers, typeDefs })\nconst rootLevelResolver = (root, args, context, info) => {\n // Your validation logic here. Throwing an error will prevent the wrapped resolver from executing.\n // Note: whatever you return here will be passed as the parent value to the wrapped resolver\n}\naddSchemaLevelResolveFunction(schema, rootLevelResolver)\n```\n\n```text\ndirective @customValidation on FIELD_DEFINITION\n\ntype Query {\n someField: String @customValidation\n someOtherField: String\n}\n```\n\n```text\ngraphql-tools\n```\n\n```text\naddSchemaLevelResolveFunction\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nSubscription\n```\n\n```text\ncontext\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":63,"estimatedTokens":405}}802{"id":"stack-49798230","source":"stackoverflow","questionId":49798230,"title":"Angular Apollo use response from refetch query within a mutation","tags":["angular","graphql","apollo"],"text":"Title: Angular Apollo use response from refetch query within a mutation\nTags: angular, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm working on an Angular project with Apollo and GraphQL. I have a mutation that updates a list of accounts with relevant details associated with it. After the successful mutation, I am using refetchqueries to query the API for updated list of accounts. Everything works till this part.\n\n```\nthis.apollo.mutate({\n mutation: mutationCreateNewAccount,\n variables: {\n accountNumber: this.accountNumber,\n accountType: this.accountType,\n routingNumber: this.routingNumber,\n nameOfAcountHolder: this.name\n },\n refetchQueries: [{\n query: queryAccounts,\n variables: { accountNumber: this.accountNumber }\n }]}).subscribe(({ data }) => console.log(data),\n```\n\nThe 'data' for the subscription returns response from the mutation but is there a way I could use the data returned by 'queryAccounts' which is also run as part of this mutation?\n\nThere seems to be a way to do this in react but I was unsuccessful to do something similar in Angular.\n\n========================================\n\nTop Answer:\nYou can have a watchQuery that will always update when refetched\n\n```\nthis.apollo.watchQuery({\n query: query,\n variables: variables\n })\n .valueChanges\n .pipe(\n map(res => res.data)\n )\n .subscribe(data => {\n //Updated your data here\n }, err => {\n\n })\n })\n```\n\n========================================\n\nCode:\n```text\nthis.apollo.mutate({\n mutation: mutationCreateNewAccount,\n variables: {\n accountNumber: this.accountNumber,\n accountType: this.accountType,\n routingNumber: this.routingNumber,\n nameOfAcountHolder: this.name\n },\n refetchQueries: [{\n query: queryAccounts,\n variables: { accountNumber: this.accountNumber }\n }]}).subscribe(({ data }) => console.log(data),\n```\n\n```text\napollo.mutate()\n```\n\n```text\nrefetchQueries\n```\n\n```text\nconsole.log(data)\n```\n\n```text\nrefetchQueries\n```\n\n```text\nthis.apollo.watchQuery({\n query: query,\n variables: variables\n })\n .valueChanges\n .pipe(\n map(res => res.data)\n )\n .subscribe(data => {\n //Updated your data here\n }, err => {\n\n })\n })\n```\n\n========================================\n\nComments:\n- Sure. But I thought there would be a way to access the query response without having to create a new watchQuery and subscription.","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":103,"estimatedTokens":624}}803{"id":"stack-41840798","source":"stackoverflow","questionId":41840798,"title":"Given a set of GraphQL variable types, is it possible to use the client schema to create a map of all valid values for each type in the set","tags":["javascript","graphql","relay"],"text":"Title: Given a set of GraphQL variable types, is it possible to use the client schema to create a map of all valid values for each type in the set\nTags: javascript, graphql, relay\nSource: Stack Overflow\n\nQuestion:\nTitle mostly says it all: I'm building a react / relay application which will allow the user to dynamically create charts at runtime displaying their various income streams over a specified time range. One feature of this chart is the ability of the user to specify the sampling interval of each income stream (e.g. `YEAR`, `QUARTER`, `MONTH`, `WEEK`, etc.) as a parameter of each stream. \n\nThese values are defined in the schema as a `GraphQLInputObjectType` instance as follows:\n\n```\nenum timeSeriesIntervalEnum {\n YEAR\n QUARTER\n MONTH\n WEEK\n}\n```\n\nOn the client-side, I have `react-relay` fragments defined of the following form:\n\n```\nfragment on BalanceSheet {\n income {\n # some income stream\n afterTax { \n values(interval: $samplingInterval)\n dates(interval: $samplingInterval)\n }\n }\n}\n```\n\nThis variable value will be populated as part of dropdown menu in a separate component where each value in the dropdown should correspond to a valid `timeSeriesIntervalEnum` value. \n\nAlthough it would certainly be possible to simply hardcode these values in, the underlying API is still being changed quite often and **I would like to reduce coupling and instead populate these fields dynamically by specifying the variable type for a given dropdown (e.g. `timeSeriesIntervalEnum`) and then use the graphql client schema to parse the values and populate either a config json file (pre-runtime) or assign the values dynamically at runtime.**\n\n*NOTE: I already do a bit of query string and fragment transpilation pre-start, so I'm not averse to creating json config files as part of this process if that is required.*\n\n========================================\n\nCode:\n```text\nenum timeSeriesIntervalEnum {\n YEAR\n QUARTER\n MONTH\n WEEK\n}\n```\n\n```text\nfragment on BalanceSheet {\n income {\n # some income stream\n afterTax { \n values(interval: $samplingInterval)\n dates(interval: $samplingInterval)\n }\n }\n}\n```\n\n```text\nYEAR\n```\n\n```text\nQUARTER\n```\n\n```text\nMONTH\n```\n\n```text\nWEEK\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\nreact-relay\n```\n\n```text\ntimeSeriesIntervalEnum\n```\n\n```text\ntimeSeriesIntervalEnum\n```\n\n```text\n{\n __type(name: \"timeSeriesIntervalEnum\") {\n name\n enumValues {\n name\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"__type\": {\n \"name\": \"timeSeriesIntervalEnum\",\n \"enumValues\": [\n {\n \"name\": \"YEAR\"\n },\n {\n \"name\": \"QUARTER\"\n },\n {\n \"name\": \"MONTH\"\n },\n {\n \"name\": \"WEEK\"\n }\n ]\n }\n }\n}\n```\n\n========================================\n\nComments:\n- How is the name of the enum known to the client deterministically?","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":133,"estimatedTokens":723}}804{"id":"stack-49034442","source":"stackoverflow","questionId":49034442,"title":"How to create issues and labels with the Github GraphQL Api?","tags":["graphql","github-api","github-graphql"],"text":"Title: How to create issues and labels with the Github GraphQL Api?\nTags: graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nV3 of the Api provides a REST interface for this:\n\n POST /repos/:owner/:repo/issues\n\n```\n{\n \"title\": \"Found a bug\",\n \"body\": \"I'm having a problem with this.\",\n \"assignees\": [\n \"octocat\"\n ],\n \"milestone\": 1,\n \"labels\": [\n \"bug\"\n ]\n}\n```\n\nhttps://developer.github.com/v3/issues/\n\nYou can even add an emoji reaction with the GraphQL Api:\n\nhttps://developer.github.com/v4/mutation/addreaction/\n\nOr a comment:\n\nhttps://developer.github.com/v4/mutation/addcomment/\n\nI have looked at the mutations available and I can only conclude that you cannot make an issue with the new Api.\n\nhttps://developer.github.com/v4/mutation/\n\n========================================\n\nCode:\n```text\n{\n \"title\": \"Found a bug\",\n \"body\": \"I'm having a problem with this.\",\n \"assignees\": [\n \"octocat\"\n ],\n \"milestone\": 1,\n \"labels\": [\n \"bug\"\n ]\n}\n```\n\n========================================\n\nComments:\n- It seems they added some mutations in \"preview\" developer.github.com/v4/mutation/createissue\n- Hey appreciate the answer. Seems like a few other people have requested this schema already. platform.github.community/t/schema-request-to-create-an-issu‌​e/… platform.github.community/t/… platform.github.community/t/how-do-i-create-an-issue/3979 Do you think you guys will implement this soon or is still going to be a while? Also is there any benefit to me adding a new request - will it help?\n- @JonathanWood in general, mutations are slower to be added. We're still trying to identify the best way to do them. That said, a mutation to create issues will likely be one of the highest priorities because of how in demand it is.\n- I have submitted an additional request detailing the desired schema: platform.github.community/t/… Thanks @bswinnerton","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":61,"estimatedTokens":478}}805{"id":"stack-70528857","source":"stackoverflow","questionId":70528857,"title":"How to use Graphql typescript types in react","tags":["reactjs","typescript","graphql"],"text":"Title: How to use Graphql typescript types in react\nTags: reactjs, typescript, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a react app with a keystone.js backend and a graphql api\n\nI have a list of products in keystones.js and a simple graphql query\n\n```\nimport gql from \"graphql-tag\";\n\nexport const ALL_PRODUCTS_QUERY = gql`\n query ProductData{\n allProducts{\n id\n price\n description\n name\n }\n }\n`\n```\n\nI'm using apollo codegen to generate the types for the graphql so I get\n\n```\nexport interface ProductData_allProducts {\n __typename: \"Product\";\n id: string;\n price: number | null;\n description: string | null;\n name: string | null;\n}\n\nexport interface ProductData {\n /**\n * Search for all Product items which match the where clause. \n */\n allProducts: (ProductData_allProducts | null)[] | null;\n}\n```\n\nIn React I can list the products and use the types in the code, here I'm using ``\n\n```\nimport { useQuery } from \"@apollo/client\";\nimport {ALL_PRODUCTS_QUERY} from '../queries/index'\nimport { ProductData } from \"../generated/ProductData\";\n\nconst Products = () => {\n\n const {data, error, loading} = useQuery(ALL_PRODUCTS_QUERY)\n if(loading) return Loading\n\n if(error) return Error: {error.message}\n\n \n\n return (\n \n \n {data?.allProducts?.map(product => (\n {product?.name}\n ))}\n \n \n );\n};\n\nexport default Products;\n```\n\nInstead of using `{product?.name}` I would like to create a `Product` component\n\n```\nimport React from 'react';\nimport { ProductData, ProductData_allProducts } from '../generated/ProductData';\n\nconst Product = ({product}:ProductData_allProducts) => {\n return (\n {product.name}\n\n );\n};\n\nexport default Product;\n```\n\nbut what should the type be for `product` here I get an error saying\n\n```\nProperty 'product' does not exist on type 'ProductData_allProducts'.\n```\n\nand on the Products page\n\n```\nimport { useQuery } from \"@apollo/client\";\nimport {ALL_PRODUCTS_QUERY} from '../queries/index'\nimport { ProductData } from \"../generated/ProductData\";\nimport Product from \"./Product\";\n\nconst Products = () => {\n\n const {data, error, loading} = useQuery(ALL_PRODUCTS_QUERY)\n if(loading) return Loading\n\n if(error) return Error: {error.message}\n\n \n\n return (\n \n \n {data?.allProducts?.map(product => (\n \n ))}\n \n \n );\n};\n\nexport default Products;\n```\n\nI now get an error on the product prop\n\n```\nType '{ product: ProductData_allProducts | null; }' is not assignable to type 'IntrinsicAttributes & ProductData_allProducts'.\n Property 'product' does not exist on type 'IntrinsicAttributes & ProductData_allProducts'.\n```\n\nSo what should the types be on the Product page when passing in the product\n\n========================================\n\nTop Answer:\nDoes the following work for you?\n\n```\ninterface ProductComponentProps {\n product: ProductData_allProducts\n}\n\nconst Product = ({product}: ProductComponentProps) => {\n return (\n {product.name}\n\n );\n};\n```\n\n========================================\n\nCode:\n```text\nimport gql from \"graphql-tag\";\n\nexport const ALL_PRODUCTS_QUERY = gql`\n query ProductData{\n allProducts{\n id\n price\n description\n name\n }\n }\n`\n```\n\n```text\nexport interface ProductData_allProducts {\n __typename: \"Product\";\n id: string;\n price: number | null;\n description: string | null;\n name: string | null;\n}\n\nexport interface ProductData {\n /**\n * Search for all Product items which match the where clause. \n */\n allProducts: (ProductData_allProducts | null)[] | null;\n}\n```\n\n```text\nimport { useQuery } from \"@apollo/client\";\nimport {ALL_PRODUCTS_QUERY} from '../queries/index'\nimport { ProductData } from \"../generated/ProductData\";\n\nconst Products = () => {\n\n const {data, error, loading} = useQuery<ProductData>(ALL_PRODUCTS_QUERY)\n if(loading) return <p>Loading</p>\n if(error) return <p>Error: {error.message}</p> \n\n return (\n <div>\n <div>\n {data?.allProducts?.map(product => (\n <div>{product?.name}</div>\n ))}\n </div>\n </div>\n );\n};\n\nexport default Products;\n```\n\n```text\nimport React from 'react';\nimport { ProductData, ProductData_allProducts } from '../generated/ProductData';\n\nconst Product = ({product}:ProductData_allProducts) => {\n return (\n <p>{product.name}</p>\n );\n};\n\nexport default Product;\n```\n\n```text\nProperty 'product' does not exist on type 'ProductData_allProducts'.\n```\n\n```text\nimport { useQuery } from \"@apollo/client\";\nimport {ALL_PRODUCTS_QUERY} from '../queries/index'\nimport { ProductData } from \"../generated/ProductData\";\nimport Product from \"./Product\";\n\n\nconst Products = () => {\n\n const {data, error, loading} = useQuery<ProductData>(ALL_PRODUCTS_QUERY)\n if(loading) return <p>Loading</p>\n if(error) return <p>Error: {error.message}</p> \n\n return (\n <div>\n <div>\n {data?.allProducts?.map(product => (\n <Product product={product} />\n ))}\n </div>\n </div>\n );\n};\n\nexport default Products;\n```\n\n```text\nType '{ product: ProductData_allProducts | null; }' is not assignable to type 'IntrinsicAttributes & ProductData_allProducts'.\n Property 'product' does not exist on type 'IntrinsicAttributes & ProductData_allProducts'.\n```\n\n```text\n<ProductData>\n```\n\n```text\n<div>{product?.name}</div>\n```\n\n```text\nProduct\n```\n\n```text\nproduct\n```\n\n```text\nconst Product = ({ product }: { product: ProductData_allProducts }) => {\n return <p>{product.name}</p>;\n};\n```\n\n```text\nconst Product = (props: ProductData_allProducts) => {\n return (\n <p>{product.name}</p>\n );\n};\n```\n\n```text\nprops\n```\n\n```text\nProductComponentProps\n```\n\n```text\nprops.product\n```\n\n```text\nname\n```\n\n```text\ndescription\n```\n\n```text\ntype Product = {\n __typename: \"Product\";\n id: string;\n price: number | null;\n description: string | null;\n name: string | null;\n};\n\nconst ProductComponent: FC<Product> = ({ name }) => {\n return <p>{name}</p>;\n};\n\nexport default ProductComponent;\n```\n\n```text\ninterface ProductComponentProps {\n product: ProductData_allProducts\n}\n\n\nconst Product = ({product}: ProductComponentProps) => {\n return (\n <p>{product.name}</p>\n );\n};\n```\n\n========================================\n\nComments:\n- I'm using `product` instead of `name` but I'm still getting `Property 'product' does not exist on type 'PropsWithChildren'`\n- I'm using `ProductData_allProducts` instead of your `Product` because they are the same\n- yea you can use your type ( its the same)\n- but I still get the same error\n- take a look i made an example: codesandbox.io/s/serene-forest-ljjgs?file=/src/App.tsx\n- That does work, but these types are generated by `apollo codegen` so I thought I shouldn't have to do something like this\n- where I use the component and pass in the `product` I get `Type 'ProductData_allProducts | null' is not assignable to type 'ProductData_allProducts'. Type 'null' is not assignable to type 'ProductData_allProducts'.`","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":351,"estimatedTokens":1746}}806{"id":"stack-46452868","source":"stackoverflow","questionId":46452868,"title":"Return Graphql Count","tags":["graphql"],"text":"Title: Return Graphql Count\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI have this Graphql query\n\n```\n\"{TABLE_NAME{\n id\n severity\n des\n ip\n hostname\n description\n\n }\n}\";\n```\n\nThat's return over 1000 records, how to do:\n\n```\nSELECT COUNT(*) FROM TABLE_NAME\n```\n\nin Graphql ?\n\n========================================\n\nTop Answer:\n```\nquery {\n posts {\n meta {\n pagination {\n total\n }\n }\n }\n}\n```\n\nwhere **posts** is the name of your *collection*\n\nsource = https://graphql.org/learn/pagination/\n\n========================================\n\nCode:\n```text\n\"{TABLE_NAME{\n id\n severity\n des\n ip\n hostname\n description\n\n }\n}\";\n```\n\n```text\nSELECT COUNT(*) FROM TABLE_NAME\n```\n\n```text\nconst TableInfo = new GraphQLObjectType({\n name: 'TableInfo',\n fields: {\n count: GraphQLInt\n }\n})\nconst Query = new GraphQLObjectType({\n name: 'Query',\n fields: {\n tableInfo: {\n type: TableInfo,\n args: {\n name: new GraphQLNonNull(GraphQLString)\n },\n resolve (source, args) {\n return new Promise((resolve, reject) => {\n connection.query(\n 'SELECT COUNT(*) from ' + args.name,\n (error, results) => {\n return error ? reject(error) : resolve(results)\n }\n )\n })\n }\n }\n }\n})\nconst schema = new GraphQLSchema({\n query: Query\n})\n```\n\n```text\nquery Info {\n tableInfo(name: \"my_table\") {\n count\n }\n}\n```\n\n```text\nquery {\n listOfElts (first: 1) { \n totalCount \n }\n}\n```\n\n```text\nquery {\n posts {\n meta {\n pagination {\n total\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- While this command may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value\n- @LordWilmore It just works nicely in my GitHub graphql call, which successfully retrieve the numbers of repositories that I have. Sometimes we just want a simple answer is enough. It seems there are not much to explain here.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This answer was a really good idea. In my case I had to modify it to `query { accounts { totalCount } }`","metadata":{"transformedAt":"2026-08-18T18:32:36.084Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":135,"estimatedTokens":606}}807{"id":"stack-57934591","source":"stackoverflow","questionId":57934591,"title":"Multiple item lookup in GraphQL Query","tags":["graphql","graphql-js","graphql-java"],"text":"Title: Multiple item lookup in GraphQL Query\nTags: graphql, graphql-js, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI'm wondering what the most common approach to looking up multiple items based on ID is. From my naive understanding, I see 3 options:\n\n### Option 1\n\nAccept array of IDs and return all results\n\n`products(ids: [ID!]!): [Product!]!`\n\nThis seems to be the most straightforward and intuitive approach, but doesn't allow clients to index into the results and strays from the pagination pattern other queries typically .\n\n### Option 2\n\nForce clients to use aliases\n\n```\nproduct(id: ID!): Product!\n```\n\nThis is easiest to implement on the server side and also allows clients to index directly into the results based on the ID (assuming they use the ID as the alias), but also forces clients to construct more complex queries.\n\n### Option 3\n\nAccept array of IDs and return paginated results (via the Connection pattern)\n\n```\nproducts(ids: [ID!]!, after: String, first: Int! = 10): ProductConnection!\n```\n\nThis stays consistent with other queries that return paginated results, but also has the same issue as #1 with not allowing clients to index directly into the results via the ID (assuming ID is used as the alias as in option 2). The connection pattern is also not immediately intuitive for users not familiar with it.\n\nAny suggestions based on your experiences? Thanks!\n\n========================================\n\nCode:\n```text\nproduct(id: ID!): Product!\n```\n\n```text\nproducts(ids: [ID!]!, after: String, first: Int! = 10): ProductConnection!\n```\n\n```text\nproducts(ids: [ID!]!): [Product!]!\n```\n\n```js\nconst query = `{ ${ids.map(id => `product${id}: product { ...Frag }\\n`).join('')} }`;\n```\n\n========================================\n\nComments:\n- I think you are covering all the ways here. I would like to mention that some people encurage queries that are build for views not for general querying. Also what *we* would often do is have the Option 2 and Option 3 both in place and offer a more flexible filter parameter on the plural version e.g. `products(filter: { id: { in: [1, 2, 3] } })`.\n- Thanks for the insight @Herku ! For the plural version, what are you returning? An array of products, or a connection? Also, are you using any library/framework for the filtering? Are there other \"filters\" you expose, other than `in`? Do you name the parameter something like `ProductFilterInput`? Appreciate the help!\n- I really don't understand all the hyper around graphQL. Why would something so simple require code to be written on server side... This tool is so far of being as magic as advertised. IMHO, graphQL is a DB DSL whose only purpose is to define authorization on what can be queried and how. But being able to query multiple elements instead of a single one, is like one of the most basic feature one can think of. Why is it needed to write more code on server side ? How is this even better than rest if you need to implement a server-side counterpart for something so basic... I don't get it\n- I'd love to know a bit more about the consequentes for client side caching for these approaches. Seems like option 2 might work out of the box (where a client doesn't repeat the same query, while option 1 and 3 will always have to query the whole list even if on id is different?\n- Well in theory you would not have to query the whole list but in practice the available caching solutions are not smart enough to handle this. If this turns out to be the bottleneck of your application you would probably need a special solution for this case.","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":64,"estimatedTokens":892}}808{"id":"stack-44382147","source":"stackoverflow","questionId":44382147,"title":"Pass in multiple cursors as variables to GitHub GraphQL API?","tags":["github-api","graphql"],"text":"Title: Pass in multiple cursors as variables to GitHub GraphQL API?\nTags: github-api, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm looking up organization members based on a list of organization ids. Each org has a paged list of members with an `endCursor`. Since each `endCursor` will be different and each org has different numbers of members (and different number of pages), how can I pass in different cursors back as variables? If so, how would each cursor be associated to the org ID from the previous query?\n\n```\nquery($orgIds:[ID!]!, $page_cursor:String) { // not sure how to pass in the cursor when different length lists are returned\n nodes(ids:$orgIds) {\n ... on Organization {\n id\n members(first: 100, after: $page_cursor) {\n edges {\n node {\n id\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n } \n }\n}\n```\n\nI've read http://graphql.org/learn/pagination/ but I'm not seeing anything related to passing in multiple cursors for the same edge list.\n\n========================================\n\nCode:\n```text\nquery($orgIds:[ID!]!, $page_cursor:String) { // not sure how to pass in the cursor when different length lists are returned\n nodes(ids:$orgIds) {\n ... on Organization {\n id\n members(first: 100, after: $page_cursor) {\n edges {\n node {\n id\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n } \n }\n}\n```\n\n```text\nendCursor\n```\n\n```text\nendCursor\n```\n\n```text\nedges {\n cursor\n node {\n id\n }\n}\n```\n\n```text\n\"edges\": [\n {\n \"cursor\": \"Y3Vyc29yOnYyOpLOAANaVM4AA1pU\",\n \"node\": {\n \"id\": \"MDQ6VXNlcjIxOTczMg==\"\n }\n },\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":78,"estimatedTokens":433}}809{"id":"stack-55225257","source":"stackoverflow","questionId":55225257,"title":"AppSync/Graphql Multiple subscriptions or one subscriptions for multiple ids?","tags":["facebook","graphql","chat","aws-appsync","real-time-data"],"text":"Title: AppSync/Graphql Multiple subscriptions or one subscriptions for multiple ids?\nTags: facebook, graphql, chat, aws-appsync, real-time-data\nSource: Stack Overflow\n\nQuestion:\nProblem : \nWe are trying to make a chat application using AWS product AppSync and we want to achive the best performance but we're facing problem with real time subscriptions in AppSync and Graphql where a single user will need to handle hundereds of subscription in some cases which we think is not the best solution, what do you suggest ?\n\nProblem Example: \n\n```\nMutation{\n addMessage(conversation_id=Int!, content:String!) : Message\n}\nSubscription{\n subscribeForNewMessages(convesration_id: Int!):Message\n @aws_subscribe(mutations: [\"addMessage\"])\n}\n```\n\nthe problem with this design is that the user need to invoke this subscription and keep listening for every single conversation, which we expect to be overwheelming the client in case if the conversations quantity is huge. \n\nQuestions :\n\nQ1 : \nWhat we are striving to achieve is one subscription for multiple (conversation_id)s, how this will be possible?\nThese folks (https://github.com/apollographql/apollo-client/issues/2633) are talking about something similar, we tested it and it doesn't work, is it a valid solution? \n\nQ2:\nRegarding Amplify; Will amplify perform well when listening for hundereds of subscription simulanuosly? does it make some sort of merging subscription and websockets or it will deal them separately?\n\nQ3: \nwhat are your comments about these designs? where there will be a service that will braodcast(invoke mutations with clients ids) the messages for chat participants , and the client will subscribe only for a single channel . like the following:\nsrc2 : AWS AppSync for chatting application\nsrc2 : Subscribe to a List of Group / Private Chats in AWS AppSync\n\n========================================\n\nCode:\n```text\nMutation{\n addMessage(conversation_id=Int!, content:String!) : Message\n}\nSubscription{\n subscribeForNewMessages(convesration_id: Int!):Message\n @aws_subscribe(mutations: [\"addMessage\"])\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":48,"estimatedTokens":522}}810{"id":"stack-62794555","source":"stackoverflow","questionId":62794555,"title":"How Test e2e Nestjs API with GRAPHQL","tags":["testing","graphql","nestjs","e2e-testing","graphql-mutation"],"text":"Title: How Test e2e Nestjs API with GRAPHQL\nTags: testing, graphql, nestjs, e2e-testing, graphql-mutation\nSource: Stack Overflow\n\nQuestion:\nWhen I create my Owner via graphql-playground it works fine,\nbut my test fail and response me that 'body.data.createOwner is undefined', there no data.\n\n```\n// owner.e2e.spec.ts\ndescribe('Owner test (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const moduleRef = await Test.createTestingModule({\n imports: [\n GraphQLModule.forRoot({\n autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n }),\n OwnerModule,\n DatabaseModule\n ]\n }).compile();\n app = moduleRef.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await app.close();\n })\n\n const createOwnerQuery = `\n mutation createOwner($OwnerInput: OwnerInput!) {\n createOwner(ownerInput: $OwnerInput) {\n _id\n name\n firstname\n email\n password\n firstsub\n expsub\n createdAt\n updatedAt\n }\n }\n `;\n \n let id: string = '';\n\n it('createOwner', () => {\n return request(app.getHttpServer())\n .post('/graphql')\n .send({\n operationName: 'createOwner',\n variables: {\n OwnerInput: {\n name: 'adar',\n firstname: 'adar',\n email: 'adar@test.com',\n password: 'testing',\n firstsub: '2020-08-14',\n expsub: '2020-07-13'\n }\n },\n query: createOwnerQuery,\n })\n .expect(({ body }) => {\n const data = body.data.createOwner {\n > 100 | const data = body.data.createOwner\n | ^\n 101 | id = data._id\n 102 | expect(data.name).toBe(owner.name)\n 103 | expect(data.email).toBe(owner.email)\n\n at owner.e2e-spec.ts:100:40\n at Test._assertFunction (../node_modules/supertest/lib/test.js:283:11)\n at Test.assert (../node_modules/supertest/lib/test.js:173:18)\n at Server.localAssert (../node_modules/supertest/lib/test.js:131:12)\n\nTest Suites: 1 failed, 1 total\nTests: 1 failed, 1 total\nSnapshots: 0 total\nTime: 9.645 s, estimated 10 s\nRan all test suites.\n```\n\n========================================\n\nCode:\n```text\n// owner.e2e.spec.ts\ndescribe('Owner test (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const moduleRef = await Test.createTestingModule({\n imports: [\n GraphQLModule.forRoot({\n autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n }),\n OwnerModule,\n DatabaseModule\n ]\n }).compile();\n app = moduleRef.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await app.close();\n })\n\n const createOwnerQuery = `\n mutation createOwner($OwnerInput: OwnerInput!) {\n createOwner(ownerInput: $OwnerInput) {\n _id\n name\n firstname\n email\n password\n firstsub\n expsub\n createdAt\n updatedAt\n }\n }\n `;\n \n let id: string = '';\n\n it('createOwner', () => {\n return request(app.getHttpServer())\n .post('/graphql')\n .send({\n operationName: 'createOwner',\n variables: {\n OwnerInput: {\n name: 'adar',\n firstname: 'adar',\n email: 'adar@test.com',\n password: 'testing',\n firstsub: '2020-08-14',\n expsub: '2020-07-13'\n }\n },\n query: createOwnerQuery,\n })\n .expect(({ body }) => {\n const data = body.data.createOwner <-- test fail at this line\n id = data._id\n expect(data.name).toBe(owner.name)\n expect(data.email).toBe(owner.email)\n expect(data.firstsub).toBe(owner.firstsub)\n })\n .expect(200)\n })\n```\n\n```text\n// Output terminal\n\n FAIL test/owner.e2e-spec.ts (9.567 s)\n Owner test (e2e)\n β createOwner (79 ms)\n\n β Owner test (e2e) βΊ createOwner\n\n TypeError: Cannot read property 'createOwner' of undefined\n\n 98 | })\n 99 | .expect(({ body }) => {\n > 100 | const data = body.data.createOwner\n | ^\n 101 | id = data._id\n 102 | expect(data.name).toBe(owner.name)\n 103 | expect(data.email).toBe(owner.email)\n\n at owner.e2e-spec.ts:100:40\n at Test._assertFunction (../node_modules/supertest/lib/test.js:283:11)\n at Test.assert (../node_modules/supertest/lib/test.js:173:18)\n at Server.localAssert (../node_modules/supertest/lib/test.js:131:12)\n\nTest Suites: 1 failed, 1 total\nTests: 1 failed, 1 total\nSnapshots: 0 total\nTime: 9.645 s, estimated 10 s\nRan all test suites.\n```\n\n========================================\n\nComments:\n- is owner a module or the entire app?\n- it's a module (also my entity)\n- Try just importing your `AppModule` instead, it will contain all the setup needed to run your application normally.","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":195,"estimatedTokens":1267}}811{"id":"stack-65241210","source":"stackoverflow","questionId":65241210,"title":"Hasura: Allow users to not vote for their own post","tags":["graphql","hasura"],"text":"Title: Hasura: Allow users to not vote for their own post\nTags: graphql, hasura\nSource: Stack Overflow\n\nQuestion:\nI have three models **User**, **Post**, **Vote**\n\nhttps://i.sstatic.net/XsAxE.png\n\nI tried to create a role-based authorization where the author (the user who creates a post/blog) can't vote for their own post/blog. To identify users, I used Hasura session variables `X-Hasura-User-Id`. Configuring (Row insert) Permission Rules for Vote table by,\n\nhttps://i.sstatic.net/lUTr9.png\n\n### Error:\n\n```\n{\n \"errors\": [\n {\n \"extensions\": {\n \"path\": \"$.selectionSet.insert_Vote_one.args.object\",\n \"code\": \"permission-error\"\n },\n \"message\": \"Check constraint violation. insert check constraint failed\"\n }\n ]\n}\n```\n\nBut which given constraint violation for the author and the other users when they try to vote a post/blog. How to solve that issue for the latter case using Permission Rules?\n\n### Update\n\n### Auth SetUp\n\nI use one of my auth server(express) to create user and access_token which contain the `user.id` as Hasura session variables `X-Hasura-User-Id`.\n\nThen I use this access_token to maintain role-based authorization:\n\nhttps://i.sstatic.net/Bcw68.png\n\n========================================\n\nCode:\n```json\n{\n \"errors\": [\n {\n \"extensions\": {\n \"path\": \"$.selectionSet.insert_Vote_one.args.object\",\n \"code\": \"permission-error\"\n },\n \"message\": \"Check constraint violation. insert check constraint failed\"\n }\n ]\n}\n```\n\n```text\nX-Hasura-User-Id\n```\n\n```text\nuser.id\n```\n\n```text\nX-Hasura-User-Id\n```\n\n```text\nX-Hasura-User-Id\n```\n\n```text\nVote.blog.User_id\n```\n\n```text\nblog\n```\n\n```text\nVote.Blog_id\n```\n\n```text\nVote.User_id\n```\n\n```text\nX-Hasura-User-Id\n```\n\n========================================\n\nComments:\n- What is your auth setup?\n- I update my question @AbrahamLabkovsky\n- Thanks, I applied the rule in the wrong way.","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":100,"estimatedTokens":470}}812{"id":"stack-54412215","source":"stackoverflow","questionId":54412215,"title":"How to pass query arguments in graphql-tool?","tags":["javascript","graphql","graphql-tools"],"text":"Title: How to pass query arguments in graphql-tool?\nTags: javascript, graphql, graphql-tools\nSource: Stack Overflow\n\nQuestion:\nI am using graphql-tool to mock up data for testing.\n\nI hope to simulate when I select a user, it opens a detail page and shows the user company info.\n\n**Query**\n\n```\nconst query = `\n query User($id: ID!) {\n user(id: $id) {\n id\n company\n }\n }\n`;\n```\n\n**Mock server**\n\n```\nimport { addMockFunctionsToSchema } from 'graphql-tools';\nimport casual from 'casual';\n\nconst allUserIds = ['u1', 'u2', 'u3'];\n\nconst mocks = {\n User: () => ({\n id: casual.random_element(allUserIds),\n name: casual.name,\n company: casual.company_name\n })\n};\n\naddMockFunctionsToSchema({ schema, mocks });\n```\n\nHowever, right now, when I query with argument id `'u1'`, it will return a random user id for example `'u2'`, which gives me a little trouble to show it in front end.\n\nI thought I can do something like this below, but turns out I am wrong. `user` is `undefined` in the code below.\n\n```\nconst mocks = {\n User: (user) => ({\n id: user.id || casual.random_element(allUserIds),\n name: casual.name,\n company: casual.company_name\n })\n};\n```\n\nIs there a way to pass the query arguments in graphql-tools? Thanks\n\n========================================\n\nCode:\n```text\nconst query = `\n query User($id: ID!) {\n user(id: $id) {\n id\n company\n }\n }\n`;\n```\n\n```text\nimport { addMockFunctionsToSchema } from 'graphql-tools';\nimport casual from 'casual';\n\nconst allUserIds = ['u1', 'u2', 'u3'];\n\nconst mocks = {\n User: () => ({\n id: casual.random_element(allUserIds),\n name: casual.name,\n company: casual.company_name\n })\n};\n\naddMockFunctionsToSchema({ schema, mocks });\n```\n\n```text\nconst mocks = {\n User: (user) => ({\n id: user.id || casual.random_element(allUserIds),\n name: casual.name,\n company: casual.company_name\n })\n};\n```\n\n```text\n'u1'\n```\n\n```text\n'u2'\n```\n\n```text\nuser\n```\n\n```text\nundefined\n```\n\n```text\nconst mocks = {\n Query: () => ({\n user: (root, user) => ({\n id: user.id || casual.random_element(allUserIds),\n name: casual.name,\n company: casual.company_name\n })\n })\n};\n```\n\n```text\nid\n```\n\n```text\nroot, arguments, context\n```\n\n```text\nu1\n```\n\n```text\nid = \"u1\"\n```\n\n========================================\n\nComments:\n- You're probably better off using a collection of fake/mock objects or a mock data generator with a consistent seed if you'd like to see your test data persistent throughout testing.\n- @ClaireLin thanks, I did try actually. But haven't figured out where I should use `casual.seed(123);`. First, I tried to put on top just after import, it does not have any effect. Then I tried to put in mocks like `const mocks = { User: () => { casual.seed(0); return { id: casual.random_element(allUserIds), ... } } };`, it will give me all users with same info.\n- Thanks!! I missed that part document. I corrected a little bit since based on your old one `User: () => ({ id: (root, { id }) => id, ...`. When I try to use `id: (root, something) => id`, `something` will always be empty object, which makes `id` is undefined. When I moved it top like `User: (root, user) => ({ id: user.id || casual.random_element(allUserIds),` then it works.\n- Ah you are right. I got confused with your query `User` and the type `User` with PascalCase. I'd suggest to the naming convention and rename the query to be camelCase `user` to reduce confusion.\n- @HongboMiao I added a live demo and updated the code snippet here to clarify that `user` is in fact a `query`.\n- Oh I did name conversion. I think you misunderstood my code in question. My `User` is under root mocks (same level with `Query`) which should be capitalized. It is for all `User` type used in all places GraphQL schema, not just in query. But anyway thanks for the direction!","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":151,"estimatedTokens":952}}813{"id":"stack-52374409","source":"stackoverflow","questionId":52374409,"title":"How to execute a mutation in GraphQL?","tags":["node.js","graphql"],"text":"Title: How to execute a mutation in GraphQL?\nTags: node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nIn GraphQL we have basically two types of operations: queries and mutations. While queries are well described in the documentation and there are many examples of them, I'm having a hard time to understand how to execute a mutation. Mutations obviously are update methods.\n\nI've created very simple Node.js server:\n\n```\nvar express = require(\"express\");\nvar graphqlHTTP = require(\"express-graphql\");\nvar graphql = require(\"graphql\");\nvar inMemoryDatabase = require(\"./inMemoryDatabase\").inMemoryDatabase;\nvar _ = require(\"lodash-node\");\n\nvar userType = new graphql.GraphQLObjectType({\n name: \"User\",\n fields: {\n id: { type: graphql.GraphQLString },\n name: { type: graphql.GraphQLString }\n }\n});\n\nvar queryType = new graphql.GraphQLObjectType({\n name: \"Query\",\n fields: {\n user: {\n type: userType,\n args: {\n id: { type: graphql.GraphQLString }\n },\n resolve: function(parent, { id }) {\n return _.find(inMemoryDatabase, { id: id });\n }\n }\n }\n});\n\nvar mutationType = new graphql.GraphQLObjectType({\n name: \"Mutation\",\n fields: {\n user: {\n type: userType,\n args: {\n id: { type: graphql.GraphQLString },\n name: { type: graphql.GraphQLString }\n },\n resolve: function(parent, { id, name }) {\n var index = _.findIndex(inMemoryDatabase, { id: id });\n inMemoryDatabase.splice(index, 1, { id: id, name: name });\n return _.find(inMemoryDatabase, { id: id });\n }\n }\n }\n});\n\nvar schema = new graphql.GraphQLSchema({\n query: queryType,\n mutation: mutationType\n});\n\nvar app = express();\napp.use(\n \"/graphql\",\n graphqlHTTP({\n schema: schema,\n graphiql: true\n })\n);\n\nvar port = 9000;\nif (process.env.PORT) {\n port = process.env.PORT;\n}\n\napp.listen(port);\nconsole.log(\"Running a GraphQL API server at localhost:\" + port + \"/graphql\");\n```\n\nIn memory database is just in an array of User objects `{id, name}`:\n\n```\nvar inMemoryDatabase = [\n {\n id: \"31ce0260-2c23-4be5-ab78-4a5d1603cbc8\",\n name: \"Mark\"\n },\n {\n id: \"2fb6fd09-2697-43e2-9404-68c2f1ffbf1b\",\n name: \"Bill\"\n }\n];\n\nmodule.exports = {\n inMemoryDatabase\n};\n```\n\nExecuting query to get user by id looks as follows:\n\n```\n{\n user(id: \"31ce0260-2c23-4be5-ab78-4a5d1603cbc8\"){\n name\n }\n}\n```\n\nHow would the mutation changing user name look like?\n\n========================================\n\nTop Answer:\nHey may completely be missing what you are saying, but the way that I look at a mutation is like this\n\n- I get some arguments and a field, that is the same thing as params and a path in rest, with those i do something (in your case lookup the user and update the attribute based on the arguments passed in\n\n- After That, i return something from the resolve function that will fulfill the type you specify in the `type` of the mutation\n\n\r\n\r\n\n```\nvar mutationType = new graphql.GraphQLObjectType({\r\n name: \"Mutation\",\r\n fields: {\r\n user: {\r\n // You must return something from your resolve function \r\n // that will fulfill userType requirements\r\n type: userType,\r\n \r\n // with these arguments, find the user and update them\r\n args: {\r\n id: { type: graphql.GraphQLString },\r\n name: { type: graphql.GraphQLString }\r\n },\r\n // this does the lookup and change of the data\r\n // the last step of your result is to return something\r\n // that will fulfill the userType interface\r\n resolve: function(parent, { id, name }) {\r\n // Find the user, Update it\r\n // return something that will respond to id and name, probably a user object\r\n }\r\n }\r\n }\r\n});\n```\n\n\r\n\r\n\r\n\nThen with that as a context, you pass some arguments and request back a user\n\n```\nmutation updateUser {\n user(id: \"1\", name: \"NewName\") {\n id\n name\n }\n}\n```\n\nIn a normal production schema you would also normally have something like `errors` that could be returned to convey the different states of the update for failed/not found\n\n========================================\n\nCode:\n```text\nvar express = require(\"express\");\nvar graphqlHTTP = require(\"express-graphql\");\nvar graphql = require(\"graphql\");\nvar inMemoryDatabase = require(\"./inMemoryDatabase\").inMemoryDatabase;\nvar _ = require(\"lodash-node\");\n\nvar userType = new graphql.GraphQLObjectType({\n name: \"User\",\n fields: {\n id: { type: graphql.GraphQLString },\n name: { type: graphql.GraphQLString }\n }\n});\n\nvar queryType = new graphql.GraphQLObjectType({\n name: \"Query\",\n fields: {\n user: {\n type: userType,\n args: {\n id: { type: graphql.GraphQLString }\n },\n resolve: function(parent, { id }) {\n return _.find(inMemoryDatabase, { id: id });\n }\n }\n }\n});\n\nvar mutationType = new graphql.GraphQLObjectType({\n name: \"Mutation\",\n fields: {\n user: {\n type: userType,\n args: {\n id: { type: graphql.GraphQLString },\n name: { type: graphql.GraphQLString }\n },\n resolve: function(parent, { id, name }) {\n var index = _.findIndex(inMemoryDatabase, { id: id });\n inMemoryDatabase.splice(index, 1, { id: id, name: name });\n return _.find(inMemoryDatabase, { id: id });\n }\n }\n }\n});\n\nvar schema = new graphql.GraphQLSchema({\n query: queryType,\n mutation: mutationType\n});\n\nvar app = express();\napp.use(\n \"/graphql\",\n graphqlHTTP({\n schema: schema,\n graphiql: true\n })\n);\n\nvar port = 9000;\nif (process.env.PORT) {\n port = process.env.PORT;\n}\n\napp.listen(port);\nconsole.log(\"Running a GraphQL API server at localhost:\" + port + \"/graphql\");\n```\n\n```text\nvar inMemoryDatabase = [\n {\n id: \"31ce0260-2c23-4be5-ab78-4a5d1603cbc8\",\n name: \"Mark\"\n },\n {\n id: \"2fb6fd09-2697-43e2-9404-68c2f1ffbf1b\",\n name: \"Bill\"\n }\n];\n\nmodule.exports = {\n inMemoryDatabase\n};\n```\n\n```text\n{\n user(id: \"31ce0260-2c23-4be5-ab78-4a5d1603cbc8\"){\n name\n }\n}\n```\n\n```text\n{id, name}\n```\n\n```text\nmutation updateUser {\n user(id: \"31ce0260-2c23-4be5-ab78-4a5d1603cbc8\", name: \"Markus\") {\n id\n name\n }\n}\n```\n\n```js\nvar mutationType = new graphql.GraphQLObjectType({\n name: \"Mutation\",\n fields: {\n user: {\n // You must return something from your resolve function \n // that will fulfill userType requirements\n type: userType,\n \n // with these arguments, find the user and update them\n args: {\n id: { type: graphql.GraphQLString },\n name: { type: graphql.GraphQLString }\n },\n // this does the lookup and change of the data\n // the last step of your result is to return something\n // that will fulfill the userType interface\n resolve: function(parent, { id, name }) {\n // Find the user, Update it\n // return something that will respond to id and name, probably a user object\n }\n }\n }\n});\n```\n\n```text\nmutation updateUser {\n user(id: \"1\", name: \"NewName\") {\n id\n name\n }\n}\n```\n\n```text\ntype\n```\n\n```text\nerrors\n```\n\n```text\nmutation {\n \n taskTrackerCreateOne\n (\n record: \n {\n id:\"63980ae0f019789eeea0cd33\", \n name:\"63980c86f019789eeea0cda0\"\n }\n )\n {\n recordId\n }\n}\n```\n\n========================================\n\nComments:\n- GraphQL has built-in error reporting and you'd typically return a field error if the mutation failed; it wouldn't specifically be encoded in the schema at all.\n- HI David, i guess it really depends on the level of errors that you are wanting. Graphql will provide basic things for like a schema error or invalid query, but if you want more rich errors that would be equivalent to things you get from rest (like 422, or some specific failure event) you have to return a new type for that. Another specific example is tying into a validation framework like in rails ActiveModel::Validations so that the errors are \"better\" and more usable by the client.\n- In Ruby I tend to use graphql-ruby.org/errors/execution_errors.html (which also describes the language-neutral JSON error response format) to return field- or mutation-level errors.\n- Ah my bad, updated :) Sometimes just putting these in graphiql or graphqlplayground will though you the typos","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":345,"estimatedTokens":1989}}814{"id":"stack-45375139","source":"stackoverflow","questionId":45375139,"title":"How to set null to field in graphql?","tags":["graphql","graphql-java"],"text":"Title: How to set null to field in graphql?\nTags: graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nWe use graphql on our project and use graphql-java 2.3.0 (we plan to update but it is not possible at the moment).\n\nI'm trying to perform such mutation:\n\n```\nmutation {\n UPDATE_User(\n\n id:3,\n type: null\n ) {id}\n }\n```\n\nResponse:\n\n```\n{\n \"errors\": [\n {\n \"validationErrorType\": \"WrongType\",\n \"message\": \"Validation error of type WrongType: argument value EnumValue{name='null'} has wrong type\",\n \"locations\": [\n {\n \"line\": 5,\n \"column\": 7\n }\n ],\n \"errorType\": \"ValidationError\"\n }\n ],\n \"data\": null\n}\n```\n\n========================================\n\nTop Answer:\nIn your schema, is 'type' parameter required ? \n\nIf not then simply omit it ! On your backend when you will retrieve the value of `type`then it will be null\n\n========================================\n\nCode:\n```text\nmutation {\n UPDATE_User(\n\n id:3,\n type: null\n ) {id}\n }\n```\n\n```text\n{\n \"errors\": [\n {\n \"validationErrorType\": \"WrongType\",\n \"message\": \"Validation error of type WrongType: argument value EnumValue{name='null'} has wrong type\",\n \"locations\": [\n {\n \"line\": 5,\n \"column\": 7\n }\n ],\n \"errorType\": \"ValidationError\"\n }\n ],\n \"data\": null\n}\n```\n\n```text\nnull\n```\n\n```text\ntype\n```\n\n========================================\n\nComments:\n- I see. Thank you. But what is the reccomended workaround? I don't think that null was not used by graphql users until now.\n- @Don_Quijote Null was only added months ago. Prior to that, all you could do was not send `type` at all, but then you can't distinguish *update to null* and *leave unchanged* cases. If this is important to you, you'll have to set a special marker value to `type` e.g. `type: \"NONE\"` and handle that appropriately in the backend.","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":92,"estimatedTokens":461}}815{"id":"stack-61864912","source":"stackoverflow","questionId":61864912,"title":"Processing an exception through Apollo Server (NestJS)","tags":["node.js","exception","graphql","nestjs","apollo-server"],"text":"Title: Processing an exception through Apollo Server (NestJS)\nTags: node.js, exception, graphql, nestjs, apollo-server\nSource: Stack Overflow\n\nQuestion:\nis there a way how to run an exception through the apollo exception handler manually?\n\nI have 90% of the application in GraphQL but still have two modules as REST and I'd like to unify the way the exceptions are handled.\n\nSo the GQL queries throw the standard 200 with errors array containing message, extensions etc.\n\n```\n{\n \"errors\": [\n {\n \"message\": { \"statusCode\": 401, \"error\": \"Unauthorized\" },\n \"locations\": [{ \"line\": 2, \"column\": 3 }],\n \"path\": [ \"users\" ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"response\": { \"statusCode\": 401, \"error\": \"Unauthorized\" },\n \"status\": 401,\n \"message\": { \"statusCode\": 401, \"error\": \"Unauthorized\" }\n }\n }\n }\n ],\n \"data\": null\n}\n```\n\nwhere the REST throws the real 401 with JSON:\n\n```\n{\n \"statusCode\": 401,\n \"error\": \"Unauthorized\"\n}\n```\n\nSo can I simply catch and wrap the **exception in the Apollo Server format** or do I have to format my REST errors manually? Thanks\n\nI am using NestJS and the GraphQL module.\n\n========================================\n\nTop Answer:\nFor future readers who also get the `response.status is not a function` error: For me trying to return an HTTP response in GraphQL mode did not work. You can prevent this by extending the answer of eol and using a switch on the `host`'s `type` to do the right error handling. For GraphQL for example this worked well in my case:\n\n```\n@Catch(RestApiError)\nexport class RestApiErrorFilter implements ExceptionFilter {\n catch (exception: RestApiError, host: GqlArgumentsHost) {\n switch (host.getType ()) {\n case 'http':\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const status = 200;\n response\n .status(status)\n .json(RestApiErrorFilter.getApolloServerFormatError(exception));\n break;\n case 'graphql':\n throw exception;\n break;\n default:\n throw new Error('unsupported host type' + host.getType())\n }\n }\n}\n```\n\nSadly you will still need to handle Apollo's `ApolloError.graphQLErrors` in the front-end separately.\n\n========================================\n\nCode:\n```text\n{\n \"errors\": [\n {\n \"message\": { \"statusCode\": 401, \"error\": \"Unauthorized\" },\n \"locations\": [{ \"line\": 2, \"column\": 3 }],\n \"path\": [ \"users\" ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"response\": { \"statusCode\": 401, \"error\": \"Unauthorized\" },\n \"status\": 401,\n \"message\": { \"statusCode\": 401, \"error\": \"Unauthorized\" }\n }\n }\n }\n ],\n \"data\": null\n}\n```\n\n```text\n{\n \"statusCode\": 401,\n \"error\": \"Unauthorized\"\n}\n```\n\n```text\n@Catch(RestApiError)\nexport class RestApiErrorFilter implements ExceptionFilter {\n catch(exception: RestApiError, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const status = 200;\n response\n .status(status) \n .json(RestApiErrorFilter.getApolloServerFormatError(exception);\n}\n\nprivate static getApolloServerFormatError(exception: RestApiErrorFilter) {\n return {}; // do your conversion here\n}\n```\n\n```js\n@Catch(RestApiError)\nexport class RestApiErrorFilter implements ExceptionFilter {\n catch (exception: RestApiError, host: GqlArgumentsHost) {\n switch (host.getType < GqlContextType > ()) {\n case 'http':\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const status = 200;\n response\n .status(status)\n .json(RestApiErrorFilter.getApolloServerFormatError(exception));\n break;\n case 'graphql':\n throw exception;\n break;\n default:\n throw new Error('unsupported host type' + host.getType())\n }\n }\n}\n```\n\n```text\nresponse.status is not a function\n```\n\n```text\nhost\n```\n\n```text\ntype\n```\n\n```text\nApolloError.graphQLErrors\n```\n\n========================================\n\nComments:\n- Yes this sounds good enough and I was thinking of this solution but I have to do the conversion myself - I was hoping I could somehow execute the Apollo Server Error Handler so it does most of the conversion for me...\n- Oh ok, I missed that, sorry! Maybe you could import this error class (github.com/apollographql/apollo-server/blob/…) and throw such an error instance? It should then be caught by the corresponding error handler: github.com/apollographql/apollo-server/blob/master/packages/‌​…\n- That looks promising! Thanks a lot - I'll give it a try this week!\n- For me it says response.status is not a function :(\n- @SerShubham: Please post a new question with all the details, thank you.","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":170,"estimatedTokens":1192}}816{"id":"stack-41051401","source":"stackoverflow","questionId":41051401,"title":"GraphQL & Relay Filtering UI","tags":["reactjs","graphql","relayjs"],"text":"Title: GraphQL & Relay Filtering UI\nTags: reactjs, graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\n**THE PROMPT**\n\nIf you were to build Google Calendar using relay, how would you structure the GraphQL schema and the Relay containers/components to properly handle showing & hiding multiple calendars?\n\n**THE ATTEMPT**\n\nOne might imagine a schema like this:\n\n```\nviewer {\n user {\n calendars(calendarIds: [String]) {\n edges,\n node {\n name,\n id,\n events(dates: [Date]) {\n ... edges, node, eventinfo...\n }\n }\n }\n }\n }\n}\n```\n\nSo, I can pull down all the calendars and all the events, or a specific calendar, or what have you.\n\nStructuring the Relay Containers and components, I would imagine the following:\n\n```\n\n \n or or etc...\n \n```\n\nSuch that the CalendarView relay container sets up the fragment requesting the calendars, and the `CalenderView` component uses `setVariables` to toggle the showing/hiding of that calendar in the view.\n\nThe problem that I'm encountering (and that's making my head spin) is that the `Day`/`Week`/`Month`/`Agenda` components are combinatorial views β that is, they require the data from all selected events.\n\n**THE PLOT THICKENS**\n\nNow, that sounds just fine β have the `CalendarView` set the calendarId variables and pass the resulting events down, right? Well... kind of. Now the fragment for `CalendarView` is constructed with a set of `calendarIds`, such that toggling one `calendar` on or off changes the entire tree of what is to be fetched.\n\n**THE GOTCHA?**\n\nAs far as I can tell, relay sees each combination of `calendarIds` as an entirely different fetch. So, when I toggle on a new `id` it fetches *all* the events, even for those calendars I've already fetched.\n\nPut code-wise:\n\n```\nfragment calendar(calendarIds: [1, 2]) { ... }\n```\n\nIs an *entirely* different fetch from:\n\n```\nfragment calendar(calendarIds: [1, 2, 3]) { ... }\n```\n\nThis is ... bad. There can be a lot of events on those calendars and the over-fetching is a killer.\n\nIn theory, I could create a container per calendar, but then how would I combine the events on those calendars and pipe them into a common sub-component? The calendars can't be layered because events need to move around in reaction to other events, even those on separate calendars (shifting left/right to show them side-by-side).\n\nThoughts? My brain hurts.\n\n========================================\n\nCode:\n```text\nviewer {\n user {\n calendars(calendarIds: [String]) {\n edges,\n node {\n name,\n id,\n events(dates: [Date]) {\n ... edges, node, eventinfo...\n }\n }\n }\n }\n }\n}\n```\n\n```text\n<CalendarView Container>\n <CalendarView>\n <WeekView> or <MonthView> or <Agenda> etc...\n <Event>\n```\n\n```text\nfragment calendar(calendarIds: [1, 2]) { ... }\n```\n\n```text\nfragment calendar(calendarIds: [1, 2, 3]) { ... }\n```\n\n```text\nCalenderView\n```\n\n```text\nsetVariables\n```\n\n```text\nDay\n```\n\n```text\nWeek\n```\n\n```text\nMonth\n```\n\n```text\nAgenda\n```\n\n```text\nCalendarView\n```\n\n```text\nCalendarView\n```\n\n```text\ncalendarIds\n```\n\n```text\ncalendar\n```\n\n```text\ncalendarIds\n```\n\n```text\nid\n```\n\n```text\ncalendar(calendarIds: [1, 2])\n```\n\n```text\ncalendar(calendarIds: [1, 2, 3])\n```\n\n```text\ncalendarIds\n```\n\n```text\nnodes(ids: [ID!])\n```\n\n```text\nnodes\n```\n\n```text\n[1,2,3]\n```\n\n```text\n[result1, result2, result3]\n```\n\n========================================\n\nComments:\n- is there documentation anywhere on the `nodes` root field? We implement a root node field via `graphql-relay` but I can't find anything on `nodes`.\n- Also, is a \"plural identifying root field\" similar to the above approach? It would seem to me that like a \"plural identifying root field\", using the `nodes` field would require objects with one-to-one mappings to the ids. Ideally, I'd be able to query using variables against a large set of object (events) that aren't nicely grouped by the input ids (input: [Array of 3 ids], output: [Array of n events]), but both approaches appear to necessitate the creation of some intermediary object (input: [Array of 3 ids], output: [Array of 3 objects that have events]).\n- The `nodes` field isn't documented, but it works as I described above. There is no need for intermediate result objects, ie you can do `node(ids: [array of 3 event ids])` and return `[array of 3 events]` - the event results just have to be in the same order as the args.\n- Thanks for the discussion here β this is super helpful. I suppose I could restructure things to request eventIds for a given calendarId, and then request events by event ids, but the ideal is to request a bunch of events for a given calendar. In which case, there's not a one-to-one mapping between calendarId and event.","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":191,"estimatedTokens":1182}}817{"id":"stack-70361016","source":"stackoverflow","questionId":70361016,"title":"Flutter GraphQL - OperationException(linkException: ResponseFormatException(originalException: FormatException: Unexpected character (at character 1)","tags":["flutter","graphql","flutter-graphql","graphql-flutter"],"text":"Title: Flutter GraphQL - OperationException(linkException: ResponseFormatException(originalException: FormatException: Unexpected character (at character 1)\nTags: flutter, graphql, flutter-graphql, graphql-flutter\nSource: Stack Overflow\n\nQuestion:\nI am getting this error while using mutate method of graphql_flutter package.\n\nTried with following versions of qraphql_flutter package:\n\n- 5.0.1-beta.1\n\n- 5.0.0\n\n- 4.0.0-beta.5\n\nError:\n\n```\nI/flutter (13946): //// EXCEPTION: OperationException(linkException: ResponseFormatException(originalException: FormatException: Unexpected character (at character 1)\nI/flutter (13946): \nI/flutter (13946): ^\n\n \n \n \n\n Redirecting to https://xxx.xxx.dev/login\n \n \n Redirecting to https://xxx.xxx.dev/login.\n \n\nI/flutter (13946): ), graphqlErrors: [])\n```\n\nI tried running query using the same code.This code works perfectly fine with query, it only throws exception when using mutation.I created a graphql helper class which can help perform every graphql operation in project using this helper class.\n\nGraphQL Helper Class:\n\n```\nimport 'package:flutter/foundation.dart';\nimport 'package:graphql_demo/app_exception.dart';\nimport 'package:graphql_flutter/graphql_flutter.dart';\n\nclass AppGraphQlClient {\n late GraphQLClient _client;\n\n AppGraphQlClient(String graphqlUrl) {\n final httpLink = HttpLink(graphqlUrl);\n\n _client = GraphQLClient(\n link: AuthorizationLink(\n }).concat(httpLink),\n cache: GraphQLCache());\n }\n\n /// Perform mutation by passing query string\n Stream?> mutateString(String query, {required Map variables}) {\n if (kDebugMode) {\n print(\"MAP $variables\");\n }\n return _client.mutate(MutationOptions(document: gql(query), variables: variables)).asStream().map((result) {\n if (kDebugMode) {\n print('//// RESULT: ${result.toString()}');\n }\n if (result.exception != null) {\n if (kDebugMode) {\n print('//// EXCEPTION: ${result.exception?.toString()}');\n print('//// EXCEPTION: ${result.exception?.graphqlErrors}');\n }\n\n throw AppException(message: (result.exception !=null)?result.exception.toString():\"Error\");\n }\n return result.data;\n });\n }\n}\n\nclass AuthorizationLink extends Link {\n @override\n Stream request(Request request, [NextLink? forward]) {\n\n String token =\n \"authentication token goes here\";\n final header = Map();\n header['Authorization'] = '''Bearer $token''';\n header['app_version'] = '3.2.3';\n header['Accept-Language'] = 'en';\n\n return forward!(request);\n }\n}\n```\n\nCan anyone provide a solution for this?\n\n========================================\n\nTop Answer:\nYou should receive a mutation result or nothing (depends on your contract), but you got `` instead. It's definitely wrong, you got an html page redirecting you to login page, instead of a json answer.\n\n========================================\n\nCode:\n```text\nI/flutter (13946): //// EXCEPTION: OperationException(linkException: ResponseFormatException(originalException: FormatException: Unexpected character (at character 1)\nI/flutter (13946): <!DOCTYPE html>\nI/flutter (13946): ^\n<html>\n <head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"refresh\" content=\"0;url='https://xxx.xxx.dev/login'\" />\n\n <title>Redirecting to https://xxx.xxx.dev/login</title>\n </head>\n <body>\n Redirecting to <a href=\"https://xxx.xxx.dev/login\">https://xxx.xxx.dev/login</a>.\n </body>\n</html>\nI/flutter (13946): ), graphqlErrors: [])\n```\n\n```text\nimport 'package:flutter/foundation.dart';\nimport 'package:graphql_demo/app_exception.dart';\nimport 'package:graphql_flutter/graphql_flutter.dart';\n\nclass AppGraphQlClient {\n late GraphQLClient _client;\n\n AppGraphQlClient(String graphqlUrl) {\n final httpLink = HttpLink(graphqlUrl);\n\n _client = GraphQLClient(\n link: AuthorizationLink(\n }).concat(httpLink),\n cache: GraphQLCache());\n }\n\n /// Perform mutation by passing query string\n Stream<Map<String, dynamic>?> mutateString(String query, {required Map<String, dynamic> variables}) {\n if (kDebugMode) {\n print(\"MAP $variables\");\n }\n return _client.mutate(MutationOptions(document: gql(query), variables: variables)).asStream().map((result) {\n if (kDebugMode) {\n print('//// RESULT: ${result.toString()}');\n }\n if (result.exception != null) {\n if (kDebugMode) {\n print('//// EXCEPTION: ${result.exception?.toString()}');\n print('//// EXCEPTION: ${result.exception?.graphqlErrors}');\n }\n\n throw AppException(message: (result.exception !=null)?result.exception.toString():\"Error\");\n }\n return result.data;\n });\n }\n}\n\nclass AuthorizationLink extends Link {\n @override\n Stream<Response> request(Request request, [NextLink? forward]) {\n\n String token =\n \"authentication token goes here\";\n final header = Map<String, String>();\n header['Authorization'] = '''Bearer $token''';\n header['app_version'] = '3.2.3';\n header['Accept-Language'] = 'en';\n\n return forward!(request);\n }\n}\n```\n\n```text\n<!DOCTYPE html>\n```\n\n========================================\n\nComments:\n- What was the problem with yours?\n- I was using invalid authentication token @VincentDaveNavaresTe\n- Lol I checked my code twice and it worked!!!","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":187,"estimatedTokens":1299}}818{"id":"stack-68378005","source":"stackoverflow","questionId":68378005,"title":"Apollo Server : throwing an error inside context always returns an http 400 error on the client","tags":["javascript","graphql","apollo","apollo-client","apollo-server"],"text":"Title: Apollo Server : throwing an error inside context always returns an http 400 error on the client\nTags: javascript, graphql, apollo, apollo-client, apollo-server\nSource: Stack Overflow\n\nQuestion:\nSo, i got an apollo server running and an apollo-client in my iOS app.\n\nI'm trying to implement an authentication process. And following apollo's documentation about authorization and authentication, i ended up trying the code they provided :\n\n```\ncontext: ({ req }) => {\n throw new AuthenticationError('you must be logged in');\n},\n```\n\nBut, while testing the code, i discovered that throwing an error wether it is a javascript one, or an apollo error, it always sends back an http 400 error :\n\n```\nError: Response not successful: Received status code 400\n at new ApolloError (errors.cjs.js:31)\n at core.cjs.js:1493\n at both (utilities.cjs.js:963)\n at utilities.cjs.js:956\n at tryCallTwo (core.js:45)\n at doResolve (core.js:200)\n at new Promise (core.js:66)\n at Object.then (utilities.cjs.js:956)\n at Object.error (utilities.cjs.js:964)\n at notifySubscription (Observable.js:140)\n```\n\nThe authentication error is not sent back. Even when i throw a custom error, with custom status code and everything it always returns the same error.\n\nAm i doing something wrong ? Or is this an issue ?\n\n========================================\n\nCode:\n```js\ncontext: ({ req }) => {\n throw new AuthenticationError('you must be logged in');\n},\n```\n\n```text\nError: Response not successful: Received status code 400\n at new ApolloError (errors.cjs.js:31)\n at core.cjs.js:1493\n at both (utilities.cjs.js:963)\n at utilities.cjs.js:956\n at tryCallTwo (core.js:45)\n at doResolve (core.js:200)\n at new Promise (core.js:66)\n at Object.then (utilities.cjs.js:956)\n at Object.error (utilities.cjs.js:964)\n at notifySubscription (Observable.js:140)\n```\n\n========================================\n\nComments:\n- Thank you for your answer, i apologize for not answering sooner :)","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":62,"estimatedTokens":495}}819{"id":"stack-47422865","source":"stackoverflow","questionId":47422865,"title":"Designing a GraphQL schema for an analytics platform","tags":["schema","analytics","graphql"],"text":"Title: Designing a GraphQL schema for an analytics platform\nTags: schema, analytics, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm just starting to explorer GraphQL as an option for my analytic platform API layer.\n\nMy UI is mainly built from tables and charts. most of the times the data represents some DB columns grouped by a dimension.\n\nI've found the following article https://www.microsoft.com/developerblog/2017/09/28/data-independent-graphql-using-view-model-based-schemas/ from Microsoft, describing their take on how suck GraphQL schemas should be designed (see below).\n\n```\ntype Query {\n channels(source: String!, query:String!, appId:String!, apiKey:String!): [Channel]\n lineCharts(source: String!, query:String!, appId:String!, apiKey:String!, filterKey:String, filterValues:[String]): [LineChart]\n pieCharts(source: String!, query:String!, appId:String!, apiKey:String!): [PieChart]\n barCharts(source: String!, query:String!, appId:String!, apiKey:String!, filterKey:String, filterValues:[String]): [BarChart]\n}\n\ntype Channel {\n name: String\n id: Int\n}\n\ntype LineChart {\n id: String\n seriesData : [Series]\n}\n\ntype PieChart {\n id: String\n labels: [String]\n values: [Int]\n}\n\ntype BarChart {\n id: String\n seriesData : [Series]\n}\n\ntype Series {\n label: String\n x_values: [String]\n y_values: [Int]\n}\n```\n\nIt seems to me that this design is strict, forcing any new chart to be added to the root Query. How can the schema be more generic, without loosing GraphQL benefits?\n\n========================================\n\nCode:\n```text\ntype Query {\n channels(source: String!, query:String!, appId:String!, apiKey:String!): [Channel]\n lineCharts(source: String!, query:String!, appId:String!, apiKey:String!, filterKey:String, filterValues:[String]): [LineChart]\n pieCharts(source: String!, query:String!, appId:String!, apiKey:String!): [PieChart]\n barCharts(source: String!, query:String!, appId:String!, apiKey:String!, filterKey:String, filterValues:[String]): [BarChart]\n}\n\ntype Channel {\n name: String\n id: Int\n}\n\ntype LineChart {\n id: String\n seriesData : [Series]\n}\n\ntype PieChart {\n id: String\n labels: [String]\n values: [Int]\n}\n\ntype BarChart {\n id: String\n seriesData : [Series]\n}\n\ntype Series {\n label: String\n x_values: [String]\n y_values: [Int]\n}\n```\n\n```text\nunion Chart = LineChart | PieChart | BarChart\n\ntype Query {\n charts(\n source: String!\n query: String!\n appId: String!\n apiKey: String!\n filterKey: String\n filterValues: [String]\n ): [Chart]\n}\n```\n\n```text\nfragment Identifiers on Chart {\n __typename\n id\n}\nquery {\n charts(...) {\n ...on LineChart {\n ...Identifiers\n seriesData\n }\n ...on PieChart {\n ...Identifiers\n labels\n values\n }\n ...on BarChart {\n ...Identifiers\n seriesData\n }\n }\n}\n```\n\n```text\nunion\n```\n\n```text\ninline/fragments\n```\n\n```text\ncharts\n```\n\n```text\nIdentifiers\n```\n\n```text\nid\n```\n\n```text\ninterfaces\n```\n\n```text\ninput types\n```\n\n========================================\n\nComments:\n- Great post, do you know of any analytics framework that works with GraphQL","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":159,"estimatedTokens":774}}820{"id":"stack-73006820","source":"stackoverflow","questionId":73006820,"title":"Redux Toolkit Query Graphql + Subscriptions","tags":["graphql","subscription","redux-toolkit","rtk-query"],"text":"Title: Redux Toolkit Query Graphql + Subscriptions\nTags: graphql, subscription, redux-toolkit, rtk-query\nSource: Stack Overflow\n\nQuestion:\nI really love graphql + rtk query but I cant get the graphql subscriptions working.\n\nI almost directly copied the streaming update example from the redux documentation. But I get the error `subscriptions are not supported over HTTP, use websockets instead`.\n\nI dont know how to solve this, any help? Can barely find any documentation about graphql subscriptions + rtk query\n\n```\nuserStatus: builder.query({\n query: ({ event_id, user_id }) => ({\n document: gql\n subscription UserStatusSubscription(\n $event_id: uuid!\n $user_id: String!\n ) {\n eetschema_event_by_pk(id: $event_id) {\n event_attendees(where: { user_id: { _eq: $user_id } }) {\n status\n event_id\n user_id\n }\n }\n }\n ,\n variables: { event_id, user_id },\n }),\n async onCacheEntryAdded(\n arg,\n { updateCachedData, cacheDataLoaded, cacheEntryRemoved }\n ) {\n // create a websocket connection when the cache subscription starts\n const ws = new WebSocket(\"ws://localhost:8080\");\n try {\n // wait for the initial query to resolve before proceeding\n await cacheDataLoaded;\n\n // when data is received from the socket connection to the server,\n // if it is a message and for the appropriate channel,\n // update our query result with the received message\n const listener = (event: MessageEvent) => {\n const data = JSON.parse(event.data);\n\n console.log(\"This is the data from the subscription!\", data);\n if (data.channel !== arg) return;\n\n updateCachedData((draft) => {\n draft = data;\n });\n };\n\n ws.addEventListener(\"message\", listener);\n } catch {\n // no-op in case cacheEntryRemoved resolves before cacheDataLoaded,\n // in which case cacheDataLoaded will throw\n }\n // cacheEntryRemoved will resolve when the cache subscription is no longer active\n await cacheEntryRemoved;\n // perform cleanup steps once the cacheEntryRemoved promise resolves\n ws.close();\n },\n }),\n```\n\n========================================\n\nCode:\n```text\nuserStatus: builder.query<\n UserStatusSubscriptionSubscription,\n {\n event_id: string;\n user_id: string;\n }\n >({\n query: ({ event_id, user_id }) => ({\n document: gql\n subscription UserStatusSubscription(\n $event_id: uuid!\n $user_id: String!\n ) {\n eetschema_event_by_pk(id: $event_id) {\n event_attendees(where: { user_id: { _eq: $user_id } }) {\n status\n event_id\n user_id\n }\n }\n }\n ,\n variables: { event_id, user_id },\n }),\n async onCacheEntryAdded(\n arg,\n { updateCachedData, cacheDataLoaded, cacheEntryRemoved }\n ) {\n // create a websocket connection when the cache subscription starts\n const ws = new WebSocket(\"ws://localhost:8080\");\n try {\n // wait for the initial query to resolve before proceeding\n await cacheDataLoaded;\n\n // when data is received from the socket connection to the server,\n // if it is a message and for the appropriate channel,\n // update our query result with the received message\n const listener = (event: MessageEvent) => {\n const data = JSON.parse(event.data);\n\n console.log(\"This is the data from the subscription!\", data);\n if (data.channel !== arg) return;\n\n updateCachedData((draft) => {\n draft = data;\n });\n };\n\n ws.addEventListener(\"message\", listener);\n } catch {\n // no-op in case cacheEntryRemoved resolves before cacheDataLoaded,\n // in which case cacheDataLoaded will throw\n }\n // cacheEntryRemoved will resolve when the cache subscription is no longer active\n await cacheEntryRemoved;\n // perform cleanup steps once the cacheEntryRemoved promise resolves\n ws.close();\n },\n }),\n```\n\n```text\nsubscriptions are not supported over HTTP, use websockets instead\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.085Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":135,"estimatedTokens":1018}}821{"id":"stack-51604231","source":"stackoverflow","questionId":51604231,"title":"GraphQL SDL enum types","tags":["enums","graphql","graphql-js"],"text":"Title: GraphQL SDL enum types\nTags: enums, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nWe have a bunch of enum types defined in an SDL and they work great for queries and mutations. \nIn the resolvers section these are mapped to the strings which represent those enums in the back end.\n\nFor example in the SDL we have :\n\n```\nenum WRRole {\n USER\n PROVIDER\n SUPPORT\n ADMIN\n SUPER_ADMIN\n GUEST\n}\n```\n\nAnd in the resolvers section we have :\n\n```\nWRRole: {\n USER: 'user',\n PROVIDER: 'provider',\n SUPPORT: 'support',\n ADMIN: 'admin',\n SUPER_ADMIN: 'super admin',\n GUEST: 'guest'\n},\n```\n\nThe resolvers match the enum values defined in the nodejs backend using Mongoose where the field is defined as :\n\n```\n...\nroles: {\n type: [\n {\n type: String,\n enum: ['user', 'provider', 'support', 'admin', 'super admin', 'guest']\n }\n ],\n default: ['user']\n},\n...\n```\n\nThe issue we have with GraphQL enums is that we cannot introspect the enums and get back the mappings using GraphQL introspection....\n\nThis causes issues with constructing UI's where we want to present the user with a dropdown list of these as options. The SDL enum values such as SUPER_USER are great for the keys but we want to display the actual backend mapped value to the use to select from. \n\nThis is just one example of many enums we have. Many of the mapped values consist of multiple words that have spaces between or words containing characters not allowed in the SDL enum value such as \"super admin\" in this case.\n\nSo my question is... How are you all handling stuff like this without having to repeat yourself or add more code to the front end to map these to more useful meaningful names for presentation ????\n\nThe order cannot be guaranteed to match the defined order of the enums in the backend so adding to the backend model enums would seriously mess up any assumptions that SUPER_USER actually maps to \"super user\" even though the resolver knows this.\n\nRegards\n\nSteve\n\n========================================\n\nCode:\n```text\nenum WRRole {\n USER\n PROVIDER\n SUPPORT\n ADMIN\n SUPER_ADMIN\n GUEST\n}\n```\n\n```text\nWRRole: {\n USER: 'user',\n PROVIDER: 'provider',\n SUPPORT: 'support',\n ADMIN: 'admin',\n SUPER_ADMIN: 'super admin',\n GUEST: 'guest'\n},\n```\n\n```text\n...\nroles: {\n type: [\n {\n type: String,\n enum: ['user', 'provider', 'support', 'admin', 'super admin', 'guest']\n }\n ],\n default: ['user']\n},\n...\n```\n\n```text\ntype Query {\n getEnumValues(enumName: String!): [EnumKeyValue!]!\n}\n\ntype EnumKeyValue {\n key: String!\n value: String\n}\n```\n\n```text\nconst enums = {\n WRRole: {\n USER: 'user',\n PROVIDER: 'provider',\n ...\n }\n};\n\nconst enumResolver = {\n WRRole: {\n USER: enums.WRRole.USER,\n PROVIDER: enums.WRRole.PROVIDER,\n ...\n }\n};\n```\n\n```text\nconst queryResolvers = {\n getEnumValues(source, args) {\n const enumKey = args.enumName;\n\n // enums is the same enums object from the previous example\n return Object.keys(enums[enumKey]).map(key => ({ \n key,\n value: enums[enumKey][key] \n }))\n\n }\n};\n```\n\n```text\nenum WRRole {\n # user\n USER\n # provider\n PROVIDER\n # support\n SUPPORT\n # admin\n ADMIN\n # super admin\n SUPER_ADMIN\n # guest\n GUEST\n }\n```\n\n```text\n{\n __type(name: \"WRRole\") {\n enumValues {\n description\n name\n }\n }\n }\n```\n\n```text\nEnum\n```\n\n```text\nSDL\n```\n\n```text\nEnum\n```\n\n```text\ngetEnumValues\n```\n\n```text\nEnum\n```\n\n```text\nEnum\n```\n\n```text\nSDL\n```\n\n========================================\n\nComments:\n- Funny enough I originally tried your \"Dirty, Abusive but quick\" solution but the result for description is always null in this case.\n- I am working on another solution at the moment as your preferred solution is way over complicated due to the fact we have a large number of enums to work with.\n- @user1790230 why is the result null? (are you using schema stitching?) have a look at this example, should work launchpad.graphql.com/5507l37qw9 I'm curious to hear what other solution you have in mind?\n- Yes. We are stitching 4 schemas together. Two of these are remote schemas and the other 2 are local to our services. It appears that NONE of the comments on enum fields are retained. All other types have their comments left intact and these can be introspected just fine. Once I get a little time I will work on the more generic solution I have in mind. That's not to say it will work but well give it a go and I'll update this post with the answer then.\n- @user1790230 If you're using graphql-tools then there is a new version ^3.1.0 that has a fix for the issue with enums descriptions not being retained, take a look here: github.com/apollographql/graphql-tools/pull/898\n- Thanks for that info Daniel. I have just upgraded to 3.1.1 and comments on enums are now working. This will save me a lot of effort and as such I have marked your answer as accepted. Thanks","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":212,"estimatedTokens":1263}}822{"id":"stack-39536078","source":"stackoverflow","questionId":39536078,"title":"Organising large number of mutations","tags":["graphql"],"text":"Title: Organising large number of mutations\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nWe have an established system which does not have a public API and we're evaluating GraphQL as a possible solution. We have a dozen or so different types, relations and possible actions/mutations.\n\nFrom what we have read and from our experimentation's we can only have a single root node and all the mutations have to be listed here. We have many modules each with many entities and many actions available on each.\n\nHow are people organising large numbers of mutations? We're struggling to find examples of large applications using GraphQL that we can learn from.\n\n========================================\n\nCode:\n```text\nmutation {\n users { \n addUser(name: \"Foo\")\n id\n }\n }\n}\n```\n\n========================================\n\nComments:\n- That's quite disappointing, as a colleague suggested, this sort of makes sense since FB themselves I would imagine do not have many mutations.","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":28,"estimatedTokens":250}}823{"id":"stack-52935158","source":"stackoverflow","questionId":52935158,"title":"How can I have one field updating/changing another one?","tags":["ruby","graphql","graphql-ruby"],"text":"Title: How can I have one field updating/changing another one?\nTags: ruby, graphql, graphql-ruby\nSource: Stack Overflow\n\nQuestion:\nI'd like to get fields resolved by another field.\n\nI have a list generated according to some arguments and would like to update the total field\n\nMy approach is probably incorrect.\n\nObviously, I'm trying to avoid re-running the same database query and passing filter up a level in the query string.\n\nSo assume the following ruby type for my query:\n\n```\nTypes::PostListType = GraphQL::ObjectType.define do\n name 'PostList'\n\n field :total, !types.Int, default_value: 0 # (user, *_args) {\n posts = function_to_filter(args[:filter])\n # how do I update total with posts.count here?\n posts.paginate(page: args[:page], per_page: args[:per_page])\n # how do I update per_page and page?\n }\n end\n\nend\n```\n\nMy query is something like this:\n\n```\nquery ProspectList {\n posts(filter:\"example\", page: 2) {\n total\n page\n per_page\n posts {\n id\n ...\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nTypes::PostListType = GraphQL::ObjectType.define do\n name 'PostList'\n\n field :total, !types.Int, default_value: 0 # <-- this is what I'd like to update in :posts resolution\n field :page, !types.Int, default_value: 0 # <-- this is what I'd like to update in :posts resolution\n field :per_page, !types.Int, default_value: 0 # <-- this is what I'd like to update in :posts resolution\n\n field :posts, types[Types::PostType] do\n argument :page, types.Int, default_value: 1\n argument :per_page, types.Int, default_value: 10 # <-- also need a limit here (hence why I need a field to tell what's been used in the end)\n argument :filter, types.String, default_value: ''\n resolve ->(user, *_args) {\n posts = function_to_filter(args[:filter])\n # how do I update total with posts.count here?\n posts.paginate(page: args[:page], per_page: args[:per_page])\n # how do I update per_page and page?\n }\n end\n\nend\n```\n\n```text\nquery ProspectList {\n posts(filter:\"example\", page: 2) {\n total\n page\n per_page\n posts {\n id\n ...\n }\n }\n}\n```\n\n```text\nTypes::PostListType = GraphQL::ObjectType.define do\n name 'PostList'\n\n field :total, !types.Int\n field :page, !types.Int\n field :per_page, !types.Int\n field :posts, types[Types::PostType]\nend\n```\n\n```text\nTypes::QueryType = GraphQL::ObjectType.define do\n name \"Query\"\n\n field :postlist, Types::PostListType do\n argument :page, types.Int, default_value: 1\n argument :per_page, types.Int, default_value: 1\n argument :filter, types.String\n resolve ->(_obj, args, _ctx) {\n result = Post.paginate(page: args[:page], per_page: args[:per_page])\n Posts = Struct.new(:posts, :page, :per_page, :total)\n Posts.new(\n result,\n args[:page],\n args[:per_page],\n result.total_entries\n )\n }\n end\nend\n```\n\n```text\nmodule Wrapper\n class PostList\n attr_accessor :posts, :total, :page, :per_page\n def initialize(posts, page, per_page)\n @posts = posts\n @total = posts.total_entries\n @page = page\n @per_page = per_page\n end\n end\nend\n\n...\n field :postlist, Types::PostListType do\n argument :page, types.Int, default_value: 1\n argument :per_page, types.Int, default_value: 1\n argument :filter, types.String\n resolve ->(_obj, args, _ctx) {\n Wrapper::PostList.new(Post.paginate(page: args[:page], per_page: args[:per_page]), args[:page], args[:per_page])\n }\n...\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":142,"estimatedTokens":885}}824{"id":"stack-48743214","source":"stackoverflow","questionId":48743214,"title":"GraphQL.NET mutation with a List> | JSON string","tags":["c#","graphql","graphql-dotnet"],"text":"Title: GraphQL.NET mutation with a List> | JSON string\nTags: c#, graphql, graphql-dotnet\nSource: Stack Overflow\n\nQuestion:\nI want to register `alarms` on my server application. To prevent passing 10+ arguments, I serialize my `alarm` on client side and pass it as `List` to my server. Deserialize it, register it and give the answer of an registered `alarm`.\n\nNow my problem is, that I don't know how to pass these parameters:\n\n### Using Mutation - DictionaryType\n\nhttps://i.sstatic.net/pnFN1.png\n\n \"Variable \\\"$params\\\" of type \\\"[String]!\\\" used in position expecting type \\\"[DictionaryType]!\\\".\"\n\n### Using Mutation - StringGraphType\n\n \"Cannot convert value to AST: System.Collections.Generic.Dictionary`2[System.String,System.Object]\",**\n\n### Server\n\n### Mutation - DictionaryType\n\n```\npublic class Mutation : ObjectGraphType\n{\n public Mutation()\n {\n Name = \"Mutation\";\n\n FieldAsync(\n \"registerStaticAlarms\",\n \"Register a list with static alarms.\",\n arguments: new QueryArguments(\n new QueryArgument>> {Name = \"params\"}\n ),\n resolve: async context =>\n {\n List parameterString = context.GetArgument>(\"params\");\n\n //TODO\n\n return null;\n }\n );\n }\n}\n```\n\n### Mutation - DictionaryType\n\n```\npublic class Mutation : ObjectGraphType\n{\n public Mutation()\n {\n Name = \"Mutation\";\n\n FieldAsync(\n \"registerStaticAlarms\",\n \"Register a list with static alarms.\",\n arguments: new QueryArguments(\n new QueryArgument>> {Name = \"params\"}\n ),\n resolve: async context =>\n {\n List parameterString = context.GetArgument>(\"params\");\n\n //TODO\n\n return null;\n }\n );\n }\n}\n```\n\n### DictionaryType\n\n```\npublic class DictionaryType : ObjectGraphType>\n{\n public DictionaryType()\n {\n Name = \"DictionaryType\";\n Description = \"Dictionary of type string, string.\";\n }\n}\n```\n\n### HtStaticAlarmBaseType\n\n```\npublic class HtStaticAlarmBaseType : ObjectGraphType\n{\n public HtStaticAlarmBaseType()\n {\n Name = \"HtStaticAlarmBase\";\n Description = \"Base class of a static alarm.\";\n\n // ##################################################\n // HtAlarmBase\n // ##################################################\n\n #region HtAlarmBase\n\n Field(\n \"AlarmClass\",\n resolve: context => context.Source.AlarmClass.ToString());\n\n Field(\n \"AlarmGroup\",\n resolve: context => context.Source.AlarmGroup);\n\n Field(\n \"ErrorCode\",\n resolve: context => (int)context.Source.ErrorCode);\n\n Field(\n \"Id\",\n resolve: context => context.Source.Id.ToString());\n\n Field(\n \"Message\",\n resolve: context => context.Source.Message);\n\n Field(\n \"Station\",\n resolve: context => context.Source.Station);\n\n Field(\n \"TimeStampCome\",\n resolve: context => context.Source.TimeStampCome?.ToString());\n\n Field(\n \"TimeStampGone\",\n resolve: context => context.Source.TimeStampGone?.ToString());\n\n Field(\n \"TimeStampAcknowledge\",\n resolve: context => context.Source.TimeStampAcknowledge?.ToString());\n\n Field(\n \"Origin\",\n resolve: context => context.Source.Origin);\n\n #endregion\n\n Field(\n \"Number\",\n resolve: context => context.Source.Number);\n\n Field(\n \"Active\",\n resolve: context => context.Source.Active);\n }\n}\n```\n\n========================================\n\nCode:\n```text\npublic class Mutation : ObjectGraphType\n{\n public Mutation()\n {\n Name = \"Mutation\";\n\n FieldAsync<HtStaticAlarmBaseType>(\n \"registerStaticAlarms\",\n \"Register a list with static alarms.\",\n arguments: new QueryArguments(\n new QueryArgument<NonNullGraphType<ListGraphType<DictionaryType>>> {Name = \"params\"}\n ),\n resolve: async context =>\n {\n List<object> parameterString = context.GetArgument<List<object>>(\"params\");\n\n //TODO\n\n return null;\n }\n );\n }\n}\n```\n\n```text\npublic class Mutation : ObjectGraphType\n{\n public Mutation()\n {\n Name = \"Mutation\";\n\n FieldAsync<HtStaticAlarmBaseType>(\n \"registerStaticAlarms\",\n \"Register a list with static alarms.\",\n arguments: new QueryArguments(\n new QueryArgument<NonNullGraphType<ListGraphType<StringGraphType>>> {Name = \"params\"}\n ),\n resolve: async context =>\n {\n List<object> parameterString = context.GetArgument<List<object>>(\"params\");\n\n //TODO\n\n return null;\n }\n );\n }\n}\n```\n\n```text\npublic class DictionaryType : ObjectGraphType<Dictionary<string,string>>\n{\n public DictionaryType()\n {\n Name = \"DictionaryType\";\n Description = \"Dictionary of type string, string.\";\n }\n}\n```\n\n```text\npublic class HtStaticAlarmBaseType : ObjectGraphType<HtStaticAlarmBase>\n{\n public HtStaticAlarmBaseType()\n {\n Name = \"HtStaticAlarmBase\";\n Description = \"Base class of a static alarm.\";\n\n\n // ##################################################\n // HtAlarmBase\n // ##################################################\n\n #region HtAlarmBase\n\n Field<StringGraphType>(\n \"AlarmClass\",\n resolve: context => context.Source.AlarmClass.ToString());\n\n Field<StringGraphType>(\n \"AlarmGroup\",\n resolve: context => context.Source.AlarmGroup);\n\n Field<IntGraphType>(\n \"ErrorCode\",\n resolve: context => (int)context.Source.ErrorCode);\n\n Field<StringGraphType>(\n \"Id\",\n resolve: context => context.Source.Id.ToString());\n\n Field<StringGraphType>(\n \"Message\",\n resolve: context => context.Source.Message);\n\n Field<StringGraphType>(\n \"Station\",\n resolve: context => context.Source.Station);\n\n Field<StringGraphType>(\n \"TimeStampCome\",\n resolve: context => context.Source.TimeStampCome?.ToString());\n\n Field<StringGraphType>(\n \"TimeStampGone\",\n resolve: context => context.Source.TimeStampGone?.ToString());\n\n Field<StringGraphType>(\n \"TimeStampAcknowledge\",\n resolve: context => context.Source.TimeStampAcknowledge?.ToString());\n\n Field<StringGraphType>(\n \"Origin\",\n resolve: context => context.Source.Origin);\n\n #endregion\n\n Field<IntGraphType>(\n \"Number\",\n resolve: context => context.Source.Number);\n\n Field<BooleanGraphType>(\n \"Active\",\n resolve: context => context.Source.Active);\n }\n}\n```\n\n```text\nalarms\n```\n\n```text\nalarm\n```\n\n```text\nList<JSONString>\n```\n\n```text\nalarm\n```\n\n```text\nmutation RegisterStaticAlarms($params: [HtStaticAlarmInputType])\n{\n registerStaticAlarms(params: $params)\n {\n id,\n number,\n message,\n errorCode\n }\n}\n```\n\n```text\npublic class Mutation : ObjectGraphType\n{\n public Mutation()\n {\n Name = \"Mutation\";\n\n Field<ListGraphType<HtStaticAlarmType>>(\n \"registerStaticAlarms\",\n arguments: new QueryArguments(\n new QueryArgument<ListGraphType<HtStaticAlarmInputType>>\n {\n Name = \"params\"\n }\n ),\n resolve: context =>\n {\n List<HtStaticAlarmInputTypeParams> paramses = context.GetArgument<List<HtStaticAlarmInputTypeParams>>(\"params\");\n\n List<HtStaticAlarmBase> list = new List<HtStaticAlarmBase>();\n foreach (HtStaticAlarmInputTypeParams p in paramses)\n {\n list.Add(HtAlarmManager.Create(p.Origin, (EHtAlarmClassType)Enum.Parse(typeof(EHtAlarmClassType), p.AlarmClass.ToString()), p.AlarmGroup, p.Station, (HtErrorCode)Enum.Parse(typeof(HtErrorCode), p.ErrorCode.ToString()), p.Message, p.Number));\n }\n\n return list;\n }\n ); \n }\n}\n```\n\n```text\n/// <summary>\n/// GraphQl type of the <see cref=\"HtStaticAlarmBase\"/>\n/// </summary>\ninternal class HtStaticAlarmType : ObjectGraphType<HtStaticAlarmBase>\n{\n public HtStaticAlarmType()\n {\n Name = \"HtStaticAlarmType\";\n Description = \"Base class of a static alarm.\";\n\n\n // ##################################################\n // HtAlarmBase\n // ##################################################\n\n #region HtAlarmBase\n\n Field<StringGraphType>(\n \"AlarmClass\",\n resolve: context => context.Source.AlarmClass.ToString());\n\n Field<StringGraphType>(\n \"AlarmGroup\",\n resolve: context => context.Source.AlarmGroup);\n\n Field<IntGraphType>(\n \"ErrorCode\",\n resolve: context => (int)context.Source.ErrorCode);\n\n Field<StringGraphType>(\n \"Id\",\n resolve: context => context.Source.Id.ToString());\n\n Field<StringGraphType>(\n \"Message\",\n resolve: context => context.Source.Message);\n\n Field<StringGraphType>(\n \"Station\",\n resolve: context => context.Source.Station);\n\n Field<StringGraphType>(\n \"TimeStampCome\",\n resolve: context => context.Source.TimeStampCome?.ToString());\n\n Field<StringGraphType>(\n \"TimeStampGone\",\n resolve: context => context.Source.TimeStampGone?.ToString());\n\n Field<StringGraphType>(\n \"TimeStampAcknowledge\",\n resolve: context => context.Source.TimeStampAcknowledge?.ToString());\n\n Field<StringGraphType>(\n \"Origin\",\n resolve: context => context.Source.Origin);\n\n #endregion\n\n Field<IntGraphType>(\n \"Number\",\n resolve: context => context.Source.Number);\n\n Field<BooleanGraphType>(\n \"Active\",\n resolve: context => context.Source.Active);\n }\n}\n\n/// <summary>\n/// GraphQL input type of the <see cref=\"HtStaticAlarmBase\"/>\n/// </summary>\ninternal class HtStaticAlarmInputType : InputObjectGraphType\n{\n public HtStaticAlarmInputType()\n {\n Name = \"HtStaticAlarmInputType\";\n Description = \"Base class of a static alarm.\";\n\n // ##################################################\n // HtAlarmBase\n // ##################################################\n\n #region HtAlarmBase\n\n Field<IntGraphType>(\"AlarmClass\");\n Field<StringGraphType>(\"AlarmGroup\");\n Field<IntGraphType>(\"ErrorCode\");\n Field<StringGraphType>(\"Id\");\n Field<StringGraphType>(\"Message\");\n Field<StringGraphType>(\"Station\");\n Field<DateGraphType>(\"TimeStampCome\");\n Field<DateGraphType>(\"TimeStampGone\");\n Field<DateGraphType>(\"TimeStampAcknowledge\");\n Field<StringGraphType>(\"Origin\");\n Field<StringGraphType>(\"IsSynced\");\n Field<StringGraphType>(\"Pending\");\n\n #endregion\n\n Field<IntGraphType>(\"Number\");\n Field<BooleanGraphType>(\"Active\"); \n }\n}\n\n/// <summary>\n/// A lightweight class to deserialize the incoming <see cref=\"HtStaticAlarmInputType\"/>\n/// </summary>\ninternal class HtStaticAlarmInputTypeParams\n{\n public int AlarmClass { get; set; }\n public string AlarmGroup { get; set; }\n public int ErrorCode { get; set; }\n public string Message { get; set; }\n public string Station { get; set; }\n public DateTime TimeStampCome { get; set; }\n public DateTime TimeStampGone { get; set; }\n public DateTime TimeStampAcknowledge { get; set; }\n public string Origin { get; set; }\n\n public int Number { get; set; }\n public bool Active { get; set; }\n}\n```\n\n```text\nproperties\n```\n\n```text\nHtStaticAlarmInputType\n```\n\n```text\nHtStaticAlarmInputTypeParams\n```\n\n```text\nCamelCasePropertyNamesContractResolver\n```\n\n```text\nJSON\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":499,"estimatedTokens":2934}}825{"id":"stack-61126561","source":"stackoverflow","questionId":61126561,"title":"What is the references field for in sequelize?","tags":["javascript","graphql","sequelize.js","sequelize-auto"],"text":"Title: What is the references field for in sequelize?\nTags: javascript, graphql, sequelize.js, sequelize-auto\nSource: Stack Overflow\n\nQuestion:\nI have a user table that has a foreign key column to a roles table. \n\nI defined all relationships in mysql and using `sequelize-auto` I generated my models. \n\nThe generated model for user was this: \n\n```\nconst user = sequelize.define('user', {\n Id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n },\n Email: {\n type: DataTypes.STRING(45),\n allowNull: false,\n unique: true,\n },\n RoleId: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n references: {\n model: 'roles',\n key: 'Id',\n },\n },\n });\n```\n\nI thought that my reference was set so that when I did the following in my resolver: \n\n```\nusers: async () => {\n const users = await db.user.findAll({\n include: [\n {\n model: db.roles,\n },\n ],\n });\n\nreturn users\n```\n\nI should have gotten back a list of user roles with the following query in the playground: \n\n```\n{users\n {roles\n {Name, Id}\n }\n}\n```\n\ninstead I got \n\n roles is not associated to user!\n\nWhat I later figured out is that I needed to make an association: \n\n```\nuser.associate = models => {\n user.hasMany(models.roles, {\n foreignKey: 'Id',\n sourceKey: 'RoleId',\n onDelete: 'cascade',\n });\n };\n```\n\nThen it worked. \n\nWhat I still dont understand is what is this for in the user-model?: \n\n```\nreferences: {\n model: 'roles',\n key: 'Id',\n },\n```\n\nI thought that it was my \"association\" with the roles table but without me explicitly adding an association this simply did nothing. Can someone please explain the meaning of `references` field?\n\n========================================\n\nTop Answer:\nThe given answer is correct but I realized later on that the reason for this question was that I assumed I could create assosiations via code so that I did not have to modify every model manualy by default. \n\nFor those of you looking to do the same I found a solution here. \n\nWhich is basically: \n\n1) inside of your models folder create an index.js file and add the following code\n\n```\nimport Sequelize from 'sequelize';\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst basename = path.basename(__filename);\n\nconst db = {};\n\n// @ts-ignore\nconst sequelize = new Sequelize('dbname', 'dbUser', 'password', {\n host: '127.0.0.1',\n port: 'PORT',\n dialect: 'mysql',\n define: {\n freezeTableName: true,\n timestamps: false,\n },\n pool: {\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000,\n },\n // \n operatorsAliases: false,\n});\n\nconst tableModel = {};\n\nfs.readdirSync(__dirname)\n .filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js')\n .forEach(file => {\n const model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n tableModel[model.name] = model;\n });\n\nObject.getOwnPropertyNames(db).forEach(modelName => {\n const currentModel = db[modelName];\n Object.getOwnPropertyNames(currentModel.rawAttributes).forEach(attributeName => {\n if (\n Object.prototype.hasOwnProperty.call(\n currentModel.rawAttributes[attributeName],\n 'references'\n ) &&\n Object.prototype.hasOwnProperty.call(\n currentModel.rawAttributes[attributeName].references,\n 'model'\n ) &&\n Object.prototype.hasOwnProperty.call(\n currentModel.rawAttributes[attributeName].references,\n 'key'\n )\n ) {\n if (\n !(\n currentModel.rawAttributes[attributeName].references.model &&\n currentModel.rawAttributes[attributeName].references.key\n )\n ) {\n console.log(\n `*SKIPPED* ${modelName} ${attributeName} references a model ${currentModel.rawAttributes[attributeName].references.model} with key ${currentModel.rawAttributes[attributeName].references.key}`\n );\n return;\n }\n\n console.log(\n `${modelName} ${attributeName} references a model ${currentModel.rawAttributes[attributeName].references.model} with key ${currentModel.rawAttributes[attributeName].references.key}`\n );\n const referencedTable =\n tableModel[currentModel.rawAttributes[attributeName].references.model];\n\n currentModel.belongsTo(referencedTable, { foreignKey: attributeName });\n referencedTable.hasMany(currentModel, { foreignKey: attributeName });\n\n }\n });\n});\n\n// @ts-ignore\ndb.sequelize = sequelize;\n// @ts-ignore\ndb.Sequelize = Sequelize;\n\n// eslint-disable-next-line eol-last\nmodule.exports = db;\n```\n\n2) inside of your resolver just reference the above: \n\n```\nconst db = require('../assets/models/index');\n```\n\n========================================\n\nCode:\n```text\nconst user = sequelize.define('user', {\n Id: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n primaryKey: true,\n autoIncrement: true,\n },\n Email: {\n type: DataTypes.STRING(45),\n allowNull: false,\n unique: true,\n },\n RoleId: {\n type: DataTypes.INTEGER(11),\n allowNull: false,\n references: {\n model: 'roles',\n key: 'Id',\n },\n },\n });\n```\n\n```text\nusers: async () => {\n const users = await db.user.findAll({\n include: [\n {\n model: db.roles,\n },\n ],\n });\n\nreturn users\n```\n\n```text\n{users\n {roles\n {Name, Id}\n }\n}\n```\n\n```text\nuser.associate = models => {\n user.hasMany(models.roles, {\n foreignKey: 'Id',\n sourceKey: 'RoleId',\n onDelete: 'cascade',\n });\n };\n```\n\n```text\nreferences: {\n model: 'roles',\n key: 'Id',\n },\n```\n\n```text\nsequelize-auto\n```\n\n```text\nreferences\n```\n\n```text\nimport Sequelize from 'sequelize';\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst basename = path.basename(__filename);\n\nconst db = {};\n\n// @ts-ignore\nconst sequelize = new Sequelize('dbname', 'dbUser', 'password', {\n host: '127.0.0.1',\n port: 'PORT',\n dialect: 'mysql',\n define: {\n freezeTableName: true,\n timestamps: false,\n },\n pool: {\n max: 5,\n min: 0,\n acquire: 30000,\n idle: 10000,\n },\n // <http://docs.sequelizejs.com/manual/tutorial/querying.html#operators>\n operatorsAliases: false,\n});\n\nconst tableModel = {};\n\nfs.readdirSync(__dirname)\n .filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js')\n .forEach(file => {\n const model = sequelize.import(path.join(__dirname, file));\n db[model.name] = model;\n tableModel[model.name] = model;\n });\n\nObject.getOwnPropertyNames(db).forEach(modelName => {\n const currentModel = db[modelName];\n Object.getOwnPropertyNames(currentModel.rawAttributes).forEach(attributeName => {\n if (\n Object.prototype.hasOwnProperty.call(\n currentModel.rawAttributes[attributeName],\n 'references'\n ) &&\n Object.prototype.hasOwnProperty.call(\n currentModel.rawAttributes[attributeName].references,\n 'model'\n ) &&\n Object.prototype.hasOwnProperty.call(\n currentModel.rawAttributes[attributeName].references,\n 'key'\n )\n ) {\n if (\n !(\n currentModel.rawAttributes[attributeName].references.model &&\n currentModel.rawAttributes[attributeName].references.key\n )\n ) {\n console.log(\n `*SKIPPED* ${modelName} ${attributeName} references a model ${currentModel.rawAttributes[attributeName].references.model} with key ${currentModel.rawAttributes[attributeName].references.key}`\n );\n return;\n }\n\n console.log(\n `${modelName} ${attributeName} references a model ${currentModel.rawAttributes[attributeName].references.model} with key ${currentModel.rawAttributes[attributeName].references.key}`\n );\n const referencedTable =\n tableModel[currentModel.rawAttributes[attributeName].references.model];\n\n currentModel.belongsTo(referencedTable, { foreignKey: attributeName });\n referencedTable.hasMany(currentModel, { foreignKey: attributeName });\n\n }\n });\n});\n\n// @ts-ignore\ndb.sequelize = sequelize;\n// @ts-ignore\ndb.Sequelize = Sequelize;\n\n// eslint-disable-next-line eol-last\nmodule.exports = db;\n```\n\n```text\nconst db = require('../assets/models/index');\n```\n\n========================================\n\nComments:\n- So it¨s a deskription but if Im focusing on being practical only in my backend enviorment and creating all relationships in the mysql workbench then this field is useless for me? If I however want to create tables from my backend to my mysql enviorment then this is of use?\n- If you will use migrations to create and modify your DB structure then you won't need 'references' in the models at all. All these references will be in migrations to help sequelize CLI to create foreign keys.\n- Current version 0.7.5 of `sequelize-auto` generates the associations automatically.","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":369,"estimatedTokens":2141}}826{"id":"stack-49869064","source":"stackoverflow","questionId":49869064,"title":"Using writeFragment to Update a Field Belonging to an Object?","tags":["graphql","apollo","react-apollo","apollo-client"],"text":"Title: Using writeFragment to Update a Field Belonging to an Object?\nTags: graphql, apollo, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get my first `writeFragment` working.\n\nHere's the object shape:\n\n```\nresolutions {\n _id\n name\n completed\n goals {\n _id\n name\n completed\n }\n}\n```\n\nI've just run a mutation on the client that successfully adds a new `goal`, and now I'm trying to get the client page to auto-update and show the new goal that was just added.\n\nI've got `readFragment` working. It reads in the Resolution successfully. I'm reading in the Resolution, rather than the goals, because as a field belonging to resolution, the goals don't have an id of their own.\n\nHere's my `update` function, showing `readFragment` and `writeFragment`:\n\n```\n {\n let resId = 'Resolution:' + resolutionId;\n\n const theRes = cache.readFragment({\n id: resId,\n fragment: GET_FRAGMENT_GOAL,\n });\n\n theRes.goals = theRes.goals.concat([createGoal]); //\n```\n\n...and here's the gql for the fragments:\n\n```\nconst GET_FRAGMENT_GOAL = gql`\n fragment targetRes on resolutions {\n name\n completed\n goals {\n _id\n name\n completed\n }\n }\n `;\n\n const SET_FRAGMENT_GOAL = gql`\n fragment targetGoal on resolutions {\n __typename\n goals\n }\n `;\n```\n\nHere's a console error I'm getting:\n\n You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types.\n\n \n Apollo Client will not be able to able to accurately map fragments.To make this error go away, use the IntrospectionFragmentMatcher as described in the docs: http://dev.apollodata.com/react/initialization.html#fragment-matcher\n\nI read up on IntrospectionFragmentMatcher and it looks like mega-overkill for my situation. It appears I'm doing something else wrong. Here's the other error I'm getting at the same time:\n\n Uncaught (in promise) TypeError: Cannot read property 'data' of undefined\n\nWhat's wrong with my call to writeFragment?\n\n========================================\n\nCode:\n```text\nresolutions {\n _id\n name\n completed\n goals {\n _id\n name\n completed\n }\n}\n```\n\n```js\n<Mutation\n mutation={CREATE_GOAL}\n update={(cache, { data: { createGoal } }) => {\n let resId = 'Resolution:' + resolutionId;\n\n const theRes = cache.readFragment({\n id: resId,\n fragment: GET_FRAGMENT_GOAL,\n });\n\n theRes.goals = theRes.goals.concat([createGoal]); //<== THIS WORKS\n\n cache.writeFragment({\n id: resId,\n fragment: SET_FRAGMENT_GOAL,\n data: { __typename: 'Resolution', goals: theRes.goals },\n });\n }}\n>\n```\n\n```text\nconst GET_FRAGMENT_GOAL = gql`\n fragment targetRes on resolutions {\n name\n completed\n goals {\n _id\n name\n completed\n }\n }\n `;\n\n\n const SET_FRAGMENT_GOAL = gql`\n fragment targetGoal on resolutions {\n __typename\n goals\n }\n `;\n```\n\n```text\nwriteFragment\n```\n\n```text\ngoal\n```\n\n```text\nreadFragment\n```\n\n```text\nupdate\n```\n\n```text\nreadFragment\n```\n\n```text\nwriteFragment\n```\n\n```text\nimport gql from \"graphql-tag\";\n\nlet resolutionQueryFragments = {\n goalParts: gql`\n fragment goalParts on Goal {\n _id\n name\n completed\n }\n `,\n};\n\n\nresolutionQueryFragments.resolutionGoals = gql`\n fragment resolutionGoals on Resolution {\n goals{\n _id\n name\n completed \n }\n }\n`;\n\nconst GET_RESOLUTIONS = gql`\n query Resolutions {\n resolutions {\n _id\n name\n completed\n ...resolutionGoals\n }\n user {\n _id\n }\n }\n ${resolutionQueryFragments.resolutionGoals}\n`;\n\nconst CREATE_RESOLUTION = gql`\n mutation createResolution($name: String!) {\n createResolution(name: $name) {\n __typename\n _id\n name\n ...resolutionGoals\n completed\n }\n }\n ${resolutionQueryFragments.resolutionGoals}\n`;\n\nconst GET_RESOLUTIONS_FOR_MUTATION_COMPONENT = gql`\n query Resolutions {\n resolutions {\n _id\n name\n completed\n ...resolutionGoals\n }\n }\n ${resolutionQueryFragments.resolutionGoals}\n`;\n\nconst CREATE_GOAL = gql`\n mutation createGoal($name: String!, $resolutionId: String!) {\n createGoal(name: $name, resolutionId: $resolutionId) {\n ...goalParts\n }\n }\n ${resolutionQueryFragments.goalParts}\n`;\n\nexport {resolutionQueryFragments, GET_RESOLUTIONS, GET_RESOLUTIONS_FOR_MUTATION_COMPONENT, CREATE_RESOLUTION, CREATE_GOAL}\n```\n\n```text\nimport React, {Component} from \"react\";\nimport gql from \"graphql-tag\";\nimport {graphql} from \"react-apollo\";\nimport {Mutation} from \"react-apollo\";\nimport {withApollo} from \"react-apollo\";\nimport {resolutionQueryFragments, CREATE_GOAL} from '../../imports/api/resolutions/queries';\n\nconst GoalForm = ({resolutionId, client}) => {\n let input;\n\n return (\n <Mutation\n mutation={CREATE_GOAL}\n update={(cache, {data: {createGoal}}) => {\n let resId = 'Resolution:' + resolutionId;\n let currentRes = cache.data.data[resId];\n let theGoals = cache.readFragment({\n id: resId,\n fragment: resolutionQueryFragments.resolutionGoals\n });\n theGoals = theGoals.goals.concat([createGoal]);\n cache.writeFragment({\n id: resId,\n fragment: resolutionQueryFragments.resolutionGoals,\n data: {goals: theGoals}\n });\n }}\n >\n {(createGoal, {data}) => (\n <div>\n <form\n onSubmit={e => {\n e.preventDefault();\n createGoal({\n variables: {\n name: input.value,\n resolutionId: resolutionId\n }\n });\n input.value = \"\";\n }}\n >\n <input\n ref={node => {\n input = node;\n }}\n />\n <button type=\"submit\">Submit</button>\n </form>\n </div>\n )}\n </Mutation>\n )\n ;\n};\n\nexport default withApollo(GoalForm);\n```\n\n========================================\n\nComments:\n- Maybe the sub fields of `goals` should be added to `SET_FRAGMENT_GOAL` just like in `GET_FRAGMENT_GOAL`?","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":300,"estimatedTokens":1646}}827{"id":"stack-59826026","source":"stackoverflow","questionId":59826026,"title":"Make an image optional in netlify cms and gatsby js","tags":["javascript","graphql","gatsby","netlify-cms","gatsby-image"],"text":"Title: Make an image optional in netlify cms and gatsby js\nTags: javascript, graphql, gatsby, netlify-cms, gatsby-image\nSource: Stack Overflow\n\nQuestion:\nI have a fairly simple Gatsby & Netlify CMS site. I can't cope with making images optional. In case of Netlify CMS it's just a matter of setting one field `required: false`. How do I write a query for Gatsby so I don't get an error 'GraphQL Error Field \"image\" must not have a selection since type \"String\" has no subfields.' when the image is in fact an empty string since it's not mandatory in my app? Is there any way around this?\n\nGraphQL query for image:\n\n```\nimage {\n childImageSharp {\n fluid(maxWidth: 2048) \n ...GatsbyImageSharpFluid\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nimage {\n childImageSharp {\n fluid(maxWidth: 2048) \n ...GatsbyImageSharpFluid\n }\n }\n}\n```\n\n```text\nrequired: false\n```\n\n```text\nexports.createSchemaCustomization = ({ actions }) => {\n const { createTypes } = actions;\n const typeDefs = `\n type MarkdownRemark implements Node {\n frontmatter: Frontmatter\n }\n \n type Frontmatter @infer {\n yourimage: File @fileByRelativePath,\n }\n `;\n createTypes(typeDefs);\n};\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":51,"estimatedTokens":304}}828{"id":"stack-54812332","source":"stackoverflow","questionId":54812332,"title":"Access the queried data from Vue component using Gridsome","tags":["vue.js","graphql","static-pages","gridsome"],"text":"Title: Access the queried data from Vue component using Gridsome\nTags: vue.js, graphql, static-pages, gridsome\nSource: Stack Overflow\n\nQuestion:\nI am new to Gridsome as well as to GraphQL. However I'm not using the GraphQL for this project.\nI just have a Gridsome project setup and some JSON data and I'm trying to define it globally so that I can access it from all my Vue pages and Components. (I know it can be imported into the component but I'm looking for more \"Gridsome way\" of doing that).\nI've done following steps to achieve this:\n\n1) Created a folder for the Json file: `data/myJson.json`.\n Json-file: \n\n```\n{\n \"startPage\": {\n \"title\": \"Welcher Typ bist Du?\",\n \"subtitle\": \"Los geht's beim lustigen Datev-Quiz!\",\n \"startButton\": \"Quiz starten\"\n }\n}\n```\n\n2) My `gridsome.server.js` is looking like this:\n\n```\nvar myJson = require('./data/questions.json');\nmodule.exports = function (api) {\n api.loadSource(store => {\n const startPage = store.addContentType({\n typeName: 'StartPage'\n });\n\n startPage.addNode({\n title: 'StartPageInfo',\n fields: {\n title: myJson.startPage.title,\n subtitle: myJson.startPage.subtitle,\n startButton: myJson.startPage.startButton\n }\n })\n })\n}\n```\n\n3) And I'm querying this data in the `index.vue` page.\n\nI can acces this data in my template. So if I do something like this \n\n```\n\n### \n\n```\n\nthen it works perfectly fine.\n\nMy problem is however, that I can't acces this queried data within Vue's `data` object or within methods and so on.\nSo something like this: \n\n```\ndata() {\n retrun {\n START_PAGE_END_POINT: this.$page.allStartPage.edges[0].node.fields\n }\n}\n```\n\ngives me an error message and tells that the `$page` is not defined.\n\nAny minds what I'm doing wrong?\n\n========================================\n\nCode:\n```text\n{\n \"startPage\": {\n \"title\": \"Welcher Typ bist Du?\",\n \"subtitle\": \"Los geht's beim lustigen Datev-Quiz!\",\n \"startButton\": \"Quiz starten\"\n }\n}\n```\n\n```text\nvar myJson = require('./data/questions.json');\nmodule.exports = function (api) {\n api.loadSource(store => {\n const startPage = store.addContentType({\n typeName: 'StartPage'\n });\n\n startPage.addNode({\n title: 'StartPageInfo',\n fields: {\n title: myJson.startPage.title,\n subtitle: myJson.startPage.subtitle,\n startButton: myJson.startPage.startButton\n }\n })\n })\n}\n```\n\n```text\n<h4 v-html=\"$page.allStartPage.edges[0].node.fields\"></h4>\n```\n\n```text\ndata() {\n retrun {\n START_PAGE_END_POINT: this.$page.allStartPage.edges[0].node.fields\n }\n}\n```\n\n```text\ndata/myJson.json\n```\n\n```text\ngridsome.server.js\n```\n\n```text\nindex.vue\n```\n\n```text\ndata\n```\n\n```text\n$page\n```\n\n```text\ndata() {\n return {\n START_PAGE_END_POINT: null,\n\n title: null,\n subtitle: null,\n startButton: null\n }\n }\n```\n\n```text\ncreated() {\n if (this.$page) {\n this.START_PAGE_END_POINT = this.$page.allStartPage.edges[0].node.fields;\n\n this.title = this.START_PAGE_END_POINT.title,\n this.subtitle = this.START_PAGE_END_POINT.subtitle,\n this.startButton = this.START_PAGE_END_POINT.startButton\n }\n }\n```\n\n```text\nthis.$page\n```\n\n```text\ncreated()\n```\n\n```text\ndata\n```\n\n```text\nnull\n```\n\n```text\ndata\n```\n\n```text\ncreated()\n```\n\n```text\n$page\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- if you `console.log(this)` in your component, you will see that the data object is transformed into `this._data` and that `$page` is at the same level `this.$page`. The `$` indicates that it is some kind of module such as `this.$router` or `this.$store`\n- I found you can access `this.$page` and `this.$static` in the `mounted()` hook, too, which helps if you want to save data from the query straight into a `data()` variable.","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":197,"estimatedTokens":949}}829{"id":"stack-54322029","source":"stackoverflow","questionId":54322029,"title":"graphqljs - Query root type must be provided","tags":["javascript","graphql","graphql-js"],"text":"Title: graphqljs - Query root type must be provided\nTags: javascript, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nHow do I get around this error? For this particular schema, I do not need any queries (they're all mutations). I cannot pass `null` and if I pass an empty `GraphQLObjectType` it gives me the error: \n\n```\nType Query must define one or more fields.\n```\n\n========================================\n\nTop Answer:\nIf you are using Node.js express -\n\nYour schema should have both Root query and root Mutation, although you don't have any query resolvers but still you need to define the root query.\n\nE.g. -\n\n```\ntype RootQuery {\nhello: String!\n}\n\nschema {\n query: RootQuery\n mutation: RootMutation\n}\n```\n\n========================================\n\nCode:\n```text\nType Query must define one or more fields.\n```\n\n```text\nnull\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\ntype Query\n```\n\n```text\ntype Query {}\n```\n\n```text\nnew GraphQLObjectType({\n name: 'Query',\n fields: {\n _dummy: { type: graphql.GraphQLString }\n }\n})\n```\n\n```text\ntype Query {\n _dummy: String\n}\n```\n\n```text\nQuery\n```\n\n```text\ntype RootQuery {\nhello: String!\n}\n\nschema {\n query: RootQuery\n mutation: RootMutation\n}\n```\n\n```text\nconst {GraphQLObjectType, GraphQLSchema, GraphQLString} = require(\"graphql\")\n\nconst Schema = new GraphQLSchema({\n query: new GraphQLObjectType({\n name: \"Query\",\n fields: () => ({\n message: {\n type: GraphQLString,\n resolve: () => \"Hello World\"\n }\n })\n })\n})\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\nQuery\n```\n\n```text\nquery\n```\n\n```text\n@Resolver()\nexport class AppResolver {\n @Query(() => String)\n hello(): string {\n return 'Hello world!';\n }\n}\n```\n\n```text\nproviders: [AppResolver, AppService],\n```\n\n========================================\n\nComments:\n- kind of odd how you need to specify Query even though you don't need it. I'll mark this as answer after I give it another while.\n- @A.Lau It's safe to mark this as accepted. If you check the spec, it specifically spells out that \"[t]he query root operation type must be provided and must be an Object type.\" Only the mutation and subscription root operation types are optional.","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":131,"estimatedTokens":560}}830{"id":"stack-59083667","source":"stackoverflow","questionId":59083667,"title":"What is the best way to mutate remote data fetched with useQuery","tags":["reactjs","graphql","react-apollo"],"text":"Title: What is the best way to mutate remote data fetched with useQuery\nTags: reactjs, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI am fairly new to graphQL and Apollo. I hope I can make myself clear:\n\nI am fetching data using the apollo/react-hook `useQuery`. Afterwards I populate a form with the data so the client can change it. When he is done, the data gets send back to the server using `useMutation`.\n\nUntil now, I use `onCompleted` to store the fetched data in the component state. That looks like this:\n\n```\nimport React, { useState } from 'react';\nimport { TextField } from '@material-ui/core'; \nconst Index = () => {\n const [state, setState] = useState(null)\n const {data, loading, error} = useQuery(query, {\n onCompleted: data => {\n // modify data slightly\n setState(data)\n }\n })\n\n return (\n setState(event.target.value)}/>\n )\n}\n```\n\nThe form than uses the values stored in the component state and the form handlers use `setState`\nto change it.\n\nMy question now is, if this is the best practice and if the storing of the fetched data in a local component state neccessary.\n\n========================================\n\nTop Answer:\nSeems like `useQuery` only has a state for `responseId`: https://github.com/trojanowski/react-apollo-hooks/blob/master/src/useQuery.ts\n\nBut you get a `refetch` function from the `useQuery` as well.\n\n```\nconst { loading, error, data, refetch } = useQuery(...);\n```\n\nTry calling `refetch()`, after you used `useMutation()` to update the data. It shouldn't trigger a rerender. You probably have to set your own state for that reason.\nMaybe something like:\n\n```\nconst handleUpdate = () =>{\n setData(refetch());\n}\n```\n\nAlternativly you get the data after using `useMutation` which is also in the state: https://github.com/trojanowski/react-apollo-hooks/blob/master/src/useMutation.ts\n\n```\nconst [update, { data }] = useMutation(UPDATE_DATA);\n```\n\n`data` will always be the newest value so you could also do:\n\n```\nuseEffect(()=>{\n setData(data);\n // OR\n // setData(refetch());\n}, [data])\n```\n\n========================================\n\nCode:\n```text\nimport React, { useState } from 'react';\nimport { TextField } from '@material-ui/core'; \nconst Index = () => {\n const [state, setState] = useState(null)\n const {data, loading, error} = useQuery<typeof queryType>(query, {\n onCompleted: data => {\n // modify data slightly\n setState(data)\n }\n })\n\n return (\n <TextField value={state} onChange={() => setState(event.target.value)}/>\n )\n}\n```\n\n```text\nuseQuery\n```\n\n```text\nuseMutation\n```\n\n```text\nonCompleted\n```\n\n```text\nsetState\n```\n\n```text\nconst Outer = () => {\n const {data, loading, error} = useQuery(query)\n\n if (!data) {\n return null // or a loading indicator, etc.\n }\n\n return <Inner data={data}/>\n}\n\nconst Inner = ({ data }) => {\n const [value, setValue] = useState(data.someField)\n\n <TextField value={value} onChange={() => setValue(event.target.value)}/>\n}\n```\n\n```text\ndata\n```\n\n```text\nconst { loading, error, data, refetch } = useQuery(...);\n```\n\n```text\nconst handleUpdate = () =>{\n setData(refetch());\n}\n```\n\n```text\nconst [update, { data }] = useMutation(UPDATE_DATA);\n```\n\n```text\nuseEffect(()=>{\n setData(data);\n // OR\n // setData(refetch());\n}, [data])\n```\n\n```text\nuseQuery\n```\n\n```text\nresponseId\n```\n\n```text\nrefetch\n```\n\n```text\nuseQuery\n```\n\n```text\nrefetch()\n```\n\n```text\nuseMutation()\n```\n\n```text\nuseMutation\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- Your code looks fine to me. It is necessary since at first `state` is null. If you don't `setState` you can't update the view, thus your form woudln't be updated.\n- I definetly need a local state or does working with apollos local states also trigger rerenders? In the real application I have a few dropdown menus.\n- Sorry i am not familiar with apollos. But since you said that apollos already has a state for the same data, you shouldn't create your own state. You should only have one state for a set of data. If apollos handles the state, then good for you!\n- Well I said it with a big question mark. I dont think it acts like a functional component state(?).\n- The `data` property exposed by Apollo is global state that represents remote data. While there's way to mutate it, it makes no sense to do so in the context of a user form. Even if it's initialized based on some other state, a form's state only represents the user's input. If we were only rendering the data, then using component state would be superfluous. But that's not the case here.\n- Thanks for your answer. In my real application I already take care of that with a loading component.\n- @MartinSchmelzer The loading component is really beside the point of the post. The key is that you're taking advantage of how state is initialized. The above would not be possible with a single component (without also using `useEffect`) because only the first set of props is used to initialize the state.","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":193,"estimatedTokens":1248}}831{"id":"stack-53995484","source":"stackoverflow","questionId":53995484,"title":"GraphQL query returns error \"Cannot return null for non-nullable field\"","tags":["javascript","node.js","graphql"],"text":"Title: GraphQL query returns error \"Cannot return null for non-nullable field\"\nTags: javascript, node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a basic GraphQL query setup as follows:\n\n**Query.js:**\n\n```\nconst Query = {\n dogs(parent, args, ctx, info) {\n return [{ name: 'Snickers' }, { name: 'Sunny' }];\n },\n};\n\nmodule.exports = Query;\n```\n\n**schema.graphql:**\n\n```\ntype Dog {\n name: String!\n}\ntype Query {\n dogs: [Dog]!\n}\n```\n\nI created a function `createServer()` for starting the server as follows:\n\n```\nconst { GraphQLServer } = require('graphql-yoga');\nconst Mutation = require('./resolvers/Mutation');\nconst Query = require('./resolvers/Query');\nconst db = require('./db');\n\nfunction createServer() {\n return new GraphQLServer({\n typeDefs: 'src/schema.graphql',\n resolvers: {\n Mutation,\n Query,\n },\n resolverValidationOptions: {\n requireResolversForResolveType: false,\n },\n context: req => ({ ...req, db }),\n });\n}\n\nmodule.exports = createServer;\n```\n\nI then tried querying `dogs` as follows:\n\n```\nquery {\n dogs {\n name\n }\n}\n```\n\nBut instead of getting the names from the array of dogs, I got the following error instead:\n\n```\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field Query.dogs.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"dogs\"\n ]\n }\n ]\n}\n```\n\nWhat seems to be causing this error?\n\n========================================\n\nTop Answer:\nI know this question has been answered, but for me the only thing that fixed this issue was to also pass the info argument.\n\n========================================\n\nCode:\n```text\nconst Query = {\n dogs(parent, args, ctx, info) {\n return [{ name: 'Snickers' }, { name: 'Sunny' }];\n },\n};\n\nmodule.exports = Query;\n```\n\n```text\ntype Dog {\n name: String!\n}\ntype Query {\n dogs: [Dog]!\n}\n```\n\n```text\nconst { GraphQLServer } = require('graphql-yoga');\nconst Mutation = require('./resolvers/Mutation');\nconst Query = require('./resolvers/Query');\nconst db = require('./db');\n\nfunction createServer() {\n return new GraphQLServer({\n typeDefs: 'src/schema.graphql',\n resolvers: {\n Mutation,\n Query,\n },\n resolverValidationOptions: {\n requireResolversForResolveType: false,\n },\n context: req => ({ ...req, db }),\n });\n}\n\nmodule.exports = createServer;\n```\n\n```text\nquery {\n dogs {\n name\n }\n}\n```\n\n```text\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field Query.dogs.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"dogs\"\n ]\n }\n ]\n}\n```\n\n```text\ncreateServer()\n```\n\n```text\ndogs\n```\n\n```text\n{}\n```\n\n```text\n{}\n```\n\n========================================\n\nComments:\n- Sounds like you're not importing Query.js correctly or your resolvers are not set up correctly. Please show the rest of the relevant code, including how you're constructing the resolvers object and how you're providing the type defs and resolvers to the GraphQLServer constructor.\n- @DanielRearden Ok hold on.\n- @DanielRearden My `prisma.graphql` has more than 300 lines of code. Should I copy a certain part of it or do you want me to copy the whole thing?\n- Not sure if any other type defs are relevant. I expect you have code that looks something like this: github.com/prisma/prisma-examples/blob/master/typescript/… and maybe a separate file like this github.com/prisma/prisma-examples/blob/master/typescript/…\n- @DanielRearden Question updated!!\n- Odd, I can run a `graphql-yoga` server with the above typeDefs and resolvers with no problems. Unless `./resolvers/Query` is not the right path for `Query`, I'm not sure what else could be wrong :/\n- If it were an incorrect path node wouldn't be able to resolve it and would throw an error: `\"Error: Cannot find module ...\"` and the server would be down. It looks like it does resolve, but to an empty object, so the `dogs` resolver is not there. Are you sure `Query.js` exports are correct?\n- @IonutAchim Is there any way I can check if the `Query.js` exports are correct? I added a `console.log(\"Query: \" + Query)` inside the `createServer()` function and it returned `Query: [Object Object]`.\n- @AndrewL, best way is to check the module exports. The console log can be misleading. If you were to not export anything, it would resolve to an empty object. So just inspect the file and see what your exports are.\n- The problem was with a typo in one of my files apparently. I marked your answer as correct regardless because your codepen helped me in finding the typo. Cheers.","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":196,"estimatedTokens":1167}}832{"id":"stack-43304656","source":"stackoverflow","questionId":43304656,"title":"React Apollo first object from subscription not being merge into previous data it actually gets removed","tags":["reactjs","graphql","apollo","graphql-subscriptions"],"text":"Title: React Apollo first object from subscription not being merge into previous data it actually gets removed\nTags: reactjs, graphql, apollo, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nI have a query which gets me a list of notes and a subscription which listens and inserts new notes by altering the query. However the problem is the first note doesn't get added.\n\nSo let me add more detail, initially the query response with an object which contains an attribute called notes which is an array of 0 length, if we try and add a note the attribute gets removed. The note is created so if I refresh my application the query will return the note then If I try and add a note again the note gets added to the array in the query object.\n\nHere is my notes container where I query for notes and create a new property to subscribe to more notes.\n\n```\nexport const NotesDataContainer = component => graphql(NotesQuery,{\n\nname: 'notes',\nprops: props => {\n\n console.log(props); // props.notes.notes is undefined on first note added when none exists.\n\n return {\n ...props,\n subscribeToNewNotes: () => {\n\n return props.notes.subscribeToMore({\n document: NotesAddedSubscription,\n updateQuery: (prevRes, { subscriptionData }) => {\n\n if (!subscriptionData.data.noteAdded) return prevRes;\n\n return update(prevRes, {\n notes: { $unshift: [subscriptionData.data.noteAdded] }\n });\n\n },\n })\n }\n }\n}\n\n})(component);\n```\n\nAny help would be great, thanks.\n\nEDIT:\n\n```\nexport const NotesQuery = gql`\n query NotesQuery {\n notes {\n _id\n title\n desc\n shared\n favourited\n }\n }\n`;\n\nexport const NotesAddedSubscription = gql`\n subscription onNoteAdded {\n noteAdded {\n _id\n title\n desc\n }\n }\n`;\n```\n\nAnother EDIT\n\n```\nclass NotesPageUI extends Component {\n\n constructor(props) {\n\n super(props);\n\n this.newNotesSubscription = null;\n\n }\n\n componentWillMount() {\n\n if (!this.newNotesSubscription) {\n\n this.newNotesSubscription = this.props.subscribeToNewNotes();\n\n }\n\n }\n\n render() {\n\n return (\n \n\n \n\n this.props.deleteNote(id) }\n favouriteNoteRequest={ this.props.favouriteNote }\n />\n\n \n )\n }\n }\n```\n\nAnother edit:\n\nhttps://github.com/jakelacey2012/react-apollo-subscription-problem\n\n========================================\n\nCode:\n```text\nexport const NotesDataContainer = component => graphql(NotesQuery,{\n\nname: 'notes',\nprops: props => {\n\n console.log(props); // props.notes.notes is undefined on first note added when none exists.\n\n return {\n ...props,\n subscribeToNewNotes: () => {\n\n return props.notes.subscribeToMore({\n document: NotesAddedSubscription,\n updateQuery: (prevRes, { subscriptionData }) => {\n\n if (!subscriptionData.data.noteAdded) return prevRes;\n\n return update(prevRes, {\n notes: { $unshift: [subscriptionData.data.noteAdded] }\n });\n\n },\n })\n }\n }\n}\n\n})(component);\n```\n\n```text\nexport const NotesQuery = gql`\n query NotesQuery {\n notes {\n _id\n title\n desc\n shared\n favourited\n }\n }\n`;\n\nexport const NotesAddedSubscription = gql`\n subscription onNoteAdded {\n noteAdded {\n _id\n title\n desc\n }\n }\n`;\n```\n\n```text\nclass NotesPageUI extends Component {\n\n constructor(props) {\n\n super(props);\n\n this.newNotesSubscription = null;\n\n }\n\n componentWillMount() {\n\n if (!this.newNotesSubscription) {\n\n this.newNotesSubscription = this.props.subscribeToNewNotes();\n\n }\n\n }\n\n render() {\n\n return (\n <div>\n\n <NoteCreation onEnterRequest={this.props.createNote} />\n\n <NotesList\n notes={ this.props.notes.notes }\n deleteNoteRequest={ id => this.props.deleteNote(id) }\n favouriteNoteRequest={ this.props.favouriteNote }\n />\n\n </div>\n )\n }\n }\n```\n\n```text\nquery NotesQuery {\n notes {\n _id\n title\n desc\n shared\n favourited\n }\n}\n```\n\n```text\nsubscription onNoteAdded {\n noteAdded {\n _id\n title\n desc\n }\n}\n```\n\n```text\nshared\n```\n\n```text\nfavourited\n```\n\n```text\nreact-apollo\n```\n\n```text\nreact-apollo\n```\n\n========================================\n\nComments:\n- can you show the code for the `NotesQuery` and the `NotesAddedSubscription`\n- @nburk I've updated my question","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":255,"estimatedTokens":1061}}833{"id":"stack-37342541","source":"stackoverflow","questionId":37342541,"title":"GraphQL Relay Mutation Config RANGE_ADD's parentName for connections","tags":["graphql","relayjs","graphql-js"],"text":"Title: GraphQL Relay Mutation Config RANGE_ADD's parentName for connections\nTags: graphql, relayjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have a page that uses GraphQL Relay connection which fetches `drafts`.\n\n```\nquery {\n connections {\n drafts(first: 10) {\n edges {\n node {\n ... on Draft {\n id\n }\n }\n }\n }\n }\n}\n```\n\nIn this page, I also create draft through `CreateDraftMutation`.\n\n```\nmutation {\n createDraft(input: {\n clientMutationId: \"1\"\n content: \"content\"\n }) {\n draft {\n id\n content\n }\n }\n}\n```\n\nAfter this mutation, I want Relay to add the created draft into its store. The best candidate for mutation config is RANGE_ADD, which is documented as following:\n\nhttps://facebook.github.io/relay/docs/guides-mutations.html\n\n RANGE_ADD \n Given a parent, a connection, and the name of the newly created edge in the response payload Relay will add the node to the store and attach it to the connection according to the range behavior specified.\n\n \n Arguments \n\n \n parentName: string\n The field name in the response that represents the parent of the connection\n\n \n parentID: string\n The DataID of the parent node that contains the connection\n\n \n connectionName: string\n The field name in the response that represents the connection\n\n \n edgeName: string\n The field name in the response that represents the newly created edge\n\n \n rangeBehaviors: {[call: string]: GraphQLMutatorConstants.RANGE_OPERATIONS}\n\n \n A map between printed, dot-separated GraphQL calls in alphabetical order, and the behavior we want Relay to exhibit when adding the new edge to connections under the influence of those calls. Behaviors can be one of 'append', 'ignore', 'prepend', 'refetch', or 'remove'.\n\nThe example from the documentation goes as the following:\n\n```\nclass IntroduceShipMutation extends Relay.Mutation {\n // This mutation declares a dependency on the faction\n // into which this ship is to be introduced.\n static fragments = {\n faction: () => Relay.QL`fragment on Faction { id }`,\n };\n // Introducing a ship will add it to a faction's fleet, so we\n // specify the faction's ships connection as part of the fat query.\n getFatQuery() {\n return Relay.QL`\n fragment on IntroduceShipPayload {\n faction { ships },\n newShipEdge,\n }\n `;\n }\n getConfigs() {\n return [{\n type: 'RANGE_ADD',\n parentName: 'faction',\n parentID: this.props.faction.id,\n connectionName: 'ships',\n edgeName: 'newShipEdge',\n rangeBehaviors: {\n // When the ships connection is not under the influence\n // of any call, append the ship to the end of the connection\n '': 'append',\n // Prepend the ship, wherever the connection is sorted by age\n 'orderby(newest)': 'prepend',\n },\n }];\n }\n /* ... */\n}\n```\n\nIf the parent is as obvious as faction, this is a piece of cake, but I've been having hard time identifying parentName and parentID if it came directly from query connections.\n\nHow do I do this?\n\nEdit:\n\nThis is how query was exported.\n\n```\nexport default new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n viewer: {\n type: viewerType,\n resolve: () => ({}),\n },\n connections: {\n type: new GraphQLObjectType({\n name: 'Connections',\n```\n\nwhich in return is used in the relay container\n\n```\nexport default Relay.createContainer(MakeRequestPage, {\n fragments: {\n connections: () => Relay.QL`\n fragment on Connections {\n```\n\n========================================\n\nCode:\n```json\nquery {\n connections {\n drafts(first: 10) {\n edges {\n node {\n ... on Draft {\n id\n }\n }\n }\n }\n }\n}\n```\n\n```json\nmutation {\n createDraft(input: {\n clientMutationId: \"1\"\n content: \"content\"\n }) {\n draft {\n id\n content\n }\n }\n}\n```\n\n```js\nclass IntroduceShipMutation extends Relay.Mutation {\n // This mutation declares a dependency on the faction\n // into which this ship is to be introduced.\n static fragments = {\n faction: () => Relay.QL`fragment on Faction { id }`,\n };\n // Introducing a ship will add it to a faction's fleet, so we\n // specify the faction's ships connection as part of the fat query.\n getFatQuery() {\n return Relay.QL`\n fragment on IntroduceShipPayload {\n faction { ships },\n newShipEdge,\n }\n `;\n }\n getConfigs() {\n return [{\n type: 'RANGE_ADD',\n parentName: 'faction',\n parentID: this.props.faction.id,\n connectionName: 'ships',\n edgeName: 'newShipEdge',\n rangeBehaviors: {\n // When the ships connection is not under the influence\n // of any call, append the ship to the end of the connection\n '': 'append',\n // Prepend the ship, wherever the connection is sorted by age\n 'orderby(newest)': 'prepend',\n },\n }];\n }\n /* ... */\n}\n```\n\n```js\nexport default new GraphQLObjectType({\n name: 'Query',\n fields: () => ({\n node: nodeField,\n viewer: {\n type: viewerType,\n resolve: () => ({}),\n },\n connections: {\n type: new GraphQLObjectType({\n name: 'Connections',\n```\n\n```text\nexport default Relay.createContainer(MakeRequestPage, {\n fragments: {\n connections: () => Relay.QL`\n fragment on Connections {\n```\n\n```text\ndrafts\n```\n\n```text\nCreateDraftMutation\n```\n\n```text\nquery {\n connections {\n id\n drafts(first: 10) {\n edges {\n node {\n ... on Draft {\n id\n }\n }\n }\n }\n }\n}\n```\n\n```text\nfaction\n```\n\n```text\nships\n```\n\n```text\nconnections\n```\n\n```text\ndrafts\n```\n\n```text\nGraphQLObject\n```\n\n```text\nconnections\n```\n\n```text\nparentName\n```\n\n```text\nconnctions\n```\n\n```text\nparentID\n```\n\n```text\nconnections\n```\n\n```text\nconnections\n```\n\n```text\ndrafts\n```\n\n```text\nconnections\n```\n\n========================================\n\nComments:\n- Is `connections` in your query a GraphQL object or connection?\n- @AhmadFerdousBinAlam I have added the snippet below. The 'Connections' GraphQLObjectType comes with fields that are connection fields.\n- `drafts` is definitely application domain term for the sake of example. I just realized `connections`, which I treated as commonly used root query like `node` or `viewer`, is also unique to our application. (My teammate came up with it). So I guess connections id should be like a global id.\n- Yes, the ID is a global ID.\n- What is parentName and parentId if you would have drafts directly under query?","metadata":{"transformedAt":"2026-08-18T18:32:36.086Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":317,"estimatedTokens":1630}}834{"id":"stack-54273965","source":"stackoverflow","questionId":54273965,"title":"GraphQL vs Elasticsearch what should i use for fast searching performance that return with many different schema?","tags":["elasticsearch","facebook-graph-api","artificial-intelligence","graphql","search-engine"],"text":"Title: GraphQL vs Elasticsearch what should i use for fast searching performance that return with many different schema?\nTags: elasticsearch, facebook-graph-api, artificial-intelligence, graphql, search-engine\nSource: Stack Overflow\n\nQuestion:\nI am making a real-time search that will indicate the correct pattern from the search string. Then it will search with this pattern and return with the correct database schema dynamically.\nExample Like: Google Assistant\n\n========================================\n\nTop Answer:\nIt depends on the Use case.\n\nRecently I realized I could have used GraphQL for Searching instead of Elasticsearch (For Just This Use case), with respect to cost of running two services one that GraphQL was reading from and other one is Elasticsearch.\n\nAll in all it good you can use these two technologies cause you may need them in different use cases.\n\n========================================\n\nComments:\n- This is too general question. I suggest you'll specify what are your requirements - is it a free text search? Are the documents have common schema? Are they large/small docs? If you'll put an example of docs and query it would be easier to help. I have a feeling that Elasticsearch might be what you are looking for, but need more info in order to tell.\n- Like: Google Assistant but it will use for one specific purpose.\n- @KenChan while it's technically true that GraphQL vs ElasticSearch comparison is apples/oranges, the question is still pretty valid. I came here looking for the same. I have Elastic as the backend. For frontend querying, should I use the tools that come with Elastic or should I insert a layer of GraphQL on top of Elastic? That's a fair ask. Your link to benefits is helpful.\n- I think calling GraphQL \"a NoSQL\" sounds like apples and oranges as well...","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":24,"estimatedTokens":452}}835{"id":"stack-59988906","source":"stackoverflow","questionId":59988906,"title":"How do I write a Apollo Server plugin to log the request and its duration","tags":["typescript","graphql","apollo","apollo-server"],"text":"Title: How do I write a Apollo Server plugin to log the request and its duration\nTags: typescript, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am surprised I could not find a library or example to do the following:\n\nI want a simple server log of each request to the server that will state what query or mutation was requested, and the elapsed time it took to complete the request\n\nI know there is the plugin and extension frameworks. But I am not sure what the best practice is to keep state between the two callbacks: `requestDidStart` and `willSendResponse`\n\nsomething that would spit out:\n\n```\npath=\"createAccountMutation\" service=20ms\n```\n\nextra credit would be to show the size of the payload\n\n```\npath=\"createAccountMutation\" service=20ms bytes=355\n```\n\nWould love to see the solution in typescript\n\nNote: I found apollo-log -- but it does not do request duration\n\nThanks!\n\n========================================\n\nTop Answer:\nHere it is in Typescript\n\n```\nimport {\n ApolloServerPlugin,\n} from 'apollo-server-plugin-base';\n\nimport { GraphQLRequestContext } from 'apollo-server-types';\nimport { GraphQLRequestListener } from 'apollo-server-plugin-base/src/index'\n\n// https://stackoverflow.com/questions/59988906/how-do-i-write-a-apollo-server-plugin-to-log-the-request-and-its-duration\nexport const LogPlugin: ApolloServerPlugin = {\n requestDidStart(_: GraphQLRequestContext): GraphQLRequestListener {\n const start = Date.now()\n let op: string\n\n return {\n didResolveOperation (context) {\n op = context.operationName\n },\n willSendResponse (context) {\n const stop = Date.now()\n const elapsed = stop - start\n const size = JSON.stringify(context.response).length * 2\n console.log(\n `operataion=${op} duration=${elapsed}ms bytes=${size}`\n )\n }\n }\n },\n}\n```\n\nall credit goes to Daniel Rearden\n\n========================================\n\nCode:\n```text\npath=\"createAccountMutation\" service=20ms\n```\n\n```text\npath=\"createAccountMutation\" service=20ms bytes=355\n```\n\n```text\nrequestDidStart\n```\n\n```text\nwillSendResponse\n```\n\n```text\nconst LogPlugin = {\n requestDidStart(requestContext) {\n const start = Date.now()\n let op\n\n return {\n didResolveOperation (context) {\n op = context.operationName\n },\n willSendResponse (context) {\n const stop = Date.now()\n const elapsed = stop - start\n const size = JSON.stringify(context.response).length * 2\n console.log(\n `Operation ${op} completed in ${elapsed} ms and returned ${size} bytes`\n )\n }\n }\n },\n}\n```\n\n```text\nrequestDidStart\n```\n\n```text\nimport {\n ApolloServerPlugin,\n} from 'apollo-server-plugin-base';\n\nimport { GraphQLRequestContext } from 'apollo-server-types';\nimport { GraphQLRequestListener } from 'apollo-server-plugin-base/src/index'\n\n\n\n// https://stackoverflow.com/questions/59988906/how-do-i-write-a-apollo-server-plugin-to-log-the-request-and-its-duration\nexport const LogPlugin: ApolloServerPlugin = {\n requestDidStart<TContext>(_: GraphQLRequestContext<TContext>): GraphQLRequestListener<TContext> {\n const start = Date.now()\n let op: string\n\n return {\n didResolveOperation (context) {\n op = context.operationName\n },\n willSendResponse (context) {\n const stop = Date.now()\n const elapsed = stop - start\n const size = JSON.stringify(context.response).length * 2\n console.log(\n `operataion=${op} duration=${elapsed}ms bytes=${size}`\n )\n }\n }\n },\n}\n```\n\n```js\nimport { MyModels } from './models'\nimport {\n ApolloServerPlugin,\n} from 'apollo-server-plugin-base';\n\nimport { GraphQLRequestContext } from 'apollo-server-types';\nimport { GraphQLRequestListener } from 'apollo-server-plugin-base/src/index'\nimport { performance } from 'perf_hooks'\n\n\nexport interface MyApolloContext {\n models: MyModels \n}\n\nexport const myDebugLoggerPlugin: ApolloServerPlugin = {\n async requestDidStart<MyApolloContext >(\n requestContext: GraphQLRequestContext<MyApolloContext >,\n ): Promise<GraphQLRequestListener<MyApolloContext >> {\n const start = performance.now()\n let operation: string | null\n\n return {\n // Apollo server lifetime methods that you can use. https://www.apollographql.com/docs/apollo-server/integrations/plugins/#responding-to-request-lifecycle-events\n async didResolveOperation(context) {\n operation = context.operationName\n },\n async willSendResponse(context) {\n const elapsed = Math.round(performance.now() - start)\n const size = JSON.stringify(context.response).length * 2\n console.log(\n `ApolloServer log: operataion=${operation} duration=${elapsed}ms bytes=${size}`,\n )\n },\n async didEncounterErrors(context) {\n console.log('Did encounter error: ', context)\n },\n }\n },\n async serverWillStart(_context) {},\n}\n```\n\n```text\nApolloServerPlugin\n```\n\n```text\nnull\n```\n\n```text\nperformance.now()\n```\n\n```text\nDate.now()\n```\n\n```text\nMyApolloContext\n```\n\n```text\napollo-server-express\n```\n\n========================================\n\nComments:\n- dude -- this looks amazing. (bonus fist bump if you make it typescript ;-) ) [but really i bet I could figure that out]! Thanks . (i'll give it a check once I prove that it works)\n- Is it possible to only catch any \"mutations\" at the willSendResponse?\n- don't forget to make \"async requestDidStart\" , \"async didResolveOperation\" and \"async willSendResponse\" for apollo v3\n- Pretty good answer! Only one point to add: you can use `requestContext.operationName` instead of creating a temporary variable and get the name from `didResolveOperation`.","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":220,"estimatedTokens":1411}}836{"id":"stack-70577447","source":"stackoverflow","questionId":70577447,"title":"AWS Graphql lambda query","tags":["amazon-web-services","aws-lambda","graphql","apollo-server"],"text":"Title: AWS Graphql lambda query\nTags: amazon-web-services, aws-lambda, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\n**I am not using AWS AppSync for this app**. I have created Graphql schema, I have made my own resolvers. For each create, query, I have made each Lambda functions. I used DynamoDB Single table concept and it's Global secondary indexes.\n\nIt was ok for me, to create an Book item. In DynamoDB, the table looks like this: https://i.sstatic.net/K9WSL.png.\n\nI am having issue with the return Graphql queries. After getting the `Items` from DynamoDB table, I have to use Map function then return the `Items` based on Graphql `type`. I feel like this is not efficient way to do that. Idk the best way query data. Also I am getting null both author and authors query.\n\nThis is my gitlab-branch.\n\n**This is my Graphql Schema**\n\n\r\n\r\n\n```\nimport { gql } from 'apollo-server-lambda';\n\nconst typeDefs = gql`\n enum Genre {\n adventure\n drama\n scifi\n }\n\n enum Authors {\n AUTHOR\n }\n\n # Root Query - all the queries supported by the schema\n\n type Query {\n \"\"\"\n All Authors query\n \"\"\"\n authors(author: Authors): [Author]\n books(book: String): [Book]\n }\n\n # Root Mutation - all the mutations supported by the schema\n type Mutation {\n createBook(input: CreateBook!): Book\n }\n\n \"\"\"\n One Author can have many books\n \"\"\"\n type Author {\n id: ID!\n authorName: String\n book: [Book]!\n }\n\n \"\"\"\n Book Schema\n \"\"\"\n type Book {\n id: ID!\n name: String\n price: String\n publishingYear: String\n publisher: String\n author: [Author]\n description: String\n page: Int\n genre: [Genre]\n }\n\n input CreateBook {\n name: String\n price: String\n publishingYear: String\n publisher: String\n author: [CreateAuthor]\n description: String\n page: Int\n genre: [Genre]\n }\n\n input CreateAuthor {\n authorName: String!\n }\n`;\nexport default typeDefs;\n```\n\n\r\n\r\n\r\n\n**This is I created the Book Item**\n\n\r\n\r\n\n```\nimport AWS from 'aws-sdk';\nimport { v4 } from 'uuid';\nimport { CreateBook } from '../../generated/schema';\n\nasync function createBook(_: unknown, { input }: { input: CreateBook }) {\n const dynamoDb = new AWS.DynamoDB.DocumentClient();\n const id = v4();\n\n const authorsName = \n input.author &&\n input.author.map(function (item) {\n return item['authorName'];\n });\n\n const params = {\n TableName: process.env.ITEM_TABLE ? process.env.ITEM_TABLE : '',\n Item: {\n PK: `AUTHOR`,\n SK: `AUTHORS#${id}`,\n GSI1PK: `BOOKS`,\n GSI1SK: `BOOK#${input.name}`,\n name: input.name,\n author: authorsName,\n price: input.price,\n publishingYear: input.publishingYear,\n publisher: input.publisher,\n page: input.page,\n description: input.description,\n genre: input.genre,\n },\n };\n\n await dynamoDb.put(params).promise();\n\n return {\n ...input,\n id,\n };\n}\n\nexport default createBook;\n```\n\n\r\n\r\n\r\n\n**This is how query the All Book**\n\n\r\n\r\n\n```\nimport AWS from 'aws-sdk';\n\nasync function books(_: unknown, input: { book: string }) {\n const dynamoDb = new AWS.DynamoDB.DocumentClient();\n\n const params = {\n TableName: process.env.ITEM_TABLE ? process.env.ITEM_TABLE : '',\n IndexName: 'GSI1',\n KeyConditionExpression: 'GSI1PK = :hkey',\n ExpressionAttributeValues: {\n ':hkey': `${input.book}`,\n },\n };\n\n const { Items } = await dynamoDb.query(params).promise();\n\n const allBooks = // NEED TO MAP THE FUNcTION THEN RETURN THE DATA BASED ON GRAPHQL //QUERIES.\n Items &&\n Items.map((i) => {\n const genre = i.genre.filter((i) => i);\n return {\n name: i.name,\n author: i.author,\n genre,\n };\n });\n\n return allBooks;\n}\n\nexport default books;\n```\n\n\r\n\r\n\r\n\n**This my Author query and Image of the console result**\n\nhttps://i.sstatic.net/l1lgS.png\n\n\r\n\r\n\n```\nimport AWS from 'aws-sdk';\nimport { Author, Authors } from '../../generated/schema';\n\nasync function authors(\n _: unknown,\n input: { author: Authors }\n): Promise {\n const dynamoDb = new AWS.DynamoDB.DocumentClient();\n\n const params = {\n TableName: process.env.ITEM_TABLE ? process.env.ITEM_TABLE : '',\n KeyConditionExpression: 'PK = :hkey',\n ExpressionAttributeValues: {\n ':hkey': `${input.author}`,\n },\n };\n\n const { Items } = await dynamoDb.query(params).promise();\n\n console.log({ Items }); // I can see the data but don't know how to returns the data like this below type without using map function\n\n // type Author {\n // id: ID!\n // authorName: String\n // book: [Book]!\n // }\n\n return Items; // return null in Graphql play ground. \n}\n\nexport default authors;\n```\n\n\r\n\r\n\r\n\nEdit: current resolver map\n\n```\n// resolver map - src/resolvers/index.ts\nconst resolvers = {\n Query: {\n books,\n authors,\n author,\n book,\n },\n Mutation: {\n createBook,\n },\n};\n```\n\n========================================\n\nCode:\n```js\nimport { gql } from 'apollo-server-lambda';\n\nconst typeDefs = gql`\n enum Genre {\n adventure\n drama\n scifi\n }\n\n enum Authors {\n AUTHOR\n }\n\n # Root Query - all the queries supported by the schema\n\n type Query {\n \"\"\"\n All Authors query\n \"\"\"\n authors(author: Authors): [Author]\n books(book: String): [Book]\n }\n\n # Root Mutation - all the mutations supported by the schema\n type Mutation {\n createBook(input: CreateBook!): Book\n }\n\n \"\"\"\n One Author can have many books\n \"\"\"\n type Author {\n id: ID!\n authorName: String\n book: [Book]!\n }\n\n \"\"\"\n Book Schema\n \"\"\"\n type Book {\n id: ID!\n name: String\n price: String\n publishingYear: String\n publisher: String\n author: [Author]\n description: String\n page: Int\n genre: [Genre]\n }\n\n input CreateBook {\n name: String\n price: String\n publishingYear: String\n publisher: String\n author: [CreateAuthor]\n description: String\n page: Int\n genre: [Genre]\n }\n\n input CreateAuthor {\n authorName: String!\n }\n`;\nexport default typeDefs;\n```\n\n```js\nimport AWS from 'aws-sdk';\nimport { v4 } from 'uuid';\nimport { CreateBook } from '../../generated/schema';\n\nasync function createBook(_: unknown, { input }: { input: CreateBook }) {\n const dynamoDb = new AWS.DynamoDB.DocumentClient();\n const id = v4();\n\n const authorsName = \n input.author &&\n input.author.map(function (item) {\n return item['authorName'];\n });\n\n const params = {\n TableName: process.env.ITEM_TABLE ? process.env.ITEM_TABLE : '',\n Item: {\n PK: `AUTHOR`,\n SK: `AUTHORS#${id}`,\n GSI1PK: `BOOKS`,\n GSI1SK: `BOOK#${input.name}`,\n name: input.name,\n author: authorsName,\n price: input.price,\n publishingYear: input.publishingYear,\n publisher: input.publisher,\n page: input.page,\n description: input.description,\n genre: input.genre,\n },\n };\n\n await dynamoDb.put(params).promise();\n\n return {\n ...input,\n id,\n };\n}\n\nexport default createBook;\n```\n\n```js\nimport AWS from 'aws-sdk';\n\nasync function books(_: unknown, input: { book: string }) {\n const dynamoDb = new AWS.DynamoDB.DocumentClient();\n\n const params = {\n TableName: process.env.ITEM_TABLE ? process.env.ITEM_TABLE : '',\n IndexName: 'GSI1',\n KeyConditionExpression: 'GSI1PK = :hkey',\n ExpressionAttributeValues: {\n ':hkey': `${input.book}`,\n },\n };\n\n const { Items } = await dynamoDb.query(params).promise();\n\n const allBooks = // NEED TO MAP THE FUNcTION THEN RETURN THE DATA BASED ON GRAPHQL //QUERIES.\n Items &&\n Items.map((i) => {\n const genre = i.genre.filter((i) => i);\n return {\n name: i.name,\n author: i.author,\n genre,\n };\n });\n\n return allBooks;\n}\n\nexport default books;\n```\n\n```js\nimport AWS from 'aws-sdk';\nimport { Author, Authors } from '../../generated/schema';\n\nasync function authors(\n _: unknown,\n input: { author: Authors }\n): Promise<Author> {\n const dynamoDb = new AWS.DynamoDB.DocumentClient();\n\n const params = {\n TableName: process.env.ITEM_TABLE ? process.env.ITEM_TABLE : '',\n KeyConditionExpression: 'PK = :hkey',\n ExpressionAttributeValues: {\n ':hkey': `${input.author}`,\n },\n };\n\n const { Items } = await dynamoDb.query(params).promise();\n\n console.log({ Items }); // I can see the data but don't know how to returns the data like this below type without using map function\n\n // type Author {\n // id: ID!\n // authorName: String\n // book: [Book]!\n // }\n\n return Items; // return null in Graphql play ground. \n}\n\nexport default authors;\n```\n\n```js\n// resolver map - src/resolvers/index.ts\nconst resolvers = {\n Query: {\n books,\n authors,\n author,\n book,\n },\n Mutation: {\n createBook,\n },\n};\n```\n\n```text\nItems\n```\n\n```text\nItems\n```\n\n```text\ntype\n```\n\n```text\nquery author(id: '1') { # Query { author } resolver\n authorName\n books { # Author { books(parent) } resolver\n name\n authors { # Book { author(parent) } resolver\n id\n }\n }\n}\n```\n\n```js\n// resolver map - passed to the Apollo Server constructor\nconst resolvers = {\n Query: {\n books,\n authors,\n author,\n book,\n },\n\n Author: {\n books(parent) { getAuthorBooks(parent); }, // parent is the author - resolver should return a list of books\n },\n\n Book: {\n authors(parent) { getBookAuthors(parent); }, // parent is the book - resolver should return a list of authors\n },\n};\n```\n\n```text\nAuthor {books(parent)}\n```\n\n```text\n[Books]\n```\n\n```text\nauthor\n```\n\n```text\nbooks(parent)\n```\n\n```text\nAuthor\n```\n\n```text\nparent\n```\n\n```text\nauthor\n```\n\n```text\n{Items: [author-record]}\n```\n\n```text\nauthor(PK: String, SK: String): [Author]\n```\n\n```text\nauthor(id: ID): Author\n```\n\n```text\nID\n```\n\n========================================\n\nComments:\n- Could you help clarify what your actual question/problem is? Is it about lambda resolver writing, like this SO answer (question is AppSync-related, Apollo Server follows similar logic)? Perhaps give a client query example and add what you mean by its \"efficient\" handling.\n- Question is how can I get, authorsβ name and his/her/their books. I am getting null atm.\n- Please add your resolver map to the question.\n- Sorry for late reply and sticking with me ππΎ. This is my branch: gitlab.com/alak/aws-book-schema-graphql\n- Both Author and Authors' query I am getting null. I newbie in Graphql. If I made any mistake please feel free to give me feedback\n- Thanks a lot @fedonev. Really neat and nice explanation.\n- Just one thing, how will you create βgetAuthorBooksβ function?\n- Glad to help. Your `src/resolvers/query` folder's `author.ts` resolver is a start. Resolvers often make use of switch statements to handle different sources of the identifying data in a single function - e.g. is this a request for author from the author query or the author as a child of book?","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":551,"estimatedTokens":2638}}837{"id":"stack-52187999","source":"stackoverflow","questionId":52187999,"title":"GraphQLError: Syntax Error: Unexpected Name \"undefined\"","tags":["javascript","reactjs","react-router","graphql"],"text":"Title: GraphQLError: Syntax Error: Unexpected Name \"undefined\"\nTags: javascript, reactjs, react-router, graphql\nSource: Stack Overflow\n\nQuestion:\nI have stored all of my queries on their on page: \n\n```\nimport gql from \"graphql-tag\";\n\nconst getStories = gql`\n query getStories {\n stories {\n id\n title\n author\n tagline\n summary\n rating\n you\n need\n go\n search\n find\n take\n returned\n changed\n }\n }\n`\n\nconst createStory = gql`\n mutation($title: String!, $author: String!) {\n create (title: $title, author: $author) {\n id\n title\n author\n tagline\n summary\n rating\n you\n need\n go\n search\n find\n take\n returned\n changed\n }\n }\n `\n const updateStory = gql`\n mutation($id: ID!) {\n update(id: $id) {\n id\n title\n author\n tagline\n summary\n rating\n you\n need\n go\n search\n find\n take\n returned\n changed\n }\n }\n `\n\n export default { getStories, updateStory, createStory };\n```\n\nOn my form page I have imported the createStory mutation and I am trying to bind it with the Component, like so:\n\n```\nimport React, { Component } from \"react\"\nimport { withRouter } from 'react-router-dom'\nimport graphql from 'graphql-tag'\nimport createStory from '../../Queries/Queries'\n\nclass Form extends Component {\n constructor(props) {\n super(props);\n this.state = {\n story: {}\n };\n }\n\n onChange = e => {\n const storyState = this.state.story;\n storyState[e.target.name] = e.target.value;\n console.log(this.props.createStory)\n console.log(storyState)\n this.setState(storyState);\n };\n\n onSubmit = e => {\n e.preventDefault();\n console.log(this.state.story)\n this.props.createStory({\n variables: {\n story: this.state.story\n }\n })\nthis.props.history.replace('/')\n};\n\nrender() {\n return (\n \n \n\n### Write A Story\n\n \n // Cut out my form details for space\n \n \n \n );\n } \n }\n\n const createStoryMutation = graphql(createStory, {\n name: 'createStory'})(Form)\n\nexport default withRouter(createStoryMutation)\n```\n\nHowever, I have continually been running receiving the error. \n\n`GraphQLError: Syntax Error: Unexpected Name \"undefined\"`\n\nAt first I suspected it was a packaging issue, so one of the ways I've been trying to solve it is by alternating between `graphql-tag` and `react-apollo`. I've but when messing with those I am constantly getting `Object(...) is not a function`, which I know has to do with whether or not the imported functions are wrapped in {brackets} or not.\n\nI have tried just about everything that I am aware of to get this code to work, yet to no avail. I know that my post mutation is to long as well(i.e. it should be wrapped in an input object), but I was just trying to make things functional before I clean up.\n\nThat being said, thank you in advance.\n\n========================================\n\nTop Answer:\nI got a similar error when following along with a youtube project on the merng stack (https://www.youtube.com/watch?v=C_2Eo72cL2k). The issue for me was that I wasn't prefacing the query with \"query\" nor wrapping it in curly braces. Doing either caused the error to go away, but the former caused a 400 bad request error in the console.\n\n========================================\n\nCode:\n```text\nimport gql from \"graphql-tag\";\n\nconst getStories = gql`\n query getStories {\n stories {\n id\n title\n author\n tagline\n summary\n rating\n you\n need\n go\n search\n find\n take\n returned\n changed\n }\n }\n`\n\nconst createStory = gql`\n mutation($title: String!, $author: String!) {\n create (title: $title, author: $author) {\n id\n title\n author\n tagline\n summary\n rating\n you\n need\n go\n search\n find\n take\n returned\n changed\n }\n }\n `\n const updateStory = gql`\n mutation($id: ID!) {\n update(id: $id) {\n id\n title\n author\n tagline\n summary\n rating\n you\n need\n go\n search\n find\n take\n returned\n changed\n }\n }\n `\n\n export default { getStories, updateStory, createStory };\n```\n\n```text\nimport React, { Component } from \"react\"\nimport { withRouter } from 'react-router-dom'\nimport graphql from 'graphql-tag'\nimport createStory from '../../Queries/Queries'\n\nclass Form extends Component {\n constructor(props) {\n super(props);\n this.state = {\n story: {}\n };\n }\n\n onChange = e => {\n const storyState = this.state.story;\n storyState[e.target.name] = e.target.value;\n console.log(this.props.createStory)\n console.log(storyState)\n this.setState(storyState);\n };\n\n onSubmit = e => {\n e.preventDefault();\n console.log(this.state.story)\n this.props.createStory({\n variables: {\n story: this.state.story\n }\n })\nthis.props.history.replace('/')\n};\n\nrender() {\n return (\n <div className=\"card\">\n <h1>Write A Story</h1>\n <form onSubmit={this.onSubmit}>\n // Cut out my form details for space\n <input type=\"submit\" value=\"Write Story\" />\n </form>\n </div>\n );\n } \n }\n\n const createStoryMutation = graphql(createStory, {\n name: 'createStory'})(Form)\n\nexport default withRouter(createStoryMutation)\n```\n\n```text\nGraphQLError: Syntax Error: Unexpected Name \"undefined\"\n```\n\n```text\ngraphql-tag\n```\n\n```text\nreact-apollo\n```\n\n```text\nObject(...) is not a function\n```\n\n```text\nimport graphql from 'graphql-tag'\n```\n\n```text\nimport { graphql } from 'react-apollo';\n```\n\n```text\ngraphql\n```\n\n```text\nexport\n```\n\n```text\nimport createStory from '../../Queries/Queries'\n```\n\n```text\nimport {createStory} from '../../Queries/Queries'\n```\n\n```text\ncreateStory\n```\n\n```text\n{ getStories, updateStory, createStory }\n```\n\n========================================\n\nComments:\n- Wow! Thanks it work! I tried to upvote you but I don't have enough contributions yet\n- No problem. Glad it worked. You should be able to accept the answer to close out the question.\n- Thanks so much - this is the mistake I was making as well. Your query should look like so: `const QUERY = gql'query { users { firstName } }'`","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":324,"estimatedTokens":1493}}838{"id":"stack-56314654","source":"stackoverflow","questionId":56314654,"title":"Nested query to unknown level GraphQL","tags":["graphql"],"text":"Title: Nested query to unknown level GraphQL\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI have a tree structure. Let's say Folder for example.\n\nHow do I query nested queries to N level using GraphQL.\n\nLet's take an example as I have following properties in class.\n\n```\npublic class DocumentField\n {\n public int Id { get; set; }\n\n public string Name { get; set; }\n\n public List Children { get; set; }\n }\n```\n\nServer side is designed in a way that if children are there then it will include as children. But graphql layer is restricting it because my query which is following.\n\nFollowing query will not bring result of children.\n\n```\nquery ($folderId: Int!) {\n folder(folderId: $folderId) {\n id,\n name\n }\n }\n```\n\nFollowing query gives error as: nested query Field children of type DocumentFieldICollection must have a sub selection\n\n```\nquery ($folderId: Int!) {\n folder(folderId: $folderId) {\n id,\n name,\n children\n }\n }\n```\n\n========================================\n\nCode:\n```text\npublic class DocumentField\n {\n public int Id { get; set; }\n\n public string Name { get; set; }\n\n public List<DocumentField> Children { get; set; }\n }\n```\n\n```text\nquery ($folderId: Int!) {\n folder(folderId: $folderId) {\n id,\n name\n }\n }\n```\n\n```text\nquery ($folderId: Int!) {\n folder(folderId: $folderId) {\n id,\n name,\n children\n }\n }\n```\n\n```text\nquery ($folderId: Int!) {\n folder(folderId: $folderId) {\n id\n name\n children {\n id \n name\n children{\n id\n name\n children{\n id\n name\n }\n }\n }\n }\n }\n```\n\n```text\nfragment\n```\n\n========================================\n\nComments:\n- Oh. now this first line is really frustrating. I have no idea how many nested levels are there from client side.","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":109,"estimatedTokens":525}}839{"id":"stack-49187470","source":"stackoverflow","questionId":49187470,"title":"How to enable gzip at GraphQL server?","tags":["encoding","graphql"],"text":"Title: How to enable gzip at GraphQL server?\nTags: encoding, graphql\nSource: Stack Overflow\n\nQuestion:\nAccording to the this article, it's encouraged that any production GraphQL services enable GZIP and encourage their clients to send the header: **Accept-Encoding: gzip**\n\nI've tested this in Postman, with \"Accept-Encoding\" enabled or disable, I didn't see any difference in the responded **\"content-length\"**.\n\nSo my question, how to enable GZIP encoding at graphQL server?\n\nhttps://i.sstatic.net/yzN3I.png\n\n========================================\n\nTop Answer:\nEnabling GZIP encoding for your GraphQL server is not a feature provided by GraphQL itself. GraphQL is primarily responsible for processing and handling your queries, but it doesn't directly manage the compression or Content-Encoding of the HTTP responses.\n\nTo enable GZIP compression for your GraphQL server, you would typically configure the underlying HTTP server that hosts your GraphQL service. If you're using a Node js-based server, you can use libraries like zlib to compress your server's HTTP responses. Alternatively, you can use existing tools and libraries like the \"compression\" middleware for Express, which makes it easier to enable GZIP compression for your GraphQL server.\n\n========================================\n\nCode:\n```text\nHTTP\n```\n\n```text\nContent-Type=Gzip\n```\n\n```text\nGraphQL\n```\n\n```text\nJSON\n```\n\n```text\ngraph\n```\n\n```text\ngraphql\n```\n\n```text\nNodeJS\n```\n\n```text\nzlib\n```\n\n```text\nexpress\n```\n\n========================================\n\nComments:\n- I think this response is very confusingly worded for what the OP is asking. I understand you're delineating between the HTTP server which is actually receiving requests and serving responses, and the GraphQL framework which delegates requests in the code. But, it is clear from the OP has an HTTP server running locally, which uses a GraphQL framework. Just because the wording in the OP was slightly off doesn't mean you should lead with \"You can't\". Would be much more helpful to the OP and future readers to lead with compression libs, then explain the diff between GQL and HTTP\n- Hmm. Since Apollo also supplies a client, I don't see why they wouldn't allow for compression at least when using their client. It would make a killer feature I think!","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":64,"estimatedTokens":575}}840{"id":"stack-61578856","source":"stackoverflow","questionId":61578856,"title":"(node:18560) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'typeFn' of undefined","tags":["mongodb","typescript","mongoose","graphql","nestjs"],"text":"Title: (node:18560) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'typeFn' of undefined\nTags: mongodb, typescript, mongoose, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am getting this error when I am trying to resolve a field(blocks) with the `@ResolveField()` decorator.\n\n**page.resolver.ts**\n\n```\nimport {\n Resolver,\n Query,\n Mutation,\n Args,\n ResolveField,\n Parent,\n} from '@nestjs/graphql';\nimport { PageService } from './page.service';\nimport { PageType } from './type/page.type';\nimport { CreatePageInput } from './input/create-page.input';\nimport { BlockService } from '../block/block.service';\nimport { Page } from './page.interface';\n\n@Resolver('Page')\nexport class PageResolver {\n constructor(\n private readonly pageService: PageService,\n private readonly blockService: BlockService,\n ) {}\n\n @Query(() => [PageType])\n pages() {\n return this.pageService.getAllPages();\n }\n\n @Query(() => [PageType])\n async page(@Args('id') id: string) {\n return this.pageService.getPage(id);\n }\n\n @Mutation(() => PageType)\n createPage(@Args('createPageInput') createPageInput: CreatePageInput) {\n return this.pageService.createPage(createPageInput);\n }\n\n @ResolveField()\n blocks(@Parent() page: Page) {\n return this.blockService.getManyBlocks(page.blockIds);\n }\n}\n```\n\n**page.interface.ts**\n\n```\nimport { Document } from 'mongoose';\n\nexport interface Page extends Document {\n readonly id: string;\n readonly name: string;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly createdBy: string;\n readonly updatedBy: string;\n readonly blockIds: string[];\n}\n```\n\n========================================\n\nCode:\n```text\nimport {\n Resolver,\n Query,\n Mutation,\n Args,\n ResolveField,\n Parent,\n} from '@nestjs/graphql';\nimport { PageService } from './page.service';\nimport { PageType } from './type/page.type';\nimport { CreatePageInput } from './input/create-page.input';\nimport { BlockService } from '../block/block.service';\nimport { Page } from './page.interface';\n\n@Resolver('Page')\nexport class PageResolver {\n constructor(\n private readonly pageService: PageService,\n private readonly blockService: BlockService,\n ) {}\n\n @Query(() => [PageType])\n pages() {\n return this.pageService.getAllPages();\n }\n\n @Query(() => [PageType])\n async page(@Args('id') id: string) {\n return this.pageService.getPage(id);\n }\n\n @Mutation(() => PageType)\n createPage(@Args('createPageInput') createPageInput: CreatePageInput) {\n return this.pageService.createPage(createPageInput);\n }\n\n @ResolveField()\n blocks(@Parent() page: Page) {\n return this.blockService.getManyBlocks(page.blockIds);\n }\n}\n```\n\n```text\nimport { Document } from 'mongoose';\n\nexport interface Page extends Document {\n readonly id: string;\n readonly name: string;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly createdBy: string;\n readonly updatedBy: string;\n readonly blockIds: string[];\n}\n```\n\n```text\n@ResolveField()\n```\n\n```text\n@Resolver(() => PageType)\n```\n\n```text\n() => PageType\n```\n\n```text\n@Resolver()\n```\n\n========================================\n\nComments:\n- I'm pretty sure if you are using `@ResolveField()` you need to use a function in the `@Resolver()` decorator, e.g. `@Resolver(() => Page)`\n- Thanks, It's solved after using `@Resolver(() => PageType)`","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":151,"estimatedTokens":828}}841{"id":"stack-60059940","source":"stackoverflow","questionId":60059940,"title":"Graphql Apollo upload in Nestjs returns invalid value {}","tags":["graphql","nestjs","apollo-server"],"text":"Title: Graphql Apollo upload in Nestjs returns invalid value {}\nTags: graphql, nestjs, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI tried adding an upload argument to a GraphQL endpoint using `graphql-upload`'s `GraphQLUpload` scalar:\n\n```\nimport { FileUpload, GraphQLUpload } from 'graphql-upload'\n\n@Mutation(() => Image, { nullable: true })\nasync addImage(@Args({name: 'image', type: () => GraphQLUpload}) image: FileUpload): Promise {\n// do stuff...\n}\n```\n\nAnd this worked initially. A few runs later however, and it started returning the following error:\n\n```\n\"Variable \\\"$image\\\" got invalid value {}; Expected type Upload. Upload value invalid.\"\n```\n\nTried testing with Insomnia client and curl:\n\n```\ncurl localhost:8000/graphql \\\n -F operations='{ \"query\": \"mutation ($image: Upload!) { addImage(image: $image) { id } }\", \"variables\": { \"image\": null } }'\n -F map='{ \"0\": [\"variables.image\"] }'\n -F 0=@/path/to/image\n```\n\n========================================\n\nTop Answer:\nUse `import {GraphQLUpload} from \"apollo-server-express\"`\n\nnot **import GraphQLUpload from 'graphql-upload'**\n\nhttps://i.sstatic.net/yGFr7.png\n\n========================================\n\nCode:\n```js\nimport { FileUpload, GraphQLUpload } from 'graphql-upload'\n\n@Mutation(() => Image, { nullable: true })\nasync addImage(@Args({name: 'image', type: () => GraphQLUpload}) image: FileUpload): Promise<Image | undefined> {\n// do stuff...\n}\n```\n\n```text\n\"Variable \\\"$image\\\" got invalid value {}; Expected type Upload. Upload value invalid.\"\n```\n\n```sh\ncurl localhost:8000/graphql \\\n -F operations='{ \"query\": \"mutation ($image: Upload!) { addImage(image: $image) { id } }\", \"variables\": { \"image\": null } }'\n -F map='{ \"0\": [\"variables.image\"] }'\n -F 0=@/path/to/image\n```\n\n```text\ngraphql-upload\n```\n\n```text\nGraphQLUpload\n```\n\n```js\nimport { Scalar } from '@nestjs/graphql'\nimport FileType from 'file-type'\nimport { GraphQLError } from 'graphql'\nimport { FileUpload } from 'graphql-upload'\nimport { isUndefined } from 'lodash'\n\n@Scalar('Upload')\nexport class Upload {\n description = 'File upload scalar type'\n\n async parseValue(value: Promise<FileUpload>) {\n const upload = await value\n const stream = upload.createReadStream()\n const fileType = await FileType.fromStream(stream)\n\n if (isUndefined(fileType)) throw new GraphQLError('Mime type is unknown.')\n\n if (fileType?.mime !== upload.mimetype)\n throw new GraphQLError('Mime type does not match file content.')\n\n return upload\n }\n}\n```\n\n```js\nimport { UnsupportedMediaTypeException } from '@nestjs/common'\nimport { Scalar } from '@nestjs/graphql'\nimport { ValueNode } from 'graphql'\nimport { FileUpload, GraphQLUpload } from 'graphql-upload'\n\nexport type CSVParseProps = {\n file: FileUpload\n promise: Promise<FileUpload>\n}\n\nexport type CSVUpload = Promise<FileUpload | Error>\nexport type CSVFile = FileUpload\n\n@Scalar('CSV', () => CSV)\nexport class CSV {\n description = 'CSV upload type.'\n supportedFormats = ['text/csv']\n\n parseLiteral(arg: ValueNode) {\n const file = GraphQLUpload.parseLiteral(arg, (arg as any).value)\n\n if (\n file.kind === 'ObjectValue' &&\n typeof file.filename === 'string' &&\n typeof file.mimetype === 'string' &&\n typeof file.encoding === 'string' &&\n typeof file.createReadStream === 'function'\n )\n return Promise.resolve(file)\n\n return null\n }\n\n // If this is `async` then any error thrown\n // hangs and doesn't return to the user. However,\n // if a non-promise is returned it fails reading the\n // stream later. We can't evaluate the `sync`\n // version of the file either as there's a data race (it's not\n // always there). So we return the `Promise` version\n // for usage that gets parsed after return...\n parseValue(value: CSVParseProps) {\n return value.promise.then((file) => {\n if (!this.supportedFormats.includes(file.mimetype))\n return new UnsupportedMediaTypeException(\n `Unsupported file format. Supports: ${this.supportedFormats.join(\n ' '\n )}.`\n )\n\n return file\n })\n }\n\n serialize(value: unknown) {\n return GraphQLUpload.serialize(value)\n }\n}\n```\n\n```js\n@Field(() => CSV)\nfile!: CSVUpload\n```\n\n```js\n// returns either the file or error to throw\nconst fileRes = await file\n\nif (isError(fileRes)) throw fileRes\n```\n\n```text\napollo-server-core\n```\n\n```text\ngraphql-upload\n```\n\n```text\ngraphql-upload\n```\n\n```text\nparseValue\n```\n\n```text\n.csv\n```\n\n```text\nArgsType\n```\n\n```js\nimport * as FileType from 'file-type'\nimport { GraphQLError, GraphQLScalarType } from 'graphql'\nimport { Readable } from 'stream'\n\nexport interface FileUpload {\n filename: string\n mimetype: string\n encoding: string\n createReadStream: () => Readable\n}\n\nexport const GraphQLUpload = new GraphQLScalarType({\n name: 'Upload',\n description: 'The `Upload` scalar type represents a file upload.',\n async parseValue(value: Promise<FileUpload>): Promise<FileUpload> {\n const upload = await value\n const stream = upload.createReadStream()\n const fileType = await FileType.fromStream(stream)\n\n if (fileType?.mime !== upload.mimetype)\n throw new GraphQLError('Mime type does not match file content.')\n\n return upload\n },\n parseLiteral(ast): void {\n throw new GraphQLError('Upload literal unsupported.', ast)\n },\n serialize(): void {\n throw new GraphQLError('Upload serialization unsupported.')\n },\n})\n```\n\n```text\ngraphql-upload\n```\n\n```text\nimport {GraphQLUpload} from \"apollo-server-express\"\n```\n\n```text\nimport { GraphQLUpload, FileUpload } from \"graphql-upload\";\n\n @Mutation(() => Boolean)\n async docUpload(\n @Arg('userID') userid: number,\n @Arg('file', () => GraphQLUpload)\n file: FileUpload\n ) {\n const { filename, createReadStream } = file;\n console.log(userid, file, filename, createReadStream);\n return true\n }\n```\n\n```text\n{\n file: '/user/mim/desktop/t.txt'\n}\n```\n\n========================================\n\nComments:\n- @xadm thanks for the reply. The spec here: github.com/jaydenseric/graphql-multipart-request-spec mentions these should be null, is this not the case?\n- it worked ... node.js errors/warnings? restart?\n- @xadm `GraphQLError: Upload value invalid. at GraphQLScalarType.parseValue (/path/to/project/nest/node_modules/graphql-upload/lib/Graph‌​QLUpload.js:66:11)`. It worked for me initially (about an hour), then the error came and I'm not sure what changed if anything.\n- Can you explain a little further how did you get your mutation working? I'm running into the same error\n- Is your `apollo-server-core` package at latest? If so, it includes `graphql-upload` in it's dependencies and has the middleware handling file uploads already.\n- Sorry for the late reply `@Mutation(() => File) async uploadFile( @Args({ name: 'input', type: () => GraphQLUpload }) fileInput: FileUpload, ): Promise { const url = await this.filesService.create(fileInput) return { url, success: true } }` Where GraphQLUpload and FileUpload are imported from my previous code and File type is just the schema that you are going to return\n- This errors for me when I upload a file: RangeError: Maximum call stack size exceeded at ReadStream.open\"\n- It might be exposed now, but at the time the type wasn't exposed (i.e. `FileUpload`). Hence the dependency and import :)\n- Sure @willsquire. Youβre comment from 12th Feb guide me. Thank you for that. After few hours trying to solve the issue, you gave me the rights tips!\n- Why this answer not at the top?!\n- I had issue just with the docker and this worked for me. you are from the future\n- apollo-server-express no longer includes `GraphQLUpload`.\n- Apollo Server no longer supports uploads out of the box.","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":272,"estimatedTokens":1936}}842{"id":"stack-68028356","source":"stackoverflow","questionId":68028356,"title":"nullable array of nullable values in nestjs code first graphql","tags":["graphql","nestjs","code-first"],"text":"Title: nullable array of nullable values in nestjs code first graphql\nTags: graphql, nestjs, code-first\nSource: Stack Overflow\n\nQuestion:\nHow can I get a field of type array that allows nullable values when using the code-first approach in nestjs graphql.\n\nThe example shows that\n\n```\n@Field(type => [String])\n ingredients: string[];\n```\n\ngenerates `[String!]!` in the `schema.gql` file. How can I get just `[String]`? using `{nullable: true}` gives me `[String!]`\n\nI was hoping to find some type of utility or parameter in the `@Field` decorator, but It seems it isn't\n\n========================================\n\nCode:\n```text\n@Field(type => [String])\n ingredients: string[];\n```\n\n```text\n[String!]!\n```\n\n```text\nschema.gql\n```\n\n```text\n[String]\n```\n\n```text\n{nullable: true}\n```\n\n```text\n[String!]\n```\n\n```text\n@Field\n```\n\n```text\n@Field(type => [Post])\nposts: Post[];\n```\n\n```js\n@Field(type => [Post], { nullable: 'items' })\nposts: Post[];`\n```\n\n```text\n@Field(() => [String], { nullable: 'itemsAndList' })\n```\n\n========================================\n\nComments:\n- Hehe, shame on me. It's clear in the docs. I guess I was a little too lazy. I hope the wording of the question helps other lazy people in the future :)\n- As a lazy person that found this helpful, thank you! π\n- @Jay do have any idea about nullable just `List`? I want my list to be nullable but not its items.\n- @e.hadid probably it's better to return an empty array instead of `null`","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":71,"estimatedTokens":364}}843{"id":"stack-56822614","source":"stackoverflow","questionId":56822614,"title":"How to use 'cache-and-network' policy on ApolloClient.query()","tags":["graphql","apollo-client"],"text":"Title: How to use 'cache-and-network' policy on ApolloClient.query()\nTags: graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm building an app using ApolloClient to query a GraphQL endpoint. I wish to utilize 'cache-and-network' fetch policy on normal queries since this particular policy only works for watchQueries. What I really want is the following:\n\nIf we can query the server, we get a response from the server.\n\nIf we can't query the server, we load the content from the cache, if it's cached\n\nThis is the code I'm using to instantiate the ApolloClient.\n\n```\nconst defaultOptions = { \n watchQuery: {\n fetchPolicy: 'cache-and-network',\n errorPolicy: 'ignore',\n },\n query: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all',\n },\n mutate: {\n errorPolicy: 'all'\n }\n}\n\nconst client = new ApolloClient({\n cache: cache,\n link: createUploadLink({\n uri: 'http://localhost:3000/graphql',\n }),\n defaultOptions\n});\n```\n\nSo I think I have two options: Catch the first query response and if failed load the contents from the cache, or use watchQuery method to issue the queries.\n\nI have no idea were how to do it so any help would be welcome!\n\n========================================\n\nCode:\n```text\nconst defaultOptions = { \n watchQuery: {\n fetchPolicy: 'cache-and-network',\n errorPolicy: 'ignore',\n },\n query: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all',\n },\n mutate: {\n errorPolicy: 'all'\n }\n}\n\n\nconst client = new ApolloClient({\n cache: cache,\n link: createUploadLink({\n uri: 'http://localhost:3000/graphql',\n }),\n defaultOptions\n});\n```\n\n```text\nfunction getZones() {\n return ApolloService.client.query({\n query: GET_ZONES_CLIENT,\n fetchPolicy: navigator.onLine ? 'network-only' : 'cache-only'\n })\n}\n```\n\n========================================\n\nComments:\n- @Daniel Rearden thanks (again) for your help. I did not have much sleep last night trying to work this out.\n- Can check this question: stackoverflow.com/q/57472440/6122411","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":83,"estimatedTokens":496}}844{"id":"stack-44141835","source":"stackoverflow","questionId":44141835,"title":"Apollo Android Client - Cannot access generated classes on classpath","tags":["java","android","android-studio","graphql","apollo-android"],"text":"Title: Apollo Android Client - Cannot access generated classes on classpath\nTags: java, android, android-studio, graphql, apollo-android\nSource: Stack Overflow\n\nQuestion:\nI've generated the Apollo classes successfully and can see them in the build directory, however they're not available on the classpath. Strangely the Enum that is generated is available but the classes themselves aren't.\n\nRunning the sample project provided on Apollo's Github does work but I cant see the difference between the configurations. \n\nmcve below.\n\nhttps://github.com/michaeljq/graphQlMCVE\n\nhttps://i.sstatic.net/pQFSA.png\n\n========================================\n\nTop Answer:\nHere is a screenshot to understand the solution faster:\nhttps://i.sstatic.net/RWMuM.png\n\n========================================\n\nCode:\n```text\nsrc/main/graphql/\n```\n\n```text\nsrc/main/graphql/\n```\n\n```text\nsrc/main/graphql/apollotest/mq/apollotest/api/\n```\n\n```text\nschema.json\n```\n\n```text\napollotest.mq.apollotest.api\n```\n\n```text\napollo {\n // instruct the compiler to generate Kotlin models\n generateKotlinModels.set(true)\n packageNamesFromFilePaths(\"com.example.your_package_name\")\n}\n```\n\n```text\nbuild.gradle\n```\n\n```text\ngraphql\n```\n\n========================================\n\nComments:\n- Why are you trying to edit or reference `build/generated` source code?\n- I'm not trying to edit it, I'm trying to access the generated class. As in import the class.\n- Your `app/build.gradle` isn't compiling that as a dependency. I don't think you can import plugins within your code (at least I've never tried)\n- Um, that doesn't look right. There should be package directories inside of `build/generated/source/apollo/`. What is the contents of your `src/main/graphql/` directory? If it is just the GraphQL document file directly, create a set of subdirectories matching your desired Java package for the generated code, and move the GraphQL file into there.\n- @CommonsWare BTW, github.com/michaeljq/graphQlMCVE/tree/master/app/src/main/…\n- @cricket_007: Yeah, I noticed that shortly after posting the comment, then was busy writing an answer... Thanks!\n- I did this but I still don't see the generated `.java` files in my project. I do see them in the `build/generated/source/apollo/mypackage` directory though. I still can't reference them from IDEA. What can be the problem?\n- @AdamArold: I don't use IDEA. Somehow, you need to teach it that `build/generated/source/apollo/` has sources to be included in your project.\n- I think it is better to copy them over to the `src/main/java` folder, or not?\n- Well, they will get regenerated when you change your GraphQL schema, your GraphQL queries, or upgrade Apollo-Android. So, IMHO, it is better to teach IDEA to pull from the generated source directory. Otherwise, you will forget to manually copy them again.\n- this is an incorrect diagram and didn't worked for me. what commonsware said was to create subfolders similar to our current architecture hierarchy . this folder system worked for me\n- @Andrii-Kovalchuk : what if internal module(app in above img) is ant project and external prj(GraphQlAndroidInFull) is in gradle. How we should generate build folder inside internal module in this case. I am using apollo client 3.1.0","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":75,"estimatedTokens":833}}845{"id":"stack-68560513","source":"stackoverflow","questionId":68560513,"title":"Improve Hasura Subscription Performance","tags":["postgresql","graphql","hasura","graphql-subscriptions"],"text":"Title: Improve Hasura Subscription Performance\nTags: postgresql, graphql, hasura, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nwe developed a web app that relies on real-time interaction between our users. We use Angular for the frontend and Hasura with GraphQL on Postgres as our backend.\nWhat we noticed is that when more than 300 users are active at the same time we experience crucial performance losses. \n\nTherefore, we want to improve our subscriptions setup. \nWe think that possible issues could be:\n\n- Too many subscriptions\n\n- too large and complex subscriptions, too many forks in the subscription\n\nConcerning 1. each user has approximately 5-10 subscriptions active when using the web app. Concerning 2. we have subscriptions that are complex as we join up to 6 tables together.\n\nThe solutions we think of:\n\n- Use more queries and limit the use of subscriptions on fields that are totally necessary to be real-time.\nSplit up complex queries/subscriptions in multiple smaller ones.\n\nAre we missing another possible cause? What else can we use to improve the overall performance?\n\nThank you for your input!\n\n========================================\n\nCode:\n```text\nsubscription{\n document{\n id\n title\n # other fields\n pages{ # array relation\n ...\n } \n tasks{ # array relation\n ...\n } \n # multiple other array/object relations\n # pagination and ordering\n }\n```\n\n```text\nsubscription{\n doc_change_date{\n max_change_date\n }\n}\n```\n\n```text\nquery\n```\n\n```text\nsubscription\n```\n\n```text\ndoc_change_date\n```\n\n```text\nmax_change_date\n```\n\n```text\nmax_change_date\n```\n\n```text\n{max_change_date}\n```\n\n```text\n{doc_change_date, dossier_change_date, msg_change_date}\n```\n\n========================================\n\nComments:\n- You don't include anything about PostgreSQL here, other than just that you are using it. You probably shouldn't use the postgresql tag if you aren't interested in digging into PostgreSQL-specific issues, such as like logging slow queries and doing `EXPLAIN (ANALYZE, BUFFER)` on them.\n- I think the 1st is the correct one. What I encountered: programmers did a lot of heavy subscriptions with all needed fields to draw a grid. We splitted logic in parts: a) subscription just for a single field: change date, b) when application saw that value is changed it runs c) query for whole dataset. Note for the subscription: it's OK if it returns sometimes false positives - anyway it's better to make unneeded query for whole dataset once or twice in a minute then to do that every second. After we did that: CPU usage on postgresql instance went down drastically\n- About \"too many subscription\": hasura can multiplex several subscriptions into a single one - personaly I would not count on that. What I would do: I would try to create a function that detects a fact: \"something was **possibly** changed and it's better to requery all data\". Let's say you have entityA, entityB, ..., entityZ - every one can be changed. You can create a single subscription that detects fact \"data in one or all entities is changed\" and trigger queries for entityA-entityZ. Single subscription -> multiple queries.\n- It would be great if try to dissect your problem, find a simplified example(s) that illustrates it and then add it to your question\n- Great answer! Thanks for sharing such detailed insights and experience\n- Thanks for sharing! We tried different things in the last weeks and had similiar conclusions.\n- 1) less subscriptions: We started to subscribe only the really necessary properties and had queries for everything else, this approach also helped us evaluate parts of our app again and remove unnecessary requests/parts of requests 2) local caching We integrated a caching Service, this way data that would unlikely change in a session(e.g. user names etc) were saved there and we could remove these properties from our queries/subscriptions, this massively increased our performance\n- Local cache: we never did subscriptions for rarely changing data so there is no benefits in using it and using it for frequently changing data is contradictory. So we did not found use case for local cache yet.","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":93,"estimatedTokens":1042}}846{"id":"stack-56126710","source":"stackoverflow","questionId":56126710,"title":"API gateway and microservices communication","tags":["node.js","rabbitmq","graphql","microservices","apollo-client"],"text":"Title: API gateway and microservices communication\nTags: node.js, rabbitmq, graphql, microservices, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am building microservices arhitecture and i need help with communication. What is best approach for API gateway to communicate with services ? My API gateway will be `graphql apollo` server and services will be `REST APIs.` Should i use REST to communicate with services or some message system like `RabbitMQ ?`\n\n========================================\n\nCode:\n```text\ngraphql apollo\n```\n\n```text\nREST APIs.\n```\n\n```text\nRabbitMQ ?\n```\n\n========================================\n\nComments:\n- One more question for you @onuriltan. Can i use maybe gRpc to communicate between gateway and services, for example authentication service and gateway and use message broker for communication between services ? Or should I use message broker always ?\n- @Lule yes you can also use gRPC, it is also faster, but I found that it is harder to use because you need to implement broadcasting, pub-sub, security among different points etc. RabbitMQ I find is more easy to configure and implement.\n- Thank you, very helpful. Going with RabbitMQ then.","metadata":{"transformedAt":"2026-08-18T18:32:36.087Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":28,"estimatedTokens":296}}847{"id":"stack-54271405","source":"stackoverflow","questionId":54271405,"title":"What is the correct shape of a curl POST request to a gqlgen GraphQL API?","tags":["go","curl","graphql"],"text":"Title: What is the correct shape of a curl POST request to a gqlgen GraphQL API?\nTags: go, curl, graphql\nSource: Stack Overflow\n\nQuestion:\nI built a simple GraphQL API extremely similar to gqlgen's \"Getting Started\" tutorial. I can query it successfully with curl. But I can't get the curl request for mutation right.\n\nschema.graphql:\n\n```\ntype Screenshot {\n id: ID!\n url: String!\n filename: String!\n username: String!\n description: String\n}\n\ninput NewScreenshot {\n id: ID!\n url: String!\n filename: String!\n username: String!\n description: String\n}\n\ntype Mutation {\n createScreenshot(input: NewScreenshot!): Screenshot!\n deleteScreenshot(id: ID!): String!\n}\n\ntype Query {\n screenShots(username: String!): [Screenshot!]!\n}\n```\n\nmodels_gen.go:\n\n```\ntype NewScreenshot struct {\n ID string `json:\"id\"`\n URL string `json:\"url\"`\n Filename string `json:\"filename\"`\n Username string `json:\"username\"`\n Description *string `json:\"description\"`\n}\n\ntype Screenshot struct {\n ID string `json:\"id\"`\n URL string `json:\"url\"`\n Filename string `json:\"filename\"`\n Username string `json:\"username\"`\n Description *string `json:\"description\"`\n}\n```\n\nresolver.go:\n\n```\nfunc (r *mutationResolver) CreateScreenshot(ctx context.Context, input NewScreenshot) (Screenshot, error) {\n id, err := uuid.NewV4()\n shot := Screenshot{\n ID: id.String(),\n Description: input.Description,\n URL: input.URL,\n Filename: input.Filename,\n Username: input.Username,\n }\n\n return shot, nil\n}\n```\n\nI've tried:\n\nGoing through the gqlgen documentation, the GraphQL schema, How to GraphQL, and several examples like this and this. And 1.5 days' worth of googling.\n\nPermutating through a lot, a lot of different shapes in my curl request. This one seems the closest:\n\n```\ncurl -v http://localhost:8080/query\n-H \"Content-Type: application/json\"\n-d '{ \"query\":\n { \"createScreenshot\":\n {\"username\": \"Odour\",\n \"url\": \"google.com\",\n \"description\": \"just another screenshot\",\n \"filename\": \"testimage\"\n }\n }\n}'\n```\n\nBut it fails with:\n\n```\n* timeout on name lookup is not supported\n* Trying ::1...\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Connected to localhost (::1) port 8080 (#0)\n> POST /query HTTP/1.1\n> Host: localhost:8080\n> User-Agent: curl/7.47.1\n> Accept: */*\n> Content-Type: application/json\n> Content-Length: 146\n>\n} [146 bytes data]\n* upload completely sent off: 146 out of 146 bytes\n\nHelp?\n\n========================================\n\nTop Answer:\nstill, i find this is more readable, (if you are on Unix):\n\n```\necho '{ \"query\":\n { \"createScreenshot\":\n {\"username\": \"Odour\",\n \"url\": \"google.com\",\n \"description\": \"just another screenshot\",\n \"filename\": \"testimage\"\n }\n }\n}' | tr -d '\\n' | curl \\\n-v http://localhost:8080/query\n-H \"Content-Type: application/json\"\n-d @-\n```\n\n`echo` will pipe the output to `tr` , which will `-d` delete all `\\n` new lines and `curl` 's `-d @-` argument and value (note `-` at the end) will make one line.\n\n========================================\n\nCode:\n```text\ntype Screenshot {\n id: ID!\n url: String!\n filename: String!\n username: String!\n description: String\n}\n\ninput NewScreenshot {\n id: ID!\n url: String!\n filename: String!\n username: String!\n description: String\n}\n\ntype Mutation {\n createScreenshot(input: NewScreenshot!): Screenshot!\n deleteScreenshot(id: ID!): String!\n}\n\ntype Query {\n screenShots(username: String!): [Screenshot!]!\n}\n```\n\n```text\ntype NewScreenshot struct {\n ID string `json:\"id\"`\n URL string `json:\"url\"`\n Filename string `json:\"filename\"`\n Username string `json:\"username\"`\n Description *string `json:\"description\"`\n}\n\ntype Screenshot struct {\n ID string `json:\"id\"`\n URL string `json:\"url\"`\n Filename string `json:\"filename\"`\n Username string `json:\"username\"`\n Description *string `json:\"description\"`\n}\n```\n\n```text\nfunc (r *mutationResolver) CreateScreenshot(ctx context.Context, input NewScreenshot) (Screenshot, error) {\n id, err := uuid.NewV4()\n shot := Screenshot{\n ID: id.String(),\n Description: input.Description,\n URL: input.URL,\n Filename: input.Filename,\n Username: input.Username,\n }\n\n return shot, nil\n}\n```\n\n```text\ncurl -v http://localhost:8080/query\n-H \"Content-Type: application/json\"\n-d '{ \"query\":\n { \"createScreenshot\":\n {\"username\": \"Odour\",\n \"url\": \"google.com\",\n \"description\": \"just another screenshot\",\n \"filename\": \"testimage\"\n }\n }\n}'\n```\n\n```text\n* timeout on name lookup is not supported\n* Trying ::1...\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Connected to localhost (::1) port 8080 (#0)\n> POST /query HTTP/1.1\n> Host: localhost:8080\n> User-Agent: curl/7.47.1\n> Accept: */*\n> Content-Type: application/json\n> Content-Length: 146\n>\n} [146 bytes data]\n* upload completely sent off: 146 out of 146 bytes\n< HTTP/1.1 400 Bad Request\n< Date: Sat, 19 Jan 2019 21:00:15 GMT\n< Content-Length: 149\n< Content-Type: text/plain; charset=utf-8\n<\n{ [149 bytes data]\n100 295 100 149 100 146 149 146 0:00:01 --:--:-- 0:00:01 145k{\"errors\":[{\"message\":\"json body could not be decoded: json: cannot unmarshal object into Go struct field params.query of type string\"}],\"data\":null}\n* Connection #0 to host localhost left intact\n```\n\n```text\n$ curl \\\n -H \"Content-Type: application/json\" \\\n -d '{ \"query\": \"mutation { createScreenshot(input: { username: \\\"Odour\\\" }) { id } }\" }' \\\n http://localhost:8080/query\n```\n\n```text\nquery\n```\n\n```text\necho '{ \"query\":\n { \"createScreenshot\":\n {\"username\": \"Odour\",\n \"url\": \"google.com\",\n \"description\": \"just another screenshot\",\n \"filename\": \"testimage\"\n }\n }\n}' | tr -d '\\n' | curl \\\n-v http://localhost:8080/query\n-H \"Content-Type: application/json\"\n-d @-\n```\n\n```text\necho\n```\n\n```text\ntr\n```\n\n```text\n-d\n```\n\n```text\n\\n\n```\n\n```text\ncurl\n```\n\n```text\n-d @-\n```\n\n```text\n-\n```\n\n========================================\n\nComments:\n- The payload is JSON, so why would you need to urlencode the double quotes?\n- @Imars Following your suggestion, I passed this in: `\"mutation { createScreenshot(input: { id:\\\"12345\\\" username: \\\"Odour\\\" url:\\\"google.com\\\" description:\\\"a screenshot\\\" filename:\\\"testname\\\" }) }\"` But I got this: `{\"errors\":[{\"message\":\"Field \\\"createScreenshot\\\" of type \\\"Screenshot!\\\" must have a selection of subfields. Did you mean \\\"createScreenshot { ... }\\\"?\",\"locations\":[{\"line\":1,\"column\":12}]}],\"data\":null}`. Also tried commas in between them, and then each field in its own braces. Still wrong. How do I pass in multiple fields?\n- The input values are fine the way you are specifying them, but as indicated by the error, you need to select some fields on the return value from `createScreenshot` which is what the `{ id }` part of my example query is doing to select the ID of the resulting Screenshot. So it should be something like: `mutation { createScreenshot(input: { ... }) { id } }`\n- Oh, right! I thought that was optional. Thank you so much! @Imars\n- Is there an easy way to send more complex queries than the example you showed? After a while it gets difficult to put the entire query string on one line...\n- @IanS Save the query in a text file (query.graphql, say) and then send it via -d \"@query.graphql\"","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":300,"estimatedTokens":1898}}848{"id":"stack-56065845","source":"stackoverflow","questionId":56065845,"title":"How to do graphql and graphql subscriptions with svelte","tags":["graphql","svelte"],"text":"Title: How to do graphql and graphql subscriptions with svelte\nTags: graphql, svelte\nSource: Stack Overflow\n\nQuestion:\nTo do graphql queries and mutations ive had success with both fetch and svelte-apollo (see https://github.com/timhall/svelte-apollo)\n\nI like the fech approach for its simplicity. \n\nSvelte-apollo features subscriptions and I will try to get it to work.\n\nBut are there alternatives?\n\nHow do you consume graphql subscriptions with svelte?\n\n========================================\n\nTop Answer:\nI'm using urql's svelte bindings. The documentation also shows how to use the bindings with subscriptions.\n\n========================================\n\nCode:\n```text\nimport { ApolloClient } from 'apollo-client';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { HttpLink } from 'apollo-link-http';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { split } from 'apollo-link';\nimport { getMainDefinition } from 'apollo-utilities';\n\nconst httpLink = new HttpLink({\n uri: 'http://localhost:3000/graphql'\n});\nconst wsLink = new WebSocketLink({\n uri: `ws://localhost:3000/subscriptions`,\n options: {\n reconnect: true\n }\n});\n\n\nconst link = split(\n // split based on operation type\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink,\n);\n\nconst client = new ApolloClient({\n link,\n cache: new InMemoryCache()\n});\n```\n\n```text\nimport gql from 'graphql-tag';\n\nclient.subscribe({\n query: gql`subscription { whatever }`\n}).subscribe(result => console.log(result.data);\n```\n\n========================================\n\nComments:\n- I'm also looking for the same suggestion. Any news?\n- Nice you can do this even without sapper. It's been almost a year since you posted this solution. Would would you write the same solution today?\n- the example on the website doesn't work. do you have a working example?","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":75,"estimatedTokens":497}}849{"id":"stack-55899674","source":"stackoverflow","questionId":55899674,"title":"How can I set a session key from inside a GraphQL resolver in NestJS?","tags":["typescript","authentication","graphql","nestjs"],"text":"Title: How can I set a session key from inside a GraphQL resolver in NestJS?\nTags: typescript, authentication, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm discovering Nest.js and I want to setup a cookie based authentication system with GraphQL.\n\nI already installed express-session middleware, here is the configuration:\n\n**main.ts**\n\n```\napp.use(\n session({\n store: new redisStore({\n client: redis\n } as any),\n name: 'qid',\n secret: SESSION_SECRET,\n resave: false,\n saveUninitialized: false,\n cookie: {\n httpOnly: true,\n secure: !isDev,\n maxAge: 1000 * 60 * 60 * 24 * 7 * 365\n }\n })\n )\n```\n\nit works fine because when I do :\n\n```\napp.use((req: any, res: any, next: any) => {\n // Debug purpose\n req.session.userId = '42'\n next()\n })\n```\n\nThe cookie is added.\n\nRight now I have two mutations, **register** and **login**.\nIn the login mutation (or in the userService), after I found a user I want to do something like `req.session.userId = user.id` but I can't find a way to do this.\n\nI tried to add `@Context() ctx` to my mutation.\nIf I console log ctx, it contains everything I expect (req.session.id for example)\n\nBut if I do `ctx.req.session.userId = 'something'`, the cookie is not set!\n\nHere is my mutation:\n\n**user.resolver.ts**\n\n```\n@Mutation('login')\n async login(\n @Args('email') email: string,\n @Args('password') password: string,\n @Context() ctx: any\n ) {\n console.log(ctx.req.session.id) // Show the actual session id\n ctx.req.session.userId = 'something' // Do not set any cookie\n return await this.userService.login(email, password)\n }\n}\n```\n\nI am totally lost and I really need help, I'd love to understand what's happening. I know I'm probably doing this totally wrong but I'm new to both Nest and GraphQL..\n\nThank you guys...\n\n========================================\n\nTop Answer:\nfor this, it's better to do the configuration in the GraphQL config file instead of the client side\n\n**graphql.config.ts**\n\n```\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\nimport { join } from 'path';\n\nexport const GraphQLConfig: ApolloDriverConfig = {\n driver: ApolloDriver,\n debug: true,\n autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n playground: {\n settings: {\n 'editor.theme': 'light', // use value dark if you want a dark theme in the playground\n 'request.credentials': 'include',\n },\n },\n};\n```\n\nand assign the config file to the module directory\n\n**user.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { GraphQLConfig } from 'src/config/graphql.config';\nimport { UserEntity } from 'src/entity/user.entity';\nimport { UserResolver } from './user.resolver';\nimport { UserService } from './user.service';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserEntity]),\n GraphQLModule.forRoot(GraphQLConfig),\n ],\n providers: [UserService, UserResolver],\n})\nexport class UserModule {}\n```\n\nand it will automatically enable credentials value to be \"include\" from \"omit\"\n\n========================================\n\nCode:\n```text\napp.use(\n session({\n store: new redisStore({\n client: redis\n } as any),\n name: 'qid',\n secret: SESSION_SECRET,\n resave: false,\n saveUninitialized: false,\n cookie: {\n httpOnly: true,\n secure: !isDev,\n maxAge: 1000 * 60 * 60 * 24 * 7 * 365\n }\n })\n )\n```\n\n```text\napp.use((req: any, res: any, next: any) => {\n // Debug purpose\n req.session.userId = '42'\n next()\n })\n```\n\n```text\n@Mutation('login')\n async login(\n @Args('email') email: string,\n @Args('password') password: string,\n @Context() ctx: any\n ) {\n console.log(ctx.req.session.id) // Show the actual session id\n ctx.req.session.userId = 'something' // Do not set any cookie\n return await this.userService.login(email, password)\n }\n}\n```\n\n```text\nreq.session.userId = user.id\n```\n\n```text\n@Context() ctx\n```\n\n```text\nctx.req.session.userId = 'something'\n```\n\n```text\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\nimport { join } from 'path';\n\nexport const GraphQLConfig: ApolloDriverConfig = {\n driver: ApolloDriver,\n debug: true,\n autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n playground: {\n settings: {\n 'editor.theme': 'light', // use value dark if you want a dark theme in the playground\n 'request.credentials': 'include',\n },\n },\n};\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { GraphQLConfig } from 'src/config/graphql.config';\nimport { UserEntity } from 'src/entity/user.entity';\nimport { UserResolver } from './user.resolver';\nimport { UserService } from './user.service';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserEntity]),\n GraphQLModule.forRoot(GraphQLConfig),\n ],\n providers: [UserService, UserResolver],\n})\nexport class UserModule {}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":212,"estimatedTokens":1248}}850{"id":"stack-71183677","source":"stackoverflow","questionId":71183677,"title":"When I run nest.js, I get a Missing \"driver\" option error","tags":["graphql","nestjs","prisma"],"text":"Title: When I run nest.js, I get a Missing \"driver\" option error\nTags: graphql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nI am using nest.js, prisma, and graphql.\n\nWhen I run the npm run start:dev command, I get an error.\n\nIf anyone knows how to solve this, please let me know.\n\nERROR [GraphQLModule] Missing\n\"driver\" option. In the latest version of \"@nestjs/graphql\" package\n(v10) a new required configuration property called \"driver\" has been\nintroduced. Check out the official documentation for more details on\nhow to migrate (https://docs.nestjs.com/graphql/migration-guide).\nExample:\n\nGraphQLModule.forRoot({\ndriver: ApolloDriver,\n})\n\n```\napp.module.ts\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';\nimport { DonationsModule } from './donations/donations.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: false,\n plugins: [ApolloServerPluginLandingPageLocalDefault()],\n typePaths: ['./**/*.graphql'],\n }),\n DonationsModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```\ngenerate-typings.ts\nimport { GraphQLDefinitionsFactory } from '@nestjs/graphql';\nimport { join } from 'path';\n\nconst definitionsFactory = new GraphQLDefinitionsFactory();\ndefinitionsFactory.generate({\n typePaths: ['./src/**/*.graphql'],\n path: join(process.cwd(), 'src/graphql.ts'),\n outputAs: 'class',\n watch: true,\n});\n```\n\nfix\n\n```\n@Module({\n imports: [\n GraphQLModule.forRoot({\n driver: ApolloDriver,\n autoSchemaFile: true,\n plugins: [ApolloServerPluginLandingPageLocalDefault()],\n typePaths: ['./**/*.graphql'],\n }),\n DonationsModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n```\n\n========================================\n\nTop Answer:\nAlso don't forget to import\n\n```\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\n```\n\n========================================\n\nCode:\n```text\napp.module.ts\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';\nimport { DonationsModule } from './donations/donations.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: false,\n plugins: [ApolloServerPluginLandingPageLocalDefault()],\n typePaths: ['./**/*.graphql'],\n }),\n DonationsModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\ngenerate-typings.ts\nimport { GraphQLDefinitionsFactory } from '@nestjs/graphql';\nimport { join } from 'path';\n\nconst definitionsFactory = new GraphQLDefinitionsFactory();\ndefinitionsFactory.generate({\n typePaths: ['./src/**/*.graphql'],\n path: join(process.cwd(), 'src/graphql.ts'),\n outputAs: 'class',\n watch: true,\n});\n```\n\n```text\n@Module({\n imports: [\n GraphQLModule.forRoot<ApolloDriverConfig>({\n driver: ApolloDriver,\n autoSchemaFile: true,\n plugins: [ApolloServerPluginLandingPageLocalDefault()],\n typePaths: ['./**/*.graphql'],\n }),\n DonationsModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n```\n\n```text\n@Module({\n imports: [\n GraphQLModule.forRoot<ApolloDriverConfig>({\n driver: ApolloDriver,\n }),\n ],\n})\n```\n\n```text\nGraphQLModule\n```\n\n```text\nimport { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';\n```\n\n========================================\n\nComments:\n- I rewrote it as above. (fix) The following error occurs at the location import { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';.\n- Cannot find module '@nestjs/apollo' or corresponding type declaration. ts(2307)\n- Have you installed @nestjs/apollo? @yuturo","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":168,"estimatedTokens":993}}851{"id":"stack-47824603","source":"stackoverflow","questionId":47824603,"title":"GraphQL custom scalar definition without `graphql-tools`","tags":["javascript","graphql","graphql-js"],"text":"Title: GraphQL custom scalar definition without `graphql-tools`\nTags: javascript, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nAfter reading this walkthrough in the official documentation:\n\nhttp://graphql.org/graphql-js/object-types/\n\nI am very confused about how to make custom scalar type resolvers without a third party library. Here is the sample code in the docs:\n\n```\nvar express = require('express');\nvar graphqlHTTP = require('express-graphql');\nvar { buildSchema } = require('graphql');\n\n// Construct a schema, using GraphQL schema language\nvar schema = buildSchema(`\n type RandomDie {\n numSides: Int!\n rollOnce: Int!\n roll(numRolls: Int!): [Int]\n }\n\n type Query {\n getDie(numSides: Int): RandomDie\n }\n`);\n\n// This class implements the RandomDie GraphQL type\nclass RandomDie {\n constructor(numSides) {\n this.numSides = numSides;\n }\n\n rollOnce() {\n return 1 + Math.floor(Math.random() * this.numSides);\n }\n\n roll({numRolls}) {\n var output = [];\n for (var i = 0; i I understand I can use `graphql-tools` to make \"executable schema\" from string-based type definitions and a resolvers object. What I'm wondering is why there is no lower level / imperative `graphql-js` API I can use to define and resolve custom scalar types? In other words, how does `graphql-tools` even work?\n\nThanks in advance!\n\nEdit:\n\nHere is some example code outlining the problem. On line 4 you can see that I am importing GraphQLJSON but it is never used. I know what to do to make this work using `graphql-tools` but I want to learn *how* it works. In other words, if `graphql-tools` did not exist, what would I do to inject a custom scalar type while still authoring my schema using `graphql` syntax? From what I can tell the only `graphql-js` solution is to use the non-declarative approach to authoring schema (second example below)\n\n```\nimport express from 'express';\nimport graphqlHTTP from 'express-graphql';\nimport { buildSchema } from 'graphql';\nimport GraphQLJSON from 'graphql-type-json'; // where should I inject this?\n\nconst schema = buildSchema(`\n type Image {\n id: ID!\n width: Int!\n height: Int!\n metadata: JSON!\n }\n\n type Query {\n getImage(id: ID!): Image!\n }\n\n scalar JSON\n`);\n\nclass Image {\n constructor(id) {\n this.id = id;\n this.width = 640;\n this.height = 480;\n }\n metadata() {\n // what do I need to do in order to have this return value parsed by GraphQLJSON\n return { foo: 'bar' };\n }\n}\n\nconst rootValue = {\n getImage: function({ id }) {\n return new Image(id);\n },\n};\n\nconst app = express();\napp.use(\n '/graphql',\n graphqlHTTP({\n schema: schema,\n rootValue: rootValue,\n graphiql: true,\n })\n);\napp.listen(4000);\n```\n\nRunning this query:\n\n```\n{\n getImage(id: \"foo\") {\n id\n width\n height\n metadata\n }\n}\n```\n\nResults in this error:\n\n`Expected a value of type \\\"JSON\\\" but received: [object Object]`\n\nThe answer I'm seeking would help me to return the JSON type without using `graphql-tools`. I have nothing against this library, but it seems bizarre to me that I must use a third party library for something so fundamental to the type resolution system in `graphql-js`. I would like to know more about why this dependency is needed before adopting it.\n\nHere is another way to make this work:\n\n```\nimport { GraphQLObjectType, GraphQLInt, GraphQLID } from 'graphql/type';\n\nconst foo = new GraphQLObjectType({\n name: 'Image',\n fields: {\n id: { type: GraphQLID },\n metadata: { type: GraphQLJSON },\n width: { type: GraphQLInt },\n height: { type: GraphQLInt },\n },\n});\n```\n\nHowever this does not allow me to author my schema using the `graphql` syntax, which is my goal.\n\n========================================\n\nTop Answer:\nBeautiful answer from @vbraden . This helped me as well to put date type in my graphQL using buildSchema just like OP. I'm posting to that for anyone else who landed here trying to put dates in their schema, and to signal boost @vbraden's awesome help. Confirmed it works!\n\n```\nimport { buildSchema } from \"graphql\";\nimport pkg from 'graphql-iso-date'\nconst { GraphQLDateTime } = pkg\n\nconst definition = `\n type Account {\n accountNumber: String,\n dateOpened: DateTime,\n dateClosed: DateTime,\n currentBalance: String,\n }\n\n scalar DateTime\n\n type Accounts {\n accounts: [Account!]!\n }\n\n type RootQuery {\n accounts: Accounts\n }\n\n schema {\n query: RootQuery\n }\n`;\n\nconst schema = new buildSchema(definition);\nObject.assign(schema._typeMap.DateTime, GraphQLDateTime)\n\nexport default schema;\n```\n\n========================================\n\nCode:\n```text\nvar express = require('express');\nvar graphqlHTTP = require('express-graphql');\nvar { buildSchema } = require('graphql');\n\n// Construct a schema, using GraphQL schema language\nvar schema = buildSchema(`\n type RandomDie {\n numSides: Int!\n rollOnce: Int!\n roll(numRolls: Int!): [Int]\n }\n\n type Query {\n getDie(numSides: Int): RandomDie\n }\n`);\n\n// This class implements the RandomDie GraphQL type\nclass RandomDie {\n constructor(numSides) {\n this.numSides = numSides;\n }\n\n rollOnce() {\n return 1 + Math.floor(Math.random() * this.numSides);\n }\n\n roll({numRolls}) {\n var output = [];\n for (var i = 0; i < numRolls; i++) {\n output.push(this.rollOnce());\n }\n return output;\n }\n}\n\n// The root provides the top-level API endpoints\nvar root = {\n getDie: function ({numSides}) {\n return new RandomDie(numSides || 6);\n }\n}\n\nvar app = express();\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n rootValue: root,\n graphiql: true,\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at localhost:4000/graphql');\n```\n\n```text\nimport express from 'express';\nimport graphqlHTTP from 'express-graphql';\nimport { buildSchema } from 'graphql';\nimport GraphQLJSON from 'graphql-type-json'; // where should I inject this?\n\nconst schema = buildSchema(`\n type Image {\n id: ID!\n width: Int!\n height: Int!\n metadata: JSON!\n }\n\n type Query {\n getImage(id: ID!): Image!\n }\n\n scalar JSON\n`);\n\nclass Image {\n constructor(id) {\n this.id = id;\n this.width = 640;\n this.height = 480;\n }\n metadata() {\n // what do I need to do in order to have this return value parsed by GraphQLJSON\n return { foo: 'bar' };\n }\n}\n\nconst rootValue = {\n getImage: function({ id }) {\n return new Image(id);\n },\n};\n\nconst app = express();\napp.use(\n '/graphql',\n graphqlHTTP({\n schema: schema,\n rootValue: rootValue,\n graphiql: true,\n })\n);\napp.listen(4000);\n```\n\n```text\n{\n getImage(id: \"foo\") {\n id\n width\n height\n metadata\n }\n}\n```\n\n```text\nimport { GraphQLObjectType, GraphQLInt, GraphQLID } from 'graphql/type';\n\nconst foo = new GraphQLObjectType({\n name: 'Image',\n fields: {\n id: { type: GraphQLID },\n metadata: { type: GraphQLJSON },\n width: { type: GraphQLInt },\n height: { type: GraphQLInt },\n },\n});\n```\n\n```text\ngraphql-tools\n```\n\n```text\ngraphql-js\n```\n\n```text\ngraphql-tools\n```\n\n```text\ngraphql-tools\n```\n\n```text\ngraphql-tools\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql-js\n```\n\n```text\nExpected a value of type \\\"JSON\\\" but received: [object Object]\n```\n\n```text\ngraphql-tools\n```\n\n```text\ngraphql-js\n```\n\n```text\ngraphql\n```\n\n```text\nimport { buildSchema } from 'graphql'\nimport GraphQLJSON from 'graphql-type-json'\n\nconst definition = `\ntype Foo {\n config: JSON\n}\n\nscalar JSON\n\nQuery {\n readFoo: Foo\n}\n\nschema {\n query: Query\n}`\n\nconst schema = buildSchema(definition)\nObject.assign(schema._typeMap.JSON, GraphQLJSON)\n```\n\n```text\nObject.assign(schema._typeMap.JSON, {\n name: 'JSON',\n serialize: GraphQLJSON.serialize,\n parseValue: GraphQLJSON.parseValue,\n parseLiteral: GraphQLJSON.parseLiteral\n})\n```\n\n```text\nimport { GraphQLScalarType, GraphQLError, Kind } from 'graphql'\n\nconst Base64Type = new GraphQLScalarType({\n name: 'Base64',\n description: 'Serializes and Deserializes Base64 strings',\n serialize (value) {\n return (new Buffer(value, 'base64')).toString()\n },\n parseValue (value) {\n return (new Buffer(value)).toString('base64')\n },\n parseLiteral (ast) {\n if (ast.kind !== Kind.STRING) {\n throw new GraphQLError('Expected Base64 to be a string but got: ' + ast.kind, [ast])\n }\n return (new Buffer(ast.value)).toString('base64')\n }\n})\n```\n\n```text\nbuildSchema\n```\n\n```text\nserialize\n```\n\n```text\nparseValue\n```\n\n```text\nparseLiteral\n```\n\n```text\nbuildSchema\n```\n\n```text\ngraphql-js\n```\n\n```text\nGraphQLScalarType\n```\n\n```text\nimport { buildSchema } from \"graphql\";\nimport pkg from 'graphql-iso-date'\nconst { GraphQLDateTime } = pkg\n\n\nconst definition = `\n type Account {\n accountNumber: String,\n dateOpened: DateTime,\n dateClosed: DateTime,\n currentBalance: String,\n }\n\n scalar DateTime\n\n type Accounts {\n accounts: [Account!]!\n }\n\n type RootQuery {\n accounts: Accounts\n }\n\n schema {\n query: RootQuery\n }\n`;\n\nconst schema = new buildSchema(definition);\nObject.assign(schema._typeMap.DateTime, GraphQLDateTime)\n\nexport default schema;\n```\n\n========================================\n\nComments:\n- Thanks for your response. I understand how to *create* custom scalar types -- this is well documented. I will edit my question to provide a more specific example outlining what's going wrong\n- if your question is around how do you set the `serialize`, `parseValue`, and `parseLiteral` handlers for a custom scalar using a string definition, you need to use graphql-js `buildSchema` to create the schema, or whatever tool creates the schema from it and then you can set `schema._typeMap.CustomScalarName.serialize = serializeHandler`, etc\n- I did try `schema._typeMap.JSON = GraphQLJSON` but this did not work\n- you cant do it that way. you need to add `scalar JSON` to the string definition then you can do something like `Object.assign(schema._typeMap.JSON, GraphQLJSON)`\n- `Object.assign` works -- awesome! Can you please edit your answer and I will mark it as accepted for future viewers? THANK YOU\n- Great answer. To extend it, if somebody is using `GraphQLScalarType` to create their custom scalar they have to assign `Foo._scalarConfig`, being `Foo` the scalar. Example with Date: `Object.assign(schema._typeMap.Date, Date._scalarConfig);`","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":478,"estimatedTokens":2537}}852{"id":"stack-56259684","source":"stackoverflow","questionId":56259684,"title":"Graphene: Enum argument doesn't seem to work","tags":["python","graphql","graphene-python"],"text":"Title: Graphene: Enum argument doesn't seem to work\nTags: python, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nIm currently having hard time on mutation enum `Argument`.\n\nBelow are my code for `Mutation`:\n\n```\nclass CreatePerson(graphene.Mutation):\n foo = graphene.String()\n\n def mutate(self, info, **kwargs):\n return CreatePerson(foo='foo')\n\n class Arguments:\n enum_arg = graphene.Argument(graphene.Enum.from_enum(EnumArg))\n```\n\nEnum class:\n\n```\nfrom enum import Enum\n\nclass EnumArg(Enum):\n Baz = 0\n Bar = 1\n Spam = 2\n Egg = 3\n```\n\nCommand using **POSTMAN**:\n\n```\n{\n \"query\": \"mutation\": {createPerson(enumArg=1) { foo }}\n}\n```\n\nBut I end up this error message:\n\n```\n\"message\": \"Argument \\\"enumArg\\\" has invalid value 1.\n Expected type \\\"EnumArg\\\", found 1.\",\n```\n\nI also tried giving `enumArg=\\\"Bar\\\"` on the `createPerson` mutation and the error still persists.\n\n========================================\n\nTop Answer:\nenum defined in backend is:\n\n```\nenum Gender {\n MALE\n FEMALE\n}\n```\n\nI am using Vue for frontend so passing data to the mutation from Vue can be done like this.\nI have defined gender as a string in my local state of the component as:\n\n```\ndata(){\n return {\n gender: ''\n }\n}\n```\n\nThe method from Vue is:\n\n```\nasync handleEditProfile () {\n const response = await this.$apollo.mutate({\n query: EDIT_PROFILE,\n variables: {\n nameAsInPan: this.nameAsInPan,\n gender: this.gender,\n dateOfBirth: this.dateOfBirth\n }\n })\n }\n```\n\nmutation used above EDIT_PROFILE:\n\n```\ngql`mutation editProfile($name: String!, $email: String!,$phone: String!, $gender: Gender!, $dateOfBirth: String!) {\n editProfile (profileInput:{name: $name, email: $email, phone: $phone, gender: $gender, dateOfBirth: $dateOfBirth}){\n id\n email\n phone\n firstName\n lastName\n nameAsInPan\n gender\n dateOfBirth\n }\n}\n`\n```\n\nuse the enum variable name as defined in the mutation and send it to Graphql, like I have used gender As\n`$gender: Gender!` in gql mutation. You don't have to worry about sending data as enum, just send it as String otherwise you will have to face JSON error, Graphql will take care of the value you send as a string (like 'MALE' or 'FEMALE') just don't forget to mention that gender is type of Gender(which is enum) in gql mutation as I did above.\n\nPlease read my answer on this link Link for reference\n\n========================================\n\nCode:\n```text\nclass CreatePerson(graphene.Mutation):\n foo = graphene.String()\n\n def mutate(self, info, **kwargs):\n return CreatePerson(foo='foo')\n\n\n class Arguments:\n enum_arg = graphene.Argument(graphene.Enum.from_enum(EnumArg))\n```\n\n```text\nfrom enum import Enum\n\nclass EnumArg(Enum):\n Baz = 0\n Bar = 1\n Spam = 2\n Egg = 3\n```\n\n```text\n{\n \"query\": \"mutation\": {createPerson(enumArg=1) { foo }}\n}\n```\n\n```text\n\"message\": \"Argument \\\"enumArg\\\" has invalid value 1.\n Expected type \\\"EnumArg\\\", found 1.\",\n```\n\n```text\nArgument\n```\n\n```text\nMutation\n```\n\n```text\nenumArg=\\\"Bar\\\"\n```\n\n```text\ncreatePerson\n```\n\n```text\nmutation {\n createPerson(enumArg: Bar) {\n foo\n }\n}\n```\n\n```text\nenum Gender {\n MALE\n FEMALE\n}\n```\n\n```text\ndata(){\n return {\n gender: ''\n }\n}\n```\n\n```text\nasync handleEditProfile () {\n const response = await this.$apollo.mutate({\n query: EDIT_PROFILE,\n variables: {\n nameAsInPan: this.nameAsInPan,\n gender: this.gender,\n dateOfBirth: this.dateOfBirth\n }\n })\n }\n```\n\n```text\ngql`mutation editProfile($name: String!, $email: String!,$phone: String!, $gender: Gender!, $dateOfBirth: String!) {\n editProfile (profileInput:{name: $name, email: $email, phone: $phone, gender: $gender, dateOfBirth: $dateOfBirth}){\n id\n email\n phone\n firstName\n lastName\n nameAsInPan\n gender\n dateOfBirth\n }\n}\n`\n```\n\n```text\n$gender: Gender!\n```\n\n========================================\n\nComments:\n- The `command` is not valid python how are you callling `command`?\n- No it is pretty valid. Check here and im using postman stackoverflow.com/a/55146271/6143656\n- @MarcoDaniel Its looking good\n- Not sure if this is a dupe. The issue here is that we can assign an arbitrary value for each enum value, but this value is only used ***internally*** by the GraphQL service itself. When referring to the enum value inside a GraphQL document, it must always be referenced by its name.\n- When i printed the `kwargs` on the `def mutate()`, the argument `enum_arg` has a value of `1`. Now the consequence problem is im using `flask-sqlalchemy` and the model field is an enum. it cannot accept value `1` as it is giving `Not a valid enum value`. I expected that it should give a ``.\n- @DanielRearden however it solve the problem of the original error which it cannot even proceed on mutation function.\n- @Roel That's probably a good question, unfortunately not one I can answer since I don't have experience with `flask-sqlalchemy`. I would suggest opening a new question.\n- And yes this is pretty accurate and well detailed explanation.","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":229,"estimatedTokens":1261}}853{"id":"stack-57336291","source":"stackoverflow","questionId":57336291,"title":"\"Cannot return null for non-nullable field\" when subscribing on NestJS with Graphql","tags":["angular","graphql","apollo-client","nestjs"],"text":"Title: \"Cannot return null for non-nullable field\" when subscribing on NestJS with Graphql\nTags: angular, graphql, apollo-client, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a nodejs backend done with `Nestjs` and I'm using `Graphql`. My frontend is Ionic/Angular using Apollo-angular for graphql stuff. \n**I'm having a problem subscribing data additions / changes.** Playground (provided by Nestjs) works just fine, which gives me a hint that the problem is in frontend.\n\nI have `game` and `scores` in my data model, each score belonging to a game. In frontend I'm trying to listen to the new scores added to a specific game.\n\n### Backend\n\nHere's a snippet from my `resolver`:\n\n```\n@Mutation(returns => Score)\nasync addScore(@Args('data') data: ScoreInput): Promise {\n return await this.scoresService.createScore(data);\n}\n\n@Subscription(returns => Score, {\n filter: (payload, variables) => payload.scoreAdded.game + '' === variables.gameId + '',\n})\nscoreAdded(@Args('gameId') gameId: string) {\n return this.pubSub.asyncIterator('scoreAdded');\n}\n```\n\nHere's the `service` method:\n\n```\nasync createScore(data: any): Promise {\n const score = await this.scoreModel.create(data);\n this.pubSub.publish('scoreAdded', { scoreAdded: score });\n}\n```\n\nThese are in my schema.gql:\n\n```\ntype Score {\n id: String\n game: String\n result: Int\n}\n\ntype Subscription {\n scoreAdded(gameId: String!): Score!\n}\n```\n\n### Frontend\n\nBased on `Apollo-angular`'s documentation, in my frontend I have this kind of service:\n\n```\nimport { Injectable } from '@angular/core';\nimport { Subscription } from 'apollo-angular';\nimport { SCORE_ADDED } from './graphql.queries';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class ScoreListenerService extends Subscription {\n document = SCORE_ADDED;\n}\n```\n\nThis is in the frontend's graphql.queries:\n\n```\nexport const SCORE_ADDED = gql`\n subscription scoreAdded($gameId: String!) {\n scoreAdded(gameId: $gameId) {\n id\n game\n result\n }\n }\n`;\n```\n\nand I'm using this service like this in my component:\n\n```\nthis.scoreListener.subscribe({ gameId: this.gameId }).subscribe(({ data }) => {\n const score = data.scoreAdded;\n console.log(score);\n});\n```\n\n### The problem\n\nWith all this, my frontend gives me an error `ERROR Error: GraphQL error: Cannot return null for non-nullable field Subscription.scoreAdded.`\n\nDoing the subscription like this in Playground works, no problem at all.\n\n```\nsubscription {\n scoreAdded(gameId: \"5d24ad2c4cf6d3151ad31e3d\") {\n id\n game\n result\n }\n}\n```\n\n### Different problem\n\nI noticed that if I use `resolve` in my backend's resolver like this:\n\n```\n@Subscription(returns => Score, {\n resolve: value => value,\n filter: (payload, variables) => payload.scoreAdded.game + '' === variables.gameId + '',\n })\n scoreAdded(@Args('gameId') gameId: string) {\n return this.pubSub.asyncIterator('scoreAdded');\n }\n```\n\nthe error in frontend goes away, BUT it screws up the data in subscription, playground getting the added score with null in each attribute and the subscribe in frontend is NOT triggered at all.\n\n**Any help, what am I doing wrong here?**\nIt looks to me that my frontend is not correct but I'm not sure is it my bad or possibly a bug in Apollo-angular...\n\n========================================\n\nTop Answer:\nProvided answer above is correct, but for those who want to see the packages version used and imported files check this solution:\n\n**package.json** dependencies\n\n```\n{\n \"dependencies\": {\n \"@apollo/client\": \"^3.2.5\",\n \"@apollo/link-ws\": \"^2.0.0-beta.3\",\n \"apollo-angular\": \"^2.0.4\",\n \"subscriptions-transport-ws\": \"^0.9.18\",\n }\n}\n```\n\n**graphql.module.ts** code\n\n```\nimport { WebSocketLink } from '@apollo/link-ws';\nimport { NgModule } from '@angular/core';\nimport { APOLLO_OPTIONS } from 'apollo-angular';\nimport { InMemoryCache, split } from '@apollo/client/core';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { HttpLink } from 'apollo-angular/http';\n\nconst uri = 'http://localhost:3000/graphql';\nconst wsUrl = 'http://localhost:3000/graphql';\n\nexport function createApollo(hLink: HttpLink) {\n \n const ws = new WebSocketLink({\n uri: wsUrl,\n options: {\n reconnect: true\n }\n });\n\n const http = hLink.create({uri});\n\n const newLink = split(\n ({ query }) => {\n const def = getMainDefinition(query);\n return def.kind === 'OperationDefinition' && def.operation === 'subscription';\n },\n ws,\n http\n );\n \n return {\n link: newLink,\n cache: new InMemoryCache(),\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all'\n }\n }\n };\n}\n\n@NgModule({\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\n========================================\n\nCode:\n```text\n@Mutation(returns => Score)\nasync addScore(@Args('data') data: ScoreInput): Promise<IScore> {\n return await this.scoresService.createScore(data);\n}\n\n@Subscription(returns => Score, {\n filter: (payload, variables) => payload.scoreAdded.game + '' === variables.gameId + '',\n})\nscoreAdded(@Args('gameId') gameId: string) {\n return this.pubSub.asyncIterator('scoreAdded');\n}\n```\n\n```text\nasync createScore(data: any): Promise<IScore> {\n const score = await this.scoreModel.create(data);\n this.pubSub.publish('scoreAdded', { scoreAdded: score });\n}\n```\n\n```text\ntype Score {\n id: String\n game: String\n result: Int\n}\n\ntype Subscription {\n scoreAdded(gameId: String!): Score!\n}\n```\n\n```text\nimport { Injectable } from '@angular/core';\nimport { Subscription } from 'apollo-angular';\nimport { SCORE_ADDED } from './graphql.queries';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class ScoreListenerService extends Subscription {\n document = SCORE_ADDED;\n}\n```\n\n```text\nexport const SCORE_ADDED = gql`\n subscription scoreAdded($gameId: String!) {\n scoreAdded(gameId: $gameId) {\n id\n game\n result\n }\n }\n`;\n```\n\n```text\nthis.scoreListener.subscribe({ gameId: this.gameId }).subscribe(({ data }) => {\n const score = data.scoreAdded;\n console.log(score);\n});\n```\n\n```text\nsubscription {\n scoreAdded(gameId: \"5d24ad2c4cf6d3151ad31e3d\") {\n id\n game\n result\n }\n}\n```\n\n```text\n@Subscription(returns => Score, {\n resolve: value => value,\n filter: (payload, variables) => payload.scoreAdded.game + '' === variables.gameId + '',\n })\n scoreAdded(@Args('gameId') gameId: string) {\n return this.pubSub.asyncIterator('scoreAdded');\n }\n```\n\n```text\nNestjs\n```\n\n```text\nGraphql\n```\n\n```text\ngame\n```\n\n```text\nscores\n```\n\n```text\nresolver\n```\n\n```text\nservice\n```\n\n```text\nApollo-angular\n```\n\n```text\nERROR Error: GraphQL error: Cannot return null for non-nullable field Subscription.scoreAdded.\n```\n\n```text\nresolve\n```\n\n```text\nconst graphqlUri = 'http://localhost:3000/graphql';\n\nexport function createApollo(httpLink: HttpLink) {\n return {\n link: httpLink.create({ graphqlUri }),\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all',\n },\n },\n };\n}\n```\n\n```text\nconst graphqlUri = 'http://localhost:3000/graphql';\nconst wsUrl = 'ws://localhost:3000/graphql';\n\nexport function createApollo(httpLink: HttpLink) {\n const link = split(\n // split based on operation type\n ({ query }) => {\n const { kind, operation } = getMainDefinition(query);\n return kind === 'OperationDefinition' && operation === 'subscription';\n },\n new WebSocketLink({\n uri: wsUrl,\n options: {\n reconnect: true,\n },\n }),\n httpLink.create({\n uri: graphqlUri,\n })\n );\n return {\n link,\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all',\n },\n },\n };\n}\n```\n\n```text\n{\n \"dependencies\": {\n \"@apollo/client\": \"^3.2.5\",\n \"@apollo/link-ws\": \"^2.0.0-beta.3\",\n \"apollo-angular\": \"^2.0.4\",\n \"subscriptions-transport-ws\": \"^0.9.18\",\n }\n}\n```\n\n```text\nimport { WebSocketLink } from '@apollo/link-ws';\nimport { NgModule } from '@angular/core';\nimport { APOLLO_OPTIONS } from 'apollo-angular';\nimport { InMemoryCache, split } from '@apollo/client/core';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { HttpLink } from 'apollo-angular/http';\n\nconst uri = 'http://localhost:3000/graphql';\nconst wsUrl = 'http://localhost:3000/graphql';\n\nexport function createApollo(hLink: HttpLink) {\n \n const ws = new WebSocketLink({\n uri: wsUrl,\n options: {\n reconnect: true\n }\n });\n\n const http = hLink.create({uri});\n\n const newLink = split(\n ({ query }) => {\n const def = getMainDefinition(query);\n return def.kind === 'OperationDefinition' && def.operation === 'subscription';\n },\n ws,\n http\n );\n \n return {\n link: newLink,\n cache: new InMemoryCache(),\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'network-only',\n errorPolicy: 'all'\n }\n }\n };\n}\n\n@NgModule({\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\n========================================\n\nComments:\n- Is `score` defined inside the service method(i.e. does create actually return the created model)?\n- Yes, the service method returns the actual saved model correctly (in all of these cases). Without defining any `resolve` on backends Subscription part, everything works well on playground but the frontend Apollo client gets the `ERROR Error: GraphQL error: Cannot return null for non-nullable field Subscription.scoreAdded.`\n- and from where do you import getMainDefinition ?\n- Found your question & answer straight away. I suspect you saved, at the least, my day. Thank you.","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":449,"estimatedTokens":2458}}854{"id":"stack-57152625","source":"stackoverflow","questionId":57152625,"title":"Use absolute path for featured image in markdown post with Gatsby","tags":["graphql","gatsby"],"text":"Title: Use absolute path for featured image in markdown post with Gatsby\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI've followed Gatsby tutorial for Working With Images in Markdown Posts and Pages which is working well but what I want to achieve is to fetch image from a static location instead of using a relative path for the image.\n\nWould like to reference image like this (in frontmatter)\n\n```\nfeaturedImage: img/IMG_20190621_112048_2.jpg\n```\n\nWhere **IMG_20190621_112048_2.jpg** is in `/src/data/img` instead of same directory as markdown file under `/src/posts`\n\nI've tried to setup `gatsby-source-filesystem` like this :\n\n```\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `posts`,\n path: `${__dirname}/src/posts`,\n },\n},\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `data`,\n path: `${__dirname}/src/data/`,\n },\n},\n```\n\nbut graphQL query in post template fails :\n\n```\nexport const query = graphql`\n query($slug: String!) {\n markdownRemark(fields: { slug: { eq: $slug } }) {\n html\n frontmatter {\n title\n featuredImage {\n childImageSharp {\n fluid(maxWidth: 800) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n }\n }\n```\n\n GraphQL Error Field \"featuredImage\" must not have a selection since\n type \"String\" has no subfields.\n\nAny idea how I could fetch image from a location distinct to the post markdown directory ?\n\n========================================\n\nTop Answer:\nIn addition to Derek Answer which allow assets of any type to be use anywhere (sound, video, gpx, ...), if looking for a solution only for images, one can use :\n\nhttps://www.gatsbyjs.org/packages/gatsby-remark-relative-images/\n\n========================================\n\nCode:\n```text\nfeaturedImage: img/IMG_20190621_112048_2.jpg\n```\n\n```text\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `posts`,\n path: `${__dirname}/src/posts`,\n },\n},\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `data`,\n path: `${__dirname}/src/data/`,\n },\n},\n```\n\n```text\nexport const query = graphql`\n query($slug: String!) {\n markdownRemark(fields: { slug: { eq: $slug } }) {\n html\n frontmatter {\n title\n featuredImage {\n childImageSharp {\n fluid(maxWidth: 800) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n }\n }\n }\n```\n\n```text\n/src/data/img\n```\n\n```text\n/src/posts\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```js\n// gatsby-node.js\n\nconst path = require('path')\n\nexports.createSchemaCustomization = ({ actions }) => {\n const { createFieldExtension, createTypes } = actions\n\n createFieldExtension({\n name: 'fileByDataPath',\n extend: () => ({\n resolve: function (src, args, context, info) {\n const partialPath = src.featureImage\n if (!partialPath) {\n return null\n }\n\n const filePath = path.join(__dirname, 'src/data', partialPath)\n const fileNode = context.nodeModel.runQuery({\n firstOnly: true,\n type: 'File',\n query: {\n filter: {\n absolutePath: {\n eq: filePath\n }\n }\n }\n })\n\n if (!fileNode) {\n return null\n }\n\n return fileNode\n }\n })\n })\n\n const typeDefs = `\n type Frontmatter @infer {\n featureImage: File @fileByDataPath\n }\n\n type MarkdownRemark implements Node @infer {\n frontmatter: Frontmatter\n }\n `\n\n createTypes(typeDefs)\n}\n```\n\n```text\ntype Frontmatter {\n featureImage: File\n }\n```\n\n```text\ntype Frontmatter {\n featureImage: File\n }\n\n type MarkdownRemark implements Node {\n frontmatter: Frontmatter\n }\n```\n\n```text\nexports.createSchemaCustomization = ({ actions }) => {\n const { createTypes } = actions\n\n const typeDefs = `\n type Frontmatter @infer {\n featureImage: File\n }\n\n type MarkdownRemark implements Node @infer {\n frontmatter: Frontmatter\n }\n `\n\n createTypes(typeDefs)\n}\n```\n\n```text\nquery Post {\n markdownRemark {\n frontmatter {\n featureImage {\n id\n }\n }\n }\n}\n```\n\n```js\nresolve: async function (src, args, context) {\n // look up original string, i.e img/photo.jpg\n const partialPath = src.featureImage\n if (!partialPath) {\n return null\n }\n\n // get the absolute path of the image file in the filesystem\n const filePath = path.join(__dirname, 'src/data', partialPath)\n \n // look for a node with matching path\n const fileNode = await context.nodeModel.runQuery({\n firstOnly: true,\n type: 'File',\n query: {\n filter: {\n absolutePath: {\n eq: filePath\n }\n }\n }\n })\n\n // no node? return\n if (!fileNode) {\n return null\n }\n\n // else return the node\n return fileNode\n }\n```\n\n```text\ncreateFieldExtension({\n name: 'fileByDataPath' // we'll use it in createTypes as `@fileByDataPath`\n extend: () => ({\n resolve, // the resolve function above\n })\n})\n\nconst typeDef = `\n type Frontmatter @infer {\n featureImage: File @fileByDataPath // <---\n }\n ...\n`\n```\n\n```text\ncreateSchemaCustomization\n```\n\n```text\nmarkdownRemark.frontmatter.featureImage\n```\n\n```text\ncreateTypes\n```\n\n```text\n@fileByDataPath\n```\n\n```text\ncreateFieldExtension\n```\n\n```text\nfrontmatter.featureImage\n```\n\n```text\nFrontmatter\n```\n\n```text\n@infer\n```\n\n```text\nfrontmatter.title\n```\n\n```text\nmarkdownRemark.html\n```\n\n```text\ncreateTypes\n```\n\n```text\nlocalhost:8000/___graphql\n```\n\n```text\nfeatureImage\n```\n\n```text\ncreateResolvers\n```\n\n```text\ncreateFileExtension\n```\n\n```text\ncreateFileExtension\n```\n\n```text\ncreateResolvers\n```\n\n```text\nsrc/data\n```\n\n```text\nfieldByDataPath\n```\n\n```text\nfrontmatter\n```\n\n```text\nfeatureImage\n```\n\n```text\nnodeModel\n```\n\n```text\nimg/photo.jpg\n```\n\n```text\nsrc.featureImage\n```\n\n```text\nsrc/data\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\nsrc/data\n```\n\n```text\nnull\n```\n\n```text\ncreateFieldExtension\n```\n\n```text\nsrc/data/\n```\n\n```text\nfileByDataPath\n```\n\n```text\nfeatureImage\n```\n\n```text\n_data\n```\n\n```text\nrunQuery\n```\n\n```text\nfeaturedImage: String\n```\n\n========================================\n\nComments:\n- I don't think so this is the exact solution for the error log what mentioned by the Post Author\n- Works like a charm, I had to rename featureImage to featuredImage to make it work with my frontmatter headers... And can be used for other means !!!\n- Any way to get the relative path to the markdown? I have \"./pic.jpb\", but I can't figure out the absolute path of the markdown file.\n- Nice, I wasn't aware that gatsby-remark-relative-images can also handle paths in frontmatter, neat!","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":48,"totalLines":418,"estimatedTokens":1667}}855{"id":"stack-61050343","source":"stackoverflow","questionId":61050343,"title":"CORS Error in Laravel 7 using Laravel Lighthouse","tags":["laravel","graphql","cors","vue-apollo","laravel-lighthouse"],"text":"Title: CORS Error in Laravel 7 using Laravel Lighthouse\nTags: laravel, graphql, cors, vue-apollo, laravel-lighthouse\nSource: Stack Overflow\n\nQuestion:\nI have an API built with Laravel and Lighthouse-php(for GraphQL). My client is built with Vue js and uses Apollo for the graphQL client-side implementation. Anytime I make a request, I get the following error:\n\n```\nAccess to fetch at 'http://localhost:8000/graphql' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.\n```\n\nNaturally, I proceeded to install laravel-cors package but I realized afterwards that it came by default with my Laravel installation (7.2.2). Which meant that `\\Fruitcake\\Cors\\HandleCors::class` was already added to the middleware array in `Kernel.php` and the cors config file was already in my config directory.\n\nAfter some googling, I realized that I needed to add `\\Fruitcake\\Cors\\HandleCors::class` to the `route.middleware` array in my `config/lighthouse.php` file\n\nIt still did not work. I have restarted the server, cleared cache, cleared config and run `composer dump-autoload` but I still get the error. I have no idea how to get past this. Any help will be appreciated.\n\n**Versions**\n\nLaravel 7.2.2 \n\nLaravel Lighthouse 4.10\n\n========================================\n\nCode:\n```text\nAccess to fetch at 'http://localhost:8000/graphql' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.\n```\n\n```text\n\\Fruitcake\\Cors\\HandleCors::class\n```\n\n```text\nKernel.php\n```\n\n```text\n\\Fruitcake\\Cors\\HandleCors::class\n```\n\n```text\nroute.middleware\n```\n\n```text\nconfig/lighthouse.php\n```\n\n```text\ncomposer dump-autoload\n```\n\n```text\n'paths' => ['api/*', 'graphql/*'],\n```\n\n```text\n'paths' => ['api/*', 'graphql'],\n```\n\n```text\nreturn [\n 'paths' => ['api/*', 'graphql'],\n 'allowed_methods' => ['*'],\n 'allowed_origins' => ['*'],\n 'allowed_origins_patterns' => [],\n 'allowed_headers' => ['*'],\n 'exposed_headers' => false,\n 'max_age' => false,\n 'supports_credentials' => false,\n];\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql/*\n```\n\n```text\nphp artisan cache:clear\n```\n\n```text\nphp artisan config:clear\n```\n\n```text\ncomposer dump-autoload\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":94,"estimatedTokens":673}}856{"id":"stack-55802275","source":"stackoverflow","questionId":55802275,"title":"GraphQL - Execute sub query conditionally","tags":["graphql","react-apollo"],"text":"Title: GraphQL - Execute sub query conditionally\nTags: graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm trying to optimise the query executed by some of my react components that are shared across the whole app, such as Footer and Header components.\n\nI'm trying not to fetch the Student Solution details when the variable `institutionPath` is not provided. \n\n```\nquery organisationAndInstitution($organisationName: String!, $institutionPath: String!, $fetchInstitution: Boolean!){\n organisation(where: {\n name: $organisationName\n }){\n name\n }\n\n studentSolutionRelationships(where:{ \n AND: [\n {\n status: PUBLISHED\n },\n {\n studentSolution: {\n status: PUBLISHED\n }\n }\n ]\n }) @include(if: $fetchInstitution) {\n status\n }\n}\n```\n\nTo do so, I added a `fetchInstitution` boolean variable and added the `@include(if: $fetchInstitution)` directive.\n\nBut directives seem to apply only on fields, not on whole queries. So I wonder if what I want to do is possible, because the way I wrote it is invalid.\n\n========================================\n\nCode:\n```text\nquery organisationAndInstitution($organisationName: String!, $institutionPath: String!, $fetchInstitution: Boolean!){\n organisation(where: {\n name: $organisationName\n }){\n name\n }\n\n studentSolutionRelationships(where:{ \n AND: [\n {\n status: PUBLISHED\n },\n {\n studentSolution: {\n status: PUBLISHED\n }\n }\n ]\n }) @include(if: $fetchInstitution) {\n status\n }\n}\n```\n\n```text\ninstitutionPath\n```\n\n```text\nfetchInstitution\n```\n\n```text\n@include(if: $fetchInstitution)\n```\n\n```text\nstudentSolutionRelationships(where:{ \n #...input fields omitted for brevity\n}) @include(if: $fetchInstitution) {\n status\n}\n```\n\n```text\n@include\n```\n\n```text\n@skip\n```\n\n```text\nif\n```\n\n```text\nBoolean\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```text\nBoolean\n```\n\n```text\nif\n```\n\n```text\nstudentSolutionRelationships\n```\n\n```text\norganisation\n```\n\n========================================\n\nComments:\n- `studentSolutionRelationships` and `organisation` are still fields, they just happen to be fields on the query root operation type. There's nothing incorrect about your approach. When you say it's \"invalid\", what do you mean? What error are you seeing?\n- FWIW, I see a missing closing bracket, but that could just be a typo here and not in your code.\n- When I try to execute this, the query hangs and eventually times out. I'm not using my own graphql server but a third party, so maybe this kind of things isn't implemented on their backend. But I didn't debug it much since I thought I wasn't doing it right, I'll take a deeper look. Thanks! (and the typo is because I removed lots of noise here, to focus on what matters)\n- And indeed you were right. The query works well on graphiql but was failing from my source code, I guess it was either not properly translated, or I made a mistake in the code. Either way, it seems to be the correct way of fetching optional fields!\n- It was indeed a dumb mistake in my code (not providing the new variable for all the calls using this query). If you want to write a proper response I'll accept it and close the issue :)","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":134,"estimatedTokens":802}}857{"id":"stack-48614730","source":"stackoverflow","questionId":48614730,"title":"How can I convert the object array to GraphQL format in Javascript?","tags":["laravel","reactjs","graphql"],"text":"Title: How can I convert the object array to GraphQL format in Javascript?\nTags: laravel, reactjs, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm working with React, and I send this information:\n\n```\nconst imageServicesClean = JSON.stringify(imageServices);\nconst query = `\n mutation {\n companyUpdate(\n idCompany:${idCompany},\n name:${nameClean},\n imageServices:${imageServicesClean})\n {\n idCompany\n name\n imageServices {\n idImageService\n name\n url\n key\n }\n }\n }`;\n```\n\nAnd the imageServicesClean is sent in this way, but return error:\n\n```\n[{\n \"idImageService\": 1,\n \"name\": \"Service1\",\n \"url\": \"\",\n \"key\": \"asdasdas\"\n}, {\n \"idImageService\": 2,\n \"name\": \"Service2\",\n \"url\": \"sdsads\",\n \"key\": \"sddsfsds_\"\n}]\n```\n\nBecause my GraphQL server (Laravel) just allows the variable without quotes, in this way:\n\n```\n[{\n idImageService: 1,\n name: \"Service1\",\n url: \"\",\n key: \"sdofunc4938urcnnwikk\"\n}, {\n idImageService: 2,\n name: \"Service2\",\n url: \"sdsads\",\n key: \"sddsfsdssss8347yuirh\"\n}]\n```\n\nSo the function `JSON.stringify` don't work for build format in GraphQL. How can I convert the object array to GraphQL format in Javascript?\n\n========================================\n\nTop Answer:\nThere is a bug in Albert reply. If you have `\":` somewhere in your string like `\"field\": \"\\\"Hello\\\": World\"`, then after regexp replace you will end up with something like this: `field: \"\\\\Hello\\\\: World\"`.\n\nI fixed this by adding `[^\\\\\"]+` to the regexp, so it looks like\n\n`imageServicesClean.replace(/\"([^(\")\"]+[^\\\\\"]+)\":/g, \"$1:\");`\n\nI am not quite sure if this is a right fix and do not causes any bugs, but it works for me for now\n\n========================================\n\nCode:\n```text\nconst imageServicesClean = JSON.stringify(imageServices);\nconst query = `\n mutation {\n companyUpdate(\n idCompany:${idCompany},\n name:${nameClean},\n imageServices:${imageServicesClean})\n {\n idCompany\n name\n imageServices {\n idImageService\n name\n url\n key\n }\n }\n }`;\n```\n\n```text\n[{\n \"idImageService\": 1,\n \"name\": \"Service1\",\n \"url\": \"\",\n \"key\": \"asdasdas\"\n}, {\n \"idImageService\": 2,\n \"name\": \"Service2\",\n \"url\": \"sdsads\",\n \"key\": \"sddsfsds_\"\n}]\n```\n\n```text\n[{\n idImageService: 1,\n name: \"Service1\",\n url: \"\",\n key: \"sdofunc4938urcnnwikk\"\n}, {\n idImageService: 2,\n name: \"Service2\",\n url: \"sdsads\",\n key: \"sddsfsdssss8347yuirh\"\n}]\n```\n\n```text\nJSON.stringify\n```\n\n```text\nconst imageServicesClean = JSON.stringify(imageServices);\nconst graphQLImageServices = imageServicesClean.replace(/\"([^(\")\"]+)\":/g,\"$1:\");\n```\n\n```text\n\":\n```\n\n```text\n\"field\": \"\\\"Hello\\\": World\"\n```\n\n```text\nfield: \"\\\\Hello\\\\: World\"\n```\n\n```text\n[^\\\\\"]+\n```\n\n```text\nimageServicesClean.replace(/\"([^(\")\"]+[^\\\\\"]+)\":/g, \"$1:\");\n```\n\n========================================\n\nComments:\n- how about using `JSON.parse(imageServices)` ?\n- `JSON.parse` takes a JSON string as argument, which is not the case\n- Hi can i ask what the `(\")` does? I thought this will be sufficient `/\"([^\"]+)\":/g,\"$1:\"`, so i'm trying to understand what is the purpose of `(\")`. Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":160,"estimatedTokens":811}}858{"id":"stack-54678151","source":"stackoverflow","questionId":54678151,"title":"How to use arrays Schema Types for GraphQL","tags":["node.js","express","graphql","lodash","graphiql"],"text":"Title: How to use arrays Schema Types for GraphQL\nTags: node.js, express, graphql, lodash, graphiql\nSource: Stack Overflow\n\nQuestion:\nTrying out GraphQL for the first time, and I'd like for one Schema Type to have access to an array of objects within another Schema Type. I'm using local data and lodash to test this before I wire it up to MongoDB. I'm getting a few errors regarding my attempts at it. I know I'm close. Any assistance would be appreciated. \n\nThe following was my latest attempt. I accessed the GraphQLList using express-graphql and used GraphQLID to access the second schema.\n\n**schema.js**\n\n```\nvar projects = [\n{\n name: \"Title 1\",\n subtitle: \"Subtitle 1\",\n summary: \"Lorem ipsum....\",\n languageId: [\"4\", \"2\"],\n id: \"1\"\n},\n...\n\nvar languages = [\n{ name: \"Javascript\", id: \"1\" },\n{ name: \"HTML\", id: \"2\" },\n{ name: \"CSS\", id: \"3\" },\n{ name: \"Python\", id: \"4\" },\n]\n...\n\nconst ProjectType = new GraphQLObjectType({\nname: 'Project',\nfields: () => ({\n id: { type: GraphQLID },\n name: { type: GraphQLString },\n subtitle: { type: GraphQLString },\n summary: { type: GraphQLString },\n languages: {\n type: new GraphQLList(GraphQLID),\n resolve(parent, args) {\n console.log(parent)\n return _.find(languages, { id: parent.languageId })\n }\n }\n})\n});\n\nconst LanguageType = new GraphQLObjectType({\nname: 'Language',\nfields: () => ({\n id: { type: GraphQLID },\n name: { type: GraphQLString },\n })\n});\n\n//Root Queries\nconst RootQuery = new GraphQLObjectType({\nname: 'RootQueryType',\nfields: {\n project: {\n type: ProjectType,\n args: { id: { type: GraphQLID } },\n resolve(parent, args) {\n\n return _.find(projects, { id: args.id });\n }\n },\n language: {\n type: LanguageType,\n args: { id: { type: GraphQLID } },\n resolve(parent, args) {\n\n return _.find(languages, { id: args.id })\n }\n }\n }\n});\n```\n\nThe intention was to bring up a list of languages used in that project in Graphiql that would look something like this...\n\n```\n{\n \"data\": {\n \"project\": {\n \"name\": \"Project 1\"\n languages{\n names{\n \"Python\"\n \"HTML\" \n }\n }\n }\n }\n }\n```\n\nInstead I'm getting the following...\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Syntax Error: Expected Name, found }\",\n \"locations\": [\n {\n \"line\": 7,\n \"column\": 7\n }\n ]\n }\n ]\n}\n```\n\nI reformatted the resolve to hard code an array of languages, and that works, but it's not functional. Any suggestions would be greatly appreciated. Thank you all for your time.\n\n========================================\n\nTop Answer:\nI had a problem with an old project for my tags. in the end, I found it by try and catch u can use this \n tags: {type: GraphQLList(GraphQLString)},\n\n========================================\n\nCode:\n```text\nvar projects = [\n{\n name: \"Title 1\",\n subtitle: \"Subtitle 1\",\n summary: \"Lorem ipsum....\",\n languageId: [\"4\", \"2\"],\n id: \"1\"\n},\n...\n\nvar languages = [\n{ name: \"Javascript\", id: \"1\" },\n{ name: \"HTML\", id: \"2\" },\n{ name: \"CSS\", id: \"3\" },\n{ name: \"Python\", id: \"4\" },\n]\n...\n\nconst ProjectType = new GraphQLObjectType({\nname: 'Project',\nfields: () => ({\n id: { type: GraphQLID },\n name: { type: GraphQLString },\n subtitle: { type: GraphQLString },\n summary: { type: GraphQLString },\n languages: {\n type: new GraphQLList(GraphQLID),\n resolve(parent, args) {\n console.log(parent)\n return _.find(languages, { id: parent.languageId })\n }\n }\n})\n});\n\nconst LanguageType = new GraphQLObjectType({\nname: 'Language',\nfields: () => ({\n id: { type: GraphQLID },\n name: { type: GraphQLString },\n })\n});\n\n//Root Queries\nconst RootQuery = new GraphQLObjectType({\nname: 'RootQueryType',\nfields: {\n project: {\n type: ProjectType,\n args: { id: { type: GraphQLID } },\n resolve(parent, args) {\n\n return _.find(projects, { id: args.id });\n }\n },\n language: {\n type: LanguageType,\n args: { id: { type: GraphQLID } },\n resolve(parent, args) {\n\n return _.find(languages, { id: args.id })\n }\n }\n }\n});\n```\n\n```text\n{\n \"data\": {\n \"project\": {\n \"name\": \"Project 1\"\n languages{\n names{\n \"Python\"\n \"HTML\" \n }\n }\n }\n }\n }\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Syntax Error: Expected Name, found }\",\n \"locations\": [\n {\n \"line\": 7,\n \"column\": 7\n }\n ]\n }\n ]\n}\n```\n\n```text\nconst ProjectType = new GraphQLObjectType({\n name: 'Project',\n fields: () => ({\n id: {type: GraphQLID},\n name: {type: GraphQLString},\n subtitle: {type: GraphQLString},\n summary: {type: GraphQLString},\n languages: {\n\n // change this type to LanguageType\n type: new GraphQLList(LanguageType),\n resolve(parent, args) {\n // No need to lodash here\n return languages.filter((language) => {\n return parent.languageId.includes(language.id)\n })\n }\n }\n })\n});\n```\n\n```text\nLanguages\n```\n\n```text\nProjects\n```\n\n```text\nlanguages\n```\n\n========================================\n\nComments:\n- That certainly got me closer. I'm now getting the following response in GraphiQL `{ \"data\": { \"project\": { \"name\": \"Title 1\", \"summary\": \"Summary 1\", \"languages\": [] } } }` The array is still empty though. I tried reformatting the dummy data so that the languages category was an array of objects. Still turned up empty, but the console log returned everything just fine.\n- I'm currently attempting to reverse the one-to-many relationship in the schema, so instead of relating one project to many languages, I'd have one language to many projects. However, I feel like that's the wrong way to go as it will have adverse consequences on the front-end.\n- Hey @AaronToliver, I update my answer. There was a problem on fetching the languages. There's no need to use lodash there, a simple filter does the work.\n- Thank you @MarcoDaniels. It's console logging perfectly now. I think I'm using the query wrong in GraphiQL, but I'll check out the documentation. Many thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.088Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":268,"estimatedTokens":1531}}859{"id":"stack-66807364","source":"stackoverflow","questionId":66807364,"title":"How can you control the serialization of Enum values in HotChocolate?","tags":["asp.net-core","graphql","hotchocolate"],"text":"Title: How can you control the serialization of Enum values in HotChocolate?\nTags: asp.net-core, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nHotChocolate serializes enum values in all upper snail case, which leads to\nbeing the enum value `FooBar` being inferred as `FOO_BAR` by Hot Chocolate, but `value.ToString()` and `Enum.GetName(value)` gives FooBar, and Hot Chocolate seems to ignore `[EnumMember(Value = \"FooBar\")]`.\n\nHow can I change the serialization to any way I'd like?\n\n========================================\n\nTop Answer:\nIf you would like to do some custom serialization and deserialization of enum values, like using `Description` instead of the `Enum Value` then do the following:\n\n```\npublic enum Colour\n{\n [Description(\"Red\")] RedColour,\n [Description(\"Blue\")] BlueColour,\n}\n\npublic class ColourEnumType : EnumType\n{\n protected override void Configure(IEnumTypeDescriptor descriptor)\n {\n descriptor.Name(\"CustomColour\").Description(\"Custom colour enum\").EnumTypeSerialization();\n }\n}\n\ninternal static void EnumTypeSerialization(this IEnumTypeDescriptor descriptor)\n where TEnum : struct, Enum\n{\n var enumValues = Enum.GetValues();\n foreach (var value in enumValues)\n descriptor.Value(value).Name(value.GetDescription());\n}\n```\n\nYou can now register the `ColourEnumType` in the service collection and `HotChocolate` will then correctly return the enum description instead of the value.\n\n```\nserviceCollection.AddGraphQLServer()\n .AddQueryType()\n .AddType()\n```\n\nI have tested this on `HotChocolate v13.0.5` and you need to write the code for the `GetDescription()` method.\n\nOne last thing to remember though is to make sure that your enum description values are GraphQL compliant. If they arent, then you need to either change your descriptions or sanitize your results during the serialization process. If not, it will cause `HotChocolate` to crash with errors that will be very hard to debug.\n\n========================================\n\nCode:\n```text\nFooBar\n```\n\n```text\nFOO_BAR\n```\n\n```text\nvalue.ToString()\n```\n\n```text\nEnum.GetName(value)\n```\n\n```text\n[EnumMember(Value = \"FooBar\")]\n```\n\n```cs\nbuilder\n .AddConvention<INamingConventions>(new YourNamingConvention())\n```\n\n```cs\npublic class YourNamingConvention\n : DefaultNamingConventions\n {\n public override NameString GetEnumValueName(object value)\n {\n if (value == null)\n {\n throw new ArgumentNullException(nameof(value));\n }\n return value.ToString().ToUpperInvariant(); // change this to whatever you like\n }\n }\n```\n\n```cs\npublic enum Colour\n{\n [Description(\"Red\")] RedColour,\n [Description(\"Blue\")] BlueColour,\n}\n\npublic class ColourEnumType : EnumType<Colour>\n{\n protected override void Configure(IEnumTypeDescriptor<Colour> descriptor)\n {\n descriptor.Name(\"CustomColour\").Description(\"Custom colour enum\").EnumTypeSerialization();\n }\n}\n\ninternal static void EnumTypeSerialization<TEnum>(this IEnumTypeDescriptor<TEnum> descriptor)\n where TEnum : struct, Enum\n{\n var enumValues = Enum.GetValues<TEnum>();\n foreach (var value in enumValues)\n descriptor.Value(value).Name(value.GetDescription());\n}\n```\n\n```cs\nserviceCollection.AddGraphQLServer()\n .AddQueryType<QueryType>()\n .AddType<ColourEnumType>()\n```\n\n```text\nDescription\n```\n\n```text\nEnum Value\n```\n\n```text\nColourEnumType\n```\n\n```text\nHotChocolate\n```\n\n```text\nHotChocolate v13.0.5\n```\n\n```text\nGetDescription()\n```\n\n```text\nHotChocolate\n```\n\n========================================\n\nComments:\n- Any clue as to why they pass in object and not an Enum to this?\n- I want to return the enum description, is that possible?","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":157,"estimatedTokens":934}}860{"id":"stack-54950868","source":"stackoverflow","questionId":54950868,"title":"GraphQL.NET how to add an enum to a GraphQL Type","tags":["asp.net",".net","asp.net-core",".net-core","graphql"],"text":"Title: GraphQL.NET how to add an enum to a GraphQL Type\nTags: asp.net, .net, asp.net-core, .net-core, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a simple enum that I am trying to include in my GraphQL type and am receiving the following error:\n\nThe GraphQL type for Field: 'Category' on parent type: 'NewsItemType'\ncould not be derived implicitly.\n\n------------------The GraphQL type for Field: 'Category' on parent type: 'NewsItemType' could not be derived implicitly.\n\n---------------The type: NewsType cannot be coerced effectively to a GraphQL type Parameter name: type\n\nmy simple enum looks like:\n\n```\npublic enum NewsType\n{\n General = 0,\n Business = 1,\n Entertainment = 2,\n Sports = 3,\n Technology = 4\n}\n```\n\nThe GraphQL `ObjectGraphType` that it is included in:\n\n```\npublic class NewsItemType : ObjectGraphType\n{\n public NewsItemType()\n {\n Field(x => x.Id).Description(\"Id of a news item.\");\n Field(x => x.Title).Description(\"Title of a new item.\");\n Field(x => x.Description).Description(\"Description of a news item.\");\n Field(x => x.Author).Description(\"Author of a news item.\");\n Field(x => x.Url).Description(\"URI location of the news item\");\n Field(x => x.ImageUrl).Description(\"URI location of the image for the news item\");\n Field(x => x.PublishDate).Description(\"Date the news item was published\");\n Field(x => x.Category).Description(\"Category of the news item.\");\n }\n}\n```\n\nand finally, the view model that the GraphQL type is based on:\n\n```\npublic class NewsItemViewModel : ViewModelBase\n{\n public string Title { get; set; }\n public string Author { get; set; }\n public string Description { get; set; }\n public string Url { get; set; }\n public string ImageUrl { get; set; }\n public DateTime PublishDate { get; set; }\n public NewsType Category { get; set; }\n}\n```\n\nWhat am I doing wrong here and how can I overcome it?\n\nEDIT:\nmy query contains the following:\n\n```\nField>(\n name: \"newsItems\",\n arguments: new QueryArguments(\n new QueryArgument() { Name = \"count\" },\n new QueryArgument() { Name = \"category\" }),\n resolve: context =>\n {\n var count = context.GetArgument(\"count\");\n var category = context.GetArgument(\"category\");\n var newsType = (NewsType)category;\n\n if (count.HasValue)\n {\n return newsItemService.GetMostRecent(newsType, count.Value);\n }\n else\n {\n return newsItemService.GetMostRecent(newsType);\n }\n }\n )\n```\n\n========================================\n\nTop Answer:\nHere's a quick way to do this for your case. Basically you don't use the default lambda expression `Field`. Instead actually write out a resolver yourself and convert the enum to the proper type. This is helping GraphQL to convert the type properly into the type you want to return.\n\n```\nField(\"category\", resolve: context => (int)context.Source.Category);\n```\n\nIf your enum was a string, you could do the same for that as well.\n\n```\nField(\"category\", resolve: context => context.Source.Category.ToString());\n```\n\nThere is another, more verbose way, shared in this answer where you inherit from the `EnumerationGraphType` first and then do the same custom resolver as above.\n\nhttps://stackoverflow.com/a/56051133/11842628\n\n========================================\n\nCode:\n```text\npublic enum NewsType\n{\n General = 0,\n Business = 1,\n Entertainment = 2,\n Sports = 3,\n Technology = 4\n}\n```\n\n```text\npublic class NewsItemType : ObjectGraphType<NewsItemViewModel>\n{\n public NewsItemType()\n {\n Field(x => x.Id).Description(\"Id of a news item.\");\n Field(x => x.Title).Description(\"Title of a new item.\");\n Field(x => x.Description).Description(\"Description of a news item.\");\n Field(x => x.Author).Description(\"Author of a news item.\");\n Field(x => x.Url).Description(\"URI location of the news item\");\n Field(x => x.ImageUrl).Description(\"URI location of the image for the news item\");\n Field(x => x.PublishDate).Description(\"Date the news item was published\");\n Field(x => x.Category).Description(\"Category of the news item.\");\n }\n}\n```\n\n```text\npublic class NewsItemViewModel : ViewModelBase\n{\n public string Title { get; set; }\n public string Author { get; set; }\n public string Description { get; set; }\n public string Url { get; set; }\n public string ImageUrl { get; set; }\n public DateTime PublishDate { get; set; }\n public NewsType Category { get; set; }\n}\n```\n\n```text\nField<ListGraphType<NewsItemType>>(\n name: \"newsItems\",\n arguments: new QueryArguments(\n new QueryArgument<IntGraphType>() { Name = \"count\" },\n new QueryArgument<IntGraphType>() { Name = \"category\" }),\n resolve: context =>\n {\n var count = context.GetArgument<int?>(\"count\");\n var category = context.GetArgument<int>(\"category\");\n var newsType = (NewsType)category;\n\n if (count.HasValue)\n {\n return newsItemService.GetMostRecent(newsType, count.Value);\n }\n else\n {\n return newsItemService.GetMostRecent(newsType);\n }\n }\n )\n```\n\n```text\nObjectGraphType\n```\n\n```text\npublic class NewsEnumType : EnumerationGraphType<NewsType>\n{\n}\n```\n\n```text\nField<NewsEnumType>(nameof(NewsItemViewModel.Category)).Description(\"Category of the news item.\");\n```\n\n```text\nField<ListGraphType<NewsItemType>>(\n name: \"newsItems\",\n arguments: new QueryArguments(\n new QueryArgument<IntGraphType>() { Name = \"count\" },\n new QueryArgument<IntGraphType>() { Name = \"category\" }),\n resolve: context =>\n {\n var count = context.GetArgument<int?>(\"count\");\n var category = context.GetArgument<int>(\"category\");\n var newsType = (NewsType)category;\n\n if (count.HasValue)\n {\n return newsItemService.GetMostRecent(newsType, count.Value);\n }\n else\n {\n return newsItemService.GetMostRecent(newsType);\n }\n }\n )\n```\n\n```text\nIntGraphType\n```\n\n```text\n(NewsType)category\n```\n\n```text\nnew QueryArgument<NewsItemType>() { Name = \"newsItem\" },\n```\n\n```text\ncategory\n```\n\n```text\nBusiness = 1\n```\n\n```text\ncategory: 'Business'\n```\n\n```text\ncategory: 1\n```\n\n```text\nField<IntGraphType>(\"category\", resolve: context => (int)context.Source.Category);\n```\n\n```text\nField<StringGraphType>(\"category\", resolve: context => context.Source.Category.ToString());\n```\n\n```text\nField\n```\n\n```text\nEnumerationGraphType<T>\n```\n\n========================================\n\nComments:\n- Thanks for the answer. I ran into this too. It's disappointing, because the GraphQL .NET documentation explicitly states that the \"Expression syntax\" should work in this case. Maybe it's a bug?","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":263,"estimatedTokens":1711}}861{"id":"stack-51165181","source":"stackoverflow","questionId":51165181,"title":"graphql with sequelize join foreign key","tags":["sequelize.js","graphql"],"text":"Title: graphql with sequelize join foreign key\nTags: sequelize.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI made simple board api system with graphql.\n\nAnd I use sequelize(version 4) for connect to database.\n\n[schema.graphql]\n\n```\ntype Article {\n article_no: Int!\n subject: String!\n content: String!\n createdAt: String!\n updatedAt: String!\n comment: String\n}\n\ntype Comment {\n article_no: Int!\n content: String!,\n createdAt: String!\n}\n\ntype Query {\n articles: [Article]!\n article(article_no: Int!): Article\n comments: [Comment]!\n comment(article_no: Int!): Comment\n}\n\ntype Mutation {\n createArticle(subject: String!, content: String!, password: String!): Boolean!\n createComment(article_no: Int!, content: String!, password: String!): Boolean!\n}\n```\n\n[resolvers.js]\n\n```\nimport { Article, Comment } from './db';\n\nconst resolvers = {\n Query: {\n articles: async () => {\n return Article.all();\n },\n article: async(_, args) => {\n return Article.find({\n where: args.article_no,\n });\n },\n comments: async () => {\n return Comment.all();\n },\n comment: async(_, args) => {\n return Comment.find({\n where: args.article_no\n });\n }\n },\n Mutation: {\n createArticle: async (_, args) => {\n try {\n const article = await Article.create({\n subject: args.subject,\n content: args.content,\n password: args.password\n });\n return true;\n } catch(e) {\n return false;\n }\n },\n createComment: async(_, args) => {\n try {\n const comment = await Comment.create({\n article_no: args.article_no,\n content: args.content,\n password: args.password\n })\n return comment;\n } catch(e) {\n return false;\n }\n }\n }\n}\n\nexport default resolvers;\n```\n\n[db.js]\n\n```\nconst Sequelize = require('sequelize');\nimport config from '../config/config';\n\nconst db = new Sequelize(config.DB, config.USER, config.PASS, {\n host: 'localhost',\n dialect: 'mysql'\n})\n\nexport const Article = db.define('article', {\n article_no: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n subject: {\n type: Sequelize.STRING(30),\n allowNull: false\n },\n content: {\n type: Sequelize.STRING(100),\n allowNull: false\n },\n password: {\n type: Sequelize.STRING(20),\n allowNull: false\n },\n comment: Sequelize.STRING\n}, {\n freezeTableName: true,\n timestamps: true,\n underscored: true\n})\n\nexport const Comment = db.define('comment', {\n content: {\n type: Sequelize.STRING(150),\n allowNull: false\n },\n password: {\n type: Sequelize.STRING(20),\n allowNull: false\n },\n}, {\n freezeTableName: true,\n timestamps: true,\n underscored: true\n})\n\nArticle.hasMany(Comment, {\n foreignKey: 'article_no',\n scope: {\n comment: 'comment'\n }\n})\nComment.belongsTo(Article, {\n foreignKey: 'article_no',\n targetKey: 'article_no',\n allowNull: false,\n as: 'comment'\n});\ndb.sync()\n.then(console.log('[*] DB Sync Done'))\n```\n\n`Article` and `Comment` is 1:N realtionship.\n\nSo I set `hasMany` to `Article` and set `belongsTo` to `Comment`.\n\nAlso Comment as comment and include it to Article's scope.\n\nBut when I request query `{ article(id:1) { subject, comment } }`,\n\ncomment return null.\n\nI refer document http://docs.sequelizejs.com/manual/tutorial/associations.html#foreign-keys and as well.\n\nBut it doesn't work.\n\nMy Expected result is here:\n\n```\n{\n \"data\": {\n \"article\": {\n \"subject\": \"test\",\n \"comment\": {\n \"article_no\":1,\n \"content: \"first comment\",\n \"created_at\": \"2018010101001\",\n # every comment related article is here\n }\n }\n }\n}\n```\n\nCurrent result is here:\n\n```\n{\n \"data\": {\n \"article\": {\n \"subject\": \"test\",\n \"comment\": null\n }\n }\n}\n```\n\nI want to display all the comments that related specific article.\n\nIs there any solution about this?\n\nThanks.\n\n========================================\n\nTop Answer:\nThere are problems with your graphql schema, and your sequelize schema...\n\nLets look at your graphql schema\n\ntype Article {\n ...\n comment: String\n}\n\nYou wrote that Article and Comment have a 1:M relation\nbut here the comment field is of type string and not even an array of string\n\nthe correct type definition for Article should be (imo):\n\ntype Article {\n ...\n comments: [Comment] \n}\n\nnow if you make the adjustments to your sequelize schema that @Daniel-Rearden\nwrote in his answer your `Article` model should have a `comments` property so it will be returned by default from the `default resolver` of the `Article` type\n\n========================================\n\nCode:\n```text\ntype Article {\n article_no: Int!\n subject: String!\n content: String!\n createdAt: String!\n updatedAt: String!\n comment: String\n}\n\ntype Comment {\n article_no: Int!\n content: String!,\n createdAt: String!\n}\n\ntype Query {\n articles: [Article]!\n article(article_no: Int!): Article\n comments: [Comment]!\n comment(article_no: Int!): Comment\n}\n\ntype Mutation {\n createArticle(subject: String!, content: String!, password: String!): Boolean!\n createComment(article_no: Int!, content: String!, password: String!): Boolean!\n}\n```\n\n```text\nimport { Article, Comment } from './db';\n\nconst resolvers = {\n Query: {\n articles: async () => {\n return Article.all();\n },\n article: async(_, args) => {\n return Article.find({\n where: args.article_no,\n });\n },\n comments: async () => {\n return Comment.all();\n },\n comment: async(_, args) => {\n return Comment.find({\n where: args.article_no\n });\n }\n },\n Mutation: {\n createArticle: async (_, args) => {\n try {\n const article = await Article.create({\n subject: args.subject,\n content: args.content,\n password: args.password\n });\n return true;\n } catch(e) {\n return false;\n }\n },\n createComment: async(_, args) => {\n try {\n const comment = await Comment.create({\n article_no: args.article_no,\n content: args.content,\n password: args.password\n })\n return comment;\n } catch(e) {\n return false;\n }\n }\n }\n}\n\nexport default resolvers;\n```\n\n```text\nconst Sequelize = require('sequelize');\nimport config from '../config/config';\n\nconst db = new Sequelize(config.DB, config.USER, config.PASS, {\n host: 'localhost',\n dialect: 'mysql'\n})\n\nexport const Article = db.define('article', {\n article_no: {\n type: Sequelize.INTEGER,\n primaryKey: true,\n autoIncrement: true\n },\n subject: {\n type: Sequelize.STRING(30),\n allowNull: false\n },\n content: {\n type: Sequelize.STRING(100),\n allowNull: false\n },\n password: {\n type: Sequelize.STRING(20),\n allowNull: false\n },\n comment: Sequelize.STRING\n}, {\n freezeTableName: true,\n timestamps: true,\n underscored: true\n})\n\nexport const Comment = db.define('comment', {\n content: {\n type: Sequelize.STRING(150),\n allowNull: false\n },\n password: {\n type: Sequelize.STRING(20),\n allowNull: false\n },\n}, {\n freezeTableName: true,\n timestamps: true,\n underscored: true\n})\n\nArticle.hasMany(Comment, {\n foreignKey: 'article_no',\n scope: {\n comment: 'comment'\n }\n})\nComment.belongsTo(Article, {\n foreignKey: 'article_no',\n targetKey: 'article_no',\n allowNull: false,\n as: 'comment'\n});\ndb.sync()\n.then(console.log('[*] DB Sync Done'))\n```\n\n```text\n{\n \"data\": {\n \"article\": {\n \"subject\": \"test\",\n \"comment\": {\n \"article_no\":1,\n \"content: \"first comment\",\n \"created_at\": \"2018010101001\",\n # every comment related article is here\n }\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"article\": {\n \"subject\": \"test\",\n \"comment\": null\n }\n }\n}\n```\n\n```text\nArticle\n```\n\n```text\nComment\n```\n\n```text\nhasMany\n```\n\n```text\nArticle\n```\n\n```text\nbelongsTo\n```\n\n```text\nComment\n```\n\n```text\n{ article(id:1) { subject, comment } }\n```\n\n```text\nArticle.findAll({ include: [Comment] })\n```\n\n```text\nArticle.addScope('defaultScope', {\n include: [Comment],\n}, { override: true })\n```\n\n```text\nArticle.find({ where: { article_no: args.article_no } })\n\n// or possibly even\nArticle.find({ where: args })\n```\n\n```text\nArticle.hasMany(Comment)\n```\n\n```text\ncomments\n```\n\n```text\nArticle\n```\n\n```text\nComment\n```\n\n```text\nComment.belongsTo(Article)\n```\n\n```text\narticle\n```\n\n```text\nComment\n```\n\n```text\nArticle\n```\n\n```text\ninclude\n```\n\n```text\naddScope\n```\n\n```text\noverride\n```\n\n```text\ninclude\n```\n\n```text\nwhere\n```\n\n```text\nfind\n```\n\n```text\ntype Article {\n ...\n comment: String\n}\n```\n\n```text\ntype Article {\n ...\n comments: [Comment] \n}\n```\n\n```text\nArticle\n```\n\n```text\ncomments\n```\n\n```text\ndefault resolver\n```\n\n```text\nArticle\n```\n\n========================================\n\nComments:\n- You said `if you call Article.hasMany(Comment), this will create a comments property on the Article model and will affect the Comment model`. But after I check the database, there is no additional column. So I think, additional column doesn't apply to real database, right?\n- And, should I set both `Article.hasMany(Comment)` and `Comment.belongsTo(Article)` in 1:N relationship? Or just set one relationship between that?\n- If I remember correctly, either `hasMany` or `belongsTo` should create the appropriate column (in this case in the articles table). Whether you use one or the other, or both depends on, again, whether you need your Article model instance to have a `comments` property or you need your Comments model instance to have an `article` property (or both).\n- FWIW, when using `sequelize.sync()` you may need to set the `force` option to true to see your changes applied to your db (docs.sequelizejs.com/class/lib/…)\n- Thanks! I will try it.\n- `Comment[]` is throw errors `Syntax Error: Expected Name, found [`. Maybe `[Comment]` is correct way.","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":555,"estimatedTokens":2497}}862{"id":"stack-58713598","source":"stackoverflow","questionId":58713598,"title":"Relations don't work properly in TypeGraphQL (You need to provide explicit type for...)","tags":["javascript","graphql","typeorm","typegraphql"],"text":"Title: Relations don't work properly in TypeGraphQL (You need to provide explicit type for...)\nTags: javascript, graphql, typeorm, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI want to create a simple relation between a user and documents in TypeGraphQL. So a user can create unlimited documents and a document has only one creator. But I am receiving an error.\n\n### User\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity, OneToMany } from \"typeorm\";\nimport { Field, ID, ObjectType } from \"type-graphql\";\n\nimport { Doc } from \"./Doc\";\n\n@ObjectType()\n@Entity()\nexport class User extends BaseEntity {\n @Field(() => ID)\n @PrimaryGeneratedColumn()\n id: number;\n\n @Field()\n @Column()\n firstName: string;\n\n @Field()\n @Column()\n lastName: string;\n\n @Field()\n @Column()\n nickname: string;\n\n @Field()\n @Column(\"text\", { unique: true })\n email: string;\n\n @Column()\n password: string;\n\n @Field({ nullable: true })\n @Column()\n created: Date;\n\n @Field()\n @Column()\n gender: string;\n\n @OneToMany(() => Doc, doc => doc.creator)\n createdDocs: Promise;\n}\n```\n\n### Doc\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity, ManyToOne } from \"typeorm\";\nimport { Field, ID, ObjectType } from \"type-graphql\";\n\nimport { User } from \"./User\";\n\n@ObjectType()\n@Entity()\nexport class Doc extends BaseEntity {\n @Field(() => ID)\n @PrimaryGeneratedColumn()\n id: number;\n\n @Field({ nullable: true })\n @Column()\n created: Date;\n\n @Field()\n @Column()\n @ManyToOne(() => User, user => user.createdDocs)\n creator: Promise;\n}\n```\n\n### Error\n\n```\nthrow new errors_1.NoExplicitTypeError(prototype.constructor.name, propertyKey, parameterIndex);\n ^\nError: You need to provide explicit type for Doc#creator !\n```\n\nBut what is causing this to happen? Of couse the column creator in the table doc is not a real \"data-type\", because it shouldn't be \"static\". It needs to be a relation and this relation can't obviously has a \"data-type\".\n\n========================================\n\nTop Answer:\nError: You need to provide explicit type for Doc#creator !\n\nIt means that, when your property type is `Promise`, the reflected type is `Object`. TypeGraphQL in that case need explicit type in decorator, like `@Field(type => User)`.\n\n========================================\n\nCode:\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity, OneToMany } from \"typeorm\";\nimport { Field, ID, ObjectType } from \"type-graphql\";\n\nimport { Doc } from \"./Doc\";\n\n@ObjectType()\n@Entity()\nexport class User extends BaseEntity {\n @Field(() => ID)\n @PrimaryGeneratedColumn()\n id: number;\n\n @Field()\n @Column()\n firstName: string;\n\n @Field()\n @Column()\n lastName: string;\n\n @Field()\n @Column()\n nickname: string;\n\n @Field()\n @Column(\"text\", { unique: true })\n email: string;\n\n @Column()\n password: string;\n\n @Field({ nullable: true })\n @Column()\n created: Date;\n\n @Field()\n @Column()\n gender: string;\n\n @OneToMany(() => Doc, doc => doc.creator)\n createdDocs: Promise<Doc[]>;\n}\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity, ManyToOne } from \"typeorm\";\nimport { Field, ID, ObjectType } from \"type-graphql\";\n\nimport { User } from \"./User\";\n\n@ObjectType()\n@Entity()\nexport class Doc extends BaseEntity {\n @Field(() => ID)\n @PrimaryGeneratedColumn()\n id: number;\n\n @Field({ nullable: true })\n @Column()\n created: Date;\n\n @Field()\n @Column()\n @ManyToOne(() => User, user => user.createdDocs)\n creator: Promise<User>;\n}\n```\n\n```text\nthrow new errors_1.NoExplicitTypeError(prototype.constructor.name, propertyKey, parameterIndex);\n ^\nError: You need to provide explicit type for Doc#creator !\n```\n\n```text\n@Field()\n```\n\n```text\n@Column()\n```\n\n```text\nPromise<User>\n```\n\n```text\nObject\n```\n\n```text\n@Field(type => User)\n```\n\n```text\n@Field(() => User) # Try this\n@ManyToOne(() => User, user => user.createdDocs)\ncreator: Promise<User>\n```\n\n========================================\n\nComments:\n- For me, there was a need to declare the relations with `@Field()`","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":205,"estimatedTokens":1018}}863{"id":"stack-54620278","source":"stackoverflow","questionId":54620278,"title":"When using GraphQL/Apollo Server, should an error be thrown for no database results?","tags":["arrays","graphql","apollo-server"],"text":"Title: When using GraphQL/Apollo Server, should an error be thrown for no database results?\nTags: arrays, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nIf a resolver gets a user from a database for example and no user was not found, should an error be thrown? What is best practice for no data found?\n\n========================================\n\nTop Answer:\nI would say that's really up to you and the schema you've defined.\n\nIf you have a schema like\n\n```\ntype Query {\n # allow null to be returned\n user(where: FindUserInput): User\n}\n```\n\nthen you could return null when no user is found.\n\nIf your schema doesn't allow returning `null`, like\n\n```\ntype Query {\n # only allowed to return a valid User object\n user(where: FindUserInput): User!\n}\n```\n\nthen throwing an error is the way to go.\n\nI don't believe there is an absolute best practice, it's more about what behavior you're looking for in your project.\n\n========================================\n\nCode:\n```text\ntype Query {\n user(username: String!): User\n}\n```\n\n```text\nnull\n```\n\n```text\nerrors\n```\n\n```text\nerrors\n```\n\n```text\nerrors\n```\n\n```text\ntype Query {\n # allow null to be returned\n user(where: FindUserInput): User\n}\n```\n\n```text\ntype Query {\n # only allowed to return a valid User object\n user(where: FindUserInput): User!\n}\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- If you know you're going to occasionally throw an error for the `user` field here, it would actually be better to make the field nullable. Because of the way GraphQL handles errors and nullability, a non-null will cause your entire `data` property to return null. Making `user` nullable means you can request other queries and still get a partial response for *those* fields, along with your error.\n- By that reasoning, shouldn't all root queries allow for null to be returned, so as to allow for partial responses? Or am I missing something?\n- Not necessarily. Let's assume our entire endpoint is gated in such a way that I can't access it unless I'm logged in. Now let's say I have a `viewer` field that returns the currently logged in User, and maybe a `config` field that returns some info. Here, `viewer` should always exist and I can make it non-null. If something goes terribly wrong and we return null, fine, blow up the whole query.\n- On the other hand, imagine we don't gate the endpoint and want to be able to request the `viewer` field as a way to check if we're currently logged in. As a client, I want to be able to request both fields to render my home page appropriately. Making `viewer` non-null will force me to either fetch `config` separately or implement some kind of retry logic.\n- Mind you, this concern applies to all fields, not just root-level ones. A non-null field that throws because it resolves to null will \"bubble up\" all the way to the first available nullable parent.\n- The point is: if business rules dictate that a field could end up null (whether because the data doesn't exist or because we're **choosing** to throw some kind of error in some scenario), that field shouldn't be marked as non-null.\n- @DanielRearden Got it. Thank you for these very detailed explanations, Daniel, very enlightening!\n- That's a very interesting take, Daniel. So if there are business logic errors, should they be moved to the response itself - for example creating a `UserResponse` type that would have a nullable `user: User` field and a nullable `error` field of type `String` or `[String!]` or `Error`? So as to keep business logic errors separate from 'pure' GraphQL errors?\n- The use cases I have in mind are varied: an invalid auth token, a malformed auth header, a user without the role/permissions to execute a query/mutation, etc.\n- All those scenarios are ones I wouldn't expect to encounter during normal use of the API. If you're processing some query, attempt to get the user from the JWT token and determine that user doesn't exist in the database, by all means throw an error. I don't know if I would go as far as to wrap all my Query type fields with some kind of `Response` type.\n- On the other hand, this is a common pattern for mutations. For example, take a look at how Shopify does things.\n- Thank you, very interesting to see the varied approaches to handling business logic errors.\n- @DanielRearden Thank you for the response. This discussion is literally about what we are facing with our current API. We have been using Mutation Response Types for some time now. We also started using Query Response Types to standardize the flow of data. For the past month we have been migrating one of the APIs to throwing errors, using Apollo Error objects and the whole thing has gotten messy and difficult to reason about. Allot of sleep has been lost on should we remove the Query Response Types or leave them be.\n- I've actually started a post on this topic as I cannot find any real discussions on it: stackoverflow.com/questions/54657425/…","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":96,"estimatedTokens":1241}}864{"id":"stack-62867425","source":"stackoverflow","questionId":62867425,"title":"Sorting results in AWS Amplify GraphQL without filtering","tags":["graphql","aws-amplify"],"text":"Title: Sorting results in AWS Amplify GraphQL without filtering\nTags: graphql, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nProvided a very simple model in `graphql.schema`, how would I perform a simple sort query?\n\n```\ntype Todo @model\n id: ID!\n text: String!\n}\n```\n\nWhich generates the following in `queries.js`.\n\n```\nexport const listTodos = /* GraphQL */ `\n query ListTodos(\n $filter: ModelTodoFilterInput\n $limit: Int\n $nextToken: String\n ) {\n listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {\n items {\n id\n text\n }\n nextToken\n }\n }\n`;\n```\n\nI have found multiple sources pointing me in the direction of the `@key` directive. This similar question addresses that approach (GraphQL with AWS Amplify - how to enable sorting on query).\n\nWhile that may seem promising and successfully generates new queries I can use, all the approaches I have tried require that I filter the data before sorting it. All I want to do is sort my todo results on a given column name, with a given sort direction (ASC/DESC).\n\nThis is how I would perform a simple (unsorted) query:\n`const todos = await API.graphql(graphqlOperation(listTodos));`\n\nI would be looking to do something along the lines of:\n`const todos = await API.graphql(graphqlOperation(listTodos, {sortField: \"text\", sortDirection: \"ASC\"} ))`.\n\n========================================\n\nTop Answer:\nDecorate your model with the `@searchable` directive, like so:\n\n```\ntype Todo @model @searchable\n{\n id: ID!\n text: String!\n}\n```\n\nAfter that, you can query your data with sorting capabilities like below:\n\n```\nimport { searchToDos } from '../graphql/queries';\nimport { API, graphqlOperation } from 'aws-amplify';\n\nconst toDoData = await API.graphql(graphqlOperation(searchToDos, {\n sort: {\n direction: 'asc',\n field: 'text'\n }\n}));\nconsole.log(toDoData.data.searchToDos.items);\n```\n\nFor more information, see\n\n- https://github.com/aws-amplify/amplify-cli/issues/1851#issuecomment-545245633\n\n- https://docs.amplify.aws/cli/graphql-transformer/directives#searchable\n\n========================================\n\nCode:\n```text\ntype Todo @model\n id: ID!\n text: String!\n}\n```\n\n```text\nexport const listTodos = /* GraphQL */ `\n query ListTodos(\n $filter: ModelTodoFilterInput\n $limit: Int\n $nextToken: String\n ) {\n listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {\n items {\n id\n text\n }\n nextToken\n }\n }\n`;\n```\n\n```text\ngraphql.schema\n```\n\n```text\nqueries.js\n```\n\n```text\n@key\n```\n\n```text\nconst todos = await API.graphql(graphqlOperation(listTodos));\n```\n\n```text\nconst todos = await API.graphql(graphqlOperation(listTodos, {sortField: \"text\", sortDirection: \"ASC\"} ))\n```\n\n```text\ntype Todo @model {\n id: ID!\n title: String!\n type: String! @index(name: \"todosByDate\", queryField: \"todosByDate\", sortKeyFields: [\"createdAt\"])\n createdAt: String!\n}\n```\n\n```text\nquery todosByDate {\n todosByDate(\n type: \"Todo\"\n sortDirection: ASC\n ) {\n items {\n id\n title\n createdAt\n }\n }\n}\n```\n\n```text\n@searchable\n```\n\n```text\n@index\n```\n\n```text\n@index\n```\n\n```text\nqueryField\n```\n\n```text\nsortKeyField\n```\n\n```text\n@searchable\n```\n\n```text\ntype Todo @model @searchable\n{\n id: ID!\n text: String!\n}\n```\n\n```text\nimport { searchToDos } from '../graphql/queries';\nimport { API, graphqlOperation } from 'aws-amplify';\n\nconst toDoData = await API.graphql(graphqlOperation(searchToDos, {\n sort: {\n direction: 'asc',\n field: 'text'\n }\n}));\nconsole.log(toDoData.data.searchToDos.items);\n```\n\n```text\n@searchable\n```\n\n========================================\n\nComments:\n- Doesn't that require an additional dependency to AWS Elasticsearch (and additional server costs?)\n- Yes, this was the only approach (without filtering) I can find at the time of writing. Using AWS Elasticsearch might be worth it if you consider the flexibility & performance ElasticSearch offers over normal DB search queries. Check out this article: aws.amazon.com/blogs/startups/…\n- The other option is you can do client-side sorting, but that'd only work efficiently for small datasets.\n- ahem...what? It's not clear at all\n- To be fair, when the answer was given back in 2020, I think @index was not an option. This is definitely a better and more updated approach.","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":207,"estimatedTokens":1072}}865{"id":"stack-49919222","source":"stackoverflow","questionId":49919222,"title":"GraphQL query, use fragment depending on some condition. GraphQL file loaded","tags":["graphql","react-apollo","apollo-client","apollostack"],"text":"Title: GraphQL query, use fragment depending on some condition. GraphQL file loaded\nTags: graphql, react-apollo, apollo-client, apollostack\nSource: Stack Overflow\n\nQuestion:\nThere is a task to request different fields of an object depending on role. Let's say administrator can view one set of metrics. Other users can see another set of metrics. The task is to request only metrics that can be viewed by the user. React application is using graphQL file loader and it should remain so.\n\nNow there are two graphql files. On defined fragment other - query with fragment import. Are there any possibilities to change used fragments depending on conditions?\n\n========================================\n\nComments:\n- You can also check conditional fragments that works really well with unions","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":13,"estimatedTokens":197}}866{"id":"stack-41090200","source":"stackoverflow","questionId":41090200,"title":"Apollo/GraphQL: Field Type to Use for Timestamp?","tags":["postgresql","graphql","apollostack"],"text":"Title: Apollo/GraphQL: Field Type to Use for Timestamp?\nTags: postgresql, graphql, apollostack\nSource: Stack Overflow\n\nQuestion:\nI'm storing a value to a postgres field that is of type `timestamp with time zone`. I was defining the field as an int in my Apollo schema, but I'm getting this error message in the resolver:\n\n column \"apptDateTime\" is of type timestamp with time zone but expression is of type integer\n\nLooking up GraphQL data types, I don't yet see any type that is cited as corresponding to a field of type timestamp. \n\nWhat's the correct field type to use in the Apollo schema for a field that is of type timestamp in the database?\n\n========================================\n\nTop Answer:\nI find this way to work with input in forms, needed convert from client (input form) to the server, and from the server to client (input form)\n\nGraphql:\n\n```\nupdatedAt: String\n```\n\nSequelize:\n\n```\nupdatedAt: { type: Sequelize.DATE },\n```\n\nPostgresql:\n\n```\n\"createdAt\" timestamp(6) with time zone DEFAULT now(),\n```\n\nValue transform to the Server:\n\n```\nvalue = dateToISO(value);\n```\n\nValue transform to the Client:\n\n```\nif ( isNil(value) ) {\n value = '';\n } else {\n value = value.toLocaleDateString() +' '+ value.toLocaleTimeString();\n }\n```\n\nthe helpers: \n\n```\nlet dateToISO = function (dateString) {\n if (!dateString) {\n return null;\n }\n let p = dateString.split(/\\D/g);\n /* It's up your date on input in this case come from DD-MM-YYYY\n for MM-DD-YYY use: return [p[1], p[2], p[0]].join('-'); */\n return [p[2], p[1], p[0]].join('-'); \n\n};\n```\n\n========================================\n\nCode:\n```text\ntimestamp with time zone\n```\n\n```text\ntimeOfNonce: {type: Sequelize.DATE}\n```\n\n```text\nscalar DATETIME\n .....\n timeOfNonce: DATETIME\n```\n\n```text\nconst deleteAllData_fromThisModel = false;\nconst alterThisTableToMatchDBConnectorsModel = true;\n\nmyDataModel.sync({force: deleteAllData_fromThisModel, \n alter: alterThisTableToMatchDBConnectorsModel}).then(err => {\n console.log('myDataModel has been synced')\n}).catch(err => {\n throw err\n});\n```\n\n```text\nupdatedAt: String\n```\n\n```text\nupdatedAt: { type: Sequelize.DATE },\n```\n\n```text\n\"createdAt\" timestamp(6) with time zone DEFAULT now(),\n```\n\n```text\nvalue = dateToISO(value);\n```\n\n```text\nif ( isNil(value) ) {\n value = '';\n } else {\n value = value.toLocaleDateString() +' '+ value.toLocaleTimeString();\n }\n```\n\n```text\nlet dateToISO = function (dateString) {\n if (!dateString) {\n return null;\n }\n let p = dateString.split(/\\D/g);\n /* It's up your date on input in this case come from DD-MM-YYYY\n for MM-DD-YYY use: return [p[1], p[2], p[0]].join('-'); */\n return [p[2], p[1], p[0]].join('-'); \n\n};\n```\n\n========================================\n\nComments:\n- Checkout the section on the date scalar: graphql.org/learn/schema/#scalar-types Probably best to define a custom scalar.\n- Iβm reading up on dates and Apollo, and I note that as Tally posts, it is required to add custom code for this purpose. I found documentation here: dev.apollodata.com/tools/graphql-tools/… The docs define the resolver map, but donβt appear to show how to include the resolver map in your schema and/or other resolvers. Can someone provide or link to an example of how to reference a resolver map from your other Apollo resolvers?\n- this is how it was done for json: github.com/taion/graphql-type-json/blob/master/src/index.js\n- can you show something of your code? did you not need : require('pg').types.setTypeParser(1114, function(stringValue) { return new Date(stringValue + \"+0000\"); // e.g., UTC offset. Use any offset that you would like. });","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":140,"estimatedTokens":909}}867{"id":"stack-52531894","source":"stackoverflow","questionId":52531894,"title":"How to throw multiple errors with express-graphql?","tags":["javascript","graphql","graphql-js","express-graphql"],"text":"Title: How to throw multiple errors with express-graphql?\nTags: javascript, graphql, graphql-js, express-graphql\nSource: Stack Overflow\n\nQuestion:\nIn an express-graphql app, I have a `userLogin` resolver like so: \n\n```\nconst userLogin = async ({ id, password }), context, info) => {\n\n if (!id) {\n throw new Error('No id provided.')\n }\n\n if (!password) {\n throw new Error('No password provided.')\n }\n\n // actual resolver logic here\n // β¦ \n}\n```\n\nIf the user doesn't provide an `id` AND a `password`, it will throw only one error. \n\n```\n{\n \"errors\": [\n {\n \"message\": \"No id provided.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"userLogin\"\n ]\n }\n ],\n \"data\": {\n \"userLogin\": null\n }\n}\n```\n\nHow is it possible to throw multiple errors in the `errors` response array?\n\n========================================\n\nCode:\n```text\nconst userLogin = async ({ id, password }), context, info) => {\n\n if (!id) {\n throw new Error('No id provided.')\n }\n\n if (!password) {\n throw new Error('No password provided.')\n }\n\n // actual resolver logic here\n // β¦ \n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"No id provided.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"userLogin\"\n ]\n }\n ],\n \"data\": {\n \"userLogin\": null\n }\n}\n```\n\n```text\nuserLogin\n```\n\n```text\nid\n```\n\n```text\npassword\n```\n\n```text\nerrors\n```\n\n```text\ntype Query {\n a: String\n b: String\n c: String\n}\n\nconst resolvers = {\n Query: {\n a: () => { throw new Error('A rejected') },\n b: () => { throw new Error('B rejected') },\n c: () => 'Still works!',\n },\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"A rejected\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"a\"\n ]\n },\n {\n \"message\": \"B rejected\",\n \"locations\": [\n {\n \"line\": 3,\n \"column\": 3\n }\n ],\n \"path\": [\n \"b\"\n ]\n }\n ],\n \"data\": {\n \"a\": null,\n \"b\": null,\n \"c\": \"Still works!\"\n }\n}\n```\n\n```text\n// The middleware\napp.use('/graphql', graphqlExpress({\n schema: schema,\n formatError: (error) => ({\n message: error.message,\n path: error.path,\n locations: error.locations,\n errors: error.originalError.details\n })\n}))\n\n// The error class\nclass CustomError extends Error {\n constructor(detailsArray) {\n this.message = String(details)\n this.details = details\n }\n}\n\n// The resolver\nconst userLogin = async ({ id, password }), context, info) => {\n const errorDetails = []\n if (!id) errorDetails.push('No id provided.')\n if (!password) errorDetails.push('No password provided.')\n if (errorDetails.length) throw new CustomError(errorDetails)\n\n // actual resolver logic here\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"[No id provided.,No password provided.]\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"userLogin\"\n ]\n \"errors\" [\n \"No id provided.\",\n \"No password provided.\"\n ]\n }\n ],\n \"data\": {\n \"userLogin\": null\n }\n}\n```\n\n```text\ntype Mutation {\n userLogin: UserLoginResponse\n}\n\ntype UserLoginResponse {\n response: User\n errors: [String!]\n}\n```\n\n```text\ntype Mutation {\n userLogin: UserLoginResponse\n}\n\ntype Errors {\n errors: [String!]!\n}\n\nunion UserLoginResponse = User | Errors\n```\n\n```text\nerrors\n```\n\n```text\nerror\n```\n\n```text\nformatError\n```\n\n```text\nerrors\n```\n\n========================================\n\nComments:\n- Maybe it's outdated but a way to achieve this is to check is it's an array then check if the elements are error or not. You'll find a topic here : github.com/graphql/graphql-js/issues/205\n- @LPK yes, that's the same issue, but I don't get how they solved itβ¦\n- I don't know `graphql` but i got an idea.You could trow a Json string maybe with all the errors.\n- Thank you for your answer. I like the second the solution you suggest. That said, I have 2 questions: 1. I could use your idea to make an array of error messages first and then throw a simple error. what is the point of making a custom error here? 2. is there a way to throw multiple errors in the `errors` arrays from the graphQL response (my original question)?\n- Sorry I wasn't clear enough. As far as I'm aware, there's no way to throw multiple errors in js and no way to pass an array of them to GraphQL. The above presents a couple of workarounds for that limitation. It's not strictly necessary to create a custom error class -- you could just create a plain error and then set the `details` property on it.","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":262,"estimatedTokens":1175}}868{"id":"stack-46021404","source":"stackoverflow","questionId":46021404,"title":"All GraphQL Scalars coming up as String (Apollo)","tags":["ios","swift","graphql","apollo","apollo-client"],"text":"Title: All GraphQL Scalars coming up as String (Apollo)\nTags: ios, swift, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am using Apollo client for GraphQL client integrations. I have added the following run script, which is suggested in the official documentation.\n\n```\ncd \"${SRCROOT}/${TARGET_NAME}/GraphQL/Open\"\n$APOLLO_FRAMEWORK_PATH/check-and-run-apollo-codegen.sh generate $(find \n. -name '*.graphql') --schema schema.json \n --output APIClient.swift\n```\n\nBut the problem that is coming up is all the scalar are right now coming up as String.\n\nFor Example:- while logging in if I create a mutation of email and password, my schema returns response as JSON while APIClient created shows response as String(instead of JSON). \n\nDue to this there is an error received which says\n\n```\nApollo.GraphQLResultError(path: [\"login\", \"response\"], underlying: Apollo.JSONDecodingError.couldNotConvert\n```\n\nthis is because String is received instead of JSON and string can not be converted into required JSON.\n\nIs anyone facing the same issue?\n\n========================================\n\nCode:\n```text\ncd \"${SRCROOT}/${TARGET_NAME}/GraphQL/Open\"\n$APOLLO_FRAMEWORK_PATH/check-and-run-apollo-codegen.sh generate $(find \n. -name '*.graphql') --schema schema.json \n --output APIClient.swift\n```\n\n```text\nApollo.GraphQLResultError(path: [\"login\", \"response\"], underlying: Apollo.JSONDecodingError.couldNotConvert\n```\n\n```text\n--passthrough-custom-scalars\n```\n\n```text\ncd \"${SRCROOT}/${TARGET_NAME}/GraphQL/Open\"\n$APOLLO_FRAMEWORK_PATH/check-and-run-apollo-codegen.sh generate $(find \n. -name '*.graphql') --schema schema.json --passthrough-custom-scalars \n--output APIOpen.swift\n```\n\n========================================\n\nComments:\n- Just to be clear, on more recent releases of the Apollo SDK for iOS, this flag is actually --passthroughCustomScalars. So your build script will look something like this: cd \"${SRCROOT}/${TARGET_NAME}\" $APOLLO_FRAMEWORK_PATH/check-and-run-apollo-cli.sh codegen:generate --queries=\"$(find . -name '*.graphql')\" --passthroughCustomScalars --schema=schema.json API.swift","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":57,"estimatedTokens":528}}869{"id":"stack-52076589","source":"stackoverflow","questionId":52076589,"title":"Could not initialize proxy with graphql-spring","tags":["java","spring-boot","graphql","graphql-java"],"text":"Title: Could not initialize proxy with graphql-spring\nTags: java, spring-boot, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI am using: graphql-spring-boot and graphql-java-tools for the implementation. \n\n**movie.graphqls**\n\n```\ntype Movie {\n id: Short\n name: String\n poster: String\n releaseDate: String\n runtime: String\n storyline: String\n rated: String\n rating: String\n inserted: String\n}\n\ntype Query {\n movies: [Movie]\n movie(id: ID!): Movie\n}\n```\n\n**Movie model**\n\n```\n@Entity\npublic class Movie {\n private Short id;\n private String name;\n private String poster;\n private Date releaseDate;\n private Time runtime;\n private String storyline;\n private String rated;\n private double rating;\n private Timestamp inserted;\n}\n```\n\nAs you can see i have no relationship with other models.\n\nfinally the class which implement **GraphQLQueryResolver** \n\n```\n@Component\npublic class Query implements GraphQLQueryResolver {\n @Autowired\n private MovieRepository movieRepository;\n public List movies() {\n return this.movieRepository.findAll();\n }\n public Movie movie(Short id) {\n return this.movieRepository.getOne(id);\n }\n}\n```\n\nthe following query works fine: \n\n```\n{\n movies{\n name\n rating\n }\n}\n```\n\nbut this query: \n\n```\n{\n movie(id: 1){\n name\n }\n}\n```\n\ngives me the following error: \n\n Exception while fetching data (/movie/rated) : could not initialize proxy [com.example.demo.model.Movie#1] - no Session\n\n========================================\n\nTop Answer:\nyou need to add the naming of strategy in your conguration file **application.properties**\n\n```\nhibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy\n```\n\n========================================\n\nCode:\n```text\ntype Movie {\n id: Short\n name: String\n poster: String\n releaseDate: String\n runtime: String\n storyline: String\n rated: String\n rating: String\n inserted: String\n}\n\n\ntype Query {\n movies: [Movie]\n movie(id: ID!): Movie\n}\n```\n\n```text\n@Entity\npublic class Movie {\n private Short id;\n private String name;\n private String poster;\n private Date releaseDate;\n private Time runtime;\n private String storyline;\n private String rated;\n private double rating;\n private Timestamp inserted;\n}\n```\n\n```text\n@Component\npublic class Query implements GraphQLQueryResolver {\n @Autowired\n private MovieRepository movieRepository;\n public List<Movie> movies() {\n return this.movieRepository.findAll();\n }\n public Movie movie(Short id) {\n return this.movieRepository.getOne(id);\n }\n}\n```\n\n```text\n{\n movies{\n name\n rating\n }\n}\n```\n\n```text\n{\n movie(id: 1){\n name\n }\n}\n```\n\n```text\npublic Movie movie(Short id) {\n return this.movieRepository.findOne(id);\n}\n```\n\n```text\ngetOne\n```\n\n```text\nfindOne\n```\n\n```text\ngetOne\n```\n\n```text\nhibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy\n```\n\n========================================\n\nComments:\n- not the same question. the problem in that question is the relationship between models, here i have no relationship !\n- Cannot resolve configuration property 'hibernate.ejb.naming_strategy'.\n- Had the same issue, I've spent 2 hours trying to solve not the actual problem that I had and you saved me, thanks! Would never guess that getById is different than findById.","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":194,"estimatedTokens":827}}870{"id":"stack-63263133","source":"stackoverflow","questionId":63263133,"title":"Is there a way to get gql tag to autocomplete with Typescript/GraphQL?","tags":["typescript","autocomplete","graphql","gql"],"text":"Title: Is there a way to get gql tag to autocomplete with Typescript/GraphQL?\nTags: typescript, autocomplete, graphql, gql\nSource: Stack Overflow\n\nQuestion:\nIs there a way to get autocomplete when writing a GraphQL query using the `gql` `...` tag, when using `Typescript`?\n\nSomething similar to when writing queries in Graphiql for example.\n\n========================================\n\nTop Answer:\nI went looking for a solution myself and I came across typescript language service plugins.\n\nApparently typescript has a plugin system which allows for the 'enhancement of existing messages between typescript and an editor'. So while they don't function as an extension of the typescript language, they allow for things like customized auto-complete and linting in template strings.\n\nAmong the example plugins in the ts docs I found ts-graphql-plugin which provides query validation, auto-completion, and tooltip info within GraphQL query template strings.\n\nI guess this at least does the same thing as the the apollo vscode extension that the current answer suggested, but it shouldn't require that you use vscode.\n\n========================================\n\nCode:\n```text\ngql\n```\n\n```text\nTypescript\n```\n\n```text\ngql\n```\n\n```text\napollographql.vscode-apollo\n```\n\n```text\napollo.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":42,"estimatedTokens":322}}871{"id":"stack-58523390","source":"stackoverflow","questionId":58523390,"title":"Deprecate a type in ApolloServer","tags":["graphql","apollo-server"],"text":"Title: Deprecate a type in ApolloServer\nTags: graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nThis is the pattern to deprecate a field in ApolloServer:\n\n```\ntype Car {\n id: ID!\n make: String\n model: String\n description: String @deprecated(reason: \"Field is deprecated!\")\n}\n```\n\nHowever, how do I deprecate a whole type - e.g. the `Car` type above?\n\n========================================\n\nCode:\n```text\ntype Car {\n id: ID!\n make: String\n model: String\n description: String @deprecated(reason: \"Field is deprecated!\")\n}\n```\n\n```text\nCar\n```\n\n```text\ndirective @deprecated(\n reason: String = \"No longer supported\"\n) on FIELD_DEFINITION | ENUM_VALUE\n```\n\n```text\n@deprecated\n```\n\n```text\nisDeprecated: Boolean\n```\n\n```text\ndeprecationReason: String\n```\n\n========================================\n\nComments:\n- As an aside, I could see type deprecation in the context of fragment usage, but regardless it's just not part of the current spec.","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":56,"estimatedTokens":238}}872{"id":"stack-36780293","source":"stackoverflow","questionId":36780293,"title":"How to decide what root value to use for GraphQL mutations","tags":["graphql"],"text":"Title: How to decide what root value to use for GraphQL mutations\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI'm experimenting with GraphQL and need help understanding how to know what root value to provide when a mutation is about to be performed.\n\n**Concrete example:** you want to update the username of the currently logged in user. The mutation looks like this:\n\n```\nmutation TestMutation {\n updateMyUsername(newName: \"CoolName\") {\n username }\n}\n```\n\nThe root object to provide here is the current user. But how do you know this when you receive the mutation without parsing it and seeing its name? No decision is possible based on URL as only one endpoint exists. And parsing the string only to send it further where it will be parsed again sounds wasteful at best.\n\nIs it maybe common practice instead to provide some extra parameters in the URL or request body to give the application more context?\n\n========================================\n\nTop Answer:\nI'm experimenting with GraphQL and need help understanding how to know what root value to provide when a mutation is about to be performed.\n\nIf you don't know what to forward as the `root` variable then you probably don't need any and you can just forward `null` or `undefined`.\n\n Concrete example: ...\n\n The root object to provide here is the current user. \n\nYou should pass the user as the `context` variable, rather than as the `root` variable.\n\nThe same way you probably do when executing a query.\n\n But how do you know this when you receive the mutation without parsing it and seeing its name?\n\nYou should forward the user object for each request in the `context` object.\n\nOr if the user data has to be loaded from a database then forward a function for loading the user.\n\n========================================\n\nCode:\n```text\nmutation TestMutation {\n updateMyUsername(newName: \"CoolName\") {\n username }\n}\n```\n\n```text\ncontext\n```\n\n```text\nroot\n```\n\n```text\nnull\n```\n\n```text\nundefined\n```\n\n```text\ncontext\n```\n\n```text\nroot\n```\n\n```text\ncontext\n```\n\n========================================\n\nComments:\n- `Since mutations are always top level...` Actually mutations don't always have to be top level. A `Mutation` is exactly the same as a `Query` and can have nested resolvers.\n- @zoran404 I think Lee knows what he's saying, seeing that he's the spec lead for GraphQL :) Mutations are by definition fields of a mutation root object, thus they're *always* top level. You can then nest the *selections* from the result, but the mutation field is itself is always top-level.\n- @kaqqao `Mutations` work exactly the same as `Queries`. Meaning that you can have `type UserMutation` that would only handle changes to the `user table`. This would only require a top level mutation field who's return type is `UserMutation` and returns an empty object.","metadata":{"transformedAt":"2026-08-18T18:32:36.089Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":85,"estimatedTokens":712}}873{"id":"stack-70823774","source":"stackoverflow","questionId":70823774,"title":"using webclient to call the grapql mutation API in spring boot","tags":["java","spring-boot","graphql","webclient"],"text":"Title: using webclient to call the grapql mutation API in spring boot\nTags: java, spring-boot, graphql, webclient\nSource: Stack Overflow\n\nQuestion:\nI am stuck while calling the graphQL mutation API in spring boot. Let me explain my scenario, I have two microservice one is the AuditConsumeService which consume the message from the activeMQ, and the other is GraphQL layer which simply takes the data from the consume service and put it inside the database. Everything well when i try to push data using graphql playground or postman. How do I push data from AuditConsumeService. In the AuditConsumeService I am trying to send mutation API as a string. the method which is responsible to send that to graphQL layer is\n\n```\npublic Mono sendLogsToGraphQL(String logs){\n return webClient\n .post()\n .uri(\"http://localhost:8080/logs/createEventLog\")\n .bodyValue(logs)\n .retrieve()\n .bodyToMono(String.class);\n }\n```\n\n***NOTE:*** I try to pass data as Object as well but no use.\nThe `String logs` will be given to it from activeMQ. The data which I am sending is;\n\n```\n{\n \"hasError\": false,\n \"message\": \"Hello There\",\n \"sender\": \"Ali Ahmad\",\n \"payload\": {\n \"type\": \"String\",\n \"title\": \"Topoic\",\n \"description\": \"This is the demo description of the activemqq\"\n },\n \"serviceInfo\":{\n \"version\": \"v1\",\n \"date\": \"2021-05-18T08:44:17.8237608+05:00\",\n \"serverStatus\": \"UP\",\n \"serviceName\": \"IdentityService\"\n }\n}\n```\n\nThe mutation will be like;\n\n```\nmutation($eventLog:EventLogInput){\n createEventLog(eventLog: $eventLog){\n hasError\n message\n payload{\n title,\n description\n }\n }\n}\n```\n\nThe `$eventLog` has json body as;\n\n```\n{\n \"eventLog\": {\n \"hasError\": false,\n \"message\": \"Hello There\",\n \"sender\": \"Ali Ahmad\",\n \"payload\": {\n \"type\": \"String\",\n \"title\": \"Topoic\",\n \"description\": \"This is the demo description of the activemqq\"\n },\n \"serviceInfo\":{\n \"version\": \"v1\",\n \"date\": \"2021-05-18T08:44:17.8237608+05:00\",\n \"serverStatus\": \"UP\",\n \"serviceName\": \"IdentityService\"\n }\n}\n}\n```\n\n***EDIT***\nThe the below answer, by updating the consumerservice as;\n\n```\n@Component\npublic class Consumer {\n @Autowired\n private AuditService auditService;\n\n private final String MUTATION_QUERY = \"mutation($eventLog: EventLogInput){\\n\" +\n \"createEventLog(eventLog: $eventLog){\\n\" +\n \"hasError\\n\" +\n \"}\\n\" +\n \"}\";\n\n @JmsListener(destination = \"Audit.queue\")\n public void consumeLogs(String logs) {\n Gson gson = new Gson();\n Object jsonObject = gson.fromJson(logs, Object.class);\n Map graphQlBody = new HashMap<>();\n graphQlBody.put(\"query\", MUTATION_QUERY);\n graphQlBody.put(\"variables\", \"{eventLog: \" + jsonObject+ \"}\");\n auditService.sendLogsToGraphQL(graphQlBody);\n }\n}\n```\n\nNow In the `sendLogsToGraphQL' will becomes.\n\n```\npublic void sendLogsToGraphQL(Map logs) {\n log.info(\"Logs: {} \", logs);\n Mono stringMono = webClient\n .post()\n .uri(\"http://localhost:8080/graphql\")\n .bodyValue(BodyInserters.fromValue(logs))\n .retrieve()\n .bodyToMono(String.class);\n log.info(\"StringMono: {}\", stringMono);\n return stringMono;\n }\n```\n\nThe data is not sending to the graphql layer with the specified url.\n\n========================================\n\nCode:\n```text\npublic Mono<String> sendLogsToGraphQL(String logs){\n return webClient\n .post()\n .uri(\"http://localhost:8080/logs/createEventLog\")\n .bodyValue(logs)\n .retrieve()\n .bodyToMono(String.class);\n }\n```\n\n```text\n{\n \"hasError\": false,\n \"message\": \"Hello There\",\n \"sender\": \"Ali Ahmad\",\n \"payload\": {\n \"type\": \"String\",\n \"title\": \"Topoic\",\n \"description\": \"This is the demo description of the activemqq\"\n },\n \"serviceInfo\":{\n \"version\": \"v1\",\n \"date\": \"2021-05-18T08:44:17.8237608+05:00\",\n \"serverStatus\": \"UP\",\n \"serviceName\": \"IdentityService\"\n }\n}\n```\n\n```text\nmutation($eventLog:EventLogInput){\n createEventLog(eventLog: $eventLog){\n hasError\n message\n payload{\n title,\n description\n }\n }\n}\n```\n\n```text\n{\n \"eventLog\": {\n \"hasError\": false,\n \"message\": \"Hello There\",\n \"sender\": \"Ali Ahmad\",\n \"payload\": {\n \"type\": \"String\",\n \"title\": \"Topoic\",\n \"description\": \"This is the demo description of the activemqq\"\n },\n \"serviceInfo\":{\n \"version\": \"v1\",\n \"date\": \"2021-05-18T08:44:17.8237608+05:00\",\n \"serverStatus\": \"UP\",\n \"serviceName\": \"IdentityService\"\n }\n}\n}\n```\n\n```text\n@Component\npublic class Consumer {\n @Autowired\n private AuditService auditService;\n\n private final String MUTATION_QUERY = \"mutation($eventLog: EventLogInput){\\n\" +\n \"createEventLog(eventLog: $eventLog){\\n\" +\n \"hasError\\n\" +\n \"}\\n\" +\n \"}\";\n\n @JmsListener(destination = \"Audit.queue\")\n public void consumeLogs(String logs) {\n Gson gson = new Gson();\n Object jsonObject = gson.fromJson(logs, Object.class);\n Map<String, Object> graphQlBody = new HashMap<>();\n graphQlBody.put(\"query\", MUTATION_QUERY);\n graphQlBody.put(\"variables\", \"{eventLog: \" + jsonObject+ \"}\");\n auditService.sendLogsToGraphQL(graphQlBody);\n }\n}\n```\n\n```text\npublic void sendLogsToGraphQL(Map<String, String> logs) {\n log.info(\"Logs: {} \", logs);\n Mono<String> stringMono = webClient\n .post()\n .uri(\"http://localhost:8080/graphql\")\n .bodyValue(BodyInserters.fromValue(logs))\n .retrieve()\n .bodyToMono(String.class);\n log.info(\"StringMono: {}\", stringMono);\n return stringMono;\n }\n```\n\n```text\nString logs\n```\n\n```text\n$eventLog\n```\n\n```text\ngraphQlBody = { \"query\" : mutation_query, \"variables\" : { \"eventLog\" : event_log_json } }\n```\n\n```text\npublic Mono<String> sendLogsToGraphQL(Map<String,Object> body){\n return webClient\n .post()\n .uri(\"http://localhost:8080/logs/createEventLog\")\n .bodyValue(BodyInserters.fromValue(body))\n .retrieve()\n .bodyToMono(String.class);\n}\n```\n\n```text\nquery\n```\n\n```text\nMap<String,Object>\n```\n\n```text\nquery\n```\n\n```text\nvariables\n```\n\n========================================\n\nComments:\n- Thanks for the reply. you define the `graphQLBody` as map, but I surprised where you use it, because I don't see its existence in the `sendLogsToGraphQL` method.\n- graphQLBody need to be passed as body for webclient post request, so in your case you need to call sendLogsToGraphQL passing that body\n- also the variable `mutation_query` inside the `graphQlBody` is a simple string which contain the query like `String mutation_query = \"mutation\"` . And same the `event_log_json` simply contain the my json string.\n- I updated my question, by adding the `ConsumeService` method which takes json as string from activeMQ, have a look please because i your answer but its not working.\n- finally I solved it, instead of sending map, i simple send string as; `final String query = \"{\\\"query\\\": \" + MUTATION_QUERY + \", \\\"variables\\\": {\\\"eventLog\\\": \" + logs + \"}}\";`, and pass this as argument to RestTemplate, and now its working.","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":275,"estimatedTokens":1782}}874{"id":"stack-60787554","source":"stackoverflow","questionId":60787554,"title":"Hasura graphql query between dates","tags":["graphql","react-apollo","gql","hasura"],"text":"Title: Hasura graphql query between dates\nTags: graphql, react-apollo, gql, hasura\nSource: Stack Overflow\n\nQuestion:\nIn my hasura.io database, I have a `booking` table, where I store bookings with the following properties:\n\n- id (autoincrement)\n\n- from (timestamptz)\n\n- to (timestamptz)\n\n- description (text)\n\nNow, from the UI, when a user makes a booking, I would like to check if there are any bookings made previously that touch the range of those dates.\n\neg. User wants to do a booking with the following dates: \n\n```\n{\n \"from\": \"2020-03-31T14:00:00+00:00\",\n \"to\": \"2020-03-31T17:00:00+00:00\"\n}\n```\n\nBut in the same date there is a booking: \n\n```\n{\n \"from\": \"2020-03-31T15:00:00+00:00\",\n \"to\": \"2020-04-01T17:00:00+00:00\"\n}\n```\n\n Notice, this booking is been made not within the range of the dates the user is trying to book. So the following query will return nothing.\n\n```\nquery CheckBooking($from: timestamptz!, $to: timestamptz!) {\n booking(where: {_and: [{from: {_lte: $from}}, {to: {_gte: $to}}]}) {\n id\n from\n to\n }\n}\n```\n\nThis above is what I've tried without success.\nCould anyone help to figure out what's the correct query to **check if there are any bookings in the range or within** the users new booking?\n\n========================================\n\nCode:\n```text\n{\n \"from\": \"2020-03-31T14:00:00+00:00\",\n \"to\": \"2020-03-31T17:00:00+00:00\"\n}\n```\n\n```text\n{\n \"from\": \"2020-03-31T15:00:00+00:00\",\n \"to\": \"2020-04-01T17:00:00+00:00\"\n}\n```\n\n```text\nquery CheckBooking($from: timestamptz!, $to: timestamptz!) {\n booking(where: {_and: [{from: {_lte: $from}}, {to: {_gte: $to}}]}) {\n id\n from\n to\n }\n}\n```\n\n```text\nbooking\n```\n\n```text\nquery CheckBooking($from: timestamptz!, $to: timestamptz!) {\n booking(where: {_or: [\n {_and: [{from: {_gte: $from}}, {from: {_lt: $to}}]},\n {_and: [{to: {_gt: $from}}, {to: {_lte: $to}}]},\n ]}) {\n id\n from\n to\n }\n}\n```\n\n```text\nfrom\n```\n\n```text\nto\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":101,"estimatedTokens":483}}875{"id":"stack-55564703","source":"stackoverflow","questionId":55564703,"title":"Passing variables with graphql using a http client","tags":["go","graphql"],"text":"Title: Passing variables with graphql using a http client\nTags: go, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to interface with shopify storefront api in golang. But this is my first encounter with graphql and I'm a bit confused.\n\nI need to pass variables for the request and did some research where I came to the conclusion that I could pass variables like shown below. But shopify keeps returning this error:\n\n```\n{\"errors\":[{\"message\":\"Parse error on \\\"variables\\\" (IDENTIFIER) at [13, 3]\",\"locations\":[{\"line\":13,\"column\":3}]}]}\n```\n\nHere is my current code:\n\n```\nbody := strings.NewReader(fmt.Sprintf(`\n mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) {\n checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) {\n userErrors {\n message\n field\n }\n checkout {\n id\n }\n }\n }\n variables: { \"lineItems\": [ { \"quantity\": 1, \"variantId\": \"%s\" } ], \"checkoutId\": \"%s\" }\n`, productID, checkoutID))\n\nreq, err := http.NewRequest(\"POST\", \"https://myshop.myshopify.com/api/graphql\", body)\nif err != nil {\n // handle err\n fmt.Println(err)\n}\nreq.Header.Set(\"Content-Type\", \"application/graphql\")\nreq.Header.Set(\"X-Shopify-Storefront-Access-Token\", \"mytoken\")\n\nresp, err := http.DefaultClient.Do(req)\nif err != nil {\n // handle err\n fmt.Println(err)\n}\ndefer resp.Body.Close()\n\ndata, err := ioutil.ReadAll(resp.Body)\nif err != nil {\n // handle err\n fmt.Println(err)\n}\n```\n\nMy question is, what is the correct way of passing variables when using `application/graphql`?\n\nAfter updating the code with the answer of @DanielRearden I'm now getting this error:\n\n```\n{\"errors\":[{\"message\":\"Variable checkoutId of type ID! was provided invalid value\",\"locations\":[{\"line\":1,\"column\":11}],\"extensions\":{\"value\":null,\"problems\":[{\"path\":[],\"explanation\":\"Expected value to not be null\"}]}},{\"message\":\"Variable lineItems of type [CheckoutLineItemInput!]! was provided invalid value\",\"locations\":[{\"line\":1,\"column\":29}],\"extensions\":{\"value\":null,\"problems\":[{\"path\":[],\"explanation\":\"Expected value to not be null\"}]}}]}\n```\n\nUpdated code:\n\n```\nbody := strings.NewReader(fmt.Sprintf(`{\n \"query\": \"mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) { checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) { userErrors { message field } checkout { id } }}\",\n \"variables\": { \n \"$lineItems\": [ \n { \"quantity\": 1, \"variantId\": \"%s\" }\n ], \n \"$checkoutId\": \"%s\"\n }\n }`, productID, checkoutID))\n ...\n ...\n req.Header.Set(\"Content-Type\", \"application/json\")\n```\n\nRemoving the `$` token on the variables as shown below returns another error:\n\n```\n{\n \"query\": \"mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) { checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) { userErrors { message field } checkout { id } }}\",\n \"variables\": { \n \"checkoutId\": \"%s\",\n \"lineItems\": [ \n { \"quantity\": 1, \"variantId\": \"%s\" }\n ]\n }\n }\n```\n\nAnd the error is: (status 500)\n\n```\n\n \n \n Something went wrong\n```\n\nBut I guess this is not a graphql issue anymore but more of a shopify api problem.\n\n========================================\n\nCode:\n```text\n{\"errors\":[{\"message\":\"Parse error on \\\"variables\\\" (IDENTIFIER) at [13, 3]\",\"locations\":[{\"line\":13,\"column\":3}]}]}\n```\n\n```text\nbody := strings.NewReader(fmt.Sprintf(`\n mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) {\n checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) {\n userErrors {\n message\n field\n }\n checkout {\n id\n }\n }\n }\n variables: { \"lineItems\": [ { \"quantity\": 1, \"variantId\": \"%s\" } ], \"checkoutId\": \"%s\" }\n`, productID, checkoutID))\n\nreq, err := http.NewRequest(\"POST\", \"https://myshop.myshopify.com/api/graphql\", body)\nif err != nil {\n // handle err\n fmt.Println(err)\n}\nreq.Header.Set(\"Content-Type\", \"application/graphql\")\nreq.Header.Set(\"X-Shopify-Storefront-Access-Token\", \"mytoken\")\n\nresp, err := http.DefaultClient.Do(req)\nif err != nil {\n // handle err\n fmt.Println(err)\n}\ndefer resp.Body.Close()\n\ndata, err := ioutil.ReadAll(resp.Body)\nif err != nil {\n // handle err\n fmt.Println(err)\n}\n```\n\n```text\n{\"errors\":[{\"message\":\"Variable checkoutId of type ID! was provided invalid value\",\"locations\":[{\"line\":1,\"column\":11}],\"extensions\":{\"value\":null,\"problems\":[{\"path\":[],\"explanation\":\"Expected value to not be null\"}]}},{\"message\":\"Variable lineItems of type [CheckoutLineItemInput!]! was provided invalid value\",\"locations\":[{\"line\":1,\"column\":29}],\"extensions\":{\"value\":null,\"problems\":[{\"path\":[],\"explanation\":\"Expected value to not be null\"}]}}]}\n```\n\n```text\nbody := strings.NewReader(fmt.Sprintf(`{\n \"query\": \"mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) { checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) { userErrors { message field } checkout { id } }}\",\n \"variables\": { \n \"$lineItems\": [ \n { \"quantity\": 1, \"variantId\": \"%s\" }\n ], \n \"$checkoutId\": \"%s\"\n }\n }`, productID, checkoutID))\n ...\n ...\n req.Header.Set(\"Content-Type\", \"application/json\")\n```\n\n```text\n{\n \"query\": \"mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) { checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) { userErrors { message field } checkout { id } }}\",\n \"variables\": { \n \"checkoutId\": \"%s\",\n \"lineItems\": [ \n { \"quantity\": 1, \"variantId\": \"%s\" }\n ]\n }\n }\n```\n\n```text\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"referrer\" content=\"never\" />\n <title>Something went wrong</title>\n```\n\n```text\napplication/graphql\n```\n\n```text\n$\n```\n\n```text\n{\n \"query\": \"mutation ($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) {...}\",\n \"variables\": {\n \"checkoutId\" \"\",\n \"lineItems\": [\n ...\n ]\n }\n}\n```\n\n```text\napplication/graphql\n```\n\n```text\napplication/graphql\n```\n\n```text\napplication/json\n```\n\n```text\nquery\n```\n\n```text\nvariables\n```\n\n========================================\n\nComments:\n- I actually already tried it too earlier, but its giving another error. I'll update my question.","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":232,"estimatedTokens":1559}}876{"id":"stack-60849034","source":"stackoverflow","questionId":60849034,"title":"Gatsby GraphQL custom date formatString","tags":["javascript","graphql","gatsby","date-formatting","template-literals"],"text":"Title: Gatsby GraphQL custom date formatString\nTags: javascript, graphql, gatsby, date-formatting, template-literals\nSource: Stack Overflow\n\nQuestion:\nI have this:\n\n```\nexport const pageQuery = graphql`\n query {\n site {\n siteMetadata {\n title\n }\n }\n allMdx(sort: { fields: [frontmatter___date], order: DESC }) {\n edges {\n node {\n excerpt\n fields {\n slug\n }\n frontmatter {\n date(formatString: \"DD 'de' MMMM, YYYY\", locale: \"pt\")\n title\n description\n }\n }\n }\n }\n }\n`\n```\n\nin the line ->> \n`date(formatString: \"DD 'de' MMMM, YYYY\", locale: \"pt\")`\nI have to insert strings but this 'de' isnt working. I know I want to display the date like:\n`25 de March, 2020.`\nBut the result is:\n`25 '32' March, 2020.`\nI know this isnt working, i know why, but I can't make it right.\nI'm Using Gatsbyjs with graphql\n\n========================================\n\nTop Answer:\n**Just Simple Put**\n\ndate(formatString: \"DD MMMM, YYYY\")\n\n`Output Like this: 04 February, 2021`\n\n========================================\n\nCode:\n```text\nexport const pageQuery = graphql`\n query {\n site {\n siteMetadata {\n title\n }\n }\n allMdx(sort: { fields: [frontmatter___date], order: DESC }) {\n edges {\n node {\n excerpt\n fields {\n slug\n }\n frontmatter {\n date(formatString: \"DD 'de' MMMM, YYYY\", locale: \"pt\")\n title\n description\n }\n }\n }\n }\n }\n`\n```\n\n```text\ndate(formatString: \"DD 'de' MMMM, YYYY\", locale: \"pt\")\n```\n\n```text\n25 de March, 2020.\n```\n\n```text\n25 '32' March, 2020.\n```\n\n```text\ndate(formatString: \"DD [de] MMMM, YYYY\", locale: \"pt\")\n```\n\n```text\nOutput Like this: 04 February, 2021\n```\n\n========================================\n\nComments:\n- here in brazil we actually use the output format of dates kinda like this: 02 of February, 2021 (for instance... but thanks a lot either way :D)","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":106,"estimatedTokens":476}}877{"id":"stack-65952794","source":"stackoverflow","questionId":65952794,"title":"How can you split the Query / Mutation / Subscription type into multiple files with HotChocolate GraphQL?","tags":["asp.net-core","graphql","hotchocolate"],"text":"Title: How can you split the Query / Mutation / Subscription type into multiple files with HotChocolate GraphQL?\nTags: asp.net-core, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI'm the new guy in the GraphQL world and trying to find a way to have multiple Query types or how to split the Query type into multiple files..\nI use Hot Chocolate for Asp.Net Core, and everything looks good and works.\nBut what if I need to combine few queries in one GraphQL API? Some really unrelated stuff, f.e. DogsQuery and CarsQuery.\n\nIn Asp.Net, I write similar to:\n\n```\npublic void ConfigureServices(IServiceCollection services)\n{\n services\n .AddGraphQLServer()\n //.AddQueryType()\n .AddQueryType();\n}\n```\n\nIt works fine if I use only one Query class simultaneously (Dogs or Cars). But how to use both?\nI've searched a lot but can't find the answer.\n\n========================================\n\nTop Answer:\nI created an extension class for `IRequestExecutorBuilder` that allows me to build queries and mutations fore each entity classes, inheriting from `EntityQuery` and `EntityMutation` and not have to worry about adding each type extensions.\n\n```\npublic static class IRequestExecutorBuilderExtensions\n{\n public static void AddGraphQLTypes(this IRequestExecutorBuilder requestExecutorBuilder)\n {\n requestExecutorBuilder\n .AddMutationType(d => d.Name(\"Mutation\"))\n .AddQueryType(d => d.Name(\"Query\"));\n\n var mutations = typeof(EntityMutation).GetAllSubTypes().ToList();\n mutations.ForEach(t => requestExecutorBuilder.AddTypeExtension(t));\n\n var queries = typeof(EntityQuery).GetAllSubTypes().ToList();\n queries.ForEach(t => requestExecutorBuilder.AddTypeExtension(t));\n }\n}\n```\n\nwhich can be called within `Program.cs`\n\n```\nbuilder.Services\n .AddGraphQLServer()\n .AddProjections()\n .RegisterDbContext(DbContextKind.Pooled)\n .AddErrorFilter(e =>\n {\n Console.WriteLine(e);\n return e;\n })\n .AddGraphQLTypes();\n```\n\nThis also relies on another `TypeExtension` class that I use often\n\n```\npublic static class TypeExtensions\n{\n public static IEnumerable GetAllSubTypes(this Type type)\n {\n var allTypes = type.Assembly.GetTypes();\n\n var types = from x in allTypes\n where x.BaseType != null && x.BaseType.Name == type.Name\n select x;\n\n return types;\n }\n}\n```\n\n========================================\n\nCode:\n```text\npublic void ConfigureServices(IServiceCollection services)\n{\n services\n .AddGraphQLServer()\n //.AddQueryType<DogsQuery>()\n .AddQueryType<CarsQuery>();\n}\n```\n\n```text\npublic void ConfigureServices(IServiceCollection services)\n{\n services\n .AddGraphQLServer()\n .AddQueryType(d => d.Name(\"Query\"))\n .AddTypeExtension<DogsQuery>()\n .AddTypeExtension<CarsQuery>();\n}\n```\n\n```text\n[ExtendObjectType(Name = \"Query\")]\n```\n\n```text\n[ExtendObjectType(Name = \"Subscription\")]\n```\n\n```text\n[ExtendObjectType(Name = \"Mutation\")]\n```\n\n```text\nQuery\n```\n\n```text\npublic static class IRequestExecutorBuilderExtensions\n{\n public static void AddGraphQLTypes(this IRequestExecutorBuilder requestExecutorBuilder)\n {\n requestExecutorBuilder\n .AddMutationType(d => d.Name(\"Mutation\"))\n .AddQueryType(d => d.Name(\"Query\"));\n\n var mutations = typeof(EntityMutation).GetAllSubTypes().ToList();\n mutations.ForEach(t => requestExecutorBuilder.AddTypeExtension(t));\n\n var queries = typeof(EntityQuery).GetAllSubTypes().ToList();\n queries.ForEach(t => requestExecutorBuilder.AddTypeExtension(t));\n }\n}\n```\n\n```text\nbuilder.Services\n .AddGraphQLServer()\n .AddProjections()\n .RegisterDbContext<MyDbContext>(DbContextKind.Pooled)\n .AddErrorFilter(e =>\n {\n Console.WriteLine(e);\n return e;\n })\n .AddGraphQLTypes();\n```\n\n```text\npublic static class TypeExtensions\n{\n public static IEnumerable<Type> GetAllSubTypes(this Type type)\n {\n var allTypes = type.Assembly.GetTypes();\n\n var types = from x in allTypes\n where x.BaseType != null && x.BaseType.Name == type.Name\n select x;\n\n return types;\n }\n}\n```\n\n```text\nIRequestExecutorBuilder\n```\n\n```text\nEntityQuery\n```\n\n```text\nEntityMutation\n```\n\n```text\nProgram.cs\n```\n\n```text\nTypeExtension\n```\n\n```text\npublic class SomeQueryType: ObjectTypeExtension\n{\n protected override void Configure(IObjectTypeDescriptor descriptor)\n {\n descriptor.Name(\"Query\");\n }\n}\n\npublic class SomeMutationType : ObjectTypeExtension\n{\n protected override void Configure(IObjectTypeDescriptor descriptor)\n {\n descriptor.Name(\"Mutation\");\n }\n}\n```\n\n```text\npublic class QueryType : ObjectType\n{\n protected override void Configure(IObjectTypeDescriptor descriptor)\n {\n descriptor.Name(\"Query\");\n }\n}\n\npublic class MutationType : ObjectType\n{\n protected override void Configure(IObjectTypeDescriptor descriptor)\n {\n descriptor.Name(\"Mutation\");\n }\n}\n```\n\n```text\nbuilder.Services.AddGraphQLServer()\n .AddQueryType<QueryType>()\n .AddMutationType<MutationType>()\n .AddTypeExtension<SomeQueryType>()\n .AddTypeExtension<SomeMutationType>()\n```\n\n```text\nQueryType\n```\n\n```text\nMutationType\n```\n\n```text\nProgram.cs\n```\n\n========================================\n\nComments:\n- Thanks a lot. I've started to use partial classes for that (at least to separate physical files for Dogs and Cars), but this approach is much elegant.","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":247,"estimatedTokens":1360}}878{"id":"stack-70958152","source":"stackoverflow","questionId":70958152,"title":"Duplicate active queries in Apollo Client Devtools","tags":["reactjs","graphql","apollo","apollo-client","hasura"],"text":"Title: Duplicate active queries in Apollo Client Devtools\nTags: reactjs, graphql, apollo, apollo-client, hasura\nSource: Stack Overflow\n\nQuestion:\nIβm using React with Apollo Client 3 and Hasura as a GraphQL server.\n\nThe component `ProductList` use the `get_products` query once.\nThen two exact copies of this query are memorized in the Apollo Cache as shown in the Apollo DevTools.\n\nMy question is - Why two identical queries get generated in the cache instead of one?\n\nApollo DevTools results\n\nhttps://i.sstatic.net/RccBV.png\n\nMy code\n\n```\nimport {\n ApolloClient,\n ApolloProvider,\n InMemoryCache,\n HttpLink,\n gql,\n useQuery,\n} from \"@apollo/client\";\n\nconst client = new ApolloClient({\n link: new HttpLink({\n uri: \"http://localhost:8080/v1/graphql\",\n }),\n cache: new InMemoryCache(),\n});\n\nfunction App() {\n return (\n \n \n \n \n \n );\n}\n\nconst ProductList = () => {\n const GET_PRODUCTS = gql`\n query get_products {\n product {\n id\n name\n __typename\n }\n }\n `;\n\n const { loading, error, data } = useQuery(GET_PRODUCTS);\n if (loading) return Loading ...\n\n;\n if (error) return {error.message}\n\n;\n return (\n <>\n \n\n### ProductList\n\n \n {data?.product.map((product: any) => {\n return \n- {product.name};\n })}\n \n \n );\n};\n\nexport default App;\n```\n\n========================================\n\nCode:\n```text\nimport {\n ApolloClient,\n ApolloProvider,\n InMemoryCache,\n HttpLink,\n gql,\n useQuery,\n} from \"@apollo/client\";\n\nconst client = new ApolloClient({\n link: new HttpLink({\n uri: \"http://localhost:8080/v1/graphql\",\n }),\n cache: new InMemoryCache(),\n});\n\nfunction App() {\n return (\n <div className=\"App\">\n <ApolloProvider client={client}>\n <ProductList />\n </ApolloProvider>\n </div>\n );\n}\n\nconst ProductList = () => {\n const GET_PRODUCTS = gql`\n query get_products {\n product {\n id\n name\n __typename\n }\n }\n `;\n\n const { loading, error, data } = useQuery(GET_PRODUCTS);\n if (loading) return <p>Loading ...</p>;\n if (error) return <p> {error.message}</p>;\n return (\n <>\n <h1>ProductList</h1>\n <ul>\n {data?.product.map((product: any) => {\n return <li key={product.id}>{product.name}</li>;\n })}\n </ul>\n </>\n );\n};\n\nexport default App;\n```\n\n```text\nProductList\n```\n\n```text\nget_products\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":148,"estimatedTokens":573}}879{"id":"stack-78740167","source":"stackoverflow","questionId":78740167,"title":"Export a GraphQL collection in Postman","tags":["graphql","postman","export"],"text":"Title: Export a GraphQL collection in Postman\nTags: graphql, postman, export\nSource: Stack Overflow\n\nQuestion:\nIs it possible to export a GraphQL collection?\n\nWhen I right-click on a regular collection there is an 'export' option, but right-clicking on a GraphQL collection lacks this option.\n\nIs it still somehow possible?\n\n========================================\n\nComments:\n- I guess the only option is to use \"Plain Collection\" with POST requests and \"GraphQL\" Body. In that way you can export a collection. The limitations are inability to use subscriptions and bad schema support.\n- I'm starting to get the feeling that you're right. The POST thing doesn't really work for me so I'll probably end up finding a different app for testing my GQL Api.","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":16,"estimatedTokens":189}}880{"id":"stack-62501369","source":"stackoverflow","questionId":62501369,"title":"Unable to retrieve errors occured in Graphql mutation in flutter project","tags":["flutter","graphql","flutter-graphql"],"text":"Title: Unable to retrieve errors occured in Graphql mutation in flutter project\nTags: flutter, graphql, flutter-graphql\nSource: Stack Overflow\n\nQuestion:\nI am using the package graphql_flutter for GraphQL operations in my flutter app. The queries and mutations are going well but I cannot retrieve the errors by following the ways mentioned in their doc. Every time I receive a generic error message which is,\n\n```\nClientException: Failed to connect to http://127.0.0.1:3006/graphql:\n```\n\nThat I get by doing,\n\n```\nprint(result.exception.toString());\n```\n\nMy mutation looks like,\n\n```\nfinal MutationOptions mutationOptions = MutationOptions(\n documentNode: gql(mutationString),\n variables: vars\n);\n\nfinal QueryResult result = await _instance._client.mutate(mutationOptions);\n\nif (result.hasException) {\n // none of the following prints the expected error.\n print(result.exception.clientException.message);\n print(result.exception.graphqlErrors);\n print(result.exception.toString());\n}\n\nprint(result.data);\n\nreturn result.data;\n```\n\nWhereas in the apollo client, My error is :\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Invalid Phone number provided\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"otp\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n ....\n```\n\nBut I get none of that.\n\nNote: The success response is coming as expected. I would like to know how can I get the graphql errors.\n\n========================================\n\nTop Answer:\nPut this in a try/ catch block and see if it can catch any exceptions\n\n```\nfinal QueryResult result = await _instance._client.mutate(mutationOptions);\n```\n\n========================================\n\nCode:\n```text\nClientException: Failed to connect to http://127.0.0.1:3006/graphql:\n```\n\n```text\nprint(result.exception.toString());\n```\n\n```text\nfinal MutationOptions mutationOptions = MutationOptions(\n documentNode: gql(mutationString),\n variables: vars\n);\n\nfinal QueryResult result = await _instance._client.mutate(mutationOptions);\n\nif (result.hasException) {\n // none of the following prints the expected error.\n print(result.exception.clientException.message);\n print(result.exception.graphqlErrors);\n print(result.exception.toString());\n}\n\nprint(result.data);\n\nreturn result.data;\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Invalid Phone number provided\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"otp\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n ....\n```\n\n```text\n127.0.0.1\n```\n\n```text\nlocalhost\n```\n\n```text\nfinal QueryResult result = await _instance._client.mutate(mutationOptions);\n```\n\n```text\nif (result.hasException) {\n if (result.exception.linkException is NetworkException) {\n // handle network issues, maybe\n }\n return Text(result.exception.toString())\n }\n```\n\n```text\nif (result.hasException) {\n if (result.exception!.linkException is ServerException) {\n ServerException exception =\n result.exception!.linkException as ServerException;\n var errorMessage = exception.parsedResponse!.errors![0].message;\n print(errorMessage);\n throw Exception(errorMessage);\n }\n }\n```\n\n========================================\n\nComments:\n- after that line i am able to print result.exception so obviously there is no exception coming from the _client.mutate call. It is already handled inside of that function.\n- Then the error should be inside the result data instead of result exception. The exception is only for syntax and network-related issues. Not the exception thrown by the middleware.\n- You should check these errors manually, like result.data[\"errors\"] != null or somethng\n- result.data prints null, and \" The exception is only for syntax and network-related issues\" - DIdn't find that anywhere in the documentation, I did the way the documentation mentions.\n- It should not be. GraphQL returns status code 200 for all the results. It's a thing of the GraphQL server. You will have to manually check if the result is actual data or errors.","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":164,"estimatedTokens":1022}}881{"id":"stack-65152638","source":"stackoverflow","questionId":65152638,"title":"How do I solve a \"Payload is not serializable: Converting circular structure to JSON\" error?","tags":["graphql","apollo","apollo-client"],"text":"Title: How do I solve a \"Payload is not serializable: Converting circular structure to JSON\" error?\nTags: graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nHow do I solve a \"Payload is not serializable: Converting circular structure to JSON\" error?\n\nI'm currently exploring Apollo, GraphQL, and Material-UI. I've never come across this error and have been looking through Stack Overflow and blog posts for solutions.\n\nI've been reading about circular structures but haven't been able to identify any in my current codebase.\n\nDo I need to stringify the variables going into `createLink`?\n\n**Full error message:**\n\n```\nNetwork request failed. Payload is not serializable: Converting circular structure to JSON\n --> starting at object with constructor 'HTMLInputElement'\n | property '__reactFiber$b12dhgch1cn' -> object with constructor 'FiberNode'\n --- property 'stateNode' closes the circle\n```\n\n**LinkList.js:**\n\n```\nexport default function LinkList() {\n const classes = useStyles();\n const { loading, error, data } = useQuery(LINK_QUERY);\n\n if (loading) {\n return (\n \n Fetching\n \n );\n }\n\n if (error) {\n return (\n \n Error! ${error.message};\n \n );\n }\n\n const linksToRender = data.allLinks;\n\n return (\n \n \n \n {linksToRender.map((link, index) => (\n \n ))}\n \n \n \n );\n}\n```\n\n**CreateLink.js:**\n\n```\nexport default function CreateLink() {\n const [state, setState] = useState({\n slug: \"\",\n description: \"\",\n link: \"\"\n });\n\n const classes = useStyles();\n\n function handleChange(e) {\n const value = e.target.value;\n setState({\n ...state,\n [e.target.name]: value\n });\n }\n\n const [createLink] = useMutation(CREATE_LINK);\n function handleSubmit(e) {\n e.preventDefault();\n console.log(state.slug);\n createLink({\n variables: {\n slug: state.slug,\n description: state.description,\n link: state.link\n }\n });\n setState({\n slug: \"\",\n description: \"\",\n link: \"\"\n });\n }\n\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n \n Shorten URL\n \n \n \n \n );\n}\n```\n\nThank you for checking out the question.\n\n========================================\n\nCode:\n```text\nNetwork request failed. Payload is not serializable: Converting circular structure to JSON\n --> starting at object with constructor 'HTMLInputElement'\n | property '__reactFiber$b12dhgch1cn' -> object with constructor 'FiberNode'\n --- property 'stateNode' closes the circle\n```\n\n```text\nexport default function LinkList() {\n const classes = useStyles();\n const { loading, error, data } = useQuery(LINK_QUERY);\n\n if (loading) {\n return (\n <Typography component={\"span\"}>\n <span className={classes.grid}>Fetching</span>\n </Typography>\n );\n }\n\n if (error) {\n return (\n <Typography component={\"span\"}>\n <span className={classes.grid}>Error! ${error.message}</span>;\n </Typography>\n );\n }\n\n const linksToRender = data.allLinks;\n\n return (\n <Typography component={\"span\"}>\n <div className={classes.root}>\n <Box className={classes.box}>\n {linksToRender.map((link, index) => (\n <Link\n className={classes.link}\n key={link.id}\n link={link}\n index={index}\n />\n ))}\n </Box>\n </div>\n </Typography>\n );\n}\n```\n\n```text\nexport default function CreateLink() {\n const [state, setState] = useState({\n slug: \"\",\n description: \"\",\n link: \"\"\n });\n\n const classes = useStyles();\n\n function handleChange(e) {\n const value = e.target.value;\n setState({\n ...state,\n [e.target.name]: value\n });\n }\n\n const [createLink] = useMutation(CREATE_LINK);\n function handleSubmit(e) {\n e.preventDefault();\n console.log(state.slug);\n createLink({\n variables: {\n slug: state.slug,\n description: state.description,\n link: state.link\n }\n });\n setState({\n slug: \"\",\n description: \"\",\n link: \"\"\n });\n }\n\n return (\n <Grid container className={classes.root}>\n <form onSubmit={handleSubmit}>\n <Grid item>\n <TextField\n className={classes.textfield}\n inputProps={{ maxLength: 12 }}\n id=\"slug\"\n name=\"slug\"\n label=\"Link Alias\"\n variant=\"outlined\"\n type=\"text\"\n value={state.slug}\n onChange={handleChange}\n />\n </Grid>\n <Grid item>\n <TextField\n required\n className={classes.textfield}\n id=\"description\"\n name=\"description\"\n label=\"Description\"\n variant=\"outlined\"\n type=\"text\"\n value={state.description}\n onChange={handleChange}\n />\n </Grid>\n <Grid item>\n <TextField\n required\n className={classes.textfield}\n id=\"link\"\n name=\"link\"\n label=\"URL\"\n variant=\"outlined\"\n type=\"text\"\n value={state.link}\n onChange={handleChange}\n />\n </Grid>\n <Grid item>\n <Button variant=\"outlined\" type=\"submit\" className={classes.button}>\n Shorten URL\n </Button>\n </Grid>\n </form>\n </Grid>\n );\n}\n```\n\n```text\ncreateLink\n```\n\n```text\ncreateLink({\n variables: {\n slug: state.slug,\n description: state.description,\n link: state.link\n }\n})\n```\n\n```text\nundefined\n```\n\n```text\nvariables\n```\n\n```text\ncreateLink()\n```\n\n========================================\n\nComments:\n- FC then no `this`\n- @xadm - Thanks for your help today! What do you mean by FC?\n- I changed `this` to `state`.\n- Glad it helps! I was facing the same error too","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":298,"estimatedTokens":1413}}882{"id":"stack-33762099","source":"stackoverflow","questionId":33762099,"title":"Why GraphQL is not designed as a valid json document?","tags":["json","facebook","graphql"],"text":"Title: Why GraphQL is not designed as a valid json document?\nTags: json, facebook, graphql\nSource: Stack Overflow\n\nQuestion:\nI wonder why facebook invented a new markup for GraphQL instead of json.\nMany rest api provide some query functionality like json-based query or json-rpc or simply using parameters.\n\nI am not trying to debate, I am just curious to find the motive.\n\n========================================\n\nCode:\n```text\n: true\n```\n\n========================================\n\nComments:\n- Don't they explain that here?\n- Not exactly, it justify very well to have a query language aside from rest api but not why they invent a markup that look like json instead of using json.","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":22,"estimatedTokens":171}}883{"id":"stack-59650831","source":"stackoverflow","questionId":59650831,"title":"onCompleted callback in useMutation doesn't have return values","tags":["reactjs","react-native","graphql","react-apollo","apollo-client"],"text":"Title: onCompleted callback in useMutation doesn't have return values\nTags: reactjs, react-native, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement login in react native using apollo.\nIn react native app\n\n```\nconst SIGN_IN = gql`\nmutation($username: String!, $password: String!) {\n signin(password: $password, username: $username) {\n user {\n username\n }\n token\n }\n}\n`;\n```\n\n// code is abbreviated.\n\n```\nfunction LoginScreen() {\n const [signIn, { loading, error }] = useMutation(SIGN_IN, {\n onCompleted({ data }) {\n if (loading) console.log(\"Loading.....\");\n console.log(\"Printing data\");\n console.log(data.signin.token);\n }\n });\n}\n```\n\nBackend server is working good.\nBut I got an error in console log says\n\n```\n[Unhandled promise rejection: TypeError: Cannot read property 'signin' of undefined]\n\n Stack trace:\n screens/LogInScreen.js:36:6 in useMutation$argument_1.onCompleted\n node_modules/@apollo/react-hooks/lib/react-hooks.cjs.js:635:25 in callOncomplete\n```\n\n**data is undefined.**\nSo I tried `{ data && console.log(data.signin.token) }` But it prints nothing.\nI read doc says \"onCompleted callback to useMutation that will be called once the mutation is complete with its return value.\"\n\nHow can I debug this? what am I missing? Any ideas?\n\n========================================\n\nCode:\n```text\nconst SIGN_IN = gql`\nmutation($username: String!, $password: String!) {\n signin(password: $password, username: $username) {\n user {\n username\n }\n token\n }\n}\n`;\n```\n\n```text\nfunction LoginScreen() {\n const [signIn, { loading, error }] = useMutation(SIGN_IN, {\n onCompleted({ data }) {\n if (loading) console.log(\"Loading.....\");\n console.log(\"Printing data\");\n console.log(data.signin.token);\n }\n });\n}\n```\n\n```text\n[Unhandled promise rejection: TypeError: Cannot read property 'signin' of undefined]\n\n Stack trace:\n screens/LogInScreen.js:36:6 in useMutation$argument_1.onCompleted\n node_modules/@apollo/react-hooks/lib/react-hooks.cjs.js:635:25 in callOncomplete\n```\n\n```text\n{ data && console.log(data.signin.token) }\n```\n\n```text\nonCompleted(data)\n```\n\n```text\nonCompleted({ signin })\n```\n\n```text\nonCompleted\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":103,"estimatedTokens":555}}884{"id":"stack-40427609","source":"stackoverflow","questionId":40427609,"title":"Apollo Client cache","tags":["reactjs","graphql","apollo"],"text":"Title: Apollo Client cache\nTags: reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI just started using apollo client on a React application and I'm stuck on caching.\nI have a home page with a list of products where I do a query to get the id and name of those products and a product page where I do query for the ID, name, description and image.\n\nI would like that if a user visits the home page fist then a specific product page to only do a query for that product's description and image, also display the name during the loading (since I should have cached it already).\nI followed \"Controlling the Store\" part of the documentation (http://dev.apollodata.com/react/cache-updates.html) but still couldn't resolve it.\n\nThe query that is done when we go to the product page still asks for both the product's id and name whereas they should be cached since I already asked for them.\n\nI think I'm missing something but I can't figure it out.\nHere is a bit of the code:\n\n```\n// Create the apollo graphql client.\nconst apolloClient = new ApolloClient({\n networkInterface: createNetworkInterface({\n uri: `${process.env.GRAPHQL_ENDPOINT}`\n }),\n queryTransformer: addTypename,\n dataIdFromObject: (result) => {\n if (result.id && result.__typename) {\n\n console.log(result.id, result.__typename); //can see this on console, seems okey\n return result.__typename + result.id;\n }\n\n // Make sure to return null if this object doesn't have an ID\n return null;\n },\n});\n\n// home page query\n// return an array of objects (Product)\nexport default graphql(gql`\n query ProductsQuery {\n products {\n id, name\n }\n }\n`)(Home);\n\n//product page query\n//return an object (Product)\nexport default graphql(gql`\n query ProductQuery($productId: ID!) {\n product(id: $productId) {\n id, name, description, image\n }\n }\n`,{\n options: props => ({ variables: { productId: props.params.id } }),\n props: ({ data: { loading, product } }) => ({\n loading,\n product,})\n})(Product);\n```\n\nAnd my console output:\n\nhttps://i.sstatic.net/7VAE6.png\n\n========================================\n\nTop Answer:\nThis question is quite old, however, there is a solution to map the query to the correct location using `cacheRedirects`\n\nIn my project, I have a `projects` query and a `project` query.\n\nI can make a `cacheRedirect` like below:\n\n```\nconst client = new ApolloClient({\n uri: \"http://localhost:3000/graphql\",\n request: async (operation) => {\n const token = await localStorage.getItem('authToken');\n operation.setContext({\n headers: {\n authorization: token\n }\n });\n },\n cacheRedirects: {\n Query: {\n project: (_, { id }, { getCacheKey }) => getCacheKey({ id, __typename: 'Project' })\n }\n }\n});\n```\n\nThen when I load my dashboard, there is 1 query which gets `projects`. And then when navigating to a single `project`. No network request is made because it's reading from the cache π\n\nRead the full documentation on Cache Redirects\n\n========================================\n\nCode:\n```text\n// Create the apollo graphql client.\nconst apolloClient = new ApolloClient({\n networkInterface: createNetworkInterface({\n uri: `${process.env.GRAPHQL_ENDPOINT}`\n }),\n queryTransformer: addTypename,\n dataIdFromObject: (result) => {\n if (result.id && result.__typename) {\n\n console.log(result.id, result.__typename); //can see this on console, seems okey\n return result.__typename + result.id;\n }\n\n // Make sure to return null if this object doesn't have an ID\n return null;\n },\n});\n\n// home page query\n// return an array of objects (Product)\nexport default graphql(gql`\n query ProductsQuery {\n products {\n id, name\n }\n }\n`)(Home);\n\n//product page query\n//return an object (Product)\nexport default graphql(gql`\n query ProductQuery($productId: ID!) {\n product(id: $productId) {\n id, name, description, image\n }\n }\n`,{\n options: props => ({ variables: { productId: props.params.id } }),\n props: ({ data: { loading, product } }) => ({\n loading,\n product,})\n})(Product);\n```\n\n```text\nproducts\n```\n\n```text\nproduct\n```\n\n```text\nreturnPartialData: true\n```\n\n```js\nconst client = new ApolloClient({\n uri: \"http://localhost:3000/graphql\",\n request: async (operation) => {\n const token = await localStorage.getItem('authToken');\n operation.setContext({\n headers: {\n authorization: token\n }\n });\n },\n cacheRedirects: {\n Query: {\n project: (_, { id }, { getCacheKey }) => getCacheKey({ id, __typename: 'Project' })\n }\n }\n});\n```\n\n```text\ncacheRedirects\n```\n\n```text\nprojects\n```\n\n```text\nproject\n```\n\n```text\ncacheRedirect\n```\n\n```text\nprojects\n```\n\n```text\nproject\n```\n\n========================================\n\nComments:\n- To give an update for point 1 of the answer: This thing is already available: dev.apollodata.com/react/cache-updates.html#cacheRedirect\n- I believe that `returnPartialData` no longer exists and instead you have to implement two queries, a summary one and a full one as per here: dev.apollodata.com/react/migration.html#returnPartialData","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":205,"estimatedTokens":1273}}885{"id":"stack-63727362","source":"stackoverflow","questionId":63727362,"title":"showing MatSnackBar message when Apollo GraphQL fails with an error","tags":["angular","angular-material","graphql","apollo"],"text":"Title: showing MatSnackBar message when Apollo GraphQL fails with an error\nTags: angular, angular-material, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI have a website that uses Angular 10 and Apollo GraphQL.\n\nWhenever a request fails I want to show an error to the user uses `MatSnackBar`, but I don't know how to provide the `MatSnackBar` component to the `OnError()` function of the `apollo-link-error`.\n\nThis is my `graphql.module.ts` code:\n\n```\nimport {NgModule} from '@angular/core';\nimport {APOLLO_OPTIONS} from 'apollo-angular';\nimport {ApolloClientOptions, ApolloLink, InMemoryCache} from '@apollo/client/core';\nimport {HttpLink} from 'apollo-angular/http';\nimport { onError } from 'apollo-link-error';\n\nfunction getNewToken(): any {\n //TODO: need to implement\n}\n\nconst errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {\n if (graphQLErrors) {\n for (const err of graphQLErrors) {\n switch (err.extensions?.code) {\n case 'UNAUTHENTICATED':\n // error code is set to UNAUTHENTICATED\n // when AuthenticationError thrown in resolver\n\n // modify the operation context with a new token\n const oldHeaders = operation.getContext().headers;\n operation.setContext({\n headers: {\n ...oldHeaders,\n authorization: getNewToken(),\n },\n });\n // retry the request, returning the new observable\n return forward(operation);\n }\n }\n graphQLErrors.map(({ message, locations, path }) =>\n console.log(\n `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,\n ),\n );\n }\n\n if (networkError) {\n console.log(`[Network error]: ${networkError}`);\n // if you would also like to retry automatically on\n // network errors, we recommend that you use\n // apollo-link-retry\n }\n }\n);\n\nconst uri = 'http://localhost:8081/graphql';\nexport function createApollo(httpLink: HttpLink): ApolloClientOptions {\n const httpLinkHandler = httpLink.create({uri});\n const httpLinkWithErrorHandling = ApolloLink.from([\n // @ts-ignore\n errorLink,\n httpLinkHandler,\n ]);\n\n return {\n link: httpLinkWithErrorHandling,\n cache: new InMemoryCache(),\n };\n}\n\n@NgModule({\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\nWhere do I display the errors using `console.info`? I want to show a snack bar instead. Any ideas?\n\n========================================\n\nCode:\n```js\nimport {NgModule} from '@angular/core';\nimport {APOLLO_OPTIONS} from 'apollo-angular';\nimport {ApolloClientOptions, ApolloLink, InMemoryCache} from '@apollo/client/core';\nimport {HttpLink} from 'apollo-angular/http';\nimport { onError } from 'apollo-link-error';\n\nfunction getNewToken(): any {\n //TODO: need to implement\n}\n\nconst errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {\n if (graphQLErrors) {\n for (const err of graphQLErrors) {\n switch (err.extensions?.code) {\n case 'UNAUTHENTICATED':\n // error code is set to UNAUTHENTICATED\n // when AuthenticationError thrown in resolver\n\n // modify the operation context with a new token\n const oldHeaders = operation.getContext().headers;\n operation.setContext({\n headers: {\n ...oldHeaders,\n authorization: getNewToken(),\n },\n });\n // retry the request, returning the new observable\n return forward(operation);\n }\n }\n graphQLErrors.map(({ message, locations, path }) =>\n console.log(\n `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,\n ),\n );\n }\n\n if (networkError) {\n console.log(`[Network error]: ${networkError}`);\n // if you would also like to retry automatically on\n // network errors, we recommend that you use\n // apollo-link-retry\n }\n }\n);\n\nconst uri = 'http://localhost:8081/graphql';\nexport function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {\n const httpLinkHandler = httpLink.create({uri});\n const httpLinkWithErrorHandling = ApolloLink.from([\n // @ts-ignore\n errorLink,\n httpLinkHandler,\n ]);\n\n return {\n link: httpLinkWithErrorHandling,\n cache: new InMemoryCache(),\n };\n}\n\n@NgModule({\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\n```text\nMatSnackBar\n```\n\n```text\nMatSnackBar\n```\n\n```text\nOnError()\n```\n\n```text\napollo-link-error\n```\n\n```text\ngraphql.module.ts\n```\n\n```text\nconsole.info\n```\n\n```js\n@NgModule({\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink, MatSnackBar],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\n```js\nexport function createApollo(httpLink: HttpLink, matSnackBar: MatSnackBar): ApolloClientOptions<any> {\n localMatSnackbar = matSnackBar;\n```\n\n```js\nif (networkError) {\n localMatSnackbar?.open(networkError.message, 'DISMISS', {\n duration: 2000,\n verticalPosition: 'top'\n });\n```\n\n```text\nMatSnackbar\n```\n\n```text\nMatSnackBar\n```\n\n```text\ncreateApollo()\n```\n\n```text\nmatSnackBar\n```\n\n```text\nonError()\n```\n\n========================================\n\nComments:\n- links are not for rendering (it's not php where you can everywhere `echo \"error\"; die;`) ... it's a part of request/response processing, chain ... response has to reach client ... app working with client gets error info - consume this info in app layer ... how it would be with axios?\n- @xadm - can I subscribe for events in the toolbar and send event from here so the toolbar will catch it and display that mat-snackbar ?\n- sorry, IDK, not working with Ang.\n- I think you summed it perfectly and this is the beauty of the dependency injection in Angular.","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":241,"estimatedTokens":1448}}886{"id":"stack-59040451","source":"stackoverflow","questionId":59040451,"title":"Defining input types in graphql-ruby","tags":["ruby-on-rails","graphql","react-apollo","graphql-ruby"],"text":"Title: Defining input types in graphql-ruby\nTags: ruby-on-rails, graphql, react-apollo, graphql-ruby\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement an input type for filters with graphql-ruby and rails.\n\nBase input type looks like:\n\n```\nmodule Types\n class BaseInputObject My own input type looks like:\n\n```\nmodule Types\n class PhotoFilterType query_type's method header looks like:\n\n```\nfield :filtered_photos, [Types::PhotoType], null: true do\n argument :filters, Types::PhotoFilterType, 'filters for photo', required: true\n end\n```\n\nAnd the query as follows:\n\n```\nconst FILTER_QUERY = gql`\n query getFilteredPhotos($filters: PhotoFilterType!) {\n filteredPhotos(filters: $filters) {\n id\n title\n width\n height\n }\n }\n`\n```\n\nInteracting with the backend using react-apollo as follows:\n\n```\nthis.props.client.query({\n query: FILTER_QUERY,\n variables: {\n filters: {\n attribution: author.length > 0 ? author : '',\n country: country.length > 0 ? country : '',\n year: year ? year : 9999\n }\n }\n })\n```\n\nI get the following error \n\n {message: \"PhotoFilterType isn't a defined input type (on $filters)\",β¦}\n\nBut when I interact with rails console, I see:\n\n```\nirb(main):004:0> Types::PhotoFilterType\n=> Types::PhotoFilterType\n```\n\nSo I don't think the type being undefined is an issue.\n\nAny idea what is going wrong and how to fix it? Thanks in advance.\n\n========================================\n\nCode:\n```text\nmodule Types\n class BaseInputObject < GraphQL::Schema::InputObject\n end\nend\n```\n\n```text\nmodule Types\n class PhotoFilterType < Types::BaseInputObject\n argument :attribution, String, \"Filters by submitter\", required: false\n argument :country, String, \"Filters by country\", required: false\n argument :year, Int, \"Filters by year\", required: false\n end\nend\n```\n\n```text\nfield :filtered_photos, [Types::PhotoType], null: true do\n argument :filters, Types::PhotoFilterType, 'filters for photo', required: true\n end\n```\n\n```text\nconst FILTER_QUERY = gql`\n query getFilteredPhotos($filters: PhotoFilterType!) {\n filteredPhotos(filters: $filters) {\n id\n title\n width\n height\n }\n }\n`\n```\n\n```text\nthis.props.client.query({\n query: FILTER_QUERY,\n variables: {\n filters: {\n attribution: author.length > 0 ? author : '',\n country: country.length > 0 ? country : '',\n year: year ? year : 9999\n }\n }\n })\n```\n\n```text\nirb(main):004:0> Types::PhotoFilterType\n=> Types::PhotoFilterType\n```\n\n```text\nconst FILTER_QUERY = gql`\n query getFilteredPhotos($filters: PhotoFilter!) { // not PhotoFilterType\n filteredPhotos(filters: $filters) {\n id\n title\n width\n height\n }\n }\n`\n```\n\n========================================\n\nComments:\n- Can you run this introspection query and paste the relevant output? gist.github.com/lunks/2e8dc2b3351b9a1741ff474c02570299","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":142,"estimatedTokens":725}}887{"id":"stack-70585823","source":"stackoverflow","questionId":70585823,"title":"Can not use both expression and non-expression parameters in the same request","tags":["amazon-web-services","graphql","dynamodb-queries"],"text":"Title: Can not use both expression and non-expression parameters in the same request\nTags: amazon-web-services, graphql, dynamodb-queries\nSource: Stack Overflow\n\nQuestion:\nBasically, I have a table with two indexes that I'm trying to query and filter.\nThe querying part works for the Table and the index but the problem happens when I try to filter:\n\n```\nValidationException: Can not use both expression and non-expression parameters in the same request: Non-expression parameters: {QueryFilter} Expression parameters: {KeyConditionExpression}\n```\n\nHere are the params passed to docClient.query():\n\n```\n{\n TableName: 'MyTable',\n Limit: 15,\n ScanIndexForward: false,\n IndexName: 'user-date-index',\n KeyConditionExpression: '#user = :yyyy',\n ExpressionAttributeNames: { '#user': 'user' },\n ExpressionAttributeValues: { ':yyyy': 'the_user_id' },\n QueryFilter: { status: { AttributeValueList: [Array], ComparisonOperator: 'EQ' } }\n}\n```\n\nWhen I call the query with the same params but without the QueryFilter, I get correct results, but I still need to filter (by status in this case, and I have about 5 other options to filter with).\n\nI've spent a few hours trying different things and the AWS docs are not clear enough and no examples are presented, I've spent a whole day to even get to that point.\n\n========================================\n\nCode:\n```text\nValidationException: Can not use both expression and non-expression parameters in the same request: Non-expression parameters: {QueryFilter} Expression parameters: {KeyConditionExpression}\n```\n\n```text\n{\n TableName: 'MyTable',\n Limit: 15,\n ScanIndexForward: false,\n IndexName: 'user-date-index',\n KeyConditionExpression: '#user = :yyyy',\n ExpressionAttributeNames: { '#user': 'user' },\n ExpressionAttributeValues: { ':yyyy': 'the_user_id' },\n QueryFilter: { status: { AttributeValueList: [Array], ComparisonOperator: 'EQ' } }\n}\n```\n\n```text\n{\n TableName: 'MyTable',\n Limit: 15,\n ScanIndexForward: false,\n IndexName: 'user-date-index',\n KeyConditionExpression: '#user = :yyyy',\n FilterExpression: '#status = :status',\n ExpressionAttributeNames: { '#user': 'user', '#status': 'status' },\n ExpressionAttributeValues: { ':yyyy': 'the_user_id', ':status': 'STATUS' }\n}\n```\n\n```text\nQueryFilter\n```\n\n```text\nQueryFilter\n```\n\n```text\nFilterExpression\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":75,"estimatedTokens":580}}888{"id":"stack-59933324","source":"stackoverflow","questionId":59933324,"title":"Laravel Lighthouse - Sorting a query by a property of a relationship","tags":["php","laravel","graphql","laravel-lighthouse"],"text":"Title: Laravel Lighthouse - Sorting a query by a property of a relationship\nTags: php, laravel, graphql, laravel-lighthouse\nSource: Stack Overflow\n\nQuestion:\nWith a schema like the below, is there a way to execute a query and have the results sorted by the `name` property of the `JobType` entity? I'd like to have a paginated list of jobs, and display the results sorted by the job type name, alphabetically.\n\n```\nextend type Query @middleware(checks: [\"auth:api\"]) {\n jobs(orderBy: _ @orderBy): [Job!]! @paginate(defaultCount: 10, model: \"App\\\\Job\")\n}\n\ntype Job {\n id: ID!\n description: String!\n job_type: JobType! @belongsTo\n}\n\ntype JobType {\n id: ID!\n name: String!\n}\n```\n\nI've tried using the `@builder` directive, then using a join in the builder to bring the name property in that way, but that seems to cause some issues with entity IDs, which causes the relationships to link to the wrong things.\n\nAny ideas?\n\n========================================\n\nTop Answer:\nJust to collect the question and accepted answer into a working example, this is what ended up working for me:\n\nGraphQL:\n\n```\nextend type Query @middleware(checks: [\"auth:api\"]) {\n jobs(@builder(method: \"App\\\\Models\\\\Job@jobsInOrder\")): [Job!]! @paginate(defaultCount: 10, model: \"App\\\\Job\")\n}\n\ntype Job {\n id: ID!\n description: String!\n job_type: JobType! @belongsTo\n}\n\ntype JobType {\n id: ID!\n name: String!\n}\n```\n\nJob.php:\n\n```\npublic function jobsInOrder(Builder $builder): Builder\n{\n\n // Connect the events with their date_times\n return $builder->join('job_types', 'jobs.id', '=', 'job_types.job_id')\n ->select('jobs.*')\n ->orderBy('job_types.name');\n}\n```\n\n========================================\n\nCode:\n```text\nextend type Query @middleware(checks: [\"auth:api\"]) {\n jobs(orderBy: _ @orderBy): [Job!]! @paginate(defaultCount: 10, model: \"App\\\\Job\")\n}\n\ntype Job {\n id: ID!\n description: String!\n job_type: JobType! @belongsTo\n}\n\ntype JobType {\n id: ID!\n name: String!\n}\n```\n\n```text\nname\n```\n\n```text\nJobType\n```\n\n```text\n@builder\n```\n\n```text\n@builder\n```\n\n```text\n->select('model.*')\n```\n\n```text\nextend type Query @middleware(checks: [\"auth:api\"]) {\n jobs(@builder(method: \"App\\\\Models\\\\Job@jobsInOrder\")): [Job!]! @paginate(defaultCount: 10, model: \"App\\\\Job\")\n}\n\ntype Job {\n id: ID!\n description: String!\n job_type: JobType! @belongsTo\n}\n\ntype JobType {\n id: ID!\n name: String!\n}\n```\n\n```php\npublic function jobsInOrder(Builder $builder): Builder\n{\n\n // Connect the events with their date_times\n return $builder->join('job_types', 'jobs.id', '=', 'job_types.job_id')\n ->select('jobs.*')\n ->orderBy('job_types.name');\n}\n```\n\n========================================\n\nComments:\n- This was the missing piece of the puzzle. Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":137,"estimatedTokens":692}}889{"id":"stack-58753161","source":"stackoverflow","questionId":58753161,"title":"How can I avoid \"auto-update\" cache when using `react-apollo-hooks` and `useSubscription` hook","tags":["reactjs","graphql","react-apollo","apollo-cache-inmemory"],"text":"Title: How can I avoid \"auto-update\" cache when using `react-apollo-hooks` and `useSubscription` hook\nTags: reactjs, graphql, react-apollo, apollo-cache-inmemory\nSource: Stack Overflow\n\nQuestion:\nI have some **Apollo-Hooks** code that uses `useSubscription` to listen for event changes in a subscription:\n\n```\nuseSubscription(MySubscription, {\n onSubscriptionData: async ({ client, subscriptionData: { data } }) => {\n if (!data) {\n return;\n }\n ...\n```\n\nThis code automatically updates the cache on the response, which is great in most circumstances\n\nHowever, I need to do some result-processing *after* the response is received, yet *prior* to the cache being updated.\n\n*Does anyone know of a way to use `useSubscription` hook, and **not** have the cache be automatically updated?* \n\nThe response will ultimately always have an entity with `__typename` in it.\n\n========================================\n\nTop Answer:\nSo, you can do a manual cache update, it would look something like this \n\n```\napollo.mutate({\n mutation: createTaskMutation,\n variables: item,\n update: (cache, { data }) => {\n try {\n let { allTasks } = cache.readQuery({ query: getTasks });\n allTasks.push(data);\n cache.writeQuery({ //\n query: getTasks,\n data: {\n 'allTasks': allTasks\n }\n });\n } catch (e) {\n // We should always catch here,\n // as the cache may be empty or the query may fail\n }\n});\n```\n\n========================================\n\nCode:\n```text\nuseSubscription<MySubscriptionUpdated>(MySubscription, {\n onSubscriptionData: async ({ client, subscriptionData: { data } }) => {\n if (!data) {\n return;\n }\n ...\n```\n\n```text\nuseSubscription\n```\n\n```text\nuseSubscription\n```\n\n```text\n__typename\n```\n\n```text\nuseSubscription<MySubscriptionUpdated>(MySubscription, {\n fetchPolicy: \"no-cache\",\n onSubscriptionData: async ({ client, subscriptionData: { data } }) => {\n if (!data) {\n return;\n }\n ...\n```\n\n```text\nfetchPolicy\n```\n\n```text\ncache-first\n```\n\n```text\nno-cache\n```\n\n```text\napollo.mutate({\n mutation: createTaskMutation,\n variables: item,\n update: (cache, { data }) => {\n try {\n let { allTasks } = cache.readQuery({ query: getTasks });\n allTasks.push(data);\n cache.writeQuery({ //\n query: getTasks,\n data: {\n 'allTasks': allTasks\n }\n });\n } catch (e) {\n // We should always catch here,\n // as the cache may be empty or the query may fail\n }\n});\n```\n\n========================================\n\nComments:\n- Even when you use an `update` function, Apollo does an auto-update before calling your `update` unless you use `fetchPolicy: 'no-cache'`. OP was asking how to prevent that auto-update.","metadata":{"transformedAt":"2026-08-18T18:32:36.090Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":121,"estimatedTokens":675}}890{"id":"stack-58286011","source":"stackoverflow","questionId":58286011,"title":"Apollo Subscriptions: Apollo Graphql is receiving updates on Playground but not on client","tags":["reactjs","graphql","apollo","apollo-client","graphql-subscriptions"],"text":"Title: Apollo Subscriptions: Apollo Graphql is receiving updates on Playground but not on client\nTags: reactjs, graphql, apollo, apollo-client, graphql-subscriptions\nSource: Stack Overflow\n\nQuestion:\nI'm using react on Apollo GraphQL subscriptions and I can receive updates on Apollo Playground but not on Client. Here is the response on the Apollo Playground:\n\nhttps://i.sstatic.net/4bwrs.png\n\nGraphql Server is on `http://localhost:4000/` and subscriptions on ws://localhost:4000/graphql. However, it works on the playground but not on client-side. I have set up Apollo client in this manner to receive updates from server:\n\n```\nimport ApolloClient from 'apollo-boost';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { HttpLink } from 'apollo-link-http';\nimport { split } from 'apollo-link';\nimport { getMainDefinition } from 'apollo-utilities';\n\nconst httpLink = new HttpLink({\n uri: 'http://localhost:4000/graphql'\n});\n\nexport const wsLink = new WebSocketLink({\n uri: `ws://localhost:4000/graphql`,\n options: {\n reconnect: false\n }\n});\n\nexport const link = split(\n // split based on operation type\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink,\n);\n\nexport const client = new ApolloClient({\n uri: 'http://localhost:4000/',\n});\n```\n\nIn my view I have used `useSubscriptions`:\n\n```\nconst MESSAGE_SENT_SUBSCRIPTION = gql`subscription {\n messageSent {\n id\n message\n }\n}`\nconst {data: newMessage, loading: newMessageLoading} = useSubscription(MESSAGE_SENT_SUBSCRIPTION, {});\n```\n\nAnd on render, I have used:\n\n```\n{!newMessageLoading && JSON.stringify(newMessage)}\n```\n\nBut from client, it doesn't receive updates but I am sure that it connects with Graphql WebSockets server.\n\nhttps://i.sstatic.net/8bNhz.png\n\nServer Side:\n\n```\nlet database = require(\"./src/database.js\")\nlet schema = require(\"./src/schema.js\");\nlet resolvers = require(\"./src/resolvers.js\");\nlet {ApolloServer} = require(\"apollo-server\");\n\n// The ApolloServer constructor requires two parameters: your schema\n// definition and your set of resolvers.\nconst server = new ApolloServer({ \n typeDefs: schema, \n resolvers: resolvers,\n context: {\n database\n }\n});\n\n// The `listen` method launches a web server.\nserver.listen().then(({ url,subscriptionsUrl ,subscriptionsPath}) => {\n console.log(`π Server ready at ${url}`);\n console.log(`realtime here at ${subscriptionsUrl} and path ${subscriptionsPath}`)\n});\n```\n\nWhat I'm doing wrong here, Is there anyone who came across with such issue?\n\n========================================\n\nTop Answer:\nI had to import ApolloClient from `apollo-client`. Here is the working configuration for client-side:\n\n```\nimport ApolloClient from 'apollo-client';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { HttpLink } from 'apollo-link-http';\nimport { split } from 'apollo-link';\nimport { onError } from 'apollo-link-error';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { getMainDefinition } from 'apollo-utilities';\n\nexport const httpLink = new HttpLink({\n uri: \"http://localhost:4000/graphql\", // use https for secure endpoint\n});\n\n// Create a WebSocket link:\nexport const wsLink = new WebSocketLink({\n uri: \"ws://localhost:4000/subscriptions\", // use wss for a secure endpoint\n options: {\n reconnect: true\n }\n});\n\n// using the ability to split links, you can send data to each link\n// depending on what kind of operation is being sent\nexport const link = split(\n // split based on operation type\n ({ query }) => {\n const { kind, operation } = getMainDefinition(query);\n return kind === 'OperationDefinition' && operation === 'subscription';\n },\n wsLink,\n httpLink,\n);\n\n// Instantiate client\nexport const client = new ApolloClient({\n link,\n uri: \"http://localhost:4000/graphql\",\n cache: new InMemoryCache()\n})\n```\n\n========================================\n\nCode:\n```text\nimport ApolloClient from 'apollo-boost';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { HttpLink } from 'apollo-link-http';\nimport { split } from 'apollo-link';\nimport { getMainDefinition } from 'apollo-utilities';\n\nconst httpLink = new HttpLink({\n uri: 'http://localhost:4000/graphql'\n});\n\nexport const wsLink = new WebSocketLink({\n uri: `ws://localhost:4000/graphql`,\n options: {\n reconnect: false\n }\n});\n\nexport const link = split(\n // split based on operation type\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink,\n);\n\n\n\nexport const client = new ApolloClient({\n uri: 'http://localhost:4000/',\n});\n```\n\n```text\nconst MESSAGE_SENT_SUBSCRIPTION = gql`subscription {\n messageSent {\n id\n message\n }\n}`\nconst {data: newMessage, loading: newMessageLoading} = useSubscription(MESSAGE_SENT_SUBSCRIPTION, {});\n```\n\n```text\n{!newMessageLoading && JSON.stringify(newMessage)}\n```\n\n```text\nlet database = require(\"./src/database.js\")\nlet schema = require(\"./src/schema.js\");\nlet resolvers = require(\"./src/resolvers.js\");\nlet {ApolloServer} = require(\"apollo-server\");\n\n// The ApolloServer constructor requires two parameters: your schema\n// definition and your set of resolvers.\nconst server = new ApolloServer({ \n typeDefs: schema, \n resolvers: resolvers,\n context: {\n database\n }\n});\n\n// The `listen` method launches a web server.\nserver.listen().then(({ url,subscriptionsUrl ,subscriptionsPath}) => {\n console.log(`π Server ready at ${url}`);\n console.log(`realtime here at ${subscriptionsUrl} and path ${subscriptionsPath}`)\n});\n```\n\n```text\nhttp://localhost:4000/\n```\n\n```text\nuseSubscriptions\n```\n\n```text\nimport ApolloClient from 'apollo-boost';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { HttpLink } from 'apollo-link-http';\nimport { split } from 'apollo-link';\nimport { onError } from 'apollo-link-error';\nimport { getMainDefinition } from 'apollo-utilities';\n\nconst httpLink = new HttpLink({\n uri: 'http://localhost:4000/graphql'\n});\n\nexport const wsLink = new WebSocketLink({\n uri: `ws://localhost:4000/subscriptions`,\n options: {\n reconnect: false\n }\n});\n\nexport const link = split(\n // split based on operation type\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' &&\n definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink,\n);\n\nexport const graphqlServer = new ApolloClient({\n link: ApolloLink.from([\n onError(({\n graphQLErrors,\n networkError\n }) => {\n if (graphQLErrors) {\n graphQLErrors.map(({\n message,\n locations,\n path\n }) =>\n console.log(\n `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`\n )\n );\n }\n if (networkError) {\n console.log(`[Network error]: ${networkError}`);\n }\n }),\n link // YOUR LINK (NOW MATCHING YOUR CODE)\n ])\n});\n```\n\n```text\n...\nconst server = new ApolloServer({ \n typeDefs: schema, \n resolvers: resolvers,\n subscriptions: {\n path: '/subscriptions'\n },\n context: {\n database\n }\n});\n...\n```\n\n```text\n/subscriptions\n```\n\n```text\nimport ApolloClient from 'apollo-client';\nimport { WebSocketLink } from 'apollo-link-ws';\nimport { HttpLink } from 'apollo-link-http';\nimport { split } from 'apollo-link';\nimport { onError } from 'apollo-link-error';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { getMainDefinition } from 'apollo-utilities';\n\nexport const httpLink = new HttpLink({\n uri: \"http://localhost:4000/graphql\", // use https for secure endpoint\n});\n\n// Create a WebSocket link:\nexport const wsLink = new WebSocketLink({\n uri: \"ws://localhost:4000/subscriptions\", // use wss for a secure endpoint\n options: {\n reconnect: true\n }\n});\n\n// using the ability to split links, you can send data to each link\n// depending on what kind of operation is being sent\nexport const link = split(\n // split based on operation type\n ({ query }) => {\n const { kind, operation } = getMainDefinition(query);\n return kind === 'OperationDefinition' && operation === 'subscription';\n },\n wsLink,\n httpLink,\n);\n\n// Instantiate client\nexport const client = new ApolloClient({\n link,\n uri: \"http://localhost:4000/graphql\",\n cache: new InMemoryCache()\n})\n```\n\n```text\napollo-client\n```\n\n========================================\n\nComments:\n- I have changed the port and getting error `ws` which is `WebSocket is closed before the connection is established.`\n- @DanielRearden client side is on port 3000 and graphql port is 4000.\n- I'll test this and let you know.\n- Looks like you copied the code from somewhere else, Can you configure your answer to match my code?\n- I copied from my project with same stack man. The only thing was changed - i've removed cache option.\n- 'onError' is not defined, can you paste on error method as well.\n- Can you compose a code using the above? For some reasons, your code is not working on my end.\n- I've completed whole code instead of you. So now you can just copy it and paste, just use CTRL+C and CTRL+V on windows/linux or CMD+C and CMD+V on macos\n- Your implementation calls an requests to localhost:3000/graphql on client.\n- Sorry, but its yours implementation, I've just copied your code to my answer. As @DanielReardens said - it's not correct to use same url for WS: and HTTP:. So you need to provide your ApolloServer initialization code to let me give you more help\n- I'm glad that you give your time to help me. I have updated the question.\n- On Apollo playground, it works fine and I am confident that from server the subscriptions work fine.\n- Updated answer with ApolloServer\n- Thanks for your support and here is the working code: gist.github.com/ilyaskarim/a1b2a05b8a9094f7f110cc5580842c8e.\n- I added same code but still subscription is not working\n- Can you post a new question? I'd like to help you. Maybe your scenario is different.\n- I have posted my question here. stackoverflow.com/questions/58659204/…","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":370,"estimatedTokens":2581}}891{"id":"stack-58718721","source":"stackoverflow","questionId":58718721,"title":"Python Graphene working with many to many relations","tags":["python","django","graphql","graphene-python","graphene-django"],"text":"Title: Python Graphene working with many to many relations\nTags: python, django, graphql, graphene-python, graphene-django\nSource: Stack Overflow\n\nQuestion:\nif this is answered somewhere else then I am sorry but 2 days after work and still no cigar... \n\nI have a player model: \n\n```\nclass Player(models.Model):\n name = models.CharField(max_length=60)\n discord_id = models.CharField(max_length=60, null=True)\n known_npcs = models.ManyToManyField(NPC)\n```\n\nThe player can know many NPCs, and any NPC can be known by many players. \n\nNPC is nothing special: \n\n```\nclass NPC(models.Model):\n image = models.ImageField()\n name = models.CharField(max_length=50)\n description = models.TextField()\n```\n\nlast part of the puzzle is the Fact a fact is some piece of information attached to a NPC, however a person can know a NPC, but not necessarily all of the fact's related to the NPC are known by the Player hence the Fact looks like this: \n\n```\nclass Fact(models.Model):\n fact = models.TextField()\n known_by = models.ManyToManyField(Player)\n npc = models.ForeignKey(NPC, on_delete=models.DO_NOTHING, null=True)\n```\n\nNow in graphene I want to create a Player and allPlayers query that would give me this: \n\n```\n{\n allPlayers {\n name\n knownNPCs {\n image\n name\n description\n factsKnown {\n fact\n }\n }\n }\n}\n```\n\n**Where the factsKnown are only the ones based on the ManyToMany relation from the Fact object.**\n\nWhat I have created so far returns the data but does not filter the Facts based on the player parent just shows all the facts related to the npc :( \n\nFact schema\n\n```\nclass FactType(DjangoObjectType):\n class Meta:\n model = Fact\n filter_fields = [\"id\"]\n\nclass Query(object):\n fact = Node.Field(FactType)\n all_Facts = graphene.List(FactType)\n\n def resolve_all_Facts(self, info, **kwargs):\n return Fact.objects.all()\n```\n\nNPCSchema\n\n```\nclass NPCType(DjangoObjectType):\n class Meta:\n model = NPCS\n\nclass Query(object):\n all_NPCs = graphene.Field(NPCType)\n facts = graphene.List(FactType)\n def resolve_all_NPCs(self, info, **kwargs):\n return NPCS.objects.all()\n```\n\nPlayerSchema:\n\n```\nclass PlayerType(DjangoObjectType):\n class Meta:\n model = Player\n interfaces = (Node,)\n filter_fields = [\"id\"]\n\nclass Query(object):\n player = Node.Field(PlayerType)\n all_players = graphene.List(PlayerType)\n\n def resolve_all_players(self, info, **kwargs):\n return Player.objects.all()\n\n def resolve_player(self, info, **kwargs):\n player = Player.objects.filter(id=info.id)\n```\n\n========================================\n\nCode:\n```text\nclass Player(models.Model):\n name = models.CharField(max_length=60)\n discord_id = models.CharField(max_length=60, null=True)\n known_npcs = models.ManyToManyField(NPC)\n```\n\n```text\nclass NPC(models.Model):\n image = models.ImageField()\n name = models.CharField(max_length=50)\n description = models.TextField()\n```\n\n```text\nclass Fact(models.Model):\n fact = models.TextField()\n known_by = models.ManyToManyField(Player)\n npc = models.ForeignKey(NPC, on_delete=models.DO_NOTHING, null=True)\n```\n\n```text\n{\n allPlayers {\n name\n knownNPCs {\n image\n name\n description\n factsKnown {\n fact\n }\n }\n }\n}\n```\n\n```text\nclass FactType(DjangoObjectType):\n class Meta:\n model = Fact\n filter_fields = [\"id\"]\n\nclass Query(object):\n fact = Node.Field(FactType)\n all_Facts = graphene.List(FactType)\n\n def resolve_all_Facts(self, info, **kwargs):\n return Fact.objects.all()\n```\n\n```text\nclass NPCType(DjangoObjectType):\n class Meta:\n model = NPCS\n\nclass Query(object):\n all_NPCs = graphene.Field(NPCType)\n facts = graphene.List(FactType)\n def resolve_all_NPCs(self, info, **kwargs):\n return NPCS.objects.all()\n```\n\n```text\nclass PlayerType(DjangoObjectType):\n class Meta:\n model = Player\n interfaces = (Node,)\n filter_fields = [\"id\"]\n\n\nclass Query(object):\n player = Node.Field(PlayerType)\n all_players = graphene.List(PlayerType)\n\n def resolve_all_players(self, info, **kwargs):\n return Player.objects.all()\n\n def resolve_player(self, info, **kwargs):\n player = Player.objects.filter(id=info.id)\n```\n\n```text\nclass PlayerType(DjangoObjectType):\nclass Meta:\n model = Player\n filter_fields = [\"id\"]\n\nfiltered_facts = graphene.List(FactGroup)\n\ndef resolve_filtered_facts(self, info, **kwargs):\n groups = defaultdict(list)\n facts = self.known_facts.all()\n for fact in facts:\n groups[fact.npc].append(fact.fact)\n grouped_facts = []\n for key, value in groups.items():\n grouped_facts.append(FactGroup(npc=key, facts=value))\n\n return grouped_facts\n```\n\n========================================\n\nComments:\n- What will happen if you do a `{ allPlayers { name knownNPCs { image name description factSet { fact } } } }`?\n- @Roel Still returns the facts not assigned in the known_by object :/ to make this funnier it knows of the connection cuz returns ``` \"allPlayers\": [ { \"id\": \"1\", \"knownNpcs\": [ { \"name\": \"XXXXX\", \"factSet\": [ { \"fact\": \"YYYYY\", \"playerSet\": [ { \"id\": \"2\" } ] } ] }, ```","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":218,"estimatedTokens":1272}}892{"id":"stack-57638770","source":"stackoverflow","questionId":57638770,"title":"Apollo GraphQL, is there a way to manipulate the data that is being written to the cache during querying?","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: Apollo GraphQL, is there a way to manipulate the data that is being written to the cache during querying?\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nAccording to Apollo GraphQL docs, Apollo Links can go in two directions - client -> server and server -> client:\n\nhttps://i.sstatic.net/59MPR.png\n\nHowever, I am not able to find docs or examples regarding links that go from server -> client. My goal is to catch and parse the incoming data that that is going to be stored in cache. This way, I can read a custom parsed data from cache. Is is possible to achieve this?\n\n========================================\n\nComments:\n- Great! Thanks you for the help!","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":15,"estimatedTokens":177}}893{"id":"stack-55688537","source":"stackoverflow","questionId":55688537,"title":"DynamoDB ReturnValues UPDATED_OLD in AppSync","tags":["amazon-dynamodb","graphql","aws-appsync","vtl"],"text":"Title: DynamoDB ReturnValues UPDATED_OLD in AppSync\nTags: amazon-dynamodb, graphql, aws-appsync, vtl\nSource: Stack Overflow\n\nQuestion:\nIm trying to update an item attribute in a **DynamoDb** table with **AppSync**. \nOnce successful i want to use the previous value of that attribute as the key in my next call (I'm using pipeline resolvers). \n\nTo achieve this with **DynamoDB** you just set **UPDATED_OLD** as the return value. \n\nI cannot find any documentation for specifying the return value of a DynamoDB resolver for AppSync.\nIve tried the following. \n\n```\n{\n \"version\" : \"2018-05-29\",\n \"operation\" : \"UpdateItem\",\n \"key\": {\n \"id\": $util.dynamodb.toDynamoDBJson(\"foo\")\n },\n \"condition\" : {\n \"expression\" : \"attribute_exists(id)\"\n },\n \"update\" : {\n \"expression\" : \"SET bar = :bar\",\n \"expressionValues\" : {\n \":bar\" : {\"S\" : \"$bar\"}\n }\n },\n \"returnValues\": \"UPDATED_OLD\"\n }\n```\n\nBut its not valid syntax.\n\n```\n\"message\": \"Unsupported element '$[returnValues]'.\"\n```\n\n========================================\n\nCode:\n```text\n{\n \"version\" : \"2018-05-29\",\n \"operation\" : \"UpdateItem\",\n \"key\": {\n \"id\": $util.dynamodb.toDynamoDBJson(\"foo\")\n },\n \"condition\" : {\n \"expression\" : \"attribute_exists(id)\"\n },\n \"update\" : {\n \"expression\" : \"SET bar = :bar\",\n \"expressionValues\" : {\n \":bar\" : {\"S\" : \"$bar\"}\n }\n },\n \"returnValues\": \"UPDATED_OLD\"\n }\n```\n\n```text\n\"message\": \"Unsupported element '$[returnValues]'.\"\n```\n\n========================================\n\nComments:\n- I was afraid that this were the case. Thank you for confirming it. Hopefully it will be rectified in some future update to make AppSync even more viable.\n- I will take it to the team as a feature request\n- Is this still the case?\n- @VasileiosLekakis Is there a Github issue associated with this feature request? This would be a valuable addition\n- @bingles we don't have track feature requests as Github issues at AWS Appsync like they do for AWS Amplify.\n- As for DeleteItem it return ALL_OLD, which makes sense.","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":75,"estimatedTokens":507}}894{"id":"stack-50318127","source":"stackoverflow","questionId":50318127,"title":"getting started in graphql-php: how to add resolver functions to schema from .graphql file?","tags":["graphql","graphql-php"],"text":"Title: getting started in graphql-php: how to add resolver functions to schema from .graphql file?\nTags: graphql, graphql-php\nSource: Stack Overflow\n\nQuestion:\nI'm totally new to GraphQL and wanted to play around with graphql-php in order to build a simple API to get started. I'm currently reading the docs and trying out the examples, but I'm stuck quite at the beginning.\n\nI want my schema to be stored in a `schema.graphql` file instead of building it manually, so I followed the docs on how to do that and it is indeed working:\n\n```\n 'You said: '];\n $result = GraphQL::executeQuery($schema, $query, $rootValue, $context, $variableValues);\n $output = $result->toArray();\n} catch (\\Exception $e) {\n $output = [\n 'error' => [\n 'message' => $e->getMessage()\n ]\n ];\n}\nheader('Content-Type: application/json; charset=UTF-8');\necho json_encode($output);\n```\n\nThis is what my `schema.graphql` file looks like:\n\n```\nschema {\n query: Query \n}\n\ntype Query {\n products: [Product!]!\n}\n\ntype Product {\n id: ID!,\n type: ProductType\n}\n\nenum ProductType {\n HDRI,\n SEMISPHERICAL_HDRI,\n SOUND\n}\n```\n\nI can query it for example with\n\n```\nquery {\n __schema {types{name}}\n}\n```\n\nand this will return the metadata as expected. But of course now I want to query for actual product data and get that from a database, and for that I'd need to define a resolver function.\n\nThe docs at http://webonyx.github.io/graphql-php/type-system/type-language/ state: \"By default, such schema is created without any resolvers. We have to rely on default field resolver and root value in order to execute a query against this schema.\" - but there is no example for doing this.\n\nHow can I add resolver functions for each of the types/fields?\n\n========================================\n\nTop Answer:\nThis approach works without instantiating a Server. In my case, I already have a server and can read HTTP data, all I needed was to read the GraphQL schema and run the query. First I read the schema from a file:\n\n```\n$schemaContent = // file_get_contents or whatever works for you\n\n $schemaDocument = GraphQL\\Language\\Parser::parse($schemaContent);\n $schemaBuilder = new GraphQL\\Utils\\BuildSchema($schemaDocument);\n $schema = $schemaBuilder->buildSchema();\n```\n\nThen I execute the query passing a custom field resolver:\n\n```\n$fieldResolver = function() {\n return call_user_func_array([$this, 'defaultFieldResolver'], func_get_args());\n };\n\n $result = GraphQL\\GraphQL::executeQuery(\n $schema,\n $query, // this was grabbed from the HTTP post data\n null,\n $appContext, // custom context\n $variables, // this was grabbed from the HTTP post data\n null,\n $fieldResolver // HERE, custom field resolver\n );\n```\n\nThe field resolver looks like this:\n\n```\nprivate static function defaultFieldResolver(\n $source,\n $args,\n $context,\n \\GraphQL\\Type\\Definition\\ResolveInfo $info\n) {\n $fieldName = $info->fieldName;\n $parentType = $info->parentType->name;\n\n if ($source === NULL) {\n // this is the root value, return value depending on $fieldName\n // ...\n } else {\n // Depending on field type ($parentType), I call different field resolvers.\n // Since our system is big, we implemented a bootstrapping mechanism\n // so modules can register field resolvers in this class depending on field type\n // ...\n\n // If no field resolver was defined for this $parentType,\n // we just rely on the default field resolver provided by graphql-php (copy/paste).\n $fieldName = $info->fieldName;\n $property = null;\n\n if (is_array($source) || $source instanceof \\ArrayAccess) {\n if (isset($source[$fieldName])) {\n $property = $source[$fieldName];\n }\n } else if (is_object($source)) {\n if (isset($source->{$fieldName})) {\n $property = $source->{$fieldName};\n }\n }\n\n return $property instanceof \\Closure\n ? $property($source, $args, $context)\n : $property;\n }\n}\n```\n\n========================================\n\nCode:\n```php\n<?php\n// graph-ql is installed via composer\nrequire('../vendor/autoload.php');\n\nuse GraphQL\\Language\\Parser;\nuse GraphQL\\Utils\\BuildSchema;\nuse GraphQL\\Utils\\AST;\nuse GraphQL\\GraphQL;\n\ntry {\n $cacheFilename = 'cached_schema.php';\n // caching, as recommended in the docs, is disabled for testing\n // if (!file_exists($cacheFilename)) {\n $document = Parser::parse(file_get_contents('./schema.graphql'));\n file_put_contents($cacheFilename, \"<?php\\nreturn \" . var_export(AST::toArray($document), true) . ';');\n /*} else {\n $document = AST::fromArray(require $cacheFilename); // fromArray() is a lazy operation as well\n }*/\n\n $typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {\n // In the docs, this function is just empty, but I needed to return the $typeConfig, otherwise I got an error\n return $typeConfig;\n };\n $schema = BuildSchema::build($document, $typeConfigDecorator);\n\n $context = (object)array();\n\n // this has been taken from one of the examples provided in the repo\n $rawInput = file_get_contents('php://input');\n $input = json_decode($rawInput, true);\n $query = $input['query'];\n $variableValues = isset($input['variables']) ? $input['variables'] : null;\n $rootValue = ['prefix' => 'You said: '];\n $result = GraphQL::executeQuery($schema, $query, $rootValue, $context, $variableValues);\n $output = $result->toArray();\n} catch (\\Exception $e) {\n $output = [\n 'error' => [\n 'message' => $e->getMessage()\n ]\n ];\n}\nheader('Content-Type: application/json; charset=UTF-8');\necho json_encode($output);\n```\n\n```text\nschema {\n query: Query \n}\n\ntype Query {\n products: [Product!]!\n}\n\ntype Product {\n id: ID!,\n type: ProductType\n}\n\nenum ProductType {\n HDRI,\n SEMISPHERICAL_HDRI,\n SOUND\n}\n```\n\n```text\nquery {\n __schema {types{name}}\n}\n```\n\n```text\nschema.graphql\n```\n\n```text\nschema.graphql\n```\n\n```text\n$rootResolver = array(\n 'emptyCart' => function($root, $args, $context, $info) {\n global $rootResolver;\n initSession();\n $_SESSION['CART']->clear();\n return $rootResolver['getCart']($root, $args, $context, $info);\n },\n 'addCartProduct' => function($root, $args, $context, $info) {\n global $rootResolver;\n\n ...\n\n return $rootResolver['getCart']($root, $args, $context, $info);\n },\n 'removeCartProduct' => function($root, $args, $context, $info) {\n global $rootResolver;\n\n ...\n\n return $rootResolver['getCart']($root, $args, $context, $info);\n },\n 'getCart' => function($root, $args, $context, $info) {\n initSession();\n return array(\n 'count' => $_SESSION['CART']->quantity(),\n 'total' => $_SESSION['CART']->total(),\n 'products' => $_SESSION['CART']->getProductData()\n );\n },\n```\n\n```text\n$config = ServerConfig::create()\n ->setSchema($schema)\n ->setRootValue($rootResolver)\n ->setContext($context)\n ->setDebug(DEBUG_MODE)\n ->setQueryBatching(true)\n;\n\n$server = new StandardServer($config);\n```\n\n```text\n$schemaContent = // file_get_contents or whatever works for you\n\n $schemaDocument = GraphQL\\Language\\Parser::parse($schemaContent);\n $schemaBuilder = new GraphQL\\Utils\\BuildSchema($schemaDocument);\n $schema = $schemaBuilder->buildSchema();\n```\n\n```text\n$fieldResolver = function() {\n return call_user_func_array([$this, 'defaultFieldResolver'], func_get_args());\n };\n\n $result = GraphQL\\GraphQL::executeQuery(\n $schema,\n $query, // this was grabbed from the HTTP post data\n null,\n $appContext, // custom context\n $variables, // this was grabbed from the HTTP post data\n null,\n $fieldResolver // HERE, custom field resolver\n );\n```\n\n```text\nprivate static function defaultFieldResolver(\n $source,\n $args,\n $context,\n \\GraphQL\\Type\\Definition\\ResolveInfo $info\n) {\n $fieldName = $info->fieldName;\n $parentType = $info->parentType->name;\n\n if ($source === NULL) {\n // this is the root value, return value depending on $fieldName\n // ...\n } else {\n // Depending on field type ($parentType), I call different field resolvers.\n // Since our system is big, we implemented a bootstrapping mechanism\n // so modules can register field resolvers in this class depending on field type\n // ...\n\n // If no field resolver was defined for this $parentType,\n // we just rely on the default field resolver provided by graphql-php (copy/paste).\n $fieldName = $info->fieldName;\n $property = null;\n\n if (is_array($source) || $source instanceof \\ArrayAccess) {\n if (isset($source[$fieldName])) {\n $property = $source[$fieldName];\n }\n } else if (is_object($source)) {\n if (isset($source->{$fieldName})) {\n $property = $source->{$fieldName};\n }\n }\n\n return $property instanceof \\Closure\n ? $property($source, $args, $context)\n : $property;\n }\n}\n```\n\n```text\n<?php\n\nrequire(\"vendor/autoload.php\") ;\nrequire(\"exemplo-graphql.php\");\nrequire(\"Usuario.php\");\n\nuse GraphQL\\GraphQL;\nuse GraphQL\\Type\\Schema;\nuse GraphQL\\Utils\\BuildSchema;\n\n$query = $_REQUEST['query'];\n\n$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {\n $name = $typeConfig['name'];\n // ... add missing options to $typeConfig based on type $name\n return $typeConfig;\n};\n\n$contents = file_get_contents('schema.graphql');\n$schema = BuildSchema::build($contents, $typeConfigDecorator);\n\n// $rawInput = file_get_contents('php://input');\n$input = json_decode($query, true);\n$query = $input['query'];\n$variableValues = isset($input['variables']) ? $input['variables'] : null;\n\ntry {\n // $rootValue = ['prefix' => 'You said: '];\n $rootValue = [\n 'usuario' => function($root, $args, $context, $info) {\n $usuario = new Usuario();\n $usuario->setNome(\"aqui tem um teste\");\n $usuario->setEmail(\"aqui tem um email\");\n return $usuario;\n },\n 'echo' => function($root, $args, $context, $info) {\n return \"aqui tem um echooo\";\n },\n 'adicionarUsuario' => function ($root, $args, $context, $info) {\n $usuario = new Usuario();\n $usuario->setNome(\"aqui tem um teste\");\n $usuario->setEmail(\"aqui tem um email\");\n return $usuario;\n }\n ];\n\n $result = GraphQL::executeQuery($schema, $query, $rootValue, null,\n $variableValues);\n\n if ($result->errors) {\n $output = [\n 'errors' => [\n [\n 'message' => $result->errors\n ]\n ]\n ];\n } else {\n $output = $result->toArray();\n }\n} catch (\\Exception $e) {\n $output = [\n 'errors' => [\n [\n 'message' => $e->getMessage()\n ]\n ]\n ];\n} \n\nheader('Content-Type: application/json');\necho json_encode($output);\n```\n\n```text\n$contents = file_get_contents($this->projectDir.'/config/schema.graphql');\n$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {\n $name = $typeConfig['name'];\n if ($name === 'Query') {\n $typeConfig['resolveField'] =\n function ($source, $args, $context, ResolveInfo $info) {\n if ($info->fieldDefinition->name == 'login') {\n if ($args['userName'] === 'test' && $args['password'] === '1234') {\n return \"Valid User.\";\n } else {\n return \"Invalid User\";\n }\n } elseif ($info->fieldDefinition->name == 'validateUser') {\n if ($args['age'] < 18) {\n return ['userId' => $args['userId'], 'category' => 'Not eligible for voting'];\n } \n }\n }\n }\n ;\n }\n return $typeConfig;\n };\n$schema = BuildSchema::build($contents, $typeConfigDecorator);\n```\n\n========================================\n\nComments:\n- Have you found any answer to this by your own? Care to here if so? Thanks!\n- Hi @Seb, I posted an answer below.\n- I found a different way, it feels rather hackish too but it works without creating a Server and will add it as answer for posterity (?)\n- This has become more important to my app, now that there are graphql webpack loaders coming out. I'm duplicating a lot of effort defining my schema as a bunch of big PHP arrays, then building my queries client-side from big strings. I could have `.graphql` files that are loaded in `buildSchema` server-side, and `import` in the client, thus making sure the definitions stay in sync.\n- I found the siler lib has a nice way to load graphql (load the schema, then load the resolvers), but it's simply on top of graphql-php. You can check out their code to see how it's done -- looks like they use `GraphQL\\Executor\\Executor` a lot to set up the resolvers. github.com/leocavalcante/siler/blob/master/src/Graphql/…","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":439,"estimatedTokens":3273}}895{"id":"stack-49944137","source":"stackoverflow","questionId":49944137,"title":"Few mutations in GitHub API v4 (GraphQL)?","tags":["github","graphql","github-api"],"text":"Title: Few mutations in GitHub API v4 (GraphQL)?\nTags: github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nUsing GitHub GraphQL API (v4), is it possible to do any of these tasks?\n\n- Create/edit/delete repositories\n\n- Create/edit/delete releases\n\n- Create/update/merge pull requests\n\n- Create tags\n\n- Create files/blobs\n\nWe were discussing migrating to GraphQL from REST but without this functionality it seems premature. Being new to GraphQL, I want to make sure I'm not missing this functionality somewhere.\n\n**UPDATE:**\n\nFrom GitHub Staff (April 21, 2018):\n\n Unfortunately, mutation coverage isnβt the best in our GraphQL API\n right now. The good news is that we have a focused team working on\n building out parity between REST and GraphQL. Itβs hard to give ETAs\n on these mutations for you, but theyβre on the list of things to do!\n\n========================================\n\nCode:\n```text\nmutation { \n createRepository(input:{name:\"foo\", visibility:PUBLIC}) { \n clientMutationId,\n repository {\n id,\n nameWithOwner\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":42,"estimatedTokens":265}}896{"id":"stack-54711837","source":"stackoverflow","questionId":54711837,"title":"Graphql input type of array of objects","tags":["javascript","node.js","express","graphql","express-graphql"],"text":"Title: Graphql input type of array of objects\nTags: javascript, node.js, express, graphql, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI have this schema: \n\n```\ntype Preference{\n _id: ID!\n uID: ID!\n preferences: [Category!]!\n}\n\ntype Category{\n name: String!\n subcategories: [String]!\n}\n\ntype RootMutation{\n createPreference(perferenceInput: PerferenceInput) : Preference\n}\n\ninput PerferenceInput{\n uID: String!\n preferences: [Category!]!\n}\n\nschema { \n query: RootQuery\n mutation: RootMutation\n}\n\ntype RootQuery {\n preferences: [Preference!]!\n category: [Category!]!\n}\n```\n\nBut Graphql gives me an error that states: `message\": \"The type of PerferenceInput.preferences must be Input Type but got: [Category].\",` which I have traced back to be related to graphql not being able to parse the `[Category]` array. \n\nI need to have this array as a nested array inside the Preference object, but somehow graphql is not able to parse this.. so, how can I pass the Category array to as an input type ?\n\n========================================\n\nCode:\n```text\ntype Preference{\n _id: ID!\n uID: ID!\n preferences: [Category!]!\n}\n\ntype Category{\n name: String!\n subcategories: [String]!\n}\n\ntype RootMutation{\n createPreference(perferenceInput: PerferenceInput) : Preference\n}\n\ninput PerferenceInput{\n uID: String!\n preferences: [Category!]!\n}\n\nschema { \n query: RootQuery\n mutation: RootMutation\n}\n\ntype RootQuery {\n preferences: [Preference!]!\n category: [Category!]!\n}\n```\n\n```text\nmessage\": \"The type of PerferenceInput.preferences must be Input Type but got: [Category].\",\n```\n\n```text\n[Category]\n```\n\n```text\nGraphQLObjectTypes\n```\n\n```text\nGraphQLInputObjectType\n```\n\n```text\nGraphQLInputObjectType\n```\n\n========================================\n\nComments:\n- This question gets asked a lot. You can't use an object type where an input object type is expected (i.e. as an argument). A more detailed explanation can be found here.","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":102,"estimatedTokens":491}}897{"id":"stack-53143743","source":"stackoverflow","questionId":53143743,"title":"Mutation with list of strings Variable \"$_v0_data\" got invalid value Graphql Node.js","tags":["node.js","express","graphql","graphql-js","prisma"],"text":"Title: Mutation with list of strings Variable \"$_v0_data\" got invalid value Graphql Node.js\nTags: node.js, express, graphql, graphql-js, prisma\nSource: Stack Overflow\n\nQuestion:\nI have this simple mutation that works fine\n\n```\ntype Mutation {\n addJob(\n url: String!\n description: String!\n position: String!\n company: String!\n date: DateTime!\n tags: [String!]!\n ): Job\n}\n```\n\nMutation Resolver\n\n```\nfunction addJob(parent, args, context, info) {\n\n console.log('Tags => ', args.tags)\n // const userId = getUserId(context)\n return context.db.mutation.createJob(\n {\n data: {\n position: args.position,\n componay: args.company,\n date: args.date,\n url: args.url,\n description: args.description,\n tags: args.tags\n }\n },\n info\n )\n}\n```\n\nhowever, once I tried to put an array of strings(tags) as you see above I I can't get it to work and I got this error \n\n```\nError: Variable \"$_v0_data\" got invalid value { ... , tags: [\"devops\", \"aws\"] }; Field \"0\" is not defined by type JobCreatetagsInput at value.tags.\n```\n\nIf I assigned an empty array to tags in the mutation there is no problem, however if I put a single string value [\"DevOps\"] for example i get the error\n\n========================================\n\nCode:\n```text\ntype Mutation {\n addJob(\n url: String!\n description: String!\n position: String!\n company: String!\n date: DateTime!\n tags: [String!]!\n ): Job\n}\n```\n\n```text\nfunction addJob(parent, args, context, info) {\n\n console.log('Tags => ', args.tags)\n // const userId = getUserId(context)\n return context.db.mutation.createJob(\n {\n data: {\n position: args.position,\n componay: args.company,\n date: args.date,\n url: args.url,\n description: args.description,\n tags: args.tags\n }\n },\n info\n )\n}\n```\n\n```text\nError: Variable \"$_v0_data\" got invalid value { ... , tags: [\"devops\", \"aws\"] }; Field \"0\" is not defined by type JobCreatetagsInput at value.tags.\n```\n\n```text\nfunction addJob(parent, args, context, info) {\n return context.db.mutation.createJob(\n {\n data: {\n position: args.position,\n componay: args.company,\n date: args.date,\n url: args.url,\n description: args.description,\n tags: { set: args.tags }\n }\n },\n info\n )\n}\n```\n\n========================================\n\nComments:\n- please add the code for the mutation\n- @Peter Added it.\n- Did you change your mutation schema recently? Did you `prisma deploy`? It seems like the `type JobCreatetagsInput` is not expecting this `String` type.\n- @Elfayer No, it's not changed at all and if I tried Prisma deploy the schema is up to date, and about this is the JobCreatetagsInput , input JobCreatetagsInput { set: [String!] }\n- Thanks for sharing, works as a charm is not clear about this in the doc.\n- @Merlyn007 glad it helped ^^","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":119,"estimatedTokens":754}}898{"id":"stack-65342101","source":"stackoverflow","questionId":65342101,"title":"How to generate Typescript definitions from AppSync GraphQL schema if I am not using amplify?","tags":["typescript","graphql","aws-amplify","aws-appsync","graphql-codegen"],"text":"Title: How to generate Typescript definitions from AppSync GraphQL schema if I am not using amplify?\nTags: typescript, graphql, aws-amplify, aws-appsync, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nI have my AppSync api set up using aws-cdk and am not using their amplify framework. I am trying to figure out how / if I can generate Typescript definitions from my AppSync `schema.graphql` file while not using amplify, i.e. no access to `amplify codegen` command. I did try installing and running it, but I assume amplify expects files to be located in certain directories, hence failing.\n\nI looked into https://graphql-code-generator.com but it wont work due to special types AppSync uses like `AWSDateTime`, a work around for this is to have api published and get schema from a graphql endpoint, but this is not ideal i.e. I'd like to be able and generate these types locally without publishing the schema.\n\nIs this doable?\n\n========================================\n\nCode:\n```text\nschema.graphql\n```\n\n```text\namplify codegen\n```\n\n```text\nAWSDateTime\n```\n\n```text\nscalar AWSDateTime\nscalar AWSPhone\nscalar AWSJSON\n```\n\n```text\nAWSDateTime\n```\n\n```text\nschema.graphql\n```\n\n```text\nscalars.graphql\n```\n\n========================================\n\nComments:\n- I am also using the CDK outside of the amplify workflow. I used: \"amplify add codegen --apiId xxxxxxxxx\" ... which allows selection of Typescript as a generation option.","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":48,"estimatedTokens":358}}899{"id":"stack-53367351","source":"stackoverflow","questionId":53367351,"title":"`Extensions` field not shown in apollo graphql response data","tags":["node.js","express","graphql","apollo","apollo-server"],"text":"Title: `Extensions` field not shown in apollo graphql response data\nTags: node.js, express, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nHere is a reproducible example. Run `app.js` and navigate the playground at http://localhost:4000/graphql\n\nYou can run queries like:\n\n```\nquery RecipeQuery{\n recipe(title:\"Recipe 2\"){\n description\n }\n}\n```\n\nProblem:\n\nI need debugging information from the `extensions` field in the response data. I'm talking about this `extensions` field:\n\n```\n\"data\":{....},\n \"extensions\": {\n \"tracing\": {}\n \"cacheControl\":{}\n }\n```\n\nBut in reality, I'm only getting the data field:\n\n```\n\"data\":{....}\n```\n\nI have already enabled `tracing` and `cacheControl` in the apollo server config but the `extensions` field is still excluded in the response data. How can I get the `extensions` data back?\n\nHere's how the apollo engine starts:\n\n```\nconst expressApp = express();\n\nconst server = new ApolloServer({\n schema,\n tracing: true,\n cacheControl: true,\n engine: false, // we will provide our own ApolloEngine\n});\n\nserver.applyMiddleware({ app: expressApp });\n\nconst engine = new ApolloEngine({\n apiKey: \"YOUR_ID\",\n\n});\n\nengine.listen(\n {\n port,\n expressApp,\n graphqlPaths: [graphqlEndpointPath],\n },\n () => console.log(`Server with Apollo Engine is running on http://localhost:${port}`),\n);\n```\n\nDependencies\n\n```\n\"dependencies\": {\n \"apollo-cache-control\": \"^0.1.1\",\n \"apollo-engine\": \"^1.1.2\",\n \"apollo-server-express\": \"^2.2.2\",\n \"graphql-depth-limit\": \"^1.1.0\",\n \"graphql-yoga\": \"^1.16.7\",\n \"type-graphql\": \"^0.15.0\"\n }\n```\n\n========================================\n\nCode:\n```text\nquery RecipeQuery{\n recipe(title:\"Recipe 2\"){\n description\n }\n}\n```\n\n```text\n\"data\":{....},\n \"extensions\": {\n \"tracing\": {}\n \"cacheControl\":{}\n }\n```\n\n```text\n\"data\":{....}\n```\n\n```text\nconst expressApp = express();\n\nconst server = new ApolloServer({\n schema,\n tracing: true,\n cacheControl: true,\n engine: false, // we will provide our own ApolloEngine\n});\n\nserver.applyMiddleware({ app: expressApp });\n\nconst engine = new ApolloEngine({\n apiKey: \"YOUR_ID\",\n\n});\n\nengine.listen(\n {\n port,\n expressApp,\n graphqlPaths: [graphqlEndpointPath],\n },\n () => console.log(`Server with Apollo Engine is running on http://localhost:${port}`),\n);\n```\n\n```text\n\"dependencies\": {\n \"apollo-cache-control\": \"^0.1.1\",\n \"apollo-engine\": \"^1.1.2\",\n \"apollo-server-express\": \"^2.2.2\",\n \"graphql-depth-limit\": \"^1.1.0\",\n \"graphql-yoga\": \"^1.16.7\",\n \"type-graphql\": \"^0.15.0\"\n }\n```\n\n```text\napp.js\n```\n\n```text\nextensions\n```\n\n```text\nextensions\n```\n\n```text\ntracing\n```\n\n```text\ncacheControl\n```\n\n```text\nextensions\n```\n\n```text\nextensions\n```\n\n```text\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n formatResponse: response => {\n console.log(response); \n /* \n ** { data } with informations such as queryType,\n ** directives ...\n ** I guess there is also the extensions key \n */\n return response;\n }\n});\n```\n\n```text\nformatResponse\n```\n\n========================================\n\nComments:\n- It is done, apollo has rebuild their entire doc recently breaking a lot of urls ):","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":192,"estimatedTokens":797}}900{"id":"stack-51915695","source":"stackoverflow","questionId":51915695,"title":"GraphQL: Updating an array","tags":["javascript","typescript","graphql","prisma"],"text":"Title: GraphQL: Updating an array\nTags: javascript, typescript, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm having some issues updating an array in the resolver. I'm building with `typescript`.\n\n### Description\n\nI have in the `datamodel.graphql` for `Prisma`:\n\n```\ntype Service @model {\n id: ID! @unique\n title: String\n content: String\n createdAt: DateTime!\n updatedAt: DateTime!\n comments: [Comment!]! // Line to be seen here\n author: User!\n offer: Offer\n isPublished: Boolean! @default(value: \"false\")\n type: [ServiceType!]!\n}\n\ntype Comment @model {\n id: ID! @unique\n author: User! @relation(name: \"WRITER\")\n service: Service!\n message: String!\n}\n```\n\nThe `Prisma` is connected to the `GraphQl` server and in this one, I defined the mutation :\n\n```\ncommentService(id: String!, comment: String!): Service!\n```\n\nSo comes the time for implementing the resolver for the given mutation and I'm doing this :\n\n```\nasync commentService(parent, {id, comment}, ctx: Context, info) {\n const userId = getUserId(ctx);\n const service = await ctx.db.query.service({\n where: {id}\n });\n if (!service) {\n throw new Error(`Service not found or you're not the author`)\n }\n\n const userComment = await ctx.db.mutation.createComment({\n data: {\n message: comment,\n service: {\n connect: {id}\n },\n author: {\n connect: {id:userId}\n },\n }\n });\n\n return ctx.db.mutation.updateService({\n where: {id},\n data: {\n comments: {\n connect: {id: userComment.id}\n }\n }\n })\n}\n```\n\n### The problem :\n\nThe only thing I'm receiving when querying the playground is `null` instead of the comment I've given.\n\nThanks for reading till so far.\n\n========================================\n\nTop Answer:\nIf I understood the question correctly, you are calling this `commentService` mutation and you get null as a result? Following your logic, you should get whatever `ctx.db.mutation.updateService` resolves with, right? If you expect that to indeed be a `Service` object, then the only reason why you might not be getting it back is a missing `await`. You probably needed to write `return await ctx.db.mutation.updateService({ ...`.\n\n========================================\n\nCode:\n```text\ntype Service @model {\n id: ID! @unique\n title: String\n content: String\n createdAt: DateTime!\n updatedAt: DateTime!\n comments: [Comment!]! // Line to be seen here\n author: User!\n offer: Offer\n isPublished: Boolean! @default(value: \"false\")\n type: [ServiceType!]!\n}\n\ntype Comment @model {\n id: ID! @unique\n author: User! @relation(name: \"WRITER\")\n service: Service!\n message: String!\n}\n```\n\n```text\ncommentService(id: String!, comment: String!): Service!\n```\n\n```text\nasync commentService(parent, {id, comment}, ctx: Context, info) {\n const userId = getUserId(ctx);\n const service = await ctx.db.query.service({\n where: {id}\n });\n if (!service) {\n throw new Error(`Service not found or you're not the author`)\n }\n\n const userComment = await ctx.db.mutation.createComment({\n data: {\n message: comment,\n service: {\n connect: {id}\n },\n author: {\n connect: {id:userId}\n },\n }\n });\n\n return ctx.db.mutation.updateService({\n where: {id},\n data: {\n comments: {\n connect: {id: userComment.id}\n }\n }\n })\n}\n```\n\n```text\ntypescript\n```\n\n```text\ndatamodel.graphql\n```\n\n```text\nPrisma\n```\n\n```text\nPrisma\n```\n\n```text\nGraphQl\n```\n\n```text\nnull\n```\n\n```text\nasync commentService(parent, {id, comment}, ctx: Context, info) {\n const userId = getUserId(ctx);\n\n return ctx.db.mutation.updateService({\n where: {id},\n data: {\n comments: {\n create: {\n message: comment,\n author: {\n connect: {id:userId}\n }\n }\n }\n }\n })\n}\n```\n\n```text\nnull\n```\n\n```text\ncommentService\n```\n\n```text\nService\n```\n\n```text\nComment\n```\n\n```text\ncommentService\n```\n\n```text\nctx.db.mutation.updateService\n```\n\n```text\nService\n```\n\n```text\nawait\n```\n\n```text\nreturn await ctx.db.mutation.updateService({ ...\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":226,"estimatedTokens":1052}}901{"id":"stack-36658671","source":"stackoverflow","questionId":36658671,"title":"Nested React/Relay component not receiving props","tags":["javascript","reactjs","graphql","relayjs"],"text":"Title: Nested React/Relay component not receiving props\nTags: javascript, reactjs, graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to pass an attribute into another component. Passing the array as `` results in `this.props.videos` being an empty object:\n\n```\n{\n \"videos\": {\n \"__dataID__\": \"client:5610611954\",\n \"__fragments__\": {\n \"2::client\": \"client:5610611954\"\n }\n }\n}\n```\n\n(GraphQL returns the correct data as confirmed by the React Chrome extension, it's just not being passed into the `VideoList`.)\n\n**components/video_list.js**\n\n```\nimport React from 'react'\nimport Relay from 'react-relay'\nimport VideoItem from '../containers/video_item' \n\nexport default class VideoList extends React.Component {\n render() {\n return(\n \n {\n this.props.videos.edges.map(video =>\n \n )\n }\n \n )\n }\n}\n```\n\n**components/channel_list.js**\n\n```\nimport React from 'react'\nimport Relay from 'react-relay'\nimport VideoList from './video_list'\n\nexport default class ChannelView extends React.Component {\n render() {\n return(\n \n \n \n\n### {this.props.channel.title}\n\n \n\n \n \n\n )\n }\n}\n```\n\n**containers/channel_list.js**\n\n```\nimport React from 'react'\nimport Relay from 'react-relay'\nimport ChannelView from '../components/channel_view'\nimport VideoList from './video_list'\n\nexport default Relay.createContainer(ChannelView, {\n fragments: {\n channel: () => Relay.QL`\n fragment on Channel {\n title\n video_list {\n ${VideoList.getFragment('videos')}\n }\n }`\n },\n});\n```\n\n**containers/video_list.js**\n\n```\nimport React from 'react'\nimport Relay from 'react-relay'\nimport VideoList from '../components/video_list'\nimport VideoItem from './video_item'\n\nexport default Relay.createContainer(VideoList, {\n initialVariables: {\n count: 28\n },\n fragments: {\n videos: () => Relay.QL`\n fragment on Videos {\n videos(first: $count) {\n pageInfo {\n hasPreviousPage\n hasNextPage\n }\n edges {\n node {\n ${VideoItem.getFragment('video')}\n }\n }\n }\n }`\n },\n});\n```\n\nWhat am I doing wrong? Am I misunderstanding how Relay works? I want to be able to set the `count` relay variable in the `VideoList` for pagination purposes. The `VideoList` object is going to be nested within multiple other components (e.g. channel, most popular, user's favorites, etc.)\n\nThank you!\n\n========================================\n\nCode:\n```text\n{\n \"videos\": {\n \"__dataID__\": \"client:5610611954\",\n \"__fragments__\": {\n \"2::client\": \"client:5610611954\"\n }\n }\n}\n```\n\n```text\nimport React from 'react'\nimport Relay from 'react-relay'\nimport VideoItem from '../containers/video_item' \n\nexport default class VideoList extends React.Component {\n render() {\n return(\n <div>\n {\n this.props.videos.edges.map(video =>\n <VideoItem key={video.id} video={video.node}/>\n )\n }\n </div>\n )\n }\n}\n```\n\n```text\nimport React from 'react'\nimport Relay from 'react-relay'\nimport VideoList from './video_list'\n\nexport default class ChannelView extends React.Component {\n render() {\n return(\n <div>\n <Column small={24}>\n <h2>{this.props.channel.title}</h2>\n </Column>\n\n <VideoList videos={this.props.channel.video_list}></VideoList>\n </div>\n\n\n )\n }\n}\n```\n\n```text\nimport React from 'react'\nimport Relay from 'react-relay'\nimport ChannelView from '../components/channel_view'\nimport VideoList from './video_list'\n\nexport default Relay.createContainer(ChannelView, {\n fragments: {\n channel: () => Relay.QL`\n fragment on Channel {\n title\n video_list {\n ${VideoList.getFragment('videos')}\n }\n }`\n },\n});\n```\n\n```text\nimport React from 'react'\nimport Relay from 'react-relay'\nimport VideoList from '../components/video_list'\nimport VideoItem from './video_item'\n\nexport default Relay.createContainer(VideoList, {\n initialVariables: {\n count: 28\n },\n fragments: {\n videos: () => Relay.QL`\n fragment on Videos {\n videos(first: $count) {\n pageInfo {\n hasPreviousPage\n hasNextPage\n }\n edges {\n node {\n ${VideoItem.getFragment('video')}\n }\n }\n }\n }`\n },\n});\n```\n\n```text\n<VideoList videos={this.props.channel.video_list}></VideoList>\n```\n\n```text\nthis.props.videos\n```\n\n```text\nVideoList\n```\n\n```text\ncount\n```\n\n```text\nVideoList\n```\n\n```text\nVideoList\n```\n\n```text\nimport React from 'react'\nimport Relay from 'react-relay'\nimport VideoList from '../containers/video_list'\n\nexport default class ChannelView extends React.Component {\n render() {\n return(\n <div>\n <Column small={24}>\n <h2>{this.props.channel.title}</h2>\n </Column>\n\n <VideoList videos={this.props.channel.video_list}></VideoList>\n </div>\n\n\n )\n }\n}\n```\n\n```text\nVideoList\n```\n\n```text\nVideoList\n```\n\n```text\n./containers/video_list.js\n```\n\n========================================\n\nComments:\n- Thank you!! Wow, I feel dumb! I must have messed around with this for over two hours trying to figure out what I was doing wrong. Thank you again André!\n- This answer saved me after two hours of scratching my head. Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":291,"estimatedTokens":1283}}902{"id":"stack-50617628","source":"stackoverflow","questionId":50617628,"title":"How to test GraphQL queries with fragments using jest","tags":["graphql","jestjs","graphql-js","graphql-tag"],"text":"Title: How to test GraphQL queries with fragments using jest\nTags: graphql, jestjs, graphql-js, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nProblem: I would like to test a GraphQL query that lives in a `.graphql` file like this:\n\n```\n#import '../../fragments/Widget.graphql'\n\nquery WidgetFragment($id: ID) {\n readWidgetFragment(id: $id) {\n ...Widget\n }\n}\n```\n\nTo create a GraphQL schema with mocked resolvers and data, I use `makeExecutableSchema` and `addMockFunctionsToSchema` from graphql-tools.\n\nTo run the query from inside a jest test, my understanding is that I need to use the `graphql()` function from graphql-js.\n\nThis function needs the query as a **string**, so I tried two different ways, but neither of them worked:\n\nParse the `.graphql` file as a normal text file, giving me the raw string (using the jest-raw-loader in my jest config).\nThis gives me: `Failed: Errors in query: Unknown fragment \"Widget\".` when I run the query.\n\n- Parse the `.graphql` file into a `query` object using jest-transform-graphql. I believe this should be the right approach, because it *should* resolve any imported fragments properly. However, to execute the query, I need to pass `query.loc.source.body` to the `graphql`, which results in the same error message as option 1.\n\n========================================\n\nTop Answer:\nUse the initial approach with parsing it as a raw text, except:\n\n- use a recursive function with a path argument (assuming you could have nested fragments)\n\n- which uses regex to extract all imports beforehand to an array (maybe use a nicer pattern :) )\n\n- append the rest of the file to a string variable\n\n- then loop through imports, resolving the `#import`s and passing them to itself and appending the result to the string variable\n\n- Finally return the result to the main function where you pass it to the `graphql()`\n\n========================================\n\nCode:\n```text\n#import '../../fragments/Widget.graphql'\n\nquery WidgetFragment($id: ID) {\n readWidgetFragment(id: $id) {\n ...Widget\n }\n}\n```\n\n```text\n.graphql\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\naddMockFunctionsToSchema\n```\n\n```text\ngraphql()\n```\n\n```text\n.graphql\n```\n\n```text\nFailed: Errors in query: Unknown fragment \"Widget\".\n```\n\n```text\n.graphql\n```\n\n```text\nquery\n```\n\n```text\nquery.loc.source.body\n```\n\n```text\ngraphql\n```\n\n```text\nimport { print } from 'graphql/language/printer'\n\nimport query from './query.gql'\n\n...\n\nprint(query)\n```\n\n```text\n#import\n```\n\n```text\ngraphql()\n```\n\n```js\n// Async wrapper around dynamic `import` function\nimport { importQuery } from \"./queries\";\n\nconst importAndReplace = async (fileToImport, sourceDocument, line) => {\n const doc = await importQuery(fileToImport);\n const targetDocument = (await sourceDocument).replace(line, doc.loc.source.body);\n return targetDocument;\n};\n\n// Inspired by `graphql-tag/loader` \n// Uses promises because of async function `importQuery` used\nexport default async graphqlOperation => {\n const { body } = graphqlOperation.loc.source;\n const lines = body.split(/\\r\\n|\\r|\\n/);\n const bodyWithInlineImports = await lines.reduce(\n async (accumulator, line) => {\n await accumulator;\n const lineSplit = line.slice(1).split(\" \");\n\n return line[0] === \"#\" && lineSplit[0] === \"import\"\n ? importAndReplace(lineSplit[1].replace(/\"/g, \"\"), accumulator, line)\n : Promise.resolve(accumulator);\n },\n Promise.resolve(body)\n );\n return bodyWithInlineImports;\n};\n```\n\n```text\nquery.definitions\n```\n\n```text\ngraphql\n```\n\n```text\ndocument.loc.source.body\n```\n\n```text\nfunction graphqlImpl\n```\n\n```text\ndocument\n```\n\n```text\nparse(source)\n```\n\n```text\n#import\n```\n\n```text\ngraphql\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":175,"estimatedTokens":925}}903{"id":"stack-51145172","source":"stackoverflow","questionId":51145172,"title":"async/await on graphql query or mutation","tags":["node.js","async-await","graphql"],"text":"Title: async/await on graphql query or mutation\nTags: node.js, async-await, graphql\nSource: Stack Overflow\n\nQuestion:\nI made API server with **graphql-yoga**. (a nodejs library)\n\nBefore searching Google, I just use query/mutation like this.\n\n### [First case]\n\n```\nQuery: {\n movies: () => { return Movies.all();}\n}\n```\n\nBut after searching I found some code that use await/async on query/mutation.\n\n### [Second case]\n\n```\nQuery: {\n movies: async () => { return await Movies.all(); }\n}\n```\n\nBy my little knowledge, second case is more safe and better case.\n\nBut I'm new at graphql and es6.\n\nIs there any process related async/await already defined in graphql?\n\nOr, do not have to consider about it?\n\nOr, use async/await is better?\n\nAny suggestions would be appreciated :)\n\nThanks.\n\n========================================\n\nCode:\n```text\nQuery: {\n movies: () => { return Movies.all();}\n}\n```\n\n```text\nQuery: {\n movies: async () => { return await Movies.all(); }\n}\n```\n\n```text\nasync/await\n```\n\n```text\nasync/await\n```\n\n========================================\n\nComments:\n- Thanks for reply :)","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":68,"estimatedTokens":274}}904{"id":"stack-49327083","source":"stackoverflow","questionId":49327083,"title":"Using GitHub's GraphQL API, how can I tell who closed an issue or pull request?","tags":["graphql","github-api"],"text":"Title: Using GitHub's GraphQL API, how can I tell who closed an issue or pull request?\nTags: graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nGiven an issue or pull request number, I'd like to get the following information using a single query to the GitHub GraphQL API:\n\n- Whether it is an issue or a pull request\n\n- The state of the issue (open, closed) or PR (open, closed, merged)\n\n- If the issue or PR is closed, who closed it and when\n\n- If the issue or PR was merged, who merged it and when\n\nUsing the following query, I have all of this working except for determining **who** closed the issue or PR:\n\n```\n{\n repository(owner: \"Automattic\", name: \"wp-calypso\") {\n issueOrPullRequest(number: 23226) {\n __typename\n ... on Closable {\n closed\n closedAt\n # TODO: How to get ClosedEvent { actor } ?\n }\n ... on Issue {\n issueState: state\n title\n }\n ... on PullRequest {\n prState: state\n title\n merged\n mergedAt\n mergeCommit {\n committer {\n user {\n login\n }\n }\n }\n }\n }\n }\n}\n```\n\nI'm running this query using GitHub's GraphQL Explorer tool: https://developer.github.com/v4/explorer/\n\nI can see the issue or PR as a `Closable` but I think I need to get from there to the last `ClosedEvent` that affected that object. This is the part I haven't been able to figure out yet.\n\nIn GitHub's v3 REST API, determining all of this information may require 2 requests. For a pull request that was **closed** (not **merged**), the `closed_by` field only appears when requesting the pull request **as an issue** (via the `issues` API call). All other pull request information is available via the `pulls` API call.\n\n========================================\n\nCode:\n```text\n{\n repository(owner: \"Automattic\", name: \"wp-calypso\") {\n issueOrPullRequest(number: 23226) {\n __typename\n ... on Closable {\n closed\n closedAt\n # TODO: How to get ClosedEvent { actor } ?\n }\n ... on Issue {\n issueState: state\n title\n }\n ... on PullRequest {\n prState: state\n title\n merged\n mergedAt\n mergeCommit {\n committer {\n user {\n login\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nClosable\n```\n\n```text\nClosedEvent\n```\n\n```text\nclosed_by\n```\n\n```text\nissues\n```\n\n```text\npulls\n```\n\n```text\n{\n repository(owner: \"Automattic\", name: \"wp-calypso\") {\n issueOrPullRequest(number: 23226) {\n __typename\n ... on Closable {\n closed\n closedAt\n }\n ... on Issue {\n timeline(last: 100) {\n edges {\n node {\n __typename\n ... on ClosedEvent {\n actor{\n login\n }\n }\n }\n }\n }\n }\n ... on PullRequest {\n timeline(last: 100) {\n edges {\n node {\n __typename\n ... on MergedEvent {\n actor{\n login\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\ntimeline(last: 1)\n```\n\n```text\nClosedEvent\n```\n\n```text\nMergedEvent\n```\n\n```text\nactor\n```\n\n========================================\n\nComments:\n- Thanks for the pointer to the `timeline` field, I think that is the connection I was missing here. However, the suggested query would end up being extremely verbose to cover the most common possibilities, and it will still fail under certain conditions (if an issue or PR has many comments or other events after being closed or merged). The code required to manipulate this response object is also far more complicated than just making 2 requests to the REST API. I'm accepting this solution as correct, but I think the overall answer is \"this task is not workable using the GraphQL API\".\n- @jnylen I agree. It would be nice to have a concise way of getting this done. Also, regarding the point of the code to parse being complicated will it still not be cheaper than making 2 over the network calls? I havent benchmarked this and so I'm unsure, just a food for thought though\n- Trade-offs... 1 network request with a very complicated query and unknown complexity on the server side, that doesn't always work, and requires complicated processing by the client (hard to test). Or, 2 relatively simple network requests for standard objects, with a slight bit of combining to do afterwards.\n- I chose 2 requests (with appropriate caching in my application). Much simpler and more maintainable this way.\n- I'm a bit disappointed in the behavior of both kinds of GitHub APIs here, to be honest.","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":176,"estimatedTokens":1153}}905{"id":"stack-40657250","source":"stackoverflow","questionId":40657250,"title":"Does graphql allow conditional execution of a step in a mutation?","tags":["graphql"],"text":"Title: Does graphql allow conditional execution of a step in a mutation?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nSince you can have multiple steps run sequentially in a mutation, can you have a conditional if statement in graphql so that later steps only run if the result from a previous step meets a condition?\n\ne.g.\n\n```\nmutation upsertLogin($idToken: String!, $email: String!, $username: String!) {\n\n User(email: $email, username: $username) {\n id\n }\n\n // only do the next step if no id from from previous step\n\n createUser(email: $email, username: $username) {\n id\n }\n\n }\n```\n\n========================================\n\nTop Answer:\nYou could probably have the resolver do this for you in case the user isn't found, however if folks try to login with wrong credentials then you run into the problem of making duplicative accounts and confused users.\n\nI'd definitely encourage you to *not* try and implement this as it's not a great UX pattern. If the user isn't found, it could be for a number of reasons (wrong password, wrong email, inactive account...)\n\nGraphQL does/could handle this in a semi-smart way, but this type of decisioning really should be left to your users.\n\n========================================\n\nCode:\n```text\nmutation upsertLogin($idToken: String!, $email: String!, $username: String!) {\n\n User(email: $email, username: $username) {\n id\n }\n\n // only do the next step if no id from from previous step\n\n createUser(email: $email, username: $username) {\n id\n }\n\n }\n```\n\n```text\nresolver(_, args) {\n if (myDB.find(args.username) === null) {\n createNewUser();\n }\n```\n\n```text\nmutation1(credentials).then(result => {\n if (result) {\n mutation2.then();\n else {\n mutation3.then();\n }\n}\n```\n\n========================================\n\nComments:\n- in my use case this is triggered by an auth0 user creation so it would only fire in the case of a verified authentication event - and is used to sync the auth0 user info with a corresponding backend service. Thus it would always only be one single reason rather than for user mistakes, etc...","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":74,"estimatedTokens":526}}906{"id":"stack-48630023","source":"stackoverflow","questionId":48630023,"title":"Wrong order of GraphQL resolver arguments (root, args, context)","tags":["graphql","graphql-js","express-graphql"],"text":"Title: Wrong order of GraphQL resolver arguments (root, args, context)\nTags: graphql, graphql-js, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm wondering why my arguments seem to be switched around inside my GraphQL resolver. I'm using express-graphql.\n\nExample of one resolver:\n\n```\ngetLocalDrivers: async (parent, args, ctx) => {\n console.log(ctx);\n }\n```\n\nI've written the argument names as they appear in the docs: http://graphql.org/learn/execution/\n\nBut when I debug and inspect the objects, it seems the args object is 1st, the context is 2nd, and the parent/root is 3rd.\n\nparent:\n\n```\nObject {location: \"020202\"}\n```\n\nargs: \n\n```\nIncomingMessage {_readableState: ReadableState, readable: false, domain: null, β¦}\n```\n\ncontext:\n\n```\nObject {fieldName: \"getLocalDrivers\", fieldNodes: ....\n```\n\nSome server code:\n\n```\napp.use(\n \"/graphql\",\n graphqlHTTP({\n schema,\n graphiql: true,\n rootValue: rootResolver\n })\n);\n```\n\nMy rootResolver:\n\n```\nvar rootResolver = {\n getLocalDrivers: async (obj, args, ctx) => {\n console.log(ctx);\n }\n}\n```\n\nSchema:\n\n```\nvar { buildSchema } = require(\"graphql\");\nvar schema = buildSchema(`\n type Query {\n getLocalDrivers(location: String): [Driver]\n }\n\n type Driver {\n name: String\n location: String \n }`);\n```\n\n========================================\n\nCode:\n```text\ngetLocalDrivers: async (parent, args, ctx) => {\n console.log(ctx);\n }\n```\n\n```text\nObject {location: \"020202\"}\n```\n\n```text\nIncomingMessage {_readableState: ReadableState, readable: false, domain: null, β¦}\n```\n\n```text\nObject {fieldName: \"getLocalDrivers\", fieldNodes: ....\n```\n\n```text\napp.use(\n \"/graphql\",\n graphqlHTTP({\n schema,\n graphiql: true,\n rootValue: rootResolver\n })\n);\n```\n\n```text\nvar rootResolver = {\n getLocalDrivers: async (obj, args, ctx) => {\n console.log(ctx);\n }\n}\n```\n\n```text\nvar { buildSchema } = require(\"graphql\");\nvar schema = buildSchema(`\n type Query {\n getLocalDrivers(location: String): [Driver]\n }\n\n type Driver {\n name: String\n location: String \n }`);\n```\n\n```text\nconst typeDefs = `\n type Query {\n getLocalDrivers(location: String): [Driver]\n }\n\n type Driver {\n name: String\n location: String \n }\n`\nconst resolvers = {\n Query: {\n getLocalDrivers: (obj, args, ctx) => {\n console.log({obj, args, ctx})\n }\n }\n}\nconst schema = makeExecutableSchema({\n typeDefs,\n resolvers,\n})\n```\n\n```text\nresolve\n```\n\n```text\nobj\n```\n\n```text\nroot\n```\n\n```text\ngetLocalDrivers\n```\n\n```text\nDriver\n```\n\n```text\nDriver\n```\n\n```text\nname\n```\n\n```text\nname\n```\n\n```text\nname\n```\n\n```text\nDriver\n```\n\n```text\ngetLocalDrivers\n```\n\n```text\nbuildQuery\n```\n\n```text\ngetLocalDrivers\n```\n\n```text\nmakeExecutableSchema\n```\n\n========================================\n\nComments:\n- Unfortunately I'm getting same results if I use `makeExecuteSchema` from graphql-tools instead of `buildSchema`.\n- If you're still passing in a root value then you will still see the same behavior. Pass in the resolvers as part of the resolvers object instead. I've updated my answer with an example.\n- I simply made new server this time using Apollo GraphQL server instead, and started using makeExecuteableSchema to make it work. My end solution though has been to switch to Express REST for now as GraphQL is giving me too much issues :-)","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":214,"estimatedTokens":826}}907{"id":"stack-62363398","source":"stackoverflow","questionId":62363398,"title":"Is it possible to use quarkus security with quarkus-smallrye-graphql?","tags":["graphql","quarkus","smallrye"],"text":"Title: Is it possible to use quarkus security with quarkus-smallrye-graphql?\nTags: graphql, quarkus, smallrye\nSource: Stack Overflow\n\nQuestion:\nI am trying to use the quarkus-smallrye-graphql extension. And it seems like I cannot use any of the security annotations such as **@Authenticated** in a class annotated with **@GraphQLApi**. I previously tried to use the smallrye-graphql project directly and I was able to use security. But now when using the offered extension in quarkus, it does not work.\n\nA simple example of api class is\n\n```\n@GraphQLApi\npublic class SomeApi {\n @Query\n @Authenticated\n public String testQuery() {\n return \"hello...\";\n }\n}\n```\n\nThis does not work with the extension and I always get the unauthorized exception. Does anyone know how to do this?\n\n========================================\n\nCode:\n```text\n@GraphQLApi\npublic class SomeApi {\n @Query\n @Authenticated\n public String testQuery() {\n return \"hello...\";\n }\n}\n```\n\n```text\n/graphql*\n```\n\n```text\nquarkus.http.auth.permission.roles1.paths\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.091Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":43,"estimatedTokens":262}}908{"id":"stack-63034980","source":"stackoverflow","questionId":63034980,"title":"GraphQLError: There can be only one fragment named","tags":["graphql","graphql-js"],"text":"Title: GraphQLError: There can be only one fragment named\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nOn a client app built with graphql-react,\n\ngraphQL query strings are made of multiple fragments like so:\n\n```\nconst fragmentAddress = `\n fragment address on Address {\n id\n number\n street\n code\n city\n }\n`\n\nconst fragmentOffice = `\n fragment office on Office {\n id\n address {\n ...address\n }\n }\n\n ${fragmentAddress}\n`\n\nconst User = `\n query User($id: ID) {\n address {\n ...address\n }\n office {\n ...office\n }\n }\n\n ${fragmentAddress}\n ${fragmentOffice}\n`\n```\n\nA query on `User` returns this error: `GraphQLError: There can be only one fragment named address`.\n\nI saw that graphql-tag has a dedup fonction, but it can't give a string back.\n\nHow is it possible to deduplicate fragments from a graphql query string?\n\n========================================\n\nCode:\n```js\nconst fragmentAddress = `\n fragment address on Address {\n id\n number\n street\n code\n city\n }\n`\n\nconst fragmentOffice = `\n fragment office on Office {\n id\n address {\n ...address\n }\n }\n\n ${fragmentAddress}\n`\n\nconst User = `\n query User($id: ID) {\n address {\n ...address\n }\n office {\n ...office\n }\n }\n\n ${fragmentAddress}\n ${fragmentOffice}\n`\n```\n\n```text\nUser\n```\n\n```text\nGraphQLError: There can be only one fragment named address\n```\n\n```js\nimport gql from 'graphql-tag'\nimport { print } from 'graphql/language/printer'\n\nconst fragmentAddress = gql`\n fragment address on Address {\n id\n number\n street\n code\n city\n }\n`\n\nconst fragmentOffice = gql`\n fragment office on Office {\n id\n address {\n ...address\n }\n }\n\n ${fragmentAddress}\n`\n\nconst User = gql`\n query User($id: ID) {\n address {\n ...address\n }\n office {\n ...office\n }\n }\n\n ${fragmentAddress}\n ${fragmentOffice}\n`\n\nconst queryString = print(query)\n```\n\n```text\ngraphql-tag\n```\n\n```text\ngraphql/language/printer\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":149,"estimatedTokens":534}}909{"id":"stack-60389096","source":"stackoverflow","questionId":60389096,"title":"In Relay.js, what is the `Client Mutation Identifier`?","tags":["graphql","graphql-js","relayjs","relay","relaymodern"],"text":"Title: In Relay.js, what is the `Client Mutation Identifier`?\nTags: graphql, graphql-js, relayjs, relay, relaymodern\nSource: Stack Overflow\n\nQuestion:\nIn the relay documentation here, it says that:\n\n Relay uses a common pattern for mutations, where there are root fields on the mutation type with a single argument, input, and **where the input and output both contain a client mutation identifier** used to reconcile requests and responses.\n\nBut in the example they provided, the input and output looked like this respectively:\n\n```\n// IntroducedShipInput\n{\n \"input\": {\n \"shipName\": \"B-Wing\",\n \"factionId\": \"1\"\n }\n}\n\n// IntroducedShipPayload\n{\n \"introduceShip\": {\n \"ship\": {\n \"id\": \"U2hpcDo5\",\n \"name\": \"B-Wing\"\n },\n \"faction\": {\n \"name\": \"Alliance to Restore the Republic\"\n }\n }\n}\n```\n\nSo what is the `client mutation` identifier? And why, and how does it get used to reconcile requests and responses?\n\n========================================\n\nCode:\n```text\n// IntroducedShipInput\n{\n \"input\": {\n \"shipName\": \"B-Wing\",\n \"factionId\": \"1\"\n }\n}\n\n// IntroducedShipPayload\n{\n \"introduceShip\": {\n \"ship\": {\n \"id\": \"U2hpcDo5\",\n \"name\": \"B-Wing\"\n },\n \"faction\": {\n \"name\": \"Alliance to Restore the Republic\"\n }\n }\n}\n```\n\n```text\nclient mutation\n```\n\n========================================\n\nComments:\n- inside they are taking unique identifier name clientMutationId while perfoming mutation\n- @MayankPandav Can you elaborate inside what are who taking unique identifier names?\n- i.postimg.cc/pdLv4GjY/Screenshot-from-2020-03-03-09-39-36.pn‌​g kindly checkout it will automatically taake its value even idk what they used to take","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":72,"estimatedTokens":418}}910{"id":"stack-63353909","source":"stackoverflow","questionId":63353909,"title":"Graphql- How to fetch result based on the condition of a field?","tags":["graphql","graphql-js"],"text":"Title: Graphql- How to fetch result based on the condition of a field?\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have a query that look like this:\n\n```\nquery MyQuery {\n products {\n edges {\n node {\n featured\n id\n image {\n altText\n mediaItemUrl\n slug\n }\n productId\n name\n onSale\n \n }\n }\n }\n}\n```\n\nWhat I want is only fetch the result that `featured` field is `true`, if the `featured` is false, then it never shown in the result.\n\nSomething like query like below in mysql:\n\n```\nSELECT id,image,name, featured FROM products WHERE featured = 'false'\n```\n\nBut in graphql query above, I can't query the featured = false.\n\nI tried:\n\n```\nquery MyQuery {\n products {\n edges {\n node {\n featured @include(if: false)\n id\n ... other field I need\n \n }\n }\n }\n}\n```\n\nBut what this query do is, if `featured` field is true, then included the `featured` field in the result, else don't included the field in the result.This is not what I want.\n\n**What I want is,**\n\nIf `featured` field of a product is `true`, then include the `products` into the result, else, remove the whole product from the result.\n\nHow can I achieve this in the `MyQuery` above?\n\n========================================\n\nCode:\n```text\nquery MyQuery {\n products {\n edges {\n node {\n featured\n id\n image {\n altText\n mediaItemUrl\n slug\n }\n productId\n name\n onSale\n \n }\n }\n }\n}\n```\n\n```text\nSELECT id,image,name, featured FROM products WHERE featured = 'false'\n```\n\n```text\nquery MyQuery {\n products {\n edges {\n node {\n featured @include(if: false)\n id\n ... other field I need\n \n }\n }\n }\n}\n```\n\n```text\nfeatured\n```\n\n```text\ntrue\n```\n\n```text\nfeatured\n```\n\n```text\nfeatured\n```\n\n```text\nfeatured\n```\n\n```text\nfeatured\n```\n\n```text\ntrue\n```\n\n```text\nproducts\n```\n\n```text\nMyQuery\n```\n\n```text\n@include\n```\n\n```text\n@skip\n```\n\n```text\nproducts\n```\n\n```text\nfilter\n```\n\n```text\nisFeatured\n```\n\n```text\nfeatured\n```\n\n```text\nproducts\n```\n\n========================================\n\nComments:\n- Thanks a lot.. After seeing your answer I figured out ady. which I realize I can do something like this `products(where: {featured: false}) {.. other stuff }` . Thanks for your help.","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":176,"estimatedTokens":572}}911{"id":"stack-61011277","source":"stackoverflow","questionId":61011277,"title":"how do I create validation rules from a GraphQL schema","tags":["validation","graphql"],"text":"Title: how do I create validation rules from a GraphQL schema\nTags: validation, graphql\nSource: Stack Overflow\n\nQuestion:\nHow can I transform a simple GraphQL schema, which I can access server-side by importing and client-side by querying, into validation rules?\n\nI can kind of see how I could do this for enums, lets say I have a title:\n\n```\nenum Title {\n Mr, Ms, Mrs, Dr\n }\n```\n\nI could access the possible values by querying\n\n```\n__type (name: \"Title\") {\n name\n enumValues {\n name\n }\n }\n```\n\nAnd now I can create a drop-down on the client or a validation on the server, but how do I encode and access for example the min/max length of a string field? Or min/max value for a number?\n\nDo I need to add a custom type for each field? Or is, there a better way?\n\n[edit] in response to Daniel's answer:\n\nI'm using yup for validation, which is a great library, but for example if a certain field was *required* on a gql InputType, how do I get that into the yup schema?\n\nAnd how do I use that yup schema on the front-end? Ideally I would like to serialise it, send it to the client, and reconstruct the validation there.\n\nThe only other way I can think of is to the code, but then I need to re-build and re-deploy the client each time the schema changes, which is of course out of the question :/\n\n========================================\n\nCode:\n```text\nenum Title {\n Mr, Ms, Mrs, Dr\n }\n```\n\n```text\n__type (name: \"Title\") {\n name\n enumValues {\n name\n }\n }\n```\n\n========================================\n\nComments:\n- Thank you! I actually *am* using yup for validation, but I don't see how that prevents me from having to duplicate information. I've made an edit to the question to explain what I mean.\n- You won't avoid duplication between your yup schema and your GraphQL schema -- in the same way there would be duplication between the types in your database and the types in your data model or GraphQL type. You'd need to utilize something like this library to serialize the yup schema. Whether you use GraphQL or another endpoint to make this available to your client is up to you.\n- There may be more appropriate libraries for serializing the schema. That's just the first one I stumbled upon. I've used yup before, but only ever used a common module to the schema between my applications, so YMMV.\n- ok, I guess that'll have to do then. Thanks for the link, being able to serialise a yup schema will go a long way!","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":63,"estimatedTokens":609}}912{"id":"stack-70925556","source":"stackoverflow","questionId":70925556,"title":"What is a correct return type of a GraphQL resolve function?","tags":["graphql","apollo-server"],"text":"Title: What is a correct return type of a GraphQL resolve function?\nTags: graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI faced with an issue that can't resolve on my own. Let's go through it step by step to point out the problem.\n\n- I have a mutation `bookAppointment` which returns an `Appointment` object\n\n- GraphQL schema says that this object should return 4 properties: `id`, `date`, `specialist`, `client`.\n\n- To the GraphQL-style the `specialist` and `client` properties should be a field level resolvers\n\n- To fetch this objects I need pass `specialistId` to the specialist field level resolver, as well as `clientId` to the client field level resolver.\n\n- At this point a problem arises.\n\n- The field level resolvers of `client`, `specialist` expects that root mutation returns fields like `clientId` and `specialistId`. But GraphQL syntax and types that were generated by that syntax doesn't include this props (make sense).\n\n- How to \"extend\" the return type of the resolver and its `interface BookAppointmentPayload` to make me and TypeScript happy?\n\nThis is my GraphQL schema\n\n```\ntype Client {\n id: ID!\n name: String!\n}\n\ntype Specialist {\n id: ID!\n name: String!\n}\n\ntype Appointment {\n id: ID!\n date: Date!\n client: Client!\n specialist: Specialist!\n}\n\ninput BookAppointmentInput {\n date: Date!\n userId: ID!\n specialistId: ID!\n}\n\ntype BookAppointmentPayload {\n appointment: Appointment!\n}\n\ntype Mutation {\n bookAppointment(input: BookAppointmentInput!): BookAppointmentPayload!\n}\n```\n\nThis is TypeScript representation of GraphQL schema\n\n```\ninterface Client {\n id: string\n name: string\n}\n\ninterface Specialist {\n id: string\n name: string\n}\n\ninterface Appointment {\n id: string\n date: Date\n client: Client\n specialist: Specialist\n}\n\ninterface BookAppointmentPayload {\n appointment: Appointment\n}\n```\n\nHere I define my resolvers objects\n\n```\nconst resolvers = {\n ...\n Mutation: {\n bookAppointment: (parent, args, context, info): BookAppointmentPayload => {\n return {\n appointment: {\n id: '1',\n date: new Date(),\n clientId: '1', // This prop doesn't exist in the TypeScript interface of Appointment, but is required for the field-level resolver of a `client` prop\n specialistId: '1' // This prop doesn't exist int he TypeScript interface of Appointment, but is required for the field-level resolver of a `specialist` prop\n }\n }\n }\n },\n Appointment: {\n client: (parent, args, context, info) => {\n // I need a clientId (e.g. args.clientId) to fetch the client object from the database\n\n return {\n id: '1',\n name: 'Jhon'\n }\n },\n specialist: (parent, args, context, info) => {\n // I need a specialistId (e.g. args.specialistId) to fetch the specialist object from the database\n\n return {\n id: '1',\n name: 'Jane'\n }\n }\n }\n}\n```\n\nSolution that come to my mind:\n\n- Create an interface which represent \"actual\" return type of the resolver\n\n```\n...\ninterface Apppointment {\n id: string\n date: Date\n clientId: string // instead of `client: Client`\n specialistId: string // instead of `specialist: Specialist`\n}\n\ninterface BookAppointmentPayload {\n appointment: Appointment\n}\n...\n```\n\nBut this doesn't reflect the GraphQL type. Also tools like `graphql-generator` generates the type with actual objects that should be included in the response, not the fields that are going to be used by field-level resolvers. (Am I wrong?)\n\nI would like to know how you're solving such issue?\n\n========================================\n\nCode:\n```text\ntype Client {\n id: ID!\n name: String!\n}\n\ntype Specialist {\n id: ID!\n name: String!\n}\n\ntype Appointment {\n id: ID!\n date: Date!\n client: Client!\n specialist: Specialist!\n}\n\ninput BookAppointmentInput {\n date: Date!\n userId: ID!\n specialistId: ID!\n}\n\ntype BookAppointmentPayload {\n appointment: Appointment!\n}\n\ntype Mutation {\n bookAppointment(input: BookAppointmentInput!): BookAppointmentPayload!\n}\n```\n\n```js\ninterface Client {\n id: string\n name: string\n}\n\ninterface Specialist {\n id: string\n name: string\n}\n\ninterface Appointment {\n id: string\n date: Date\n client: Client\n specialist: Specialist\n}\n\ninterface BookAppointmentPayload {\n appointment: Appointment\n}\n```\n\n```js\nconst resolvers = {\n ...\n Mutation: {\n bookAppointment: (parent, args, context, info): BookAppointmentPayload => {\n return {\n appointment: {\n id: '1',\n date: new Date(),\n clientId: '1', // This prop doesn't exist in the TypeScript interface of Appointment, but is required for the field-level resolver of a `client` prop\n specialistId: '1' // This prop doesn't exist int he TypeScript interface of Appointment, but is required for the field-level resolver of a `specialist` prop\n }\n }\n }\n },\n Appointment: {\n client: (parent, args, context, info) => {\n // I need a clientId (e.g. args.clientId) to fetch the client object from the database\n\n return {\n id: '1',\n name: 'Jhon'\n }\n },\n specialist: (parent, args, context, info) => {\n // I need a specialistId (e.g. args.specialistId) to fetch the specialist object from the database\n\n return {\n id: '1',\n name: 'Jane'\n }\n }\n }\n}\n```\n\n```js\n...\ninterface Apppointment {\n id: string\n date: Date\n clientId: string // instead of `client: Client`\n specialistId: string // instead of `specialist: Specialist`\n}\n\ninterface BookAppointmentPayload {\n appointment: Appointment\n}\n...\n```\n\n```text\nbookAppointment\n```\n\n```text\nAppointment\n```\n\n```text\nid\n```\n\n```text\ndate\n```\n\n```text\nspecialist\n```\n\n```text\nclient\n```\n\n```text\nspecialist\n```\n\n```text\nclient\n```\n\n```text\nspecialistId\n```\n\n```text\nclientId\n```\n\n```text\nclient\n```\n\n```text\nspecialist\n```\n\n```text\nclientId\n```\n\n```text\nspecialistId\n```\n\n```text\ninterface BookAppointmentPayload\n```\n\n```text\ngraphql-generator\n```\n\n```text\n# GraphQL SDL\n\ntype Appointment {\n id: String!\n client: User!\n specialist: Specialist!\n}\n\ntype BookAppointmentInput { ... }\n\ntype BookAppointmentPayload {\n appointment: Appointment!\n}\n\ntype Mutation {\n bookAppointment: (input: BookAppointmentInput!): BookAppointmentPayload!\n}\n```\n\n```js\ninterface AppointmentDatabaseEntity {\n id: string\n clientId: string // In GraphQL-world this prop is an object, but not in JS. Use this prop in field-level resolver to fetch entire object\n specialistId: string // In GraphQL-world this prop is an object, but not in JS. Use this prop in field-level resolver to fetch entire object\n}\n\ninterface BookAppointmentPayload {\n appointment: AppointmentDatabaseEntity // The return type SHOULDN'T be equal to the GraphQL type (Appointment) \n}\n\nconst resolvers = {\n Mutatiuon: {\n bookAppointment: (parent, args, context, info) => {\n const appointment = { id: '1', specialistId: '1', clientId: '1' }\n\n return {\n id: appointment.id,\n specialistId: appointment.specialistId, // Pass this prop to the child resolvers to fetch entire object\n clientId: appointment.clientId // Pass this prop to the child resolvers to fetch entire object\n }\n }\n },\n Appointment: {\n client: (parent: AppointmentDatabaseEntity, args, context, info) => {\n const client = database.getClient(parent.clientId) // Fetching entire object by the property from the parent object\n \n return {\n id: client.id,\n name: client.name,\n email: client.email\n }\n },\n specialist: (parent: AppointmentDatabaseEntity, args, context, info) => {\n const specialist = database.getSpecialist(parent.specialistId) // Fetching entire object by the property from the parent object\n \n return {\n id: specialist.id,\n name: specialist.name,\n email: specialist.email\n }\n }\n }\n}\n```\n\n```yaml\nplugins\n config:\n mappers:\n User: ./my-models#UserDbObject # User is GraphQL object, which will be replaced with UserDbObject\n Book: ./my-modelsBook # Same rule goes here\n```\n\n```text\ngraphql-generator\n```\n\n```text\nmappers\n```\n\n========================================\n\nComments:\n- This is a common problem and the way that I've solved it in the past is to make the `clientId` and `specialistId` part of the type up front so you have something to \"point\" to those objects. If you're against having those in the types, you need to have some underlying structure in whatever the database is holding that does the equivalent, i.e. have a hidden id field to access those references. In general you can have these on your `Appointment` interface or have `client` and `specialist` point back to the appointment (this is useful in the case when clients can have many appointments)\n- Thanks for the reply. \"This is a common problem\" I couldn't find any mentions about that neither in generator tools nor in graphql doc itself. Putting this props inside GraphQL schema seems like a duplication, where fetching `client` and `specialist` by `appointmentId` from the database is not optimal by performance.\n- Wow, that `mappers` bit is such a hidden piece of information! Thank you so much. Hours of searching before finally finding your answer here.","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":404,"estimatedTokens":2267}}913{"id":"stack-61268907","source":"stackoverflow","questionId":61268907,"title":"Is it possible in GraphQL to send an Enum with multiple values","tags":["c#","enums","graphql","graphql-dotnet"],"text":"Title: Is it possible in GraphQL to send an Enum with multiple values\nTags: c#, enums, graphql, graphql-dotnet\nSource: Stack Overflow\n\nQuestion:\nIn C# it's possible to create an Enum with a Flags Attribute.(https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute?view=netstandard-2.1)\nThis means that that an Enum can look like this:\n\n```\n[Flags]\nenum EnumWithFlags \n{\n None = 0,\n FlagOne = 1,\n FlagTwo = 2,\n FlagThree = 4\n}\n```\n\nEnumWithFlags can have a value of 5, which means it will have both FlagThree and FlagOne.\n\nIs this also possible with a Enum inputtype? And is there an example for this?\n\n========================================\n\nCode:\n```text\n[Flags]\nenum EnumWithFlags \n{\n None = 0,\n FlagOne = 1,\n FlagTwo = 2,\n FlagThree = 4\n}\n```\n\n```text\ntype Foo {\n flags: [EnumWithFlags]\n }\n\n enum EnumWithFlags {\n NONE\n FLAG_ONE\n FLAG_TWO\n FLAG_TREE\n }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":49,"estimatedTokens":231}}914{"id":"stack-62629823","source":"stackoverflow","questionId":62629823,"title":"String interpolation is not allowed in graphql tag. (Gatsby)","tags":["javascript","reactjs","graphql","interpolation","gatsby"],"text":"Title: String interpolation is not allowed in graphql tag. (Gatsby)\nTags: javascript, reactjs, graphql, interpolation, gatsby\nSource: Stack Overflow\n\nQuestion:\nAttempting to use an alias for a long complicated Ids within my graphql query:\n\nFAILED TO COMPILE: String interpolation is not allowed in graphql tag:\n\n```\nconst query = graphql`\n query MyQuery {\n wordpress {\n menu(id: \"${wordpress(\"mainMenu\")}\") {\n ...rest of query\n }\n }\n }\n`\n```\n\n========================================\n\nCode:\n```text\nconst query = graphql`\n query MyQuery {\n wordpress {\n menu(id: \"${wordpress(\"mainMenu\")}\") {\n ...rest of query\n }\n }\n }\n`\n```\n\n```text\n// inside template file\nexport const query = graphql`\n query MyQuery($id: String!) {\n menu(id: { eq: $id }) {\n ...rest of query\n }\n }\n`\n```\n\n```text\n// gatsby-node.js\nconst postTemplate = path.resolve(`./src/templates/post.js`)\nallWordpressPost.edges.forEach(edge => {\n createPage({\n path: `/${edge.node.slug}/`,\n component: slash(postTemplate),\n context: {\n id: edge.node.id, // π\n },\n })\n})\n```\n\n```text\ncreatePage\n```\n\n```text\ngatsby-node.js\n```\n\n========================================\n\nComments:\n- Docs here gatsbyjs.com/docs/page-query/#the-longer-answer","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":73,"estimatedTokens":314}}915{"id":"stack-61310638","source":"stackoverflow","questionId":61310638,"title":"Associate user information from Cognito with AWS Amplify GraphQL","tags":["swift","amazon-web-services","graphql","amazon-cognito","aws-amplify"],"text":"Title: Associate user information from Cognito with AWS Amplify GraphQL\nTags: swift, amazon-web-services, graphql, amazon-cognito, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI am on xcode 11.4, Swift 4. The goal is to:\n\nsign up a new user in Cognito User Pool, and then save an associated user record using Amplify GraphQL. \n\nCRUD the user's record after signing in with Cognito User Pool. \n\nThe problem is I do not know how to associate Cognito with Amplify GraphQL. For example, in Google Firebase auth and Firestore, I would get a unique user id `UID` after signing up, then I would create an associated user record in `Firestore` with the key as this `UID`. Then on user signin/authentication, I can get this `UID` from firebase auth and find the associated record in firestore. \n\nCurrently with the AWS stack, I created a user model in `schema.graphql` as:\n\n```\ntype User @model @auth(rules: [{ allow: owner, ownerField: \"id\", operations: [create, update, delete]}]){\n id: ID!\n firstName : String\n lastName : String\n handle : String\n email : String!\n}\n```\n\nSo that only authenticated user can create, update and delete. Next somewhere in `SignUpController` I create a new user:\n\n```\nAWSMobileClient.default().signUp( username: email\n , password: password\n , userAttributes: [\"email\": email]) { (signUpResult, error) in\n if let signUpResult = signUpResult {\n\n switch(signUpResult.signUpConfirmationState) {\n case .confirmed:\n self.showAlert(msg: \"You already have an account. Please go back and press log in\")\n case .unconfirmed:\n break \n case .unknown:\n self.showAlert(msg: \"Network error\")\n }\n } else if let error = error { ... }\n```\n\nAnd then confirm the user w/ code:\n\n```\nAWSMobileClient.default().confirmSignUp(username: email, confirmationCode: code) { (signUpResult, error) in\n if let signUpResult = signUpResult {\n switch(signUpResult.signUpConfirmationState) {\n case .confirmed:\n // This is where I need to create an associated user account\n break\n case .unconfirmed:\n self.showAlert(title: \"Error\", msg: \"User is not confirmed and needs verification via \\(signUpResult.codeDeliveryDetails!.deliveryMedium) sent at \\(signUpResult.codeDeliveryDetails!.destination!)\")\n case .unknown:\n self.showAlert(title: \"Error\", msg: \"Network error\")\n }\n } else { //if let error = error {\n self.showAlert(title: \"Error\", msg: \"Network error\")\n }\n```\n\nRight now my solution in `case .confirmed` is to sign in immediately, and then fetch the user's `client token` via:\n\n```\nclass CognitoPoolProvider : AWSCognitoUserPoolsAuthProviderAsync {\n\n /// this token may not be what you want ...\n func getLatestAuthToken(_ callback: @escaping (String?, Error?) -> Void) {\n\n AWSMobileClient.default().getTokens { (token, error) in\n if let error = error {\n callback(nil,error)\n }\n callback(token?.accessToken?.tokenString, error)\n }\n }\n}\n```\n\nThis turns out to be the wrong solution, since the user's client token changes all the time. \n\nOverall, this is a standard hello-world problem, and there should be a standard out of box solution provided by AWS. I search the docs and github, but cannot find a satisfactory answer.\n\n========================================\n\nCode:\n```text\ntype User @model @auth(rules: [{ allow: owner, ownerField: \"id\", operations: [create, update, delete]}]){\n id: ID!\n firstName : String\n lastName : String\n handle : String\n email : String!\n}\n```\n\n```text\nAWSMobileClient.default().signUp( username: email\n , password: password\n , userAttributes: [\"email\": email]) { (signUpResult, error) in\n if let signUpResult = signUpResult {\n\n switch(signUpResult.signUpConfirmationState) {\n case .confirmed:\n self.showAlert(msg: \"You already have an account. Please go back and press log in\")\n case .unconfirmed:\n break \n case .unknown:\n self.showAlert(msg: \"Network error\")\n }\n } else if let error = error { ... }\n```\n\n```text\nAWSMobileClient.default().confirmSignUp(username: email, confirmationCode: code) { (signUpResult, error) in\n if let signUpResult = signUpResult {\n switch(signUpResult.signUpConfirmationState) {\n case .confirmed:\n // This is where I need to create an associated user account\n break\n case .unconfirmed:\n self.showAlert(title: \"Error\", msg: \"User is not confirmed and needs verification via \\(signUpResult.codeDeliveryDetails!.deliveryMedium) sent at \\(signUpResult.codeDeliveryDetails!.destination!)\")\n case .unknown:\n self.showAlert(title: \"Error\", msg: \"Network error\")\n }\n } else { //if let error = error {\n self.showAlert(title: \"Error\", msg: \"Network error\")\n }\n```\n\n```text\nclass CognitoPoolProvider : AWSCognitoUserPoolsAuthProviderAsync {\n\n /// this token may not be what you want ...\n func getLatestAuthToken(_ callback: @escaping (String?, Error?) -> Void) {\n\n AWSMobileClient.default().getTokens { (token, error) in\n if let error = error {\n callback(nil,error)\n }\n callback(token?.accessToken?.tokenString, error)\n }\n }\n}\n```\n\n```text\nUID\n```\n\n```text\nFirestore\n```\n\n```text\nUID\n```\n\n```text\nUID\n```\n\n```text\nschema.graphql\n```\n\n```text\nSignUpController\n```\n\n```text\ncase .confirmed\n```\n\n```text\nclient token\n```\n\n```text\nevent.userName\n```\n\n```text\ncustom:id\n```\n\n========================================\n\nComments:\n- The username `AWSMobileClient.default().username` and identityId `AWSMobileClient.default().identityId` should both be unique.\n- @Don what does that mean? Does it mean I can save the user with field `id:String!` set to `AWSMobileClient.default().username`?\n- @Don just to add to previous comment, on my iphone `identityId` is nil regardless of auth state, but `username` is unique across emails, and same across signin sessions for every email. I assume this is true in general as well? So does it make sense to use `username` as the `id:String!` parameter in `model`, so is this an anti-pattern in aws-amplify land.\n- what is the issue when creating it on the client side?\n- We may have multiple clients, so how do we ensure/trust code/workflow consistently between client apps? --> We must force them use unique workflow, ensure if you registered my app, you must have associate account. What happen if Client code sign up wrong/bug workflow, then try again and can't use old account because we don't have associate account?","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":196,"estimatedTokens":1642}}916{"id":"stack-49521575","source":"stackoverflow","questionId":49521575,"title":"Implement multiple interfaces in graphql","tags":["reactjs","graphql","relay","relaymodern"],"text":"Title: Implement multiple interfaces in graphql\nTags: reactjs, graphql, relay, relaymodern\nSource: Stack Overflow\n\nQuestion:\nI am using the relay compiler and it is not letting me compile a schema with a type that implements multiple interfaces. I made a small test project:\n\npackage.json\n\n```\n{\n \"scripts\": {\n \"relay\": \"relay-compiler --src ./ --schema schema.graphqls\"\n },\n \"dependencies\": {\n \"react-relay\": \"1.5.0\"\n },\n \"devDependencies\": {\n \"relay-compiler\": \"1.5.0\"\n }\n}\n```\n\nschema.graphqls\n\n```\ninterface First {\n a: String\n}\n\ninterface Second {\n b: String\n}\n\ntype Something implements First, Second {\n a: String\n b: String\n}\n```\n\ntest.js\n\n```\nimport { graphql } from \"react-relay\";\n\ngraphql`fragment Test_item on Something {\n a\n b\n}`;\n```\n\nIf you run this with npm run relay (after npm install) you get the error:\n\n```\nError: Error loading schema. Expected the schema to be a .graphql or a .json\nfile, describing your GraphQL server's API. Error detail:\n\nGraphQLError: Syntax Error: Unexpected Name \"Second\"\n```\n\nAny ideas why this is happening?\n\n========================================\n\nCode:\n```text\n{\n \"scripts\": {\n \"relay\": \"relay-compiler --src ./ --schema schema.graphqls\"\n },\n \"dependencies\": {\n \"react-relay\": \"1.5.0\"\n },\n \"devDependencies\": {\n \"relay-compiler\": \"1.5.0\"\n }\n}\n```\n\n```text\ninterface First {\n a: String\n}\n\ninterface Second {\n b: String\n}\n\ntype Something implements First, Second {\n a: String\n b: String\n}\n```\n\n```text\nimport { graphql } from \"react-relay\";\n\ngraphql`fragment Test_item on Something {\n a\n b\n}`;\n```\n\n```text\nError: Error loading schema. Expected the schema to be a .graphql or a .json\nfile, describing your GraphQL server's API. Error detail:\n\nGraphQLError: Syntax Error: Unexpected Name \"Second\"\n```\n\n```text\ntype Something implements First & Second\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":113,"estimatedTokens":459}}917{"id":"stack-61892657","source":"stackoverflow","questionId":61892657,"title":"Docusaurus v2 and GraphQL Playground integration","tags":["graphql","docusaurus","graphql-playground"],"text":"Title: Docusaurus v2 and GraphQL Playground integration\nTags: graphql, docusaurus, graphql-playground\nSource: Stack Overflow\n\nQuestion:\nI'd like to render **GraphQL Playground** as a React component in one of my *pages* but it fails due to missing `file-loader` in webpack. Is there a way to fix this in **docs** or do I need to create new plugin with new webpack config?\n\nIs it good idea to integrate Playground and Docusaurus at all?\n\nThanks for your ideas...\n\n========================================\n\nTop Answer:\nA few Docusaurus sites have embedded playgrounds:\n\n- Hermes\n\n- Uniforms\n\nIn your case you will have to write a plugin to extend the webpack config with `file-loader`.\n\n========================================\n\nCode:\n```text\nfile-loader\n```\n\n```js\nimport BrowserOnly from '@docusaurus/BrowserOnly';\nconst Explorer = () => {\n const { siteConfig } = useDocusaurusContext();\n return (\n <Layout\n title={siteConfig.title}\n description=\"Slerp GraphQL Explorer\">\n <main>\n <BrowserOnly fallback={<div>Loading...</div>}>\n {() => {\n const GraphEx = GraphExplorer\n return <GraphEx />\n }}\n </BrowserOnly>\n </main>\n </Layout>\n );\n}\n```\n\n```text\nfile-loader\n```\n\n```js\nimport React from \"react\";\nimport { createGraphiQLFetcher } from \"@graphiql/toolkit\";\nimport { GraphiQL } from \"graphiql\";\nimport \"graphiql/graphiql.css\";\n\nconst fetcher = createGraphiQLFetcher({\n url: \"https://my.graphql.api/graphql\",\n});\n\nexport default function GraphqlPlayGround() {\n return <GraphiQL fetcher={fetcher} />;\n}\n```\n\n```text\nModule not found: Error: Can't resolve 'react/jsx-runtime' in '/Users/user/Desktop/Saleor/DocAuth0/node_modules/@graphiql/react/dist'\nDid you mean 'jsx-runtime.js'?\nBREAKING CHANGE: The request 'react/jsx-runtime' failed to resolve only because it was resolved as fully specified\n(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\"type\": \"module\"').\nThe extension in the request is mandatory for it to be fully specified.\nAdd the extension to the request.\n```\n\n```js\nmodule.exports = function (context, options) {\n return {\n name: 'my-loaders',\n configureWebpack(config, isServer) {\n return {\n module: {\n rules: [\n {\n test: /\\.m?js/,\n resolve: {\n fullySpecified: false\n }\n },\n ],\n },\n };\n },\n };\n};\n```\n\n```json\n{\n \"name\": \"my-loaders\",\n \"version\": \"0.0.0\",\n \"private\": true\n}\n```\n\n```json\nplugins: [\n // ...\n 'my-loaders'\n // ...\n]\n```\n\n```js\n{\n // ...\n \"dependencies\": {\n // ...\n \"my-loaders\": \"file:plugins/my-loaders\",\n // ...\n },\n // ...\n}\n```\n\n```bash\nnpm i\n```\n\n```text\ngraphiql\n```\n\n```text\nmy-loaders\n```\n\n```text\nindex.js\n```\n\n```text\nconfigureWebpack()\n```\n\n```text\nwebpack\n```\n\n```text\n/plugins/my-loaders/index.js\n```\n\n```text\n/plugins/my-loaders/package.json\n```\n\n```text\n/docusaurus.config.js\n```\n\n```text\n/package.json\n```\n\n========================================\n\nComments:\n- Docusaurus also seems to mess up the css for the playground component...\n- @EthanSK that's right. It turned out that it requires too much effort to render `` in Docusaurus and I chose to load it in `` and communicate using `postMessage` browser API.\n- I focus on GraphQL Playground that can be embedded as a React compment, not playground in general. But thank you anyway. Now I know that custom plugin is the way.","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":174,"estimatedTokens":900}}918{"id":"stack-62111313","source":"stackoverflow","questionId":62111313,"title":"AWS Appsync implementation using GraphQL-client library in .Net","tags":["c#",".net","websocket","graphql","aws-appsync"],"text":"Title: AWS Appsync implementation using GraphQL-client library in .Net\nTags: c#, .net, websocket, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement an app sync subscription similar to this python example but in .net https://aws.amazon.com/blogs/mobile/appsync-websockets-python/\n\nI started this using the nuget package GraphQL.Client https://www.nuget.org/packages/GraphQL.Client\nThe execution of Query/Mutation is working fine like given in the readme of https://github.com/graphql-dotnet/graphql-client\nBut subscription is not working.\n\n**My code using the GraphQL.Client:**\n\n```\nusing var graphQLClient = new GraphQLHttpClient(\"https://.appsync-realtime-api..amazonaws.com/graphql\", new NewtonsoftJsonSerializer());\n\n graphQLClient.HttpClient.DefaultRequestHeaders.Add(\"host\", \"\"); //As given in the python example\n\ngraphQLClient.HttpClient.DefaultRequestHeaders.Add(\"x-api-key\", \"\");\nvar req= new GraphQLRequest\n{\n Query = @\"subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){ content }}\",\n Variables = new{}\n};\n\nIObservable> subscriptionStream = graphQLClient.CreateSubscriptionStream(req, (Exception ex) =>\n{\n Console.WriteLine(\"Error: {0}\", ex.ToString());\n});\n\nvar subscription = subscriptionStream.Subscribe(response =>\n{\n Console.WriteLine($\"Response'{Newtonsoft.Json.JsonConvert.SerializeObject(response)}' \");\n},\nex =>\n{\nConsole.WriteLine(\"Error{0}\", ex.ToString());\n});\n```\n\nIts giving the exception \"The remote party closed the WebSocket connection without completing the close handshake.\"\n\n**stack trace:**\n\nat System.Net.WebSockets.ManagedWebSocket.d__66`2.MoveNext()\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\n at GraphQL.Client.Http.Websocket.GraphQLHttpWebSocket.d__40.MoveNext() in C:\\Users\\UserName\\Source\\repos\\graphql-client\\src\\GraphQL.Client\\Websocket\\GraphQLHttpWebSocket.cs:line 546\n\n***Then I tried without this nuget and using standard websocket*** \n\n**Code without nuget:**\n\n```\nstatic public async Task CallWebsocket()\n {\n try\n {\n _client = new ClientWebSocket();\n _client.Options.AddSubProtocol(\"graphql-ws\");\n _client.Options.SetRequestHeader(\"host\", \"\");\n _client.Options.SetRequestHeader(\"x-api-key\", \"\");\n\n await _client.ConnectAsync(new Uri(\"https://.appsync-realtime-api..amazonaws.com/graphql\"), CancellationToken.None);\n await SendCommand();\n var docList = await Receive();\n }\n catch(Exception ex)\n {\n\n }\n }\n\n static private async Task SendCommand()\n {\n ArraySegment outputBuffer = new ArraySegment(Encoding.UTF8.GetBytes(\"'query' : 'subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){ content }}'\"));\n await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);\n }\n static private async Task Receive()\n {\n var receiveBufferSize = 1536;\n byte[] buffer = new byte[receiveBufferSize];\n var result = await _client.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None);\n var resultJson = (new UTF8Encoding()).GetString(buffer);\n return resultJson;\n }\n```\n\nI am getting below exception:\n\n**Inner exception**: \"An established connection was aborted by the software in your host machine.\"\n\n**Inner exception message**: \"Unable to read data from the transport connection: An established connection was aborted by the software in your host machine..\"\n\n**Message**: \"The remote party closed the WebSocket connection without completing the close handshake.\"\n\nCould anyone please help with the correct implementation.\n\n========================================\n\nTop Answer:\nFor others who face same issues, I have created a nuget package now.\nhttps://www.nuget.org/packages/DotNetCSharp.AWS.AppSync.Client/1.1.1\nYou can use it as below.\n\n```\n//Create Client Specify eithen APIKey or AuthToken\nvar Client = new AppSyncClient(\"\", new AuthOptions()\n{\n// APIKey = \"\",\nAuthToken = \"\"\n});\n\n//To Subscribe an query\nGuid newId = Guid.NewGuid();\nawait Client.CreateSubscriptionAsync(new QueryOptions()\n{\nQuery = \"subscription \",\nSubscriptionId = newId\n},\n(data) =>\n{\n\n});\n\n//To unsubscribe an subscription\nawait Client.UnSubscribe(newId);\n\n//To close the websocket\nawait Client.Close();\n```\n\n========================================\n\nCode:\n```text\nusing var graphQLClient = new GraphQLHttpClient(\"https://<MY-API-PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql\", new NewtonsoftJsonSerializer());\n\n graphQLClient.HttpClient.DefaultRequestHeaders.Add(\"host\", \"<API HOST without https or absolute path and 'realtime-' text in the api address>\"); //As given in the python example\n\ngraphQLClient.HttpClient.DefaultRequestHeaders.Add(\"x-api-key\", \"<API KEY>\");\nvar req= new GraphQLRequest\n{\n Query = @\"subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){ content }}\",\n Variables = new{}\n};\n\nIObservable<GraphQLResponse<Response>> subscriptionStream = graphQLClient.CreateSubscriptionStream<Response>(req, (Exception ex) =>\n{\n Console.WriteLine(\"Error: {0}\", ex.ToString());\n});\n\nvar subscription = subscriptionStream.Subscribe(response =>\n{\n Console.WriteLine($\"Response'{Newtonsoft.Json.JsonConvert.SerializeObject(response)}' \");\n},\nex =>\n{\nConsole.WriteLine(\"Error{0}\", ex.ToString());\n});\n```\n\n```text\nstatic public async Task CallWebsocket()\n {\n try\n {\n _client = new ClientWebSocket();\n _client.Options.AddSubProtocol(\"graphql-ws\");\n _client.Options.SetRequestHeader(\"host\", \"<HOST URL without wss but now with 'realtime' text in api url because otherwise we are getting SSL error>\");\n _client.Options.SetRequestHeader(\"x-api-key\", \"<API KEY>\");\n\n await _client.ConnectAsync(new Uri(\"https://<MY-APPSYNC_API_PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql\"), CancellationToken.None);\n await SendCommand();\n var docList = await Receive();\n }\n catch(Exception ex)\n {\n\n }\n }\n\n static private async Task SendCommand()\n {\n ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(\"'query' : 'subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){ content }}'\"));\n await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);\n }\n static private async Task<string> Receive()\n {\n var receiveBufferSize = 1536;\n byte[] buffer = new byte[receiveBufferSize];\n var result = await _client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);\n var resultJson = (new UTF8Encoding()).GetString(buffer);\n return resultJson;\n }\n```\n\n```text\n2.MoveNext()\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\n at System.Runtime.CompilerServices.TaskAwaiter\n```\n\n```js\n{\n \"graphqlApi\": {\n \"name\": \"myNewRealTimeGraphQL-API\",\n \"authenticationType\": \"<API_KEY>\",\n \"tags\": {},\n \"apiId\": \"example123456\",\n \"uris\": {\n \"GRAPHQL\": \"https://abc.appsync-api.us-west-2.amazonaws.com/graphql\",\n \"REALTIME\": \"wss://abc.appsync-realtime-api.us-west-2.amazonaws.com/graphql\"\n },\n \"arn\": \"arn:aws:appsync:us-west-2: xxxxxxxxxxxx:apis/xxxxxxxxxxxx\"\n }\n}\n```\n\n```cs\n// These are declared at the same level as your _client\n\n// This comes from the graphqlApi.uris.GRAPHQL in step 0, set as a var here for clarity\n_gqlHost = \"abc.appsync-api.us-west-2.amazonaws.com\";\n\n// This comes from the graphqlApi.uris.REALTIME in step 0, set as a var here for clarity\n_realtimeUri = \"wss://abc.appsync-realtime-api.us-west-2.amazonaws.com/graphql\";\n\n_apiKey = \"<API KEY>\";\n\nstatic public async Task CallWebsocket()\n{\n \n // Step 1\n // This is JSON needed by the server, it will be converted to base64\n // (note: might be better to use something like Json.NET for this task)\n var header = var test = $@\"{{\n \"\"host\"\":\"\"{_gqlHost}\"\",\n \"\"x-api-key\"\": \"\"{_apiKey}\"\"\n }}\";\n\n // Now we need to encode the previous JSON to base64\n var headerB64 = System.Convert.ToBase64String(\n System.Text.Encoding.UTF8.GetBytes(header));\n\n UriBuilder connectionUriBuilder = new UriBuilder(_realtimeUri);\n connectionUriBuilder.Query = $\"header={headerB64}&payload=e30=\";\n \n try\n {\n _client = new ClientWebSocket();\n _client.Options.AddSubProtocol(\"graphql-ws\");\n\n // Step 2\n await _client.ConnectAsync(connectionUriBuilder.Uri), CancellationToken.None);\n // Step 3\n await SendConnectionInit();\n await Receive();\n }\n catch(Exception ex)\n {\n\n }\n}\n\nstatic private async Task SendConnectionInit()\n{\n ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(@\"{\"\"type\"\": \"\"connection_init\"\"}\"));\n await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);\n}\n\nstatic private async Task SendSubscription()\n{\n // This detail is important, note that the subscription is a stringified JSON that will be embeded in the \"data\" field below\n var subscription = $@\"{{\\\"\"query\\\"\": \\\"\"subscription SubscribeToEventComments{{ subscribeToEventComments{{ content }} }}\\\"\", \\\"\"variables\\\"\": {{}} }}\";\n \n var register = $@\"{{\n \"\"id\"\": \"\"<SUB_ID>\"\",\n \"\"payload\"\": {{\n \"\"data\"\": \"\"{subscription}\"\",\n \"\"extensions\"\": {{\n \"\"authorization\"\": {{\n \"\"host\"\": \"\"{_gqlHost}\"\",\n \"\"x-api-key\"\":\"\"{_apiKey}\"\"\n }}\n }}\n }},\n \"\"type\"\": \"\"start\"\"\n }}\";\n \n // The output should look like below, note again the \"data\" field contains a stringified JSON that represents the subscription \n /*\n {\n \"id\": \"<SUB_ID>\",\n \"payload\": {\n \"data\": \"{\\\"query\\\": \\\"subscription SubscribeToEventComments{ subscribeToEventComments{ content}}\\\", \\\"variables\\\": {} }\",\n \"extensions\": {\n \"authorization\": {\n \"host\": \"abc.appsync-api.us-west-2.amazonaws.com\",\n \"x-api-key\":\"<API KEY>\"\n }\n }\n },\n \"type\": \"start\"\n }\n */\n\n ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(register));\n await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);\n}\n\nstatic private async Task Deregister()\n{\n var deregister = $@\"{{\n \"\"type\"\": \"\"stop\"\",\n \"\"id\"\": \"\"<SUB_ID>\"\"\n }}\"\n ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(deregister));\n await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);\n}\n\nstatic private async Task Receive()\n{\n while (_socket.State == WebSocketState.Open)\n {\n ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);\n WebSocketReceiveResult result= null;\n using (var ms = new MemoryStream())\n {\n // This loop is needed because the server might send chunks of data that need to be assembled by the client\n // see: https://stackoverflow.com/questions/23773407/a-websockets-receiveasync-method-does-not-await-the-entire-message\n do\n {\n result = await socket.ReceiveAsync(buffer, CancellationToken.None);\n ms.Write(buffer.Array, buffer.Offset, result.Count);\n }\n while (!result.EndOfMessage);\n\n ms.Seek(0, SeekOrigin.Begin);\n\n using (var reader = new StreamReader(ms, Encoding.UTF8))\n {\n // convert stream to string\n var message = reader.ReadToEnd();\n Console.WriteLine(message)\n // quick and dirty way to check response\n if (message.Contains(\"connection_ack\"))\n {\n // Step 4\n await SendSubscription();\n } else if (message.Contains(\"data\")) // Step 6\n {\n // Step 7 \n await Deregister();\n // Step 8\n await _client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);\n }\n }\n }\n }\n}\n```\n\n```text\naws appsync get-graphql-api --api-id example123456\n```\n\n```text\n//Create Client Specify eithen APIKey or AuthToken\nvar Client = new AppSyncClient(\"<Appsync URL>\", new AuthOptions()\n{\n// APIKey = \"<API Key>\",\nAuthToken = \"<JWT Token>\"\n});\n\n//To Subscribe an query\nGuid newId = Guid.NewGuid();\nawait Client.CreateSubscriptionAsync<Message>(new QueryOptions()\n{\nQuery = \"subscription <Subscription Query>\",\nSubscriptionId = newId\n},\n(data) =>\n{\n\n});\n\n//To unsubscribe an subscription\nawait Client.UnSubscribe(newId);\n\n//To close the websocket\nawait Client.Close();\n```\n\n========================================\n\nComments:\n- Thank you for taking time and helping me out. In last two days I too wrote the code again from scratch using this documentation docs.aws.amazon.com/appsync/latest/devguide/…. The Websocket connections, acknowledgement and data handling are working. But when I see your code I see few coding standards that I had missed in the way I am handling Deregister and Disconnect. I will fix those.\n- This is great. Have you published the code for this on any public repo? I'd love to have a look under the hood.","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":403,"estimatedTokens":3531}}919{"id":"stack-52612936","source":"stackoverflow","questionId":52612936,"title":"Gatsby - fetching remote images with createRemoteFileNode","tags":["graphql","gatsby"],"text":"Title: Gatsby - fetching remote images with createRemoteFileNode\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI've been trying to fetch images from remote URL to Gatsby Source File system, to take advantage of lazy loading with `gatsby-image` plugin. I have a restful API which returns json with a string containing the image url. I followed this guide as I'm quite new to Gatsby Node Api and wasn't sure how to tackle this. Everything worked well until the point with adding additional properties to image with `createNodeField`. The properties seem to be added (I can see the object with `fields` property when I log the fileNode to the console. However, when trying to query the images, I get an error:\n\nhttps://i.sstatic.net/RFDjQ.png\n\nI'm wondering if there's something wrong in my code or is it due to the changes in gatsby? I'm using gatsby version `2.0.2`. Is there a better option to somehow add additional properties to the image in order to be able to query just the needed ones?\n\nHere's how my `gatsby.node.js` looks like:\n\n```\nconst axios = require('axios');\nconst { createRemoteFileNode } = require(`gatsby-source-filesystem`);\n \nexports.sourceNodes = ({ actions, createNodeId, node, store, cache } => {\n const { createNode, createNodeField } = actions;\n const processProject = project => {\n project.photos.forEach(async photo => {\n let fileNode;\n\n try {\n fileNode = await createRemoteFileNode({\n url: photo.photo.url,\n store,\n cache,\n createNode,\n createNodeId: id => `projectPhoto-${photo.id}`,\n });\n\n await createNodeField({\n node: fileNode,\n name: 'ProjectPhoto',\n value: 'true',\n });\n\n await createNodeField({\n node: fileNode,\n name: 'created_at',\n value: photo.created_at,\n });\n } catch (error) {\n console.warn('error creating node', error);\n }\n });\n }\n \n return axios.get(baseApiUrl).then(res => {\n res.data.forEach(project => {\n const nodeData = processProject(project);\n createNode(nodeData);\n });\n });\n}\n```\n\n========================================\n\nCode:\n```js\nconst axios = require('axios');\nconst { createRemoteFileNode } = require(`gatsby-source-filesystem`);\n \nexports.sourceNodes = ({ actions, createNodeId, node, store, cache } => {\n const { createNode, createNodeField } = actions;\n const processProject = project => {\n project.photos.forEach(async photo => {\n let fileNode;\n\n try {\n fileNode = await createRemoteFileNode({\n url: photo.photo.url,\n store,\n cache,\n createNode,\n createNodeId: id => `projectPhoto-${photo.id}`,\n });\n\n await createNodeField({\n node: fileNode,\n name: 'ProjectPhoto',\n value: 'true',\n });\n\n await createNodeField({\n node: fileNode,\n name: 'created_at',\n value: photo.created_at,\n });\n } catch (error) {\n console.warn('error creating node', error);\n }\n });\n }\n \n return axios.get(baseApiUrl).then(res => {\n res.data.forEach(project => {\n const nodeData = processProject(project);\n createNode(nodeData);\n });\n });\n}\n```\n\n```text\ngatsby-image\n```\n\n```text\ncreateNodeField\n```\n\n```text\nfields\n```\n\n```text\n2.0.2\n```\n\n```text\ngatsby.node.js\n```\n\n```js\nconst axios = require('axios');\nconst { createRemoteFileNode } = require(`gatsby-source-filesystem`);\n\nexports.sourceNodes = ({ actions, createNodeId, node, store, cache } => {\n const { createNode, createNodeField } = actions;\n const processProject = project => {\n for (const photo of project.photos) {\n let fileNode;\n\n try {\n fileNode = await createRemoteFileNode({\n url: photo.photo.url,\n store,\n cache,\n createNode,\n createNodeId: id => `projectPhoto-${photo.id}`,\n });\n\n await createNodeField({\n node: fileNode,\n name: 'ProjectPhoto',\n value: 'true',\n });\n\n await createNodeField({\n node: fileNode,\n name: 'created_at',\n value: photo.created_at,\n });\n } catch (error) {\n console.warn('error creating node', error);\n }\n }\n }\n\n return axios.get(baseApiUrl).then(res => {\n res.data.forEach(project => {\n const nodeData = processProject(project);\n createNode(nodeData);\n });\n });\n}\n```\n\n```text\n.forEach\n```\n\n========================================\n\nComments:\n- Gatsby fetches assets whence you run the dev/build commands so, I'd say try and loose the async pattern. It's not really giving you anything here and it might be mixing the execution times such that the Node APIs are firing out of sequence.\n- You mean to just use `.then` to consume the Promise instead of async/await? I don't think it should be an issue. The example in gatsby-source-filesystem plugin docs uses async/await too.\n- Just an idea. Out of order execution stuff seems to happen a lot with Gatsby builds on my end. The other thing that kinda jumps out at me is that maybe you don't need to be using the node API to do this. I only use `createPage` to pass the minimum data into Node to dynamically create the page. On the page itself, I do image queries via GraphQL. Does this make sense? Check out this question I made couple weeks back, similar problem I had with Contentful: stackoverflow.com/questions/52360940/…\n- Thanks, I haven't thought of using just `createPage`. That actually makes a lot of sense. Unfortunately I also wanted to add an index page with listings of all the projects (I don't generate that page dynamically, but I guess I could do that as well). Somehow I managed to get everything working by restructuring everything a bit. I've used `onCreateNode` (apart from images I create other data) and just declared the parent/children relationship there. Also it seems like using forEach didn't play nice with async/await. I used for of loop and somehow this works.\n- Interesting solution, just curious - what was the end goal of this code? What exactly gets created, a big page of images?\n- I have an api which gives me back json with array of objects (each object is a project with some details + urls for images). I wanted to display all the images for a given project along with the project details. At the end I modified solutions from what's here. I created Project Node, then added ProjectPhoto Nodes and created parent/child link between them. The idea was to 1) get data from the api 2) grab those image from urls using `createRemoteFileNode`, so they could be lazy loaded 3) create connection between those 2 nodes to be able to pull correct images for the project.\n- It was my first time playing with Gatsby Node API, so probably I overcomplicated things a bit and I'm not 100% sure if that would be the best approach for this.\n- How would you query this ?\n- @SakhiMansoor `export const pageQuery = graphql` query($id: String!) { ProjectImages: project(id: { eq: $id }) { childrenFile { id childImageSharp { fluid(maxWidth: 720, quality: 85) { ...GatsbyImageSharpFluid } } } } } `;` You can check this repo for more context.","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":187,"estimatedTokens":1763}}920{"id":"stack-44398301","source":"stackoverflow","questionId":44398301,"title":"How to construct a graphql mutation query request in php","tags":["php","graphql","apollo","apollo-server"],"text":"Title: How to construct a graphql mutation query request in php\nTags: php, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am having the hardest time figuring out how to properly format a graphql api mutation POST request in php.\n\nIf I hard code the string and use it as the data in my POST request it works like this:\n`'{\"query\":\"mutation{addPlay(input: {title: \\\"two\\\"}){ properties { title } } }\"}'`\n\nBut if I have a php array of the input values:\n\n```\n$test_data = array(\n 'title' => 'two'\n);\n```\n\nI can't seem to format it correctly. json_encode also puts double quotes around the keys which graphql is rejecting with the error `Syntax Error GraphQL request (1:26) Expected Name, found String`.\n\nI ultimately need a solution that will convert a larger more complex array to something usable.\n\n========================================\n\nCode:\n```text\n$test_data = array(\n 'title' => 'two'\n);\n```\n\n```text\n'{\"query\":\"mutation{addPlay(input: {title: \\\"two\\\"}){ properties { title } } }\"}'\n```\n\n```text\nSyntax Error GraphQL request (1:26) Expected Name, found String\n```\n\n```text\n$test_data = array(\n 'title' => 'two'\n);\n\n$request_data = array(\n 'query' => 'mutation ($input: PlayInput) { addPlay(input: $input) { properties { title } }}',\n 'variables' => array(\n 'input' => $test_data,\n ),\n);\n\n$request_data_json = json_encode($request_data);\n```\n\n```text\n$request_data_json\n```\n\n========================================\n\nComments:\n- Thanks @sagannotcarl for this I have been struggling for 2 days.","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":62,"estimatedTokens":382}}921{"id":"stack-50342116","source":"stackoverflow","questionId":50342116,"title":"How to get updated data from apollo cache","tags":["reactjs","redux","graphql","apollo","react-apollo"],"text":"Title: How to get updated data from apollo cache\nTags: reactjs, redux, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nDoes Apollo client have some sort of thing like `mapStateToProps` (Redux)?\n\nlet's say I have a component, after query I know there's data in the cache so I do something like:\n\n```\nclass Container extends React.Component {\n ...\n ...\n render() {\n const notes = this.props.client.readFragment(NOTES_FRAGMENT)\n // notes has everything I need\n return ();\n }\n\n }\n export default WithApollo(Container);\n```\n\nHowever when I have a sibling component which calls mutation and do update, the `` component's props never get updates.\n\n```\nclass AnotherContainer extends React.Component {\n render() {\n return(\n so my question is, how do I update the `` component's props whenever I do writeFragment? is there anything like mapStateToProps thing to \"connect\" the `notes` props to the cache, so whenever it updates, will trigger the React lifecycle?\n\n========================================\n\nCode:\n```text\nclass Container extends React.Component {\n ...\n ...\n render() {\n const notes = this.props.client.readFragment(NOTES_FRAGMENT)\n // notes has everything I need\n return (<Child notes={notes} />);\n }\n\n }\n export default WithApollo(Container);\n```\n\n```text\nclass AnotherContainer extends React.Component {\n render() {\n return(\n <Mutation\n mutation={UPDATE_NOTE}\n update={(cache, {data: {updateNote}}) =? {\n const list = cache.readFragment({\n fragment: NOTES_FRAGMENT\n })\n // manipulate list\n cache.writeFragment({fragment:NOTES_FRAGMENT, data })\n }\n }\n )\n }\n}\n```\n\n```text\nmapStateToProps\n```\n\n```text\n<Child />\n```\n\n```text\n<Child />\n```\n\n```text\nnotes\n```\n\n```text\nreact-apollo\n```\n\n```text\nwatchQuery\n```\n\n```text\nreadFragment\n```\n\n```text\nQuery\n```\n\n```text\ngraphql\n```\n\n```text\nconnect\n```\n\n```text\ncache-only\n```\n\n```text\ncache-first\n```\n\n```text\ngraphql\n```\n\n```text\nprops\n```\n\n```text\nQuery\n```\n\n========================================\n\nComments:\n- Thanks for clearing out many of my doubts of graphql. and yeah I'm actually using query component in other places and works, but for small piece of data, so there is not a a similar like `Fragment` version of Query component right?\n- As far as I'm aware, only queries are observable so a fragment equivalent of the `Query` component isn't really feasible right now","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":132,"estimatedTokens":625}}922{"id":"stack-42457480","source":"stackoverflow","questionId":42457480,"title":"Uncaught Error: react-apollo only supports a query, subscription, or a mutation per HOC","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: Uncaught Error: react-apollo only supports a query, subscription, or a mutation per HOC\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm trying to wrap my `Chat` component with two queries and one mutation using `compose`.\n\nHowever, I'm still getting the following error in the console:\n\n **Uncaught Error:** `react-apollo` only supports a query, subscription, or a mutation per HOC. `[object Object]` had 2 queries, 0 subscriptions and 0 mutations. You can use '`compose`' to join multiple operation types to a component\n\nHere are my queries and the export statement:\n\n```\n// this query seems to cause the issue\nconst findConversations = gql`\n query allConversations($customerId: ID!) {\n allConversations(filter: {\n customerId: $customerId\n })\n } {\n id\n }\n`\n\nconst createMessage = gql`\n mutation createMessage($text: String!, $conversationId: ID!) {\n createMessage(text: $text, conversationId: $conversationId) {\n id\n text\n }\n }\n`\n\nconst allMessages = gql`\n query allMessages($conversationId: ID!) {\n allMessages(filter: {\n conversation: {\n id: $conversationId\n }\n })\n {\n text\n createdAt\n }\n }\n`\n\nexport default compose(\n graphql(findConversations, {name: 'findConversationsQuery'}),\n graphql(allMessages, {name: 'allMessagesQuery'}),\n graphql(createMessage, {name : 'createMessageMutation'})\n)(Chat)\n```\n\nApparently, the issue is with the `findConversations` query. If I comment it out, I don't get the error and the component loads properly:\n\n```\n// this works\nexport default compose(\n // graphql(findConversations, {name: 'findConversationsQuery'}),\n graphql(allMessages, {name: 'allMessagesQuery'}),\n graphql(createMessage, {name : 'createMessageMutation'})\n)(Chat)\n```\n\nCan anyone tell me what I'm missing? \n\nBy the way, I also have a subscription set up on the `allMessagesQuery`, in case that's relevant:\n\n```\ncomponentDidMount() {\n\n this.newMessageSubscription = this.props.allMessagesQuery.subscribeToMore({\n document: gql`\n subscription {\n createMessage(filter: {\n conversation: {\n id: \"${this.props.conversationId}\"\n }\n }) {\n text\n createdAt\n }\n }\n `,\n updateQuery: (previousState, {subscriptionData}) => {\n ...\n },\n onError: (err) => console.error(err),\n })\n\n}\n```\n\n========================================\n\nCode:\n```text\n// this query seems to cause the issue\nconst findConversations = gql`\n query allConversations($customerId: ID!) {\n allConversations(filter: {\n customerId: $customerId\n })\n } {\n id\n }\n`\n\nconst createMessage = gql`\n mutation createMessage($text: String!, $conversationId: ID!) {\n createMessage(text: $text, conversationId: $conversationId) {\n id\n text\n }\n }\n`\n\nconst allMessages = gql`\n query allMessages($conversationId: ID!) {\n allMessages(filter: {\n conversation: {\n id: $conversationId\n }\n })\n {\n text\n createdAt\n }\n }\n`\n\nexport default compose(\n graphql(findConversations, {name: 'findConversationsQuery'}),\n graphql(allMessages, {name: 'allMessagesQuery'}),\n graphql(createMessage, {name : 'createMessageMutation'})\n)(Chat)\n```\n\n```text\n// this works\nexport default compose(\n // graphql(findConversations, {name: 'findConversationsQuery'}),\n graphql(allMessages, {name: 'allMessagesQuery'}),\n graphql(createMessage, {name : 'createMessageMutation'})\n)(Chat)\n```\n\n```text\ncomponentDidMount() {\n\n this.newMessageSubscription = this.props.allMessagesQuery.subscribeToMore({\n document: gql`\n subscription {\n createMessage(filter: {\n conversation: {\n id: \"${this.props.conversationId}\"\n }\n }) {\n text\n createdAt\n }\n }\n `,\n updateQuery: (previousState, {subscriptionData}) => {\n ...\n },\n onError: (err) => console.error(err),\n })\n\n}\n```\n\n```text\nChat\n```\n\n```text\ncompose\n```\n\n```text\nreact-apollo\n```\n\n```text\n[object Object]\n```\n\n```text\ncompose\n```\n\n```text\nfindConversations\n```\n\n```text\nallMessagesQuery\n```\n\n```text\nquery allConversations($customerId: ID!) {\n allConversations(filter: {\n customerId: $customerId\n })\n}\n```\n\n```text\n{\n id\n}\n```\n\n```text\nquery allConversations($customerId: ID!) {\n allConversations(filter: { customerId: $customerId }){\n id\n }\n}\n```\n\n```text\nfindConversationsQuery\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":227,"estimatedTokens":1104}}923{"id":"stack-59596736","source":"stackoverflow","questionId":59596736,"title":"Proper error handling when performing multiple mutations in graphql","tags":["error-handling","graphql","mutation"],"text":"Title: Proper error handling when performing multiple mutations in graphql\nTags: error-handling, graphql, mutation\nSource: Stack Overflow\n\nQuestion:\nGiven the following GraphQL mutations:\n\n```\ntype Mutation {\n updateUser(id: ID!, newEmail: String!): User\n updatePost(id: ID!, newTitle: String!): Post\n}\n```\n\nThe Apollo docs state that it's totally possible to perform multiple mutations in one request, say\n\n```\nmutation($userId: ID!, $newEmail: String!, $postId: ID!, $newTitle: String!) {\n updateUser(id: $userId, newEmail: $newEmail) {\n id\n email\n }\n updatePost(id: $postId, newTitle: $newTitle) {\n id\n title\n }\n}\n```\n\n**1. Does anyone actually do this?** And if you don't do this explicitly, will batching cause this kind of mutation merging?\n\n**2. If you perform run multiple things within on mutation, how would you handle errors properly?**\n\nI've seen a bunch of people recommending to throw errors on the server so that the server would respond with something that looks like this:\n\n```\n{\n errors: [\n {\n statusCode: 422,\n error: 'Unprocessable Entity'\n path: [\n 'updateUser'\n ],\n message: {\n message: 'Validation failed',\n fields: {\n newEmail: 'The new email is not a valid email address.'\n }\n },\n },\n {\n statusCode: 422,\n error: 'Unprocessable Entity'\n path: [\n 'updatePost'\n ],\n message: {\n message: 'Validation failed',\n fields: {\n newTitle: 'The given title is too short.'\n }\n },\n }\n ],\n data: {\n updateUser: null,\n updatePost: null,\n }\n}\n```\n\nBut how do I know which error belongs to which mutation? We can't assume, that the first error in the `errors` array belongs to the first mutation, because if `updateUser` succeeds, the array would simple contain one entry. Would I then have to iterate over all errors and check if the path matches my mutation name? :D\n\nAnother approach is to include the error in a dedicated response type, say `UpdateUserResponse` and `UpdatePostResponse`. This approach enables me to correctly address errors.\n\n```\ntype UpdateUserResponse {\n error: Error\n user: User\n}\n\ntype UpdatePostResponse {\n error: Error\n post: Post\n}\n```\n\nBut I have a feeling that this will bloat my schema quite a lot.\n\n========================================\n\nCode:\n```text\ntype Mutation {\n updateUser(id: ID!, newEmail: String!): User\n updatePost(id: ID!, newTitle: String!): Post\n}\n```\n\n```text\nmutation($userId: ID!, $newEmail: String!, $postId: ID!, $newTitle: String!) {\n updateUser(id: $userId, newEmail: $newEmail) {\n id\n email\n }\n updatePost(id: $postId, newTitle: $newTitle) {\n id\n title\n }\n}\n```\n\n```text\n{\n errors: [\n {\n statusCode: 422,\n error: 'Unprocessable Entity'\n path: [\n 'updateUser'\n ],\n message: {\n message: 'Validation failed',\n fields: {\n newEmail: 'The new email is not a valid email address.'\n }\n },\n },\n {\n statusCode: 422,\n error: 'Unprocessable Entity'\n path: [\n 'updatePost'\n ],\n message: {\n message: 'Validation failed',\n fields: {\n newTitle: 'The given title is too short.'\n }\n },\n }\n ],\n data: {\n updateUser: null,\n updatePost: null,\n }\n}\n```\n\n```text\ntype UpdateUserResponse {\n error: Error\n user: User\n}\n\ntype UpdatePostResponse {\n error: Error\n post: Post\n}\n```\n\n```text\nerrors\n```\n\n```text\nupdateUser\n```\n\n```text\nUpdateUserResponse\n```\n\n```text\nUpdatePostResponse\n```\n\n```text\ntype Mutation {\n updateUser(id: ID!, newEmail: String!): UpdateUserPayload!\n}\n\nunion UpdateUserPayload = User | Error\n```\n\n```text\nmutation($userId: ID!, $newEmail: String!) {\n updateUser(id: $userId, newEmail: $newEmail) {\n __typename\n ... on User {\n id\n email\n }\n ... on Error {\n message\n code\n }\n }\n}\n```\n\n```text\nunion UpdateUserPayload = User | EmailExistsError | EmailInvalidError\n```\n\n```text\npath\n```\n\n```text\ntitle\n```\n\n```text\npath\n```\n\n```text\nupdatePost.title\n```\n\n```text\ndata\n```\n\n```text\nerrors\n```\n\n```text\n__typename\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.092Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":233,"estimatedTokens":997}}924{"id":"stack-56088305","source":"stackoverflow","questionId":56088305,"title":"How to avoid wrapping errors collection in a error object in Apollo Server V2 in error response","tags":["node.js","graphql","apollo-server"],"text":"Title: How to avoid wrapping errors collection in a error object in Apollo Server V2 in error response\nTags: node.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nWe are migrating our Apollo Graphql Server v1 projects to v2.\n\nWe noticed that there is a change in the error response format.\n\nIn v2, the errors list in the response is wrapped within an error object.\n\nBut, in v1, it is not so. We want to have a a consistent standard and not introduce the wrapping behaviour in v2.\n\nI understand that GraphQL services may provide add additional fields via extensions as per below link.\nLink: https://graphql.github.io/graphql-spec/June2018/#sec-Errors\n\nI have tested Apollo GraphQL V2 and this is how it is implemented there.\n\nIn v1 it is as expected.\n\nIn v1,we see error response as below,\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Field \\\"announcement\\\" must not have a selection since type \\\"String\\\" has no subfields.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 16\n }\n ]\n }\n ]\n}\n```\n\nIn v2, we see error response as below,\n\n```\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Field \\\"announcement\\\" must not have a selection since type \\\"String\\\" has no subfields.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 16\n }\n ],\n \"extensions\": {\n \"code\": \"GRAPHQL_VALIDATION_FAILED\",\n \"exception\": {\n \"stacktrace\": [\n ...\n ]\n }\n }\n }\n ]\n }\n}\n```\n\nIn v1 error response, errors list is not wrapped inside error object. In v2,it is wrapped in error object.\n\nBut, my question is why is the **errors list** wrapped inside a **error object** in v2. \nIn v1, there was only the errors list in the response.\n\nWe a standard for all services (both REST and non-REST) to have a standard format and it was as per the v1 version. But, now we see it has been wrapped in a error object. \n\nIs there any way we can configure Apollo Server to not wrap the errors list within a error object.\n\n========================================\n\nCode:\n```text\n{\n \"errors\": [\n {\n \"message\": \"Field \\\"announcement\\\" must not have a selection since type \\\"String\\\" has no subfields.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 16\n }\n ]\n }\n ]\n}\n```\n\n```text\n{\n \"error\": {\n \"errors\": [\n {\n \"message\": \"Field \\\"announcement\\\" must not have a selection since type \\\"String\\\" has no subfields.\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 16\n }\n ],\n \"extensions\": {\n \"code\": \"GRAPHQL_VALIDATION_FAILED\",\n \"exception\": {\n \"stacktrace\": [\n ...\n ]\n }\n }\n }\n ]\n }\n}\n```\n\n```text\nerror\n```\n\n========================================\n\nComments:\n- Yes. I got it. It is a bug with GraphQL Playground and not with Apollo GraphQL v2. you are right.","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":128,"estimatedTokens":700}}925{"id":"stack-52004990","source":"stackoverflow","questionId":52004990,"title":"How to upload file with GraphQL and Apollo Upload Server in NodeJS?","tags":["node.js","graphql","apollo-server"],"text":"Title: How to upload file with GraphQL and Apollo Upload Server in NodeJS?\nTags: node.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI did not get any proper example to upload a file via GraphQL, Apollo Server in NodeJS.\n\nI have written a mutation to send the message that is perfectly working. Here is the code sendMessage.js Mutation\n\n```\nconst sendMessage = {\n type: ChatType,\n args: {\n input: {\n type: new GraphQLNonNull(new GraphQLInputObjectType({\n name: 'ChatMessageInput',\n fields: {\n toUserId:{\n name:'To User ID',\n type: new GraphQLNonNull(GraphQLID)\n },\n message:{\n name:'Message',\n type: new GraphQLNonNull(GraphQLString)\n }\n }\n }))\n },\n file:{\n name: \"File\",\n type: uploadType\n }\n },\n async resolve(_, input, context) {\n\n }\n };\n\nmodule.exports = sendMessage;\n```\n\nHere the code I have written for creating the GraphQl End Point.\n\n```\napp.use('/api', bodyParser.json(), jwtCheck, \napolloUploadExpress({ uploadDir: \"./uploads\",maxFileSize: 10000000, maxFiles: 10 }),\ngraphqlExpress(req => ({\n schema,\n context: {\n user: req.user,\n header:req.headers\n },\n formatError: error => ({\n status:error.message[0].status,\n message: error.message[0].message,\n state: error.message\n })\n})),function (err, req, res, next) {\n if (err.name === 'UnauthorizedError') { // Send the error rather than to show it on the console\n //console.log(err);\n res.status(401).send({errors:[err]});\n }\n else {\n next(err);\n }\n}\n);\n```\n\nNow, I want to add upload file functionality in the same mutation. Please help me how can I do that.\n\nThanks in advance.\n\n========================================\n\nTop Answer:\nI'm sure you'll find all needed parts (client+server) in apollo-universal-starter-kit project.\n\n========================================\n\nCode:\n```text\nconst sendMessage = {\n type: ChatType,\n args: {\n input: {\n type: new GraphQLNonNull(new GraphQLInputObjectType({\n name: 'ChatMessageInput',\n fields: {\n toUserId:{\n name:'To User ID',\n type: new GraphQLNonNull(GraphQLID)\n },\n message:{\n name:'Message',\n type: new GraphQLNonNull(GraphQLString)\n }\n }\n }))\n },\n file:{\n name: \"File\",\n type: uploadType\n }\n },\n async resolve(_, input, context) {\n\n }\n };\n\nmodule.exports = sendMessage;\n```\n\n```text\napp.use('/api', bodyParser.json(), jwtCheck, \napolloUploadExpress({ uploadDir: \"./uploads\",maxFileSize: 10000000, maxFiles: 10 }),\ngraphqlExpress(req => ({\n schema,\n context: {\n user: req.user,\n header:req.headers\n },\n formatError: error => ({\n status:error.message[0].status,\n message: error.message[0].message,\n state: error.message\n })\n})),function (err, req, res, next) {\n if (err.name === 'UnauthorizedError') { // Send the error rather than to show it on the console\n //console.log(err);\n res.status(401).send({errors:[err]});\n }\n else {\n next(err);\n }\n}\n);\n```\n\n========================================\n\nComments:\n- Thanks for your answer. You defined the upload model in gql language. I did not know how to define an interface in node js without gql. The way I wrote mutation definition code (in the given question), could you please guide me how can I do that in that same way.. Please help me regarding this. Thanks","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":143,"estimatedTokens":867}}926{"id":"stack-60337299","source":"stackoverflow","questionId":60337299,"title":"How to federate two apollo services that provide the same type","tags":["graphql","apollo","apollo-federation"],"text":"Title: How to federate two apollo services that provide the same type\nTags: graphql, apollo, apollo-federation\nSource: Stack Overflow\n\nQuestion:\nI am new to apollo and I have two apollo service that I want to federate by using apollo federation:\n\n**Productservice:**\n\n```\nextend type Query {\n job(id: String!): Job\n}\n\ntype Seo {\n title: String! \n description: String! \n keywords: String! \n}\n\ntype Product @key(fields: \"id\") {\n id: ID!\n title: String!\n seo: Seo!\n}\n```\n\n**StaffService:**\n\n```\nextend type Query {\n staffMember(id: String!): StaffMember\n}\n\ntype Seo {\n title: String! \n description: String! \n keywords: String! \n}\n\ntype StaffMember @key(fields: \"id\") {\n id: ID!\n title: String!\n seo: Seo!\n}\n```\n\nHow can I use the type **Seo** in response objects of both objects? Is the correct procedure to create an interface Seo and implement StaffMemberSeo and ProductSeo or is there an annotation that allows me to define the exactly same type within two services?\n\n========================================\n\nCode:\n```text\nextend type Query {\n job(id: String!): Job\n}\n\ntype Seo {\n title: String! \n description: String! \n keywords: String! \n}\n\ntype Product @key(fields: \"id\") {\n id: ID!\n title: String!\n seo: Seo!\n}\n```\n\n```text\nextend type Query {\n staffMember(id: String!): StaffMember\n}\n\ntype Seo {\n title: String! \n description: String! \n keywords: String! \n}\n\ntype StaffMember @key(fields: \"id\") {\n id: ID!\n title: String!\n seo: Seo!\n}\n```\n\n========================================\n\nComments:\n- `Seo` should be included in the `seo` field of the query result. Are you asking how to have its fields unnested directly in the query result and not nested in the `seo` field?\n- No, the question is about having defined Seo two times. I think the answer to the question is that the design of apollo doesn't allow it and I have to rename Seo to StaffSeo and ProductSeo.","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":93,"estimatedTokens":471}}927{"id":"stack-57753943","source":"stackoverflow","questionId":57753943,"title":"How to skip empty objects in query conditional fragment?","tags":["graphql","apollo-client","aws-appsync"],"text":"Title: How to skip empty objects in query conditional fragment?\nTags: graphql, apollo-client, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI have a query to return objects of type `ObjectA`. The response is using a conditional fragment.\n\n```\nunion Objects = ObjectA | ObjectB | ObjectC\n\ngetObjects {\n ... on ObjectA {\n name\n }\n}\n```\n\nThe resolver will return all objects\n\n```\n$util.toJSON($ctx.result.objects)\n```\n\nHowever, I got a response:\n\n```\n[\n {\n \"name\": \"apple\"\n },\n {\n \"name\": \"airplane\"\n },\n {},\n {}\n]\n```\n\nThe last two \"empty\" objects are not of type `ObjectA`.\n\nMy question is, is there a way using conditional fragment to exclude \"empty\" objects from different type?\n\n========================================\n\nCode:\n```text\nunion Objects = ObjectA | ObjectB | ObjectC\n\ngetObjects {\n ... on ObjectA {\n name\n }\n}\n```\n\n```text\n$util.toJSON($ctx.result.objects)\n```\n\n```text\n[\n {\n \"name\": \"apple\"\n },\n {\n \"name\": \"airplane\"\n },\n {},\n {}\n]\n```\n\n```text\nObjectA\n```\n\n```text\nObjectA\n```\n\n========================================\n\nComments:\n- Right. That's what I have found out too upon checking graphql's way of doing conditional fragment with unions.\n- and 2 years later... so sad. π","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":85,"estimatedTokens":303}}928{"id":"stack-53352739","source":"stackoverflow","questionId":53352739,"title":"Generate Graphql schema from json api response","tags":["schema","graphql","apollo-server"],"text":"Title: Generate Graphql schema from json api response\nTags: schema, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am using **Apollo server 2.0** as graphql aggregation layer over my rest apis ( different microservices).\n\nI want to generate **graphql schema** directly from the api response of microservices instead of manually writing them by hand which could be error prone.\n\ne.g If my api response is \n\n```\nconst restApiResponse = {\n \"id\": 512,\n \"personName\": \"Caribbean T20 2016\",\n \"personShortName\": \"caribbean-t20 2016\",\n \"startDate\": \"2016-06-29T19:30:00.000Z\",\n \"endDate\": \"2016-08-08T18:29:59.000Z\",\n \"status\": 0,\n};\n```\n\nThen I want to generate below schema based on the **typeName** supplied e.g `Person`\n -\n\n```\ntype Person {\n id: Float\n personName: String\n personShortName: String\n startDate: String\n endDate: String\n status: Float\n}\n```\n\n========================================\n\nTop Answer:\nThis doesn't really answer your question, but I would recommend you NOT do this. GraphQL defines itself as \"unapologetically client-driven\", which suggests to me that every query you define should be expressly defined as something the client specifically wants. If you only have FLAT data, you don't need GraphQL, and REST is good enough. If you do not, you'll need to carefully craft and specifically nest your data in the way that the client wants, and makes sense to your UI. There is plenty of tooling to make this easier, but I would advise against what you're asking for.\n\n========================================\n\nCode:\n```text\nconst restApiResponse = {\n \"id\": 512,\n \"personName\": \"Caribbean T20 2016\",\n \"personShortName\": \"caribbean-t20 2016\",\n \"startDate\": \"2016-06-29T19:30:00.000Z\",\n \"endDate\": \"2016-08-08T18:29:59.000Z\",\n \"status\": 0,\n};\n```\n\n```text\ntype Person {\n id: Float\n personName: String\n personShortName: String\n startDate: String\n endDate: String\n status: Float\n}\n```\n\n```text\nPerson\n```\n\n```text\nconst { composeWithJson } = require('graphql-compose-json');\nconst { GQC } = require('graphql-compose');\nconst { printSchema } = require('graphql'); // CommonJS\n\n\nconst restApiResponse = {\n \"id\": 399,\n \"templateId\": 115,\n \"amount\": 100000,\n \"amountINR\": 100000,\n \"amountUSD\": 0,\n \"currencyCode\": \"INR\",\n \"createdAt\": \"2018-06-07T00:08:28.000Z\",\n \"createdBy\": 36,\n};\n\nconst GqlType = composeWithJson('Template', restApiResponse);\nconst PersonGraphQLType = GqlType.getType();\n\nGqlType.addResolver({\n name: 'findById',\n type: GqlType,\n args: {\n id: 'Int!',\n },\n resolve: rp => {\n },\n });\n\n GQC.rootQuery().addFields({\n person: GqlType.getResolver('findById'),\n });\n\nconst schema = GQC.buildSchema();\n\nconsole.log(printSchema(schema));\n```\n\n```text\ntype Template {\n id: Float\n templateId: Float\n amount: Float\n amountINR: Float\n amountUSD: Float\n currencyCode: String\n createdAt: String\n createdBy: Float\n}\n```\n\n========================================\n\nComments:\n- What are you currently using for response validation for those REST endpoints?\n- @Daniel First of all I didn't get \"response validation\" part. But not doing response validation right now. Its completly being written from scratch.\n- Not sure what you mean by \"written from scratch\" in this context. It's common to see some form of response (output) validation -- i.e. a mechanism that will validate your responses against some schema. Swagger, Joi and JSON Schema are all examples of that. The reason I ask is that if you're already using something like that, chances are there's a tool available to convert that schema into a GraphQL schema.\n- @DanielRearden Oh yes from swagger I could remember we declare a yaml file. But in this case I haven't any schema validation.\n- So you could look into something like swagger-to-graphql or graphql-liftoff","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":130,"estimatedTokens":955}}929{"id":"stack-59187078","source":"stackoverflow","questionId":59187078,"title":"Send an enum to graphql API from react app","tags":["javascript","reactjs","graphql","react-apollo","apollo-client"],"text":"Title: Send an enum to graphql API from react app\nTags: javascript, reactjs, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have an input (attached image) that I need to send to the graphql api from react application.\n\nhttps://i.sstatic.net/yg5HX.png\n\nI am using below code to send this object and enum with init to graphql api\n**Reactjs Code** \n\n```\nconst RequestActionEnum = {\nNEW: 'New',\nUPDATE: 'Update',\nARCHIVE: 'Archive'\n}\n\nLocalCodeMutation({\n variables: {\n data: {\n id: null,\n city: values.jurisdiction,\n country: values.country,\n description: values.description,\n edition: values.edition,\n name: values.codeName,\n note: 'test',\n requestType: RequestActionEnum.NEW, // this is where i am sending enum value to api \n state: values.state\n }\n }\n });\n```\n\nBelow code is where I am calling the mutation\n\n```\nconst [LocalCodeMutation] = useMutation(LOCALCODE_MUTATION, {\nrefetchQueries: () => [\n { query: GET_LOCALCODES },\n],\n});\n\nexport const LOCALCODE_MUTATION = gql`\n mutation LocalCodeMutation($data: LocalCodeRequestParamsInput) {\nlocalCodeMutation(data: $data) {\n ok\n errors\n localCodeInsertedId\n }\n }\n`;\n```\n\nI am getting this error when I send to the API:\n\n Error: GraphQL error: Variable $data got invalid value.\n\nHow can I send enum value to graphQL api from react component.\n\nCould any one please suggest any ideas on this?\n\n========================================\n\nCode:\n```text\nconst RequestActionEnum = {\nNEW: 'New',\nUPDATE: 'Update',\nARCHIVE: 'Archive'\n}\n\nLocalCodeMutation({\n variables: {\n data: {\n id: null,\n city: values.jurisdiction,\n country: values.country,\n description: values.description,\n edition: values.edition,\n name: values.codeName,\n note: 'test',\n requestType: RequestActionEnum.NEW, // this is where i am sending enum value to api \n state: values.state\n }\n }\n });\n```\n\n```text\nconst [LocalCodeMutation] = useMutation(LOCALCODE_MUTATION, {\nrefetchQueries: () => [\n { query: GET_LOCALCODES },\n],\n});\n\nexport const LOCALCODE_MUTATION = gql`\n mutation LocalCodeMutation($data: LocalCodeRequestParamsInput) {\nlocalCodeMutation(data: $data) {\n ok\n errors\n localCodeInsertedId\n }\n }\n`;\n```\n\n```text\n{\n someField(someArgument: NEW)\n}\n```\n\n```text\nRequestActionEnum\n```\n\n```text\nNEW\n```\n\n```text\nUPDATE\n```\n\n```text\nARCHIVE\n```\n\n```text\n\"NEW\"\n```\n\n```text\n\"New\"\n```\n\n========================================\n\nComments:\n- Why downvote on this question ? Is there Anything wrong with this question\n- Thanks for the support , I need to send βNewβ to the api in that case what I need to do could you please guide me .thanks\n- I'm assuming you're referring to some other API you're calling from your GraphQL resolver?\n- i am calling .net core from this and using types with mutations inside it. Other than that nothing I am using\n- I need to compare the string βNewβ inside api with the coming value from react app, could you please let me know how can I achieve this\n- I'm not sure what you're asking here. The react app should be sending `NEW` instead of `New` since that's what's in your schema. You can change your schema so that the enum value is `New` instead if you like (they don't *have* to be all caps). Or you can just transform the value you receive inside your resolver. How that's done with a GraphQL.net needs to be a separate question. That has nothing to do with the error you're seeing.\n- even if i am did like this New: NEW i am getting same error, I am not sure where i am doing wrong here\n- It could also be an issue with another part of the object you're sending. Take a look at the complete error message you're getting back. Or update your question to include the full message.","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":150,"estimatedTokens":942}}930{"id":"stack-32497759","source":"stackoverflow","questionId":32497759,"title":"Recursive data & components, later fetches throwing an error","tags":["reactjs","graphql","relayjs"],"text":"Title: Recursive data & components, later fetches throwing an error\nTags: reactjs, graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nFirst off my graphql data model:\n\n```\ntype Human {\n id: !String,\n name: !String,\n children: [Human]\n}\n```\n\nThe only route (relay route config) I'm atm using:\n\n```\nclass extends Relay.Route {\n static queries = {\n human: () => Relay.QL`query RootQuery { viewer }`\n };\n static routeName = 'AppHomeRoute';\n}\n```\n\nThe list component:\n\n```\nclass HumanList extends Component {\n render() {\n let {children} = this.props.human;\n\n let subListsHTML = human ? children.map(child => (\n \n )) : '';\n\n return {subListsHTML};\n }\n}\n\nexport default Relay.createContainer(HumanList, {\n fragments: {\n human: () => Relay.QL`\n fragment on Human {\n children {\n id,\n ${HumanListItem.getFragment('human')}\n }\n }\n `\n }\n});\n```\n\nThe list item component:\n\n```\nclass HumanListItem extends Component {\n state = {expanded: false};\n\n render() {\n let {human} = this.props;\n\n let sublistHTML = '';\n if (this.state.expanded) {\n sublistHTML = ;\n }\n\n return (\n \n {human.name}\n {sublistHTML}\n \n );\n }\n\n onClickHead() {\n this.props.relay.setVariables({expanded: true});\n this.setState({expanded: true});\n }\n\n}\n\nHumanListItem.defaultProps = {viewer: {}};\n\nexport default Relay.createContainer(HumanListItem, {\n\n initialVariables: {\n expanded: false\n },\n\n fragments: {\n human: (variables) => Relay.QL`\n fragment on Human {\n name,\n ${HumanList.getFragment('human').if(variables.expanded)}\n }\n `\n }\n\n});\n```\n\nWhich runs fine for the root list. But as soon as I click on a ListItem and it is expanded, I get the following error:\n\n`Warning: RelayContainer: Expected prop 'human' supplied 'HumanList' to be data fetched by Relay. This is likely an error unless you are purposely passing in mock data that conforms to the shape of this component's fragment.`\n\nI can't make much sense of it, since the data I'm passing is not mocked but directly fetched by Relay as can be seen in the HumanList comp.\n\n========================================\n\nCode:\n```js\ntype Human {\n id: !String,\n name: !String,\n children: [Human]\n}\n```\n\n```js\nclass extends Relay.Route {\n static queries = {\n human: () => Relay.QL`query RootQuery { viewer }`\n };\n static routeName = 'AppHomeRoute';\n}\n```\n\n```js\nclass HumanList extends Component {\n render() {\n let {children} = this.props.human;\n\n let subListsHTML = human ? children.map(child => (\n <HumanListItem key={child.id} human={child}/>\n )) : '';\n\n return <ul>{subListsHTML}</ul>;\n }\n}\n\nexport default Relay.createContainer(HumanList, {\n fragments: {\n human: () => Relay.QL`\n fragment on Human {\n children {\n id,\n ${HumanListItem.getFragment('human')}\n }\n }\n `\n }\n});\n```\n\n```js\nclass HumanListItem extends Component {\n state = {expanded: false};\n\n render() {\n let {human} = this.props;\n\n let sublistHTML = '';\n if (this.state.expanded) {\n sublistHTML = <ul><HumanList human={human}/></ul>;\n }\n\n return (\n <li>\n <div onClick={this.onClickHead.bind(this)}>{human.name}</div>\n {sublistHTML}\n </li>\n );\n }\n\n onClickHead() {\n this.props.relay.setVariables({expanded: true});\n this.setState({expanded: true});\n }\n\n}\n\nHumanListItem.defaultProps = {viewer: {}};\n\nexport default Relay.createContainer(HumanListItem, {\n\n initialVariables: {\n expanded: false\n },\n\n fragments: {\n human: (variables) => Relay.QL`\n fragment on Human {\n name,\n ${HumanList.getFragment('human').if(variables.expanded)}\n }\n `\n }\n\n});\n```\n\n```text\nWarning: RelayContainer: Expected prop 'human' supplied 'HumanList' to be data fetched by Relay. This is likely an error unless you are purposely passing in mock data that conforms to the shape of this component's fragment.\n```\n\n```js\nclass HumanListItem extends Component {\n onClickHead() {\n this.props.relay.setVariables({expanded: true});\n this.setState({expanded: true}); // <-- this causes the component to re-render before data is ready\n }\n```\n\n```js\nclass HumanListItem extends Component {\n // no need for `state.expanded`\n\n render() {\n let {human} = this.props;\n\n let sublistHTML = '';\n if (this.props.relay.variables.expanded) {\n // `variables` are the *currently fetched* data\n // if `variables.expanded` is true, expanded data is fetched\n sublistHTML = <ul><HumanList human={human}/></ul>;\n }\n\n return (\n <li>\n <div onClick={this.onClickHead.bind(this)}>{human.name}</div>\n {sublistHTML}\n </li>\n );\n }\n\n onClickHead() {\n this.props.relay.setVariables({expanded: true});\n // no need for `setState()`\n }\n\n}\n\nHumanListItem.defaultProps = {viewer: {}};\n\nexport default Relay.createContainer(HumanListItem, {\n\n initialVariables: {\n expanded: false\n },\n\n fragments: {\n human: (variables) => Relay.QL`\n fragment on Human {\n name,\n ${HumanList.getFragment('human').if(variables.expanded)}\n }\n `\n }\n\n});\n```\n\n```text\n<HumanList>\n```\n\n========================================\n\nComments:\n- Thank's a lot! It already felt strange setting the state and the variables. Should have taken that as a hint... I still have an error but I think that's related to my graphql implementation, so this is solved!","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":273,"estimatedTokens":1330}}931{"id":"stack-50341358","source":"stackoverflow","questionId":50341358,"title":"Elixir, Absinthe How can I get user created after a date with absinthe?","tags":["elixir","graphql","phoenix-framework","absinthe"],"text":"Title: Elixir, Absinthe How can I get user created after a date with absinthe?\nTags: elixir, graphql, phoenix-framework, absinthe\nSource: Stack Overflow\n\nQuestion:\nI am trying to get users that were created before/after certain date and I get this error. \n\n\"message\": \"Argument \\\"filter\\\" has invalid value $filter.\\nIn field \\\"insertedAfter\\\": Expected type \\\"NaiveDateTime\\\", found \\\"2018-05-13\\\".\",\n\nThe error makes sense since \"2018-05-13\" is not NativeDateTime... However, I thought NativeDateTime should parse the string \"2018-05-13\". I am trying to apply what I learned from a book but having hard time. I also created a custom date scalar but I basically encountered the same error.\n\nHow can I accomplish being able to search user created after certain date with phoenix and absinthe?\n\n```\nquery($filter: UserFilter){\n allUsers(filter: $filter){\n id\n firstName\n lastName\n }\n}\n\nvalues\n{\n \"filter\": {\n \"insertedAfter\": \"2018-05-13\"\n }\n}\n```\n\nEcto schema, account > user.ex\n\n```\nschema \"users\" do\n field :avatar_img, :string\n field :email, :string, null: false\n field :fb_token, :string\n field :first_name, :string\n field :google_token, :string\n field :last_name, :string\n field :password, :string, null: false\n field :admin_user_id, :string\n\n timestamps()\n end\n```\n\ntypes.ex\n\n```\nuse Absinthe.Schema.Notation\n use Absinthe.Ecto, repo: ElixirBlog.Repo\n import_types Absinthe.Type.Custom\n\n object :user do\n field :id, non_null(:id)\n field :first_name, non_null(:string)\n field :last_name, non_null(:string)\n field :email, non_null(:string)\n field :password, non_null(:string)\n field :avatar_img, :string\n field :admin_user_id, :string\n field :fb_token, :string\n field :google_token, :string\n field :inserted_at, :naive_datetime\n field :updated_at, :naive_datetime\nend\n```\n\nAbsinthe schema\nschema.ex\n\n```\nuse Absinthe.Schema\nimport_types Elixir.Schema.Types\n\ninput_object :user_filter do\n field :id, :integer\n field :first_name, :string\n field :last_name, :string\n field :email, :string\n field :inserted_before, :naive_datetime\n field :inserted_after, :naive_datetime\nend\n\nquery do\n field :all_users, list_of(:user) do\n arg :filter, :user_filter\n arg :order, type: :sort_order, default_value: :asc\n resolve &ElixirBlogWeb.UsersResolver.all_users/3\n end\nend\n```\n\nusers_resolver.ex\n\n```\nalias Elixir.Account\n\ndef all_users(_root, args, _info) do\n users = Account.list_users(args)\n {:ok, users}\nend\n```\n\naccount.ex\n\n```\ndef list_users(args) do\n args\n |> Enum.reduce(User, fn\n {:order, order}, query ->\n query |> order_by({^order, :first_name})\n {:filter, filter}, query ->\n query |> filter_with(filter)\n end)\n |> Repo.all\nend\n\ndefp filter_with(query, filter) do\n Enum.reduce(filter, query, fn\n {:id, id}, query ->\n from q in query, where: q.id == ^id\n {:first_name, first_name}, query ->\n from q in query, where: ilike(q.first_name, ^\"%#{first_name}%\")\n {:last_name, last_name}, query ->\n from q in query, where: ilike(q.last_name, ^\"%#{last_name}%\")\n {:email, email}, query ->\n from q in query, where: ilike(q.email, ^\"%#{email}%\")\n {:inserted_before, date}, query ->\n from q in query, where: q.inserted_at \n from q in query, where: q.inserted_at >= ^date\n end)\nend\n```\n\nmix.exs\n\n```\n{:phoenix, \"~> 1.3.2\"},\n {:phoenix_ecto, \"~> 3.2\"},\n {:absinthe, \"~> 1.4\"},\n {:absinthe_plug, \"~> 1.4\"},\n {:absinthe_ecto, \"~> 0.1.3\"},\n```\n\n========================================\n\nCode:\n```text\nquery($filter: UserFilter){\n allUsers(filter: $filter){\n id\n firstName\n lastName\n }\n}\n\nvalues\n{\n \"filter\": {\n \"insertedAfter\": \"2018-05-13\"\n }\n}\n```\n\n```text\nschema \"users\" do\n field :avatar_img, :string\n field :email, :string, null: false\n field :fb_token, :string\n field :first_name, :string\n field :google_token, :string\n field :last_name, :string\n field :password, :string, null: false\n field :admin_user_id, :string\n\n timestamps()\n end\n```\n\n```text\nuse Absinthe.Schema.Notation\n use Absinthe.Ecto, repo: ElixirBlog.Repo\n import_types Absinthe.Type.Custom\n\n object :user do\n field :id, non_null(:id)\n field :first_name, non_null(:string)\n field :last_name, non_null(:string)\n field :email, non_null(:string)\n field :password, non_null(:string)\n field :avatar_img, :string\n field :admin_user_id, :string\n field :fb_token, :string\n field :google_token, :string\n field :inserted_at, :naive_datetime\n field :updated_at, :naive_datetime\nend\n```\n\n```text\nuse Absinthe.Schema\nimport_types Elixir.Schema.Types\n\ninput_object :user_filter do\n field :id, :integer\n field :first_name, :string\n field :last_name, :string\n field :email, :string\n field :inserted_before, :naive_datetime\n field :inserted_after, :naive_datetime\nend\n\nquery do\n field :all_users, list_of(:user) do\n arg :filter, :user_filter\n arg :order, type: :sort_order, default_value: :asc\n resolve &ElixirBlogWeb.UsersResolver.all_users/3\n end\nend\n```\n\n```text\nalias Elixir.Account\n\ndef all_users(_root, args, _info) do\n users = Account.list_users(args)\n {:ok, users}\nend\n```\n\n```text\ndef list_users(args) do\n args\n |> Enum.reduce(User, fn\n {:order, order}, query ->\n query |> order_by({^order, :first_name})\n {:filter, filter}, query ->\n query |> filter_with(filter)\n end)\n |> Repo.all\nend\n\ndefp filter_with(query, filter) do\n Enum.reduce(filter, query, fn\n {:id, id}, query ->\n from q in query, where: q.id == ^id\n {:first_name, first_name}, query ->\n from q in query, where: ilike(q.first_name, ^\"%#{first_name}%\")\n {:last_name, last_name}, query ->\n from q in query, where: ilike(q.last_name, ^\"%#{last_name}%\")\n {:email, email}, query ->\n from q in query, where: ilike(q.email, ^\"%#{email}%\")\n {:inserted_before, date}, query ->\n from q in query, where: q.inserted_at <= ^date\n {:inserted_after, date}, query ->\n from q in query, where: q.inserted_at >= ^date\n end)\nend\n```\n\n```text\n{:phoenix, \"~> 1.3.2\"},\n {:phoenix_ecto, \"~> 3.2\"},\n {:absinthe, \"~> 1.4\"},\n {:absinthe_plug, \"~> 1.4\"},\n {:absinthe_ecto, \"~> 0.1.3\"},\n```\n\n```text\n:naive_datetime\n```\n\n```text\nAbsinthe\n```\n\n```text\nThe DateTime appears in a JSON response as an ISO8601 formatted string.\n```\n\n```text\n\"2018-05-13 00:00:07\"\n```\n\n========================================\n\nComments:\n- Thank you for your answer. So we need to change the input date in the frontend because users are not going to type ~N[2018-05-13 00:00:00]. I was wondering if there's any other way?\n- @ζ’
ζ΄₯εͺζ¨Ή Nope. You can figure out to transfer the type.\n- Okay. I changed the variable, `\"insertedAfter\": \"~N[2018-05-13 00:00:00]\"` It still gives me `\"message\": \"Argument \\\"filter\\\" has invalid value $filter.\\nIn field \\\"insertedAfter\\\": Expected type \\\"NaiveDateTime\\\", found \\\"~N[2018-05-13 00:00:00]\\\".\",`\n- @ζ’
ζ΄₯εͺζ¨Ή `~N[2018-05-13 00:00:00]` is a sigil instead of string. Plz read the url I gave. : P\n- `~N[2018-05-13 00:00:00]` instead of `\"~N[2018-05-13 00:00:00]\"`.\n- When I put `\"insertedAfter\": ~N[2018-05-13 00:00:00]`, GraphiQL gives me error: Variables are invalid JSON: Unexpected token ~ in JSON at position 37. It is expecting JSON format.\n- Try \"2018-05-13 00:00:07\" instead of ~N[2018-05-13 00:00:00]. @ζ’
ζ΄₯εͺζ¨Ή","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":296,"estimatedTokens":1781}}932{"id":"stack-59632995","source":"stackoverflow","questionId":59632995,"title":"Using GitHub GraphQL API programmatically, getting a Bad Request with RestTemplate.execute, but works ok on Postman","tags":["spring-boot","graphql","github-api"],"text":"Title: Using GitHub GraphQL API programmatically, getting a Bad Request with RestTemplate.execute, but works ok on Postman\nTags: spring-boot, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nI'm trying to consume GitHub's v4 API using GraphQL from within a Spring Boot application (namely, my app is a server that is trying to consume the API on a Service as part of resolving a GET request on one of the app's controllers).\n\nI tried the following test POST request on Postman, getting the data I was expecting successfully:\n\n```\nPOST /graphql HTTP/1.1\nHost: api.github.com\nContent-Type: application/json\nAuthorization: Bearer [MY PERSONAL GITHUB TOKEN]\nUser-Agent: PostmanRuntime/7.20.1\nAccept: */*\nCache-Control: no-cache\nPostman-Token: 55f54f00-83f6-4acb-a6f8-4a3bde9147e7,abb6f600-8b79-4697-bd31-e04836386a24\nHost: api.github.com\nAccept-Encoding: gzip, deflate\nContent-Length: 264\nConnection: keep-alive\ncache-control: no-cache\n\nquery{repository(owner:\"ccjmk\", name:\"super-happiness\"){object(expression:\"master\"){... on Commit{history{totalCount}}}}}\n```\n\nResponse:\n\n```\n{\"data\":{\"repository\":{\"object\":{\"history\":{\"totalCount\":19}}}}}\n```\n\n(I don't see any notable headers but I could add anything that might be valuable)\n\nThen, on the Java end, I tried this in the service: (I also tried hitting the v3 API successfully, adding the method used on the service too for reference)\n\n```\n@Override\n public String fetchCommitsv3(String ownerUsername, String repository) {\n\n final String uri = String.format(\"https://api.github.com/repos/%s/%s/commits\", ownerUsername, repository);\n\n RestTemplate restTemplate = new RestTemplate();\n String result = restTemplate.getForObject(uri, String.class);\n return result;\n }\n\n @Override\n public ResponseEntity fetchCommitsv4(String ownerUsername, String repository) {\n\n final String uri = String.format(\"https://api.github.com/graphql\");\n String query = \"query{repository(owner:\\\"\"+ownerUsername+\"\\\", name:\\\"\"+repository+\"\\\"){object(expression:\\\"master\\\"){... on Commit{history{totalCount}}}}}\";\n\n String gitHubToken = [MY GITHUB TOKEN];\n\n RestTemplate restTemplate = new RestTemplate();\n restTemplate.setRequestFactory(new HttpComponentsAsyncClientHttpRequestFactory());\n HttpHeaders headers = new HttpHeaders();\n //headers.add(\"Authorization\", \"Bearer \"+gitHubToken);\n headers.set(\"Authorization\",\"Bearer \"+gitHubToken);\n headers.setContentType(MediaType.APPLICATION_JSON);\n HttpEntity entity = new HttpEntity<>(query, headers);\n\n ResponseEntity result = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class);\n return result;\n }\n```\n\nThat's triggering a 400 Bad Request reponse, at the end the full post. To me, both requests look the same, but they are surely different, only I can't pin-point where! Any help would be much appreciated, because I'm sure \n\nSpringBoot Log:\n\n```\n2020-01-07 16:48:24.419 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/tdd/insights/github/v4/commits/ccjmk/super-happiness]\n2020-01-07 16:48:24.432 DEBUG 21236 --- [nio-8088-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /tdd/insights/github/v4/commits/ccjmk/super-happiness\n2020-01-07 16:48:24.450 DEBUG 21236 --- [nio-8088-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity com.penguin.formula.tdd.web.controller.InsightsController.commitsv4(java.lang.String,java.lang.String) throws java.lang.Exception]\n2020-01-07 16:48:24.451 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/tdd/insights/github/v4/commits/ccjmk/super-happiness] is: -1\n2020-01-07 16:51:35.166 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.client.RestTemplate : Created POST request for \"https://api.github.com/graphql\"\n2020-01-07 16:51:35.169 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.client.RestTemplate : Setting request Accept header to [text/plain, application/json, application/*+json, */*]\n2020-01-07 16:51:35.182 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.client.RestTemplate : Writing [query{repository(owner:\"ccjmk\", name:\"super-happiness\"){object(expression:\"master\"){... on Commit{history{totalCount}}}}}] as \"application/json\" using [org.springframework.http.converter.StringHttpMessageConverter@7dcd6967]\n2020-01-07 16:51:35.404 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.client.protocol.RequestAddCookies : CookieSpec selected: default\n2020-01-07 16:51:35.607 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.client.protocol.RequestAuthCache : Auth cache not set in the context\n2020-01-07 16:51:35.644 DEBUG 21236 --- [nio-8088-exec-1] h.i.c.PoolingHttpClientConnectionManager : Connection request: [route: {s}->https://api.github.com:443][total kept alive: 0; route allocated: 0 of 5; total allocated: 0 of 10]\n2020-01-07 16:51:35.861 DEBUG 21236 --- [nio-8088-exec-1] h.i.c.PoolingHttpClientConnectionManager : Connection leased: [id: 0][route: {s}->https://api.github.com:443][total kept alive: 0; route allocated: 1 of 5; total allocated: 1 of 10]\n2020-01-07 16:51:35.889 DEBUG 21236 --- [nio-8088-exec-1] o.a.http.impl.execchain.MainClientExec : Opening connection {s}->https://api.github.com:443\n2020-01-07 16:51:35.928 DEBUG 21236 --- [nio-8088-exec-1] .i.c.DefaultHttpClientConnectionOperator : Connecting to api.github.com/140.82.118.5:443\n2020-01-07 16:51:35.930 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Connecting socket to api.github.com/140.82.118.5:443 with timeout 0\n2020-01-07 16:51:35.983 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Enabled protocols: [TLSv1, TLSv1.1, TLSv1.2]\n2020-01-07 16:51:35.988 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Enabled cipher suites:[TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]\n2020-01-07 16:51:35.993 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Starting handshake\n2020-01-07 16:51:36.648 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Secure session established\n2020-01-07 16:51:36.651 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : negotiated protocol: TLSv1.2\n2020-01-07 16:51:36.654 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : negotiated cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\n2020-01-07 16:51:36.658 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : peer principal: CN=*.github.com, O=\"GitHub, Inc.\", L=San Francisco, ST=California, C=US\n2020-01-07 16:51:36.661 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : peer alternative names: [*.github.com, github.com]\n2020-01-07 16:51:36.665 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : issuer principal: CN=DigiCert SHA2 High Assurance Server CA, OU=www.digicert.com, O=DigiCert Inc, C=US\n2020-01-07 16:51:36.700 DEBUG 21236 --- [nio-8088-exec-1] .i.c.DefaultHttpClientConnectionOperator : Connection established 192.168.1.98:48784140.82.118.5:443\n2020-01-07 16:51:36.702 DEBUG 21236 --- [nio-8088-exec-1] o.a.http.impl.execchain.MainClientExec : Executing request POST /graphql HTTP/1.1\n2020-01-07 16:51:36.705 DEBUG 21236 --- [nio-8088-exec-1] o.a.http.impl.execchain.MainClientExec : Proxy auth state: UNCHALLENGED\n2020-01-07 16:51:36.743 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> POST /graphql HTTP/1.1\n2020-01-07 16:51:36.745 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Accept: text/plain, application/json, application/*+json, */*\n2020-01-07 16:51:36.747 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Authorization: Bearer {{MY PERSONAL TOKEN}}\n2020-01-07 16:51:36.748 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Content-Type: application/json\n2020-01-07 16:51:36.752 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Accept-Charset: big5, big5-hkscs, cesu-8, euc-jp, euc-kr, gb18030, gb2312, gbk, ibm-thai, ibm00858, ibm01140, ibm01141, ibm01142, ibm01143, ibm01144, ibm01145, ibm01146, ibm01147, ibm01148, ibm01149, ibm037, ibm1026, ibm1047, ibm273, ibm277, ibm278, ibm280, ibm284, ibm285, ibm290, ibm297, ibm420, ibm424, ibm437, ibm500, ibm775, ibm850, ibm852, ibm855, ibm857, ibm860, ibm861, ibm862, ibm863, ibm864, ibm865, ibm866, ibm868, ibm869, ibm870, ibm871, ibm918, iso-2022-cn, iso-2022-jp, iso-2022-jp-2, iso-2022-kr, iso-8859-1, iso-8859-13, iso-8859-15, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-9, jis_x0201, jis_x0212-1990, koi8-r, koi8-u, shift_jis, tis-620, us-ascii, utf-16, utf-16be, utf-16le, utf-32, utf-32be, utf-32le, utf-8, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, windows-31j, x-big5-hkscs-2001, x-big5-solaris, x-compound_text, x-euc-jp-linux, x-euc-tw, x-eucjp-open, x-ibm1006, x-ibm1025, x-ibm1046, x-ibm1097, x-ibm1098, x-ibm1112, x-ibm1122, x-ibm1123, x-ibm1124, x-ibm1166, x-ibm1364, x-ibm1381, x-ibm1383, x-ibm300, x-ibm33722, x-ibm737, x-ibm833, x-ibm834, x-ibm856, x-ibm874, x-ibm875, x-ibm921, x-ibm922, x-ibm930, x-ibm933, x-ibm935, x-ibm937, x-ibm939, x-ibm942, x-ibm942c, x-ibm943, x-ibm943c, x-ibm948, x-ibm949, x-ibm949c, x-ibm950, x-ibm964, x-ibm970, x-iscii91, x-iso-2022-cn-cns, x-iso-2022-cn-gb, x-iso-8859-11, x-jis0208, x-jisautodetect, x-johab, x-macarabic, x-maccentraleurope, x-maccroatian, x-maccyrillic, x-macdingbat, x-macgreek, x-machebrew, x-maciceland, x-macroman, x-macromania, x-macsymbol, x-macthai, x-macturkish, x-macukraine, x-ms932_0213, x-ms950-hkscs, x-ms950-hkscs-xp, x-mswin-936, x-pck, x-sjis_0213, x-utf-16le-bom, x-utf-32be-bom, x-utf-32le-bom, x-windows-50220, x-windows-50221, x-windows-874, x-windows-949, x-windows-950, x-windows-iso2022jp\n2020-01-07 16:51:36.755 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Content-Length: 121\n2020-01-07 16:51:36.757 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Host: api.github.com\n2020-01-07 16:51:36.759 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Connection: Keep-Alive\n2020-01-07 16:51:36.760 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_232)\n2020-01-07 16:51:36.762 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Accept-Encoding: gzip,deflate\n2020-01-07 16:51:36.770 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"POST /graphql HTTP/1.1[\\r][\\n]\"\n2020-01-07 16:51:36.773 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Accept: text/plain, application/json, application/*+json, */*[\\r][\\n]\"\n2020-01-07 16:51:36.774 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Authorization: Bearer {{MY PERSONAL TOKEN}}[\\r][\\n]\"\n2020-01-07 16:51:36.776 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Content-Type: application/json[\\r][\\n]\"\n2020-01-07 16:51:36.781 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Accept-Charset: big5, big5-hkscs, cesu-8, euc-jp, euc-kr, gb18030, gb2312, gbk, ibm-thai, ibm00858, ibm01140, ibm01141, ibm01142, ibm01143, ibm01144, ibm01145, ibm01146, ibm01147, ibm01148, ibm01149, ibm037, ibm1026, ibm1047, ibm273, ibm277, ibm278, ibm280, ibm284, ibm285, ibm290, ibm297, ibm420, ibm424, ibm437, ibm500, ibm775, ibm850, ibm852, ibm855, ibm857, ibm860, ibm861, ibm862, ibm863, ibm864, ibm865, ibm866, ibm868, ibm869, ibm870, ibm871, ibm918, iso-2022-cn, iso-2022-jp, iso-2022-jp-2, iso-2022-kr, iso-8859-1, iso-8859-13, iso-8859-15, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-9, jis_x0201, jis_x0212-1990, koi8-r, koi8-u, shift_jis, tis-620, us-ascii, utf-16, utf-16be, utf-16le, utf-32, utf-32be, utf-32le, utf-8, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, windows-31j, x-big5-hkscs-2001, x-big5-solaris, x-compound_text, x-euc-jp-linux, x-euc-tw, x-eucjp-open, x-ibm1006, x-ibm1025, x-ibm1046, x-ibm1097, x-ibm1098, x-ibm1112, x-ibm1122, x-ibm1123, x-ibm1124, x-ibm1166, x-ibm1364, x-ibm1381, x-ibm1383, x-ibm300, x-ibm33722, x-ibm737, x-ibm833, x-ibm834, x-ibm856, x-ibm874, x-ibm875, x-ibm921, x-ibm922, x-ibm930, x-ibm933, x-ibm935, x-ibm937, x-ibm939, x-ibm942, x-ibm942c, x-ibm943, x-ibm943c, x-ibm948, x-ibm949, x-ibm949c, x-ibm950, x-ibm964, x-ibm970, x-iscii91, x-iso-2022-cn-cns, x-iso-2022-cn-gb, x-iso-8859-11, x-jis0208, x-jisautodetect, x-johab, x-macarabic, x-maccentraleurope, x-maccroatian, x-maccyrillic, x-macdingbat, x-macgreek, x-machebrew, x-maciceland, x-macroman, x-macromania, x-macsymbol, x-macthai, x-macturkish, x-macukraine, x-ms932_0213, x-ms950-hkscs, x-ms950-hkscs-xp, x-mswin-936, x-pck, x-sjis_0213, x-utf-16le-bom, x-utf-32be-bom, x-utf-32le-bom, x-windows-50220, x-windows-50221, x-windows-874, x-windows-949, x-windows-950, x-windows-iso2022jp[\\r][\\n]\"\n2020-01-07 16:51:36.783 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Content-Length: 121[\\r][\\n]\"\n2020-01-07 16:51:36.785 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Host: api.github.com[\\r][\\n]\"\n2020-01-07 16:51:36.787 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Connection: Keep-Alive[\\r][\\n]\"\n2020-01-07 16:51:36.789 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_232)[\\r][\\n]\"\n2020-01-07 16:51:36.791 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Accept-Encoding: gzip,deflate[\\r][\\n]\"\n2020-01-07 16:51:36.793 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"[\\r][\\n]\"\n2020-01-07 16:51:36.795 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"query{repository(owner:\"ccjmk\", name:\"super-happiness\"){object(expression:\"master\"){... on Commit{history{totalCount}}}}}\"\n2020-01-07 16:51:37.070 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 https://api.github.com:443] can be kept alive indefinitely\n2020-01-07 16:51:37.377 DEBUG 21236 --- [nio-8088-exec-1] h.i.c.DefaultManagedHttpClientConnection : http-outgoing-0: set socket timeout to 0\n2020-01-07 16:51:37.380 DEBUG 21236 --- [nio-8088-exec-1] h.i.c.PoolingHttpClientConnectionManager : Connection released: [id: 0][route: {s}->https://api.github.com:443][total kept alive: 1; route allocated: 1 of 5; total allocated: 1 of 10]\n```\n\n========================================\n\nCode:\n```text\nPOST /graphql HTTP/1.1\nHost: api.github.com\nContent-Type: application/json\nAuthorization: Bearer [MY PERSONAL GITHUB TOKEN]\nUser-Agent: PostmanRuntime/7.20.1\nAccept: */*\nCache-Control: no-cache\nPostman-Token: 55f54f00-83f6-4acb-a6f8-4a3bde9147e7,abb6f600-8b79-4697-bd31-e04836386a24\nHost: api.github.com\nAccept-Encoding: gzip, deflate\nContent-Length: 264\nConnection: keep-alive\ncache-control: no-cache\n\nquery{repository(owner:\"ccjmk\", name:\"super-happiness\"){object(expression:\"master\"){... on Commit{history{totalCount}}}}}\n```\n\n```text\n{\"data\":{\"repository\":{\"object\":{\"history\":{\"totalCount\":19}}}}}\n```\n\n```text\n@Override\n public String fetchCommitsv3(String ownerUsername, String repository) {\n\n final String uri = String.format(\"https://api.github.com/repos/%s/%s/commits\", ownerUsername, repository);\n\n RestTemplate restTemplate = new RestTemplate();\n String result = restTemplate.getForObject(uri, String.class);\n return result;\n }\n\n @Override\n public ResponseEntity<String> fetchCommitsv4(String ownerUsername, String repository) {\n\n final String uri = String.format(\"https://api.github.com/graphql\");\n String query = \"query{repository(owner:\\\"\"+ownerUsername+\"\\\", name:\\\"\"+repository+\"\\\"){object(expression:\\\"master\\\"){... on Commit{history{totalCount}}}}}\";\n\n String gitHubToken = [MY GITHUB TOKEN];\n\n RestTemplate restTemplate = new RestTemplate();\n restTemplate.setRequestFactory(new HttpComponentsAsyncClientHttpRequestFactory());\n HttpHeaders headers = new HttpHeaders();\n //headers.add(\"Authorization\", \"Bearer \"+gitHubToken);\n headers.set(\"Authorization\",\"Bearer \"+gitHubToken);\n headers.setContentType(MediaType.APPLICATION_JSON);\n HttpEntity<String> entity = new HttpEntity<>(query, headers);\n\n ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class);\n return result;\n }\n```\n\n```text\n2020-01-07 16:48:24.419 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/tdd/insights/github/v4/commits/ccjmk/super-happiness]\n2020-01-07 16:48:24.432 DEBUG 21236 --- [nio-8088-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /tdd/insights/github/v4/commits/ccjmk/super-happiness\n2020-01-07 16:48:24.450 DEBUG 21236 --- [nio-8088-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity com.penguin.formula.tdd.web.controller.InsightsController.commitsv4(java.lang.String,java.lang.String) throws java.lang.Exception]\n2020-01-07 16:48:24.451 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/tdd/insights/github/v4/commits/ccjmk/super-happiness] is: -1\n2020-01-07 16:51:35.166 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.client.RestTemplate : Created POST request for \"https://api.github.com/graphql\"\n2020-01-07 16:51:35.169 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.client.RestTemplate : Setting request Accept header to [text/plain, application/json, application/*+json, */*]\n2020-01-07 16:51:35.182 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.client.RestTemplate : Writing [query{repository(owner:\"ccjmk\", name:\"super-happiness\"){object(expression:\"master\"){... on Commit{history{totalCount}}}}}] as \"application/json\" using [org.springframework.http.converter.StringHttpMessageConverter@7dcd6967]\n2020-01-07 16:51:35.404 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.client.protocol.RequestAddCookies : CookieSpec selected: default\n2020-01-07 16:51:35.607 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.client.protocol.RequestAuthCache : Auth cache not set in the context\n2020-01-07 16:51:35.644 DEBUG 21236 --- [nio-8088-exec-1] h.i.c.PoolingHttpClientConnectionManager : Connection request: [route: {s}->https://api.github.com:443][total kept alive: 0; route allocated: 0 of 5; total allocated: 0 of 10]\n2020-01-07 16:51:35.861 DEBUG 21236 --- [nio-8088-exec-1] h.i.c.PoolingHttpClientConnectionManager : Connection leased: [id: 0][route: {s}->https://api.github.com:443][total kept alive: 0; route allocated: 1 of 5; total allocated: 1 of 10]\n2020-01-07 16:51:35.889 DEBUG 21236 --- [nio-8088-exec-1] o.a.http.impl.execchain.MainClientExec : Opening connection {s}->https://api.github.com:443\n2020-01-07 16:51:35.928 DEBUG 21236 --- [nio-8088-exec-1] .i.c.DefaultHttpClientConnectionOperator : Connecting to api.github.com/140.82.118.5:443\n2020-01-07 16:51:35.930 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Connecting socket to api.github.com/140.82.118.5:443 with timeout 0\n2020-01-07 16:51:35.983 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Enabled protocols: [TLSv1, TLSv1.1, TLSv1.2]\n2020-01-07 16:51:35.988 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Enabled cipher suites:[TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]\n2020-01-07 16:51:35.993 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Starting handshake\n2020-01-07 16:51:36.648 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : Secure session established\n2020-01-07 16:51:36.651 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : negotiated protocol: TLSv1.2\n2020-01-07 16:51:36.654 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : negotiated cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\n2020-01-07 16:51:36.658 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : peer principal: CN=*.github.com, O=\"GitHub, Inc.\", L=San Francisco, ST=California, C=US\n2020-01-07 16:51:36.661 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : peer alternative names: [*.github.com, github.com]\n2020-01-07 16:51:36.665 DEBUG 21236 --- [nio-8088-exec-1] o.a.h.c.ssl.SSLConnectionSocketFactory : issuer principal: CN=DigiCert SHA2 High Assurance Server CA, OU=www.digicert.com, O=DigiCert Inc, C=US\n2020-01-07 16:51:36.700 DEBUG 21236 --- [nio-8088-exec-1] .i.c.DefaultHttpClientConnectionOperator : Connection established 192.168.1.98:48784<->140.82.118.5:443\n2020-01-07 16:51:36.702 DEBUG 21236 --- [nio-8088-exec-1] o.a.http.impl.execchain.MainClientExec : Executing request POST /graphql HTTP/1.1\n2020-01-07 16:51:36.705 DEBUG 21236 --- [nio-8088-exec-1] o.a.http.impl.execchain.MainClientExec : Proxy auth state: UNCHALLENGED\n2020-01-07 16:51:36.743 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> POST /graphql HTTP/1.1\n2020-01-07 16:51:36.745 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Accept: text/plain, application/json, application/*+json, */*\n2020-01-07 16:51:36.747 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Authorization: Bearer {{MY PERSONAL TOKEN}}\n2020-01-07 16:51:36.748 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Content-Type: application/json\n2020-01-07 16:51:36.752 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Accept-Charset: big5, big5-hkscs, cesu-8, euc-jp, euc-kr, gb18030, gb2312, gbk, ibm-thai, ibm00858, ibm01140, ibm01141, ibm01142, ibm01143, ibm01144, ibm01145, ibm01146, ibm01147, ibm01148, ibm01149, ibm037, ibm1026, ibm1047, ibm273, ibm277, ibm278, ibm280, ibm284, ibm285, ibm290, ibm297, ibm420, ibm424, ibm437, ibm500, ibm775, ibm850, ibm852, ibm855, ibm857, ibm860, ibm861, ibm862, ibm863, ibm864, ibm865, ibm866, ibm868, ibm869, ibm870, ibm871, ibm918, iso-2022-cn, iso-2022-jp, iso-2022-jp-2, iso-2022-kr, iso-8859-1, iso-8859-13, iso-8859-15, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-9, jis_x0201, jis_x0212-1990, koi8-r, koi8-u, shift_jis, tis-620, us-ascii, utf-16, utf-16be, utf-16le, utf-32, utf-32be, utf-32le, utf-8, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, windows-31j, x-big5-hkscs-2001, x-big5-solaris, x-compound_text, x-euc-jp-linux, x-euc-tw, x-eucjp-open, x-ibm1006, x-ibm1025, x-ibm1046, x-ibm1097, x-ibm1098, x-ibm1112, x-ibm1122, x-ibm1123, x-ibm1124, x-ibm1166, x-ibm1364, x-ibm1381, x-ibm1383, x-ibm300, x-ibm33722, x-ibm737, x-ibm833, x-ibm834, x-ibm856, x-ibm874, x-ibm875, x-ibm921, x-ibm922, x-ibm930, x-ibm933, x-ibm935, x-ibm937, x-ibm939, x-ibm942, x-ibm942c, x-ibm943, x-ibm943c, x-ibm948, x-ibm949, x-ibm949c, x-ibm950, x-ibm964, x-ibm970, x-iscii91, x-iso-2022-cn-cns, x-iso-2022-cn-gb, x-iso-8859-11, x-jis0208, x-jisautodetect, x-johab, x-macarabic, x-maccentraleurope, x-maccroatian, x-maccyrillic, x-macdingbat, x-macgreek, x-machebrew, x-maciceland, x-macroman, x-macromania, x-macsymbol, x-macthai, x-macturkish, x-macukraine, x-ms932_0213, x-ms950-hkscs, x-ms950-hkscs-xp, x-mswin-936, x-pck, x-sjis_0213, x-utf-16le-bom, x-utf-32be-bom, x-utf-32le-bom, x-windows-50220, x-windows-50221, x-windows-874, x-windows-949, x-windows-950, x-windows-iso2022jp\n2020-01-07 16:51:36.755 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Content-Length: 121\n2020-01-07 16:51:36.757 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Host: api.github.com\n2020-01-07 16:51:36.759 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Connection: Keep-Alive\n2020-01-07 16:51:36.760 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_232)\n2020-01-07 16:51:36.762 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 >> Accept-Encoding: gzip,deflate\n2020-01-07 16:51:36.770 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"POST /graphql HTTP/1.1[\\r][\\n]\"\n2020-01-07 16:51:36.773 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Accept: text/plain, application/json, application/*+json, */*[\\r][\\n]\"\n2020-01-07 16:51:36.774 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Authorization: Bearer {{MY PERSONAL TOKEN}}[\\r][\\n]\"\n2020-01-07 16:51:36.776 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Content-Type: application/json[\\r][\\n]\"\n2020-01-07 16:51:36.781 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Accept-Charset: big5, big5-hkscs, cesu-8, euc-jp, euc-kr, gb18030, gb2312, gbk, ibm-thai, ibm00858, ibm01140, ibm01141, ibm01142, ibm01143, ibm01144, ibm01145, ibm01146, ibm01147, ibm01148, ibm01149, ibm037, ibm1026, ibm1047, ibm273, ibm277, ibm278, ibm280, ibm284, ibm285, ibm290, ibm297, ibm420, ibm424, ibm437, ibm500, ibm775, ibm850, ibm852, ibm855, ibm857, ibm860, ibm861, ibm862, ibm863, ibm864, ibm865, ibm866, ibm868, ibm869, ibm870, ibm871, ibm918, iso-2022-cn, iso-2022-jp, iso-2022-jp-2, iso-2022-kr, iso-8859-1, iso-8859-13, iso-8859-15, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-9, jis_x0201, jis_x0212-1990, koi8-r, koi8-u, shift_jis, tis-620, us-ascii, utf-16, utf-16be, utf-16le, utf-32, utf-32be, utf-32le, utf-8, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, windows-31j, x-big5-hkscs-2001, x-big5-solaris, x-compound_text, x-euc-jp-linux, x-euc-tw, x-eucjp-open, x-ibm1006, x-ibm1025, x-ibm1046, x-ibm1097, x-ibm1098, x-ibm1112, x-ibm1122, x-ibm1123, x-ibm1124, x-ibm1166, x-ibm1364, x-ibm1381, x-ibm1383, x-ibm300, x-ibm33722, x-ibm737, x-ibm833, x-ibm834, x-ibm856, x-ibm874, x-ibm875, x-ibm921, x-ibm922, x-ibm930, x-ibm933, x-ibm935, x-ibm937, x-ibm939, x-ibm942, x-ibm942c, x-ibm943, x-ibm943c, x-ibm948, x-ibm949, x-ibm949c, x-ibm950, x-ibm964, x-ibm970, x-iscii91, x-iso-2022-cn-cns, x-iso-2022-cn-gb, x-iso-8859-11, x-jis0208, x-jisautodetect, x-johab, x-macarabic, x-maccentraleurope, x-maccroatian, x-maccyrillic, x-macdingbat, x-macgreek, x-machebrew, x-maciceland, x-macroman, x-macromania, x-macsymbol, x-macthai, x-macturkish, x-macukraine, x-ms932_0213, x-ms950-hkscs, x-ms950-hkscs-xp, x-mswin-936, x-pck, x-sjis_0213, x-utf-16le-bom, x-utf-32be-bom, x-utf-32le-bom, x-windows-50220, x-windows-50221, x-windows-874, x-windows-949, x-windows-950, x-windows-iso2022jp[\\r][\\n]\"\n2020-01-07 16:51:36.783 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Content-Length: 121[\\r][\\n]\"\n2020-01-07 16:51:36.785 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Host: api.github.com[\\r][\\n]\"\n2020-01-07 16:51:36.787 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Connection: Keep-Alive[\\r][\\n]\"\n2020-01-07 16:51:36.789 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_232)[\\r][\\n]\"\n2020-01-07 16:51:36.791 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"Accept-Encoding: gzip,deflate[\\r][\\n]\"\n2020-01-07 16:51:36.793 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"[\\r][\\n]\"\n2020-01-07 16:51:36.795 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 >> \"query{repository(owner:\"ccjmk\", name:\"super-happiness\"){object(expression:\"master\"){... on Commit{history{totalCount}}}}}\"\n2020-01-07 16:51:37.070 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"HTTP/1.1 400 Bad Request[\\r][\\n]\"\n2020-01-07 16:51:37.077 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Date: Tue, 07 Jan 2020 16:51:36 GMT[\\r][\\n]\"\n2020-01-07 16:51:37.083 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Content-Type: application/json; charset=utf-8[\\r][\\n]\"\n2020-01-07 16:51:37.087 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Content-Length: 89[\\r][\\n]\"\n2020-01-07 16:51:37.091 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Server: GitHub.com[\\r][\\n]\"\n2020-01-07 16:51:37.094 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Status: 400 Bad Request[\\r][\\n]\"\n2020-01-07 16:51:37.097 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Cache-Control: no-cache[\\r][\\n]\"\n2020-01-07 16:51:37.099 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-OAuth-Scopes: read:enterprise, read:org, read:packages, read:repo_hook, read:user, repo[\\r][\\n]\"\n2020-01-07 16:51:37.101 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-Accepted-OAuth-Scopes: repo[\\r][\\n]\"\n2020-01-07 16:51:37.103 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-GitHub-Media-Type: unknown, github.v4[\\r][\\n]\"\n2020-01-07 16:51:37.105 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-RateLimit-Limit: 5000[\\r][\\n]\"\n2020-01-07 16:51:37.107 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-RateLimit-Remaining: 5000[\\r][\\n]\"\n2020-01-07 16:51:37.109 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-RateLimit-Reset: 1578419496[\\r][\\n]\"\n2020-01-07 16:51:37.112 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Access-Control-Expose-Headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type[\\r][\\n]\"\n2020-01-07 16:51:37.114 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Access-Control-Allow-Origin: *[\\r][\\n]\"\n2020-01-07 16:51:37.116 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Strict-Transport-Security: max-age=31536000; includeSubdomains; preload[\\r][\\n]\"\n2020-01-07 16:51:37.118 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-Frame-Options: deny[\\r][\\n]\"\n2020-01-07 16:51:37.119 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-Content-Type-Options: nosniff[\\r][\\n]\"\n2020-01-07 16:51:37.121 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-XSS-Protection: 1; mode=block[\\r][\\n]\"\n2020-01-07 16:51:37.123 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Referrer-Policy: origin-when-cross-origin, strict-origin-when-cross-origin[\\r][\\n]\"\n2020-01-07 16:51:37.125 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"Content-Security-Policy: default-src 'none'[\\r][\\n]\"\n2020-01-07 16:51:37.127 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"X-GitHub-Request-Id: BE90:B6DD:27E5493C:2F86CC08:5E14B718[\\r][\\n]\"\n2020-01-07 16:51:37.129 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"[\\r][\\n]\"\n2020-01-07 16:51:37.131 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.wire : http-outgoing-0 << \"{\"message\":\"Problems parsing JSON\",\"documentation_url\":\"https://developer.github.com/v4\"}\"\n2020-01-07 16:51:37.175 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << HTTP/1.1 400 Bad Request\n2020-01-07 16:51:37.177 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Date: Tue, 07 Jan 2020 16:51:36 GMT\n2020-01-07 16:51:37.178 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Content-Type: application/json; charset=utf-8\n2020-01-07 16:51:37.180 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Content-Length: 89\n2020-01-07 16:51:37.182 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Server: GitHub.com\n2020-01-07 16:51:37.184 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Status: 400 Bad Request\n2020-01-07 16:51:37.185 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Cache-Control: no-cache\n2020-01-07 16:51:37.187 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-OAuth-Scopes: read:enterprise, read:org, read:packages, read:repo_hook, read:user, repo\n2020-01-07 16:51:37.189 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-Accepted-OAuth-Scopes: repo\n2020-01-07 16:51:37.191 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-GitHub-Media-Type: unknown, github.v4\n2020-01-07 16:51:37.192 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-RateLimit-Limit: 5000\n2020-01-07 16:51:37.194 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-RateLimit-Remaining: 5000\n2020-01-07 16:51:37.195 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-RateLimit-Reset: 1578419496\n2020-01-07 16:51:37.197 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Access-Control-Expose-Headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type\n2020-01-07 16:51:37.199 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Access-Control-Allow-Origin: *\n2020-01-07 16:51:37.200 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Strict-Transport-Security: max-age=31536000; includeSubdomains; preload\n2020-01-07 16:51:37.202 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-Frame-Options: deny\n2020-01-07 16:51:37.204 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-Content-Type-Options: nosniff\n2020-01-07 16:51:37.206 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-XSS-Protection: 1; mode=block\n2020-01-07 16:51:37.207 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Referrer-Policy: origin-when-cross-origin, strict-origin-when-cross-origin\n2020-01-07 16:51:37.209 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << Content-Security-Policy: default-src 'none'\n2020-01-07 16:51:37.210 DEBUG 21236 --- [nio-8088-exec-1] org.apache.http.headers : http-outgoing-0 << X-GitHub-Request-Id: BE90:B6DD:27E5493C:2F86CC08:5E14B718\n2020-01-07 16:51:37.288 DEBUG 21236 --- [nio-8088-exec-1] o.a.http.impl.execchain.MainClientExec : Connection can be kept alive indefinitely\n2020-01-07 16:51:37.336 DEBUG 21236 --- [nio-8088-exec-1] o.s.web.client.RestTemplate : POST request for \"https://api.github.com/graphql\" resulted in 400 (Bad Request); invoking error handler\n2020-01-07 16:51:37.375 DEBUG 21236 --- [nio-8088-exec-1] h.i.c.PoolingHttpClientConnectionManager : Connection [id: 0][route: {s}->https://api.github.com:443] can be kept alive indefinitely\n2020-01-07 16:51:37.377 DEBUG 21236 --- [nio-8088-exec-1] h.i.c.DefaultManagedHttpClientConnection : http-outgoing-0: set socket timeout to 0\n2020-01-07 16:51:37.380 DEBUG 21236 --- [nio-8088-exec-1] h.i.c.PoolingHttpClientConnectionManager : Connection released: [id: 0][route: {s}->https://api.github.com:443][total kept alive: 1; route allocated: 1 of 5; total allocated: 1 of 10]\n```\n\n```text\nquery{repository(owner:\"ccjmk\", name:\"super-happiness\"){object(expression:\"master\"){... on Commit{history{totalCount}}}}}\n```\n\n```text\n{\n \"message\": \"Problems parsing JSON\",\n \"documentation_url\": \"https://developer.github.com/v4\"\n}\n```\n\n```text\n{\"query\":\"query{repository(owner:\\\"ccjmk\\\", name:\\\"super-happiness\\\"){object(expression:\\\"master\\\"){... on Commit{history{totalCount}}}}}\"}\n```\n\n```text\n{\n \"data\": {\n \"repository\": {\n \"object\": {\n \"history\": {\n \"totalCount\": 19\n }\n }\n }\n }\n}\n```\n\n========================================\n\nComments:\n- The body seems to be exactly the same indeed, but what strikes me as odd is the `Content-Length`. It is 264 in your Postman example and 121 in your code.\n- `query{repository(owner:\"ccjmk\", name:\"super-happiness\"){object(expression:\"master\"){... on Commit{history{totalCount}}}}}` is indeed 121 characters.\n- Good catch! I noticed that the content-type on postman doesn't match either. I originally had a \"longer\" body, with spaces and tabs, and thought it was that, but after sending again the same exact body I pasted here (and on the java app), I noticed that it still gets extra length. I have been using the GraphQL body setting on Postman, which I thought was merely syntax-highlighting, but after sending that body Raw, it fails, so there's something added there.\n- See stackoverflow.com/a/42523727/40064 for more details on how to use Postman with GraphQL and a 'Raw' body\n- Got it, thanks for the hint on the content-type! It's actually being sent as a json so you gotta jsonify it first. I'll make a proper answer.\n- content-length*","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":324,"estimatedTokens":10623}}933{"id":"stack-72287494","source":"stackoverflow","questionId":72287494,"title":"Using enums from prisma in nestJS graphQL models","tags":["enums","graphql","nestjs","prisma"],"text":"Title: Using enums from prisma in nestJS graphQL models\nTags: enums, graphql, nestjs, prisma\nSource: Stack Overflow\n\nQuestion:\nMy object that is supposed to be returned:\n\n```\n@ObjectType()\nexport class User {\n @Field(() => String)\n email: string\n\n @Field(() => [Level])\n level: Level[]\n}\n```\n\nLevel is an enum generated by prisma, defined in schema.prisma:\n\n```\nenum Level {\n EASY\n MEDIUM\n HARD\n}\n```\n\nNow I'm trying to return this User object in my GraphQL Mutation:\n\n```\n@Mutation(() => User, { name: 'some-endpoint' })\n```\n\nWhen running this code, I'm getting the following error:\n\n```\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the \"Level\". Make sure your class is decorated with an appropriate decorator.\n```\n\nWhat am I doing wrong here? Can't enums from prisma be used as a field?\n\n========================================\n\nTop Answer:\nYou're probably missing the registration of the enum type in GraphQL:\n\n```\n// user.model.ts\nregisterEnumType(Level, { name: \"Level\" });\n```\n\n========================================\n\nCode:\n```js\n@ObjectType()\nexport class User {\n @Field(() => String)\n email: string\n\n @Field(() => [Level])\n level: Level[]\n}\n```\n\n```text\nenum Level {\n EASY\n MEDIUM\n HARD\n}\n```\n\n```js\n@Mutation(() => User, { name: 'some-endpoint' })\n```\n\n```text\nUnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the \"Level\". Make sure your class is decorated with an appropriate decorator.\n```\n\n```text\nimport { Level } from '@prisma/client'\n\n@ObjectType()\nexport class User {\n @Field(() => String)\n email: string\n\n @Field(() => Level)\n level: Level\n}\n\nregisterEnumType(Level, {\n name: 'Level',\n});\n```\n\n```text\nregisterEnumType\n```\n\n```text\n@Field(() => Enum)\n```\n\n```text\n// user.model.ts\nregisterEnumType(Level, { name: \"Level\" });\n```\n\n```text\nenum Role {\n USER = 'USER',\n ADMIN = 'ADMIN',\n}\n\nregisterEnumType(Role, {\n name: 'Role',\n});\n\nexport class CreateUserInput {\n@IsEnum(Role)\n@Field(() => Role, { nullable: true })\nrole?: Role;\n}\n```\n\n```text\nasync create(createUserInput: CreateUserInput): Promise<User> {\n return this.prisma.user.create({\n data: {\n ...createUserInput,\n },\n });\n }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":138,"estimatedTokens":555}}934{"id":"stack-67798146","source":"stackoverflow","questionId":67798146,"title":"Provide explicit type for the mutation GraphQL","tags":["graphql","nestjs"],"text":"Title: Provide explicit type for the mutation GraphQL\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a mutation which will accept list of products. But doing so GraphQL is throwing error for **createMultipleProducts** method. Not sure what is the mistake here.\n\n```\nimport { Inject } from \"@nestjs/common\";\nimport { Args, Mutation, Query, Resolver } from \"@nestjs/graphql\";\nimport { ClientProxy } from \"@nestjs/microservices\";\nimport { ProductRequest } from \"src/types/ms-product/product.request.type\";\nimport { ProductResponse } from \"src/types/ms-product/product.response.type\";\n@Resolver(of => ProductResponse)\nexport class ProductResolver {\n\n constructor(\n @Inject('SERVICE__PRODUCT') private readonly clientServiceProduct: ClientProxy\n ) {}\n\n @Mutation(returns => ProductResponse)\n async createProduct(@Args('data') product: ProductRequest): Promise {\n const PATTERN = {cmd: 'ms-product-create'};\n const PAYLOAD = product;\n return this.clientServiceProduct.send(PATTERN, PAYLOAD)\n .toPromise()\n .then((response: ProductResponse) => {\n return response;\n })\n .catch((error) => {\n return error;\n })\n }\n\n @Mutation(returns => [ProductResponse])\n async createMultipleProducts(@Args('data') products: [ProductRequest]): Promise> {\n try {\n const PROMISES = products.map(async (product: ProductRequest) => {\n const PATTERN = {cmd: 'ms-product-create'};\n const PAYLOAD = product;\n return await this.clientServiceProduct.send(PATTERN, PAYLOAD).toPromise();\n });\n \n return await Promise.all(PROMISES);\n } catch (error) {\n throw new Error(error);\n }\n }\n\n @Query(returns => ProductResponse)\n async readProduct(@Args('data') id: string) {\n return {}\n }\n}\n```\n\nI'm getting this error:\n\n```\nUnhandledPromiseRejectionWarning: Error: Undefined type error. Make sure you are providing an explicit type for the \"createMultipleProducts\" (parameter at index [0]) of the \"ProductResolver\" class.\n```\n\n========================================\n\nTop Answer:\nNew format 2022\n\n```\n@Query(returns => ProductResponse)\n async readProduct(@Args('data', () => String ) id: string) {\n return {}\n }\n```\n\n========================================\n\nCode:\n```text\nimport { Inject } from \"@nestjs/common\";\nimport { Args, Mutation, Query, Resolver } from \"@nestjs/graphql\";\nimport { ClientProxy } from \"@nestjs/microservices\";\nimport { ProductRequest } from \"src/types/ms-product/product.request.type\";\nimport { ProductResponse } from \"src/types/ms-product/product.response.type\";\n@Resolver(of => ProductResponse)\nexport class ProductResolver {\n\n constructor(\n @Inject('SERVICE__PRODUCT') private readonly clientServiceProduct: ClientProxy\n ) {}\n\n @Mutation(returns => ProductResponse)\n async createProduct(@Args('data') product: ProductRequest): Promise<ProductResponse> {\n const PATTERN = {cmd: 'ms-product-create'};\n const PAYLOAD = product;\n return this.clientServiceProduct.send(PATTERN, PAYLOAD)\n .toPromise()\n .then((response: ProductResponse) => {\n return response;\n })\n .catch((error) => {\n return error;\n })\n }\n\n @Mutation(returns => [ProductResponse])\n async createMultipleProducts(@Args('data') products: [ProductRequest]): Promise<Array<ProductResponse>> {\n try {\n const PROMISES = products.map(async (product: ProductRequest) => {\n const PATTERN = {cmd: 'ms-product-create'};\n const PAYLOAD = product;\n return await this.clientServiceProduct.send(PATTERN, PAYLOAD).toPromise();\n });\n \n return await Promise.all(PROMISES);\n } catch (error) {\n throw new Error(error);\n }\n }\n\n @Query(returns => ProductResponse)\n async readProduct(@Args('data') id: string) {\n return {}\n }\n}\n```\n\n```text\nUnhandledPromiseRejectionWarning: Error: Undefined type error. Make sure you are providing an explicit type for the \"createMultipleProducts\" (parameter at index [0]) of the \"ProductResolver\" class.\n```\n\n```js\n@Mutation(returns => [ProductResponse])\nasync createMultipleProducts(@Args({ name: 'data', type: () => [ProductRequest] }) products: ProductRequest[]): Promise<Array<ProductResponse>> {\n ...\n}\n```\n\n```text\n@Query(returns => ProductResponse)\n async readProduct(@Args('data', () => String ) id: string) {\n return {}\n }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":143,"estimatedTokens":1058}}935{"id":"stack-66160935","source":"stackoverflow","questionId":66160935,"title":"HotChocolate with Authorize attribute, how to get currently logged on user?","tags":[".net-core","graphql","hotchocolate"],"text":"Title: HotChocolate with Authorize attribute, how to get currently logged on user?\nTags: .net-core, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI've got a GraphQL mutation using HotChocolate with the `[Authorize]` attribute from `HotChocolate.AspNetCore.Authorization` to enforce authorization on my GraphQL endpoints.\n\nThis works fine, I can only call the mutation once I'm logged in as an Admin ...\n\n... but now I'd like to retrieve the user which is authorized, but I don't seem to find a way to do it.\n\n```\n[ExtendObjectType(Name = \"Mutation\")]\n[Authorize(Roles = new[] { \"Administrators\" })]\npublic class MyMutations\n{\n public bool SomeMethod()\n {\n // In a regular Web API controller, you can do User.Identity.Name to fetch the user name of the current user. What is the equivalent in Hot Chocolate?\n var userName = \"\";\n\n return false;\n }\n}\n```\n\nAny ideas?\n\n========================================\n\nCode:\n```text\n[ExtendObjectType(Name = \"Mutation\")]\n[Authorize(Roles = new[] { \"Administrators\" })]\npublic class MyMutations\n{\n public bool SomeMethod()\n {\n // In a regular Web API controller, you can do User.Identity.Name to fetch the user name of the current user. What is the equivalent in Hot Chocolate?\n var userName = \"\";\n\n\n return false;\n }\n}\n```\n\n```text\n[Authorize]\n```\n\n```text\nHotChocolate.AspNetCore.Authorization\n```\n\n```cs\n[ExtendObjectType(Name = \"Mutation\")]\n[Authorize(Roles = new[] { \"Administrators\" })]\npublic class MyMutations\n{\n public bool SomeMethod([Service] IHttpContextAccessor contextAccessor)\n {\n var user = contextAccessor.HttpContext.User; // <-> There is your user\n\n // In a regular Web API controller, you can do User.Identity.Name to fetch the user name of the current user. What is the equivalent in Hot Chocolate?\n var userName = \"\";\n\n\n return false;\n }\n}\n```\n\n========================================\n\nComments:\n- Well I'll be damned. I thought that *could* be the case, but I actually just did not try it. Silly me :) Thanks!","metadata":{"transformedAt":"2026-08-18T18:32:36.093Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":77,"estimatedTokens":513}}936{"id":"stack-70755517","source":"stackoverflow","questionId":70755517,"title":"Why helmet blocks apollo api","tags":["node.js","graphql","apollo-server"],"text":"Title: Why helmet blocks apollo api\nTags: node.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nCould u please tell me why helmet blocks apollo api at localhost:4000/api? When i comment helmet it works fine as before.\n\nIt appears that you might be offline. POST to this endpoint to query your graph:\n\ncurl --request POST \n\n--header 'content-type: application/json' \n\n--url '' \n\n--data '{\"query\":\"query { __typename }\"}'\n\n```\nconst { ApolloServer } = require ('apollo-server-express');\nconst { ApolloServerPluginDrainHttpServer } = require ('apollo-server-core');\nconst express= require ('express');\nconst http = require ('http');\nconst models = require('./models')\nrequire ('dotenv').config();\nconst db = require('./db')\nconst DB_HOST = process.env.DB_HOST\nconst typeDefs = require('./schema')\nconst resolvers = require('./resolvers/index')\nconst jwt = require('jsonwebtoken');\nconst cors = require('cors')\nconst helmet = require('helmet')\n\ndb.connect(DB_HOST);\n\n// get the user info from a JWT\nconst getUser = token => {\n if (token) {\n try {\n // return the user information from the token\n //console.log(jwt.verify(token, process.env.JWT_SECRET))\n return jwt.verify(token, process.env.JWT_SECRET);\n } catch (err) {\n // if there's a problem with the token, throw an error\n throw new Error('Session invalid');\n }\n }\n};\n\nasync function startApolloServer(typeDefs, resolvers) {\n \n const app = express();\n app.use(cors())\n //app.use(helmet())\n const httpServer = http.createServer(app);\n\n const server = new ApolloServer({\n typeDefs,\n resolvers,\n context: ({ req }) => {\n // get the user token from the headers\n const token = req.headers.authorization;\n // try to retrieve a user with the token\n const user = getUser(token);\n // for now, let's log the user to the console:\n //console.log(user);\n // add the db models and the user to the context\n return { models, user };\n },\n plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],\n });\n\n await server.start();\n server.applyMiddleware({ app,path: '/api' });\n await new Promise(resolve => httpServer.listen({ port: 4000 }, resolve));\n console.log(`π Apollo Server ready at http://localhost:4000${server.graphqlPath}`);\n \n app.get('/', function (req, res) {\n res.send('Welcome in note app.')\n })\n}\n\nstartApolloServer(typeDefs, resolvers)\n```\n\n========================================\n\nTop Answer:\n`app.use(helmet());`\n\nis an alias for the following:\n\n```\napp.use(helmet.contentSecurityPolicy());\napp.use(helmet.crossOriginEmbedderPolicy());\napp.use(helmet.crossOriginOpenerPolicy());\napp.use(helmet.crossOriginResourcePolicy());\napp.use(helmet.dnsPrefetchControl());\napp.use(helmet.expectCt());\napp.use(helmet.frameguard());\napp.use(helmet.hidePoweredBy());\napp.use(helmet.hsts());\napp.use(helmet.ieNoOpen());\napp.use(helmet.noSniff());\napp.use(helmet.originAgentCluster());\napp.use(helmet.permittedCrossDomainPolicies());\napp.use(helmet.referrerPolicy());\napp.use(helmet.xssFilter());\n```\n\nI had the same problem, so I swapped out the alias for adding each one individually. When I commented out the first two (`contentSecurityPolicy` & `crossOriginEmbedderPolicy`), Apollo came back to life.\n\nFor the record, commenting out these policies is not recommended for production, but it should unblock anyone who gets stuck here.\n\n========================================\n\nCode:\n```text\nconst { ApolloServer } = require ('apollo-server-express');\nconst { ApolloServerPluginDrainHttpServer } = require ('apollo-server-core');\nconst express= require ('express');\nconst http = require ('http');\nconst models = require('./models')\nrequire ('dotenv').config();\nconst db = require('./db')\nconst DB_HOST = process.env.DB_HOST\nconst typeDefs = require('./schema')\nconst resolvers = require('./resolvers/index')\nconst jwt = require('jsonwebtoken');\nconst cors = require('cors')\nconst helmet = require('helmet')\n\ndb.connect(DB_HOST);\n\n\n// get the user info from a JWT\nconst getUser = token => {\n if (token) {\n try {\n // return the user information from the token\n //console.log(jwt.verify(token, process.env.JWT_SECRET))\n return jwt.verify(token, process.env.JWT_SECRET);\n } catch (err) {\n // if there's a problem with the token, throw an error\n throw new Error('Session invalid');\n }\n }\n};\n\n\nasync function startApolloServer(typeDefs, resolvers) {\n \n const app = express();\n app.use(cors())\n //app.use(helmet())\n const httpServer = http.createServer(app);\n\n const server = new ApolloServer({\n typeDefs,\n resolvers,\n context: ({ req }) => {\n // get the user token from the headers\n const token = req.headers.authorization;\n // try to retrieve a user with the token\n const user = getUser(token);\n // for now, let's log the user to the console:\n //console.log(user);\n // add the db models and the user to the context\n return { models, user };\n },\n plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],\n });\n\n await server.start();\n server.applyMiddleware({ app,path: '/api' });\n await new Promise(resolve => httpServer.listen({ port: 4000 }, resolve));\n console.log(`π Apollo Server ready at http://localhost:4000${server.graphqlPath}`);\n \n app.get('/', function (req, res) {\n res.send('Welcome in note app.')\n })\n}\n\nstartApolloServer(typeDefs, resolvers)\n```\n\n```text\nconst isDevelopment = appConfig.env === 'development'\n\n app.use(\n helmet({\n crossOriginEmbedderPolicy: !isDevelopment,\n contentSecurityPolicy: !isDevelopment,\n }),\n )\n```\n\n```text\napp.use(helmet.contentSecurityPolicy());\napp.use(helmet.crossOriginEmbedderPolicy());\napp.use(helmet.crossOriginOpenerPolicy());\napp.use(helmet.crossOriginResourcePolicy());\napp.use(helmet.dnsPrefetchControl());\napp.use(helmet.expectCt());\napp.use(helmet.frameguard());\napp.use(helmet.hidePoweredBy());\napp.use(helmet.hsts());\napp.use(helmet.ieNoOpen());\napp.use(helmet.noSniff());\napp.use(helmet.originAgentCluster());\napp.use(helmet.permittedCrossDomainPolicies());\napp.use(helmet.referrerPolicy());\napp.use(helmet.xssFilter());\n```\n\n```text\napp.use(helmet());\n```\n\n```text\ncontentSecurityPolicy\n```\n\n```text\ncrossOriginEmbedderPolicy\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":225,"estimatedTokens":1543}}937{"id":"stack-72801198","source":"stackoverflow","questionId":72801198,"title":"apollo-client refetch queries","tags":["reactjs","graphql","apollo-client"],"text":"Title: apollo-client refetch queries\nTags: reactjs, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI got a cart with items with the option to delete items by your choice,\nIt works nice and you dont need to refresh the page to see results, but if you only add 1 item to the cart and trying to remove that item it won't remove unless you refresh the page.. can't understand why would like to get some hints .\n\nI console logged cart info , if there is more than 1 item it will delete and will console, but if there's only one it won't log and won't delete. ( again, only if I refresh )\n\nDelete product mutation -\n\n```\nconst [deleteProduct, { loading: deleteLoading, error: deleteError }] =\n useMutation(DELETE_FROM_CART, {\n variables: { productId, userId: cart?.userId },\n\n refetchQueries: [\n {\n query: GET_USER_CART,\n variables: { userId: cart?.userId },\n awaitRefetchQueries: true,\n },\n ],\n });\n```\n\nGET_USER_CART:\n\n```\nconst GET_USER_CART = gql`\n query ($userId: ID!) {\n getUserCart(userId: $userId) {\n userId\n cartProducts {\n productId\n size\n productPrice\n }\n }\n }\n`;\n\n const { data: cartData, loading: cartLoading } = useQuery(GET_USER_CART, {\n variables: { userId: userInfo?.id },\n });\n```\n\nAlso tried to update cache instead refetching query but the same result\n\n```\nconst [deleteProduct, { loading: deleteLoading, error: deleteError }] =\nuseMutation(DELETE_FROM_CART, {\n variables: { productId, userId: cart?.userId },\n update(cache, { data }) {\n const updatedCart = data?.deleteProductFromCart;\n const existCart = cache.readQuery({\n query: GET_USER_CART,\n variables: { userId: cart?.userId },\n });\n if (existCart && updatedCart) {\n cache.writeQuery({\n query: GET_USER_CART,\n variables: { userId: cart?.userId },\n data: {\n getUserCart: { ...existCart.getUserCart, updatedCart },\n },\n });\n }\n },\n});\n```\n\n========================================\n\nCode:\n```text\nconst [deleteProduct, { loading: deleteLoading, error: deleteError }] =\n useMutation(DELETE_FROM_CART, {\n variables: { productId, userId: cart?.userId },\n\n refetchQueries: [\n {\n query: GET_USER_CART,\n variables: { userId: cart?.userId },\n awaitRefetchQueries: true,\n },\n ],\n });\n```\n\n```text\nconst GET_USER_CART = gql`\n query ($userId: ID!) {\n getUserCart(userId: $userId) {\n userId\n cartProducts {\n productId\n size\n productPrice\n }\n }\n }\n`;\n\n\n const { data: cartData, loading: cartLoading } = useQuery(GET_USER_CART, {\n variables: { userId: userInfo?.id },\n });\n```\n\n```text\nconst [deleteProduct, { loading: deleteLoading, error: deleteError }] =\nuseMutation(DELETE_FROM_CART, {\n variables: { productId, userId: cart?.userId },\n update(cache, { data }) {\n const updatedCart = data?.deleteProductFromCart;\n const existCart = cache.readQuery({\n query: GET_USER_CART,\n variables: { userId: cart?.userId },\n });\n if (existCart && updatedCart) {\n cache.writeQuery({\n query: GET_USER_CART,\n variables: { userId: cart?.userId },\n data: {\n getUserCart: { ...existCart.getUserCart, updatedCart },\n },\n });\n }\n },\n});\n```\n\n```text\nconst [deleteProduct, { loading: deleteLoading, error: deleteError }] =\n useMutation(DELETE_FROM_CART, {\n variables: { productId, userId: cart?.userId },\n\n refetchQueries: [\n {\n query: GET_USER_CART,\n //Make sure that variables are the same ones as the ones you used to get GET_USER_CART data. If it is different, it wont work. Check if your variables are the same on useQuery you called before and this query\n variables: { userId: cart?.userId },\n awaitRefetchQueries: true,\n },\n ],\n });\n```\n\n```text\nconst {data, loading, error, refetch} = useQuery(GET_USER_CART, {variables: {}})\n\nconst [deleteProduct, { loading: deleteLoading, error: deleteError }] =\n useMutation(DELETE_FROM_CART, {\n variables: { productId, userId: cart?.userId },\nonComplete: (data) => {\n//call refetch here. \nrefetch()\n}\n });\n```\n\n```text\nconst [deleteProduct, { loading: deleteLoading, error: deleteError }] =\n useMutation(DELETE_FROM_CART, {\n variables: { productId, userId: cart?.userId },\n update(cache, { data }) {\n cache.modify({\n fields: {\n getUserCart(existingCart, { readField }) {\n if (data) {\n //If your existingCart is an object, then use something else instead of filter. I am assuming that your getUserCart returns an array\n return existingCart.filter(\n (taskRef) => data.deleteProductFromCart.id !== readField(\"id\", taskRef)\n );\n }\n },\n },\n });\n },\n });\n```\n\n========================================\n\nComments:\n- Can you your GET_USER_CART query function? The useQuery function where you fetch your data\n- Sure I will edit the post!\n- Added my answer below with 3 ways to update the cache, but in your case, the most probably thing that happens is that your userId: cart?.userId is undefined, so it doesn't update the query data correctly. useQuery variables: { userId: userInfo?.id } and useMutation query: GET_USER_CART, variables: { userId: cart?.userId }, must match","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":190,"estimatedTokens":1310}}938{"id":"stack-72836597","source":"stackoverflow","questionId":72836597,"title":"How to create new commit with the github graphql API?","tags":["github","graphql"],"text":"Title: How to create new commit with the github graphql API?\nTags: github, graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a new commit using the github graphql api, using the createCommitOnBranch mutation.\nWhat value should one use for expectedHeadOid: \"?????\"?\nHow can one get such value from the Graphql API?\n\nThis is my attempt so far:\n\n```\n{\nmutation m1 {\n createCommitOnBranch(\n input: {\n branch: \n {repositoryNameWithOwner: \"some_repo/some_owner\",\n branchName: \"main\"\n },\n message: {headline: \"headline!\"},\n fileChanges: {\n additions: {path: \"README.md\", contents: \"SGVsbG8gV29ybGQ=\"}\n }\n expectedHeadOid: \"?????\"\n }\n ) \n}\n}\n```\n\n========================================\n\nCode:\n```text\n{\nmutation m1 {\n createCommitOnBranch(\n input: {\n branch: \n {repositoryNameWithOwner: \"some_repo/some_owner\",\n branchName: \"main\"\n },\n message: {headline: \"headline!\"},\n fileChanges: {\n additions: {path: \"README.md\", contents: \"SGVsbG8gV29ybGQ=\"}\n }\n expectedHeadOid: \"?????\"\n }\n ) \n}\n}\n```\n\n```text\nexpectedHeadOid=`git rev-parse HEAD~`\n```\n\n```text\n\"message\": \"Expected branch to point to \\\"f786b7e2e0ec290972a2ada6858217ba16305933\\\" \n but it did not. Pull and try again.\"\n```\n\n```text\n{\n repository(name: \"my-new-repository\", owner: \"AnnaBurd\") {\n defaultBranchRef {\n target {\n ... on Commit {\n history(first: 1) {\n nodes {\n oid\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\n----------------------mutation ------------------\nmutation ($input: CreateCommitOnBranchInput!) {\n createCommitOnBranch(input: $input) {\n commit {\n url\n }\n }\n}\n\n-----------variables for mutation---------------\n{\n \"input\": {\n \"branch\": {\n \"repositoryNameWithOwner\": \"AnnaBurd/my-new-repository\",\n \"branchName\": \"main\"\n },\n \"message\": {\n \"headline\": \"Hello from GraphQL!\"\n },\n \"fileChanges\": {\n \"additions\": [\n {\n \"path\": \"myfile.txt\",\n \"contents\": \"SGVsbG8gZnJvbSBKQVZBIGFuZCBHcmFwaFFM\" <------- encoded base 64\n }\n ]\n },\n \"expectedHeadOid\": \"db7a5d870738bf11ce1fc115267d13406f5d0e76\" <----- oid from step 1\n }\n}\n```\n\n```text\n\"expectedHeadOid\": \"git rev-parse HEAD\"\n```\n\n```text\nHEAD\n```\n\n```text\nHEAD\n```\n\n```text\ncreatecommitonbranch\n```\n\n```text\nexpectedHeadOid\n```\n\n```text\nexpectedHeadOid\n```\n\n```text\ndefaultBranchRef\n```\n\n```text\nCreateCommitOnBranchInput\n```\n\n```text\nCreateCommitOnBranchInput\n```\n\n========================================\n\nComments:\n- So impressed, you are a legend! I was able to accomplish step 1. with the following: {repository(name: \"my-new-repository\", owner: \"AnnaBurd\") { { object(expression: \"main\") { oid } }. Is there any meaningful delta between the solutions? Is there any good resource to learn this API?\n- @Oded Great, did you manage to make it work?\n- @Oded Sorry, I did not see at first our edited comment.\n- @Oded Beside the official GitHub GraphQL explorer, and its official documentation, a GraphQL playground can be useful to play around with this: github.com/graphql/graphql-playground (you have a all collection of them). github.com/EasyGraphQL/easygraphql-tester could help too.\n- Yes I did, with either your Step 1. or the one I added in comment above. The links you shared are great, but am not see how they lead to knowing how to reach the great solution you shared: iq.opengenus.org/api-requests-in-java/…. Guess it is time for my first Medium post","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":158,"estimatedTokens":884}}939{"id":"stack-55091665","source":"stackoverflow","questionId":55091665,"title":"How to add multiple resolvers in a type (Apollo-server)","tags":["graphql","apollo-server"],"text":"Title: How to add multiple resolvers in a type (Apollo-server)\nTags: graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI have used `express-graphql` and there i used to do something like this.\n\n```\nconst SubCategoryType = new ObjectType({\n name: 'SubCategory',\n fields: () => ({\n id: { type: IDType },\n name: { type: StringType },\n category: {\n type: CategoryType,\n resolve: parentValue => getCategoryBySubCategory(parentValue.id)\n },\n products: {\n type: List(ProductType),\n resolve: parentValue => getProductsBySubCategory(parentValue.id)\n }\n })\n});\n```\n\nHere I have multiple resolvers, `id and name` are fetched directly from the result. and the category and products have there own database operation. and so on. \nNow I am working on `apollo-server` and I can't find a way to replicate this.\n\nfor example I have a type\n\n```\ntype Test {\n something: String\n yo: String\n comment: Comment\n }\n type Comment {\n text: String\n createdAt: String\n author: User\n }\n```\n\nand in my resolver I want to split it up, for example something like this\n\n```\ntext: {\n something: 'value',\n yo: 'value',\n comment: getComments();\n}\n```\n\nNOTE: this is just a representation of what I need.\n\n========================================\n\nCode:\n```text\nconst SubCategoryType = new ObjectType({\n name: 'SubCategory',\n fields: () => ({\n id: { type: IDType },\n name: { type: StringType },\n category: {\n type: CategoryType,\n resolve: parentValue => getCategoryBySubCategory(parentValue.id)\n },\n products: {\n type: List(ProductType),\n resolve: parentValue => getProductsBySubCategory(parentValue.id)\n }\n })\n});\n```\n\n```text\ntype Test {\n something: String\n yo: String\n comment: Comment\n }\n type Comment {\n text: String\n createdAt: String\n author: User\n }\n```\n\n```text\ntext: {\n something: 'value',\n yo: 'value',\n comment: getComments();\n}\n```\n\n```text\nexpress-graphql\n```\n\n```text\nid and name\n```\n\n```text\napollo-server\n```\n\n```text\ntype Query {\n getTest: Test\n}\ntype Test {\n id: Int!\n something: String\n yo: String\n comment: Comment\n}\ntype Comment {\n id: Int!\n text: String\n createdAt: String\n author: User\n}\ntype User {\n id: Int!\n name: String\n email: String\n}\n```\n\n```js\nconst resolver = {\n // root Query resolver\n Query: {\n getTest: (root, args, ctx, info) => getTest()\n },\n // Test resolver\n Test: {\n // resolves field 'comment' on Test\n // the 'parent' arg contains the result from the parent resolver (here, getTest on root)\n comment: (parent, args, ctx, info) => getComment(parent.commentId)\n },\n // Comment resolver\n Comment: {\n // resolves field 'author' on Comment\n // the 'parent' arg contains the result from the parent resolver (here, comment on Test)\n author: (parent, args, ctx, info) => getUser(parent.userId)\n },\n}\n```\n\n```text\ngetTest()\n```\n\n```text\nsomething\n```\n\n```text\nyo\n```\n\n```text\ncommentId\n```\n\n```text\ngetComment(id)\n```\n\n```text\nid\n```\n\n```text\ntext\n```\n\n```text\ncreatedAt\n```\n\n```text\nuserId\n```\n\n```text\ngetUser(id)\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\nemail\n```\n\n========================================\n\nComments:\n- Let me try this and get back to you\n- It worked. :) Couldn't find it in docs though, do you have any docs link which explains this well? and like this, won't my resolvers be hard to manage? It would be helpful if you some tips. As I am using apollo-server for first time.\n- @Sarmad You can find the basic documentation about apollo-server resolvers here. Think of resolvers as \"bubbling up\" from your root Query or Mutation: if a field is not directly resolved in the parent resolver, then it must be resolved by a child resolver. You can also use child resolvers to override the value of a given field under certain conditions (for instance, you might want to *null* a field when a user is not authenticated). If you have any specific questions, I'll be happy to help if I can. :)\n- As your resolvers get more complex, I encourage you to put any type-specific resolver in its own file, and then aggregate all your resolvers in a `resolvers.js` file. You'll find your code much easier to maintain that way. Let me know if you want me to add an example of such a directory structure in my answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":212,"estimatedTokens":1061}}940{"id":"stack-43921059","source":"stackoverflow","questionId":43921059,"title":"Testing GraphQL API","tags":["node.js","mocha.js","chai","graphql","chai-http"],"text":"Title: Testing GraphQL API\nTags: node.js, mocha.js, chai, graphql, chai-http\nSource: Stack Overflow\n\nQuestion:\nI'm testing my GraphQL API, but I would like to clean it up a little bit. It's worth noting I'm using `chai-http` for the network requests. Here's what I'm currently doing (which works):\n\n```\nlet createUser = (()=> {\n return new Promise((resolve, reject) => {\n chai.request(server)\n .post('/api/graphql/')\n .set('content-type', 'application/json')\n .send({ 'query' : \n 'mutation users { \\\n user : addUser(inputs: { \\\n firstName: \\\"Test\\\", \\\n lastName: \\\"User\\\", \\\n email: \\\"test@test.com\\\", \\\n }) { \\\n id, \\\n firstName \\\n } \\\n }'\n })\n .end((err, res) => {\n if (err) { reject(err) }\n let data = res.body.data;\n let user = data.user;\n resolve(user);\n })\n });\n});\n```\n\nHowever, I would like to clean it up a bit and do something like this:\n\n```\nlet createUser = (() => {\n let newUser = {\n firstName: 'Test',\n lastName: 'User',\n email: 'test@test.com'\n };\n\n return new Promise((resolve, reject) => {\n chai.request(server)\n .post('/api/graphql/')\n .set('content-type', 'application/json')\n .send({ 'query' : \n 'mutation users { \\\n user : addUser(inputs: ' + JSON.stringify(newUser) + ') { \\\n id, \\\n firstName \\\n } \\\n }'\n })\n .end((err, res) => {\n if (err) { reject(err) }\n let data = res.body.data;\n let user = data.user;\n resolve(user);\n })\n });\n});\n```\n\nHowever, this style does of placing the object inputs does not work and returns a bad request error. Here is what part of the returned error object reads:\n\nhttps://i.sstatic.net/08XoE.png\n\nAny ideas why this doesn't work? Thanks in advance!\n\n========================================\n\nCode:\n```text\nlet createUser = (()=> {\n return new Promise((resolve, reject) => {\n chai.request(server)\n .post('/api/graphql/')\n .set('content-type', 'application/json')\n .send({ 'query' : \n 'mutation users { \\\n user : addUser(inputs: { \\\n firstName: \\\"Test\\\", \\\n lastName: \\\"User\\\", \\\n email: \\\"test@test.com\\\", \\\n }) { \\\n id, \\\n firstName \\\n } \\\n }'\n })\n .end((err, res) => {\n if (err) { reject(err) }\n let data = res.body.data;\n let user = data.user;\n resolve(user);\n })\n });\n});\n```\n\n```text\nlet createUser = (() => {\n let newUser = {\n firstName: 'Test',\n lastName: 'User',\n email: 'test@test.com'\n };\n\n return new Promise((resolve, reject) => {\n chai.request(server)\n .post('/api/graphql/')\n .set('content-type', 'application/json')\n .send({ 'query' : \n 'mutation users { \\\n user : addUser(inputs: ' + JSON.stringify(newUser) + ') { \\\n id, \\\n firstName \\\n } \\\n }'\n })\n .end((err, res) => {\n if (err) { reject(err) }\n let data = res.body.data;\n let user = data.user;\n resolve(user);\n })\n });\n});\n```\n\n```text\nchai-http\n```\n\n```text\nlet createUser = (() => {\n let newUser = {\n firstName: 'Test',\n lastName: 'User',\n email: 'test@test.com'\n };\n\n return new Promise((resolve, reject) => {\n chai.request(server)\n .post('/api/graphql/')\n .set('content-type', 'application/json')\n .send({\n 'query' : 'mutation users ($input: CreateUserInput!) { \\\n user : addUser(inputs: $input) { \\\n id, \\\n firstName \\\n } \\\n }',\n 'variables' : {\n 'input': newUser\n }\n })\n .end((err, res) => {\n if (err) { reject(err) }\n let data = res.body.data;\n let user = data.user;\n resolve(user);\n })\n });\n});\n```\n\n```text\nquery\n```\n\n```text\nvariables\n```\n\n========================================\n\nComments:\n- Thanks bud, will try it out! @vince\n- Hey @vince, anyway to clean up the response I want back? Say I wanted id, firstName, lastName, facebookUID, email, etc.. returned after creation? What do you think?\n- In that case you could always just return more fields. Right now, the query is returning `id` and `firstName`, but you can also keep adding to that list and include `lastName`, `facebookUID`, `email`, etc.","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":185,"estimatedTokens":1045}}941{"id":"stack-61878602","source":"stackoverflow","questionId":61878602,"title":"How to useQuery on props change with Apollo?","tags":["javascript","reactjs","graphql","apollo"],"text":"Title: How to useQuery on props change with Apollo?\nTags: javascript, reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nCurrently I have a BooksList component and I'm passing down props to my BooksDetails component when a title is clicked. How do I use an Apollo hook to only query on props change?\n\nI'm not sure how to do this using hooks. I've looked through the UseQuery documentation from Apollo. I couldn't find documentation on UseLazyQuery.\n\nI've tried the following, but it always returns undefined: \n\n```\nconst { loading, error, data } = useQuery(getBookQuery, {\n options: (props) => {\n return {\n variables: {\n id: props.bookId\n }\n }\n }\n })\n```\n\nBookList:\n\n```\nconst BookList = () => {\n const {loading, error, data} = useQuery(getBooksQuery)\n const [selectedId, setId] = useState('');\n\n return (\n \n \n {data && data.books.map(book => (\n \n- setId(book.id)} key={book.id}>{book.name}\n )) }\n \n \n \n );\n};\n\nexport default BookList;\n```\n\nBookDetails:\n\n```\nconst BookDetails = (props) => {\n\n const { loading, error, data } = useQuery(getBookQuery, {\n options: (props) => {\n return {\n variables: {\n id: props.bookId\n }\n }\n }\n })\n\n console.log(data)\n return (\n \n Output Book Details here\n\n \n );\n};\n\nexport default BookDetails;\n```\n\nEDIT - I forgot to add that my GetBookQuery has a parameter of ID so an example would be `getBookQuery(123)`.\n\n========================================\n\nTop Answer:\nI was also following along the same example and I came up here with the same question. I tried doing the following way. This might be helpful for someone.\n\n**BookDetails.js**:\n\n```\nfunction BookDetails({ bookId }) {\n const [loadDetails, { loading, error, data }] = useLazyQuery(getBook);\n\n useEffect(() => {\n if (bookId) {\n loadDetails({ variables: { id: bookId } });\n }\n }, [bookId, loadDetails]);\n\n if (!bookId) return null;\n if (loading) return Loading...\n\n;\n if (error) return Error!\n\n;\n\n // for example purpose\n return {JSON.stringify(data)};\n}\n\nexport default BookDetails;\n```\n\n========================================\n\nCode:\n```text\nconst { loading, error, data } = useQuery(getBookQuery, {\n options: (props) => {\n return {\n variables: {\n id: props.bookId\n }\n }\n }\n })\n```\n\n```text\nconst BookList = () => {\n const {loading, error, data} = useQuery(getBooksQuery)\n const [selectedId, setId] = useState('');\n\n\n return (\n <div id='main'>\n <ul id='book-list'>\n {data && data.books.map(book => (\n <li onClick={() => setId(book.id)} key={book.id}>{book.name}</li>\n )) }\n </ul>\n <BookDetails bookId={selectedId} />\n </div>\n );\n};\n\nexport default BookList;\n```\n\n```text\nconst BookDetails = (props) => {\n\n const { loading, error, data } = useQuery(getBookQuery, {\n options: (props) => {\n return {\n variables: {\n id: props.bookId\n }\n }\n }\n })\n\n console.log(data)\n return (\n <div id='book-details'>\n <p>Output Book Details here</p>\n </div>\n );\n};\n\nexport default BookDetails;\n```\n\n```text\ngetBookQuery(123)\n```\n\n```js\nconst [getBook, { loading, error, data }] = useLazyQuery(getBooksQuery);\n```\n\n```js\nimport React from 'react';\nimport { useLazyQuery } from '@apollo/react-hooks';\n\nconst BookList = () => {\n const [getBook, { loading, error, data }] = useLazyQuery(getBooksQuery);\n\n return (\n <div id='main'>\n <ul id='book-list'>\n {data && data.books.map(book => (\n <li onClick={() => getBook({ variables: { id: book.id } })}} key={book.id}>{book.name}</li>\n )) }\n </ul>\n <BookDetails data={data} />\n </div>\n );\n};\n\nexport default BookList;\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nfunction BookDetails({ bookId }) {\n const [loadDetails, { loading, error, data }] = useLazyQuery(getBook);\n\n useEffect(() => {\n if (bookId) {\n loadDetails({ variables: { id: bookId } });\n }\n }, [bookId, loadDetails]);\n\n if (!bookId) return null;\n if (loading) return <p>Loading...</p>;\n if (error) return <p>Error!</p>;\n\n // for example purpose\n return <div>{JSON.stringify(data)}</div>;\n}\n\nexport default BookDetails;\n```\n\n========================================\n\nComments:\n- just `useQuery(getBookQuery, { variables: { id: props.bookId } } )` ?\n- apollographql.com/docs/react/data/queries/…\n- The issue I've had with this is that the onClick will be in my `BookList` component. How will I pass the data from the query down to `BookDetails`?\n- You can pass the full `data` to the `BookDetails` component as props, then extract the information you need from that object\n- If I'm already using `const {loading, error, data} = useQuery(getBooksQuery)`, what variable names can i use for the useLazyQuery? Can i use `const [getBook, { loading2, error2, data2 }] = useLazyQuery(getBookQuery);`?\n- Ah, I just realized it's destructuring so I would have to do: `const [getBook, { loading: loading2, error: error2, data: data2 }] = useLazyQuery(getBookQuery);` , my bad! Is there a better naming convention I should use for the variables?\n- To avoid variable names clash, you could use a more descriptive variable name for example instead of `loading2` you could use `loadingBooks` or whatever you're actually loading. Similarly, `data2` becomes `booksData`. Let me know if that helps.","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":232,"estimatedTokens":1320}}942{"id":"stack-52226819","source":"stackoverflow","questionId":52226819,"title":"Authenticate Apollo Client to AWS AppSync with Cognito User Pools","tags":["javascript","amazon-web-services","graphql","apollo","aws-appsync"],"text":"Title: Authenticate Apollo Client to AWS AppSync with Cognito User Pools\nTags: javascript, amazon-web-services, graphql, apollo, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI am trying to connect to my AWS AppSync API using the plain Apollo Client but I am not sure how to structure the authentication header correctly. \n\nSo far I have followed the header authentication documentation here: https://www.apollographql.com/docs/react/recipes/authentication.html\n\nAnd have this code, which I adapted to include the token call to the Amplify authentication service but it returns a 401 error:\n\n```\nconst httpLink = createHttpLink({\n uri: '[API end point address]/graphql'\n});\n\nconst authLink = setContext((_, { headers }) => {\n const token = async () => (await Auth.currentSession()).getAccessToken().getJwtToken();\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\"\n }\n }\n})\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n})\n```\n\nThe only documentation I can find relating to this doesn't provide any technical instructions: \n\n When using Amazon Cognito User Pools, you can create groups that users\n belong to. This information is encoded in a JWT token that your\n application sends to AWS AppSync in an authorization header when\n sending GraphQL operations.\n\nFrom here: https://docs.aws.amazon.com/appsync/latest/devguide/security.html\n\nI know that token is fine because if I use the AppSync JavaScript API then it works. Is there anywhere I can go to find out how to achieve this or does someone know how? \n\nEdit: \n\nSo far i have tried changing this line:\n\n```\nauthorization: token ? `Bearer ${token}` : \"\"\n```\n\nThe following attempts: \n\n```\ntoken\n\njwtToken: token\n\nauthorization: token\n\nAuthorization: token\n```\n\nNone of these have worked either.\n\n========================================\n\nTop Answer:\nYou can see an example of it on Github from AWS sample.\nWorks with AppSync but very similar.\n\n\r\n\r\n\n```\n// AppSync client instantiation\r\nconst client = new AWSAppSyncClient({\r\n url: GRAPHQL_API_ENDPOINT_URL,\r\n region: GRAPHQL_API_REGION,\r\n auth: {\r\n type: AUTH_TYPE,\r\n // Get the currently logged in users credential.\r\n jwtToken: async () => (await Auth.currentSession()).getAccessToken().getJwtToken(),\r\n },\r\n // Amplify uses Amazon IAM to authorize calls to Amazon S3. This provides the relevant IAM credentials.\r\n complexObjectsCredentials: () => Auth.currentCredentials()\r\n});\n```\n\n\r\n\r\n\r\n\nLink to the AWS repo\n\n========================================\n\nCode:\n```text\nconst httpLink = createHttpLink({\n uri: '[API end point address]/graphql'\n});\n\nconst authLink = setContext((_, { headers }) => {\n const token = async () => (await Auth.currentSession()).getAccessToken().getJwtToken();\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\"\n }\n }\n})\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n})\n```\n\n```text\nauthorization: token ? `Bearer ${token}` : \"\"\n```\n\n```text\ntoken\n\njwtToken: token\n\nauthorization: token\n\nAuthorization: token\n```\n\n```text\nBearer\n```\n\n```js\n// AppSync client instantiation\nconst client = new AWSAppSyncClient({\n url: GRAPHQL_API_ENDPOINT_URL,\n region: GRAPHQL_API_REGION,\n auth: {\n type: AUTH_TYPE,\n // Get the currently logged in users credential.\n jwtToken: async () => (await Auth.currentSession()).getAccessToken().getJwtToken(),\n },\n // Amplify uses Amazon IAM to authorize calls to Amazon S3. This provides the relevant IAM credentials.\n complexObjectsCredentials: () => Auth.currentCredentials()\n});\n```\n\n========================================\n\nComments:\n- That makes sense, but annoyingly the case for Cognito user pools is blank. Editing question to show things tried so far.\n- Based on what I read from the AppSync developer guide, the Cognito User Pool Auth should use the OPENID_CONNECT method using the JWT token provided by the Cognito User Pool service.\n- Also, this is specified on line 144 of the link I posted.\n- The `Authorization: token` format should be the key to getting it to work, so I think the issue is likely with your Cognito User Pool config or the token itself rather than with the Apollo setup.\n- Sorry, you are correct, I saw that line but did not realise that you nothing in the case meant that it does what the following case does.\n- isnt this for apollo v2 ?","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":161,"estimatedTokens":1107}}943{"id":"stack-51957480","source":"stackoverflow","questionId":51957480,"title":"How to pass :current_user in Graphql resolver","tags":["ruby-on-rails","ruby-on-rails-5","graphql","graphql-ruby"],"text":"Title: How to pass :current_user in Graphql resolver\nTags: ruby-on-rails, ruby-on-rails-5, graphql, graphql-ruby\nSource: Stack Overflow\n\nQuestion:\nI have QueryType \n\n```\nTypes::QueryType = GraphQL::ObjectType.define do\n name 'Query'\n\n field :allProjects, function: Resolvers::Projects\nend\n```\n\nAnd Resolver like this \n\n```\nrequire 'search_object/plugin/graphql'\n\nmodule Resolvers\n class Projects\n include SearchObject.module(:graphql)\n\n type !types[Types::ProjectType]\n\n scope { Project.all }\n\n ProjectFilter = GraphQL::InputObjectType.define do\n name 'ProjectFilter'\n\n argument :OR, -> { types[ProjectFilter] }\n argument :description_contains, types.String\n argument :title_contains, types.String\n end\n\n option :filter, type: ProjectFilter, with: :apply_filter\n option :first, type: types.Int, with: :apply_first\n option :skip, type: types.Int, with: :apply_skip\n\n def apply_first(scope, value)\n scope.limit(value)\n end\n\n def apply_skip(scope, value)\n scope.offset(value)\n end\n\n def apply_filter(scope, value)\n branches = normalize_filters(value).reduce { |a, b| a.or(b) }\n scope.merge branches\n end\n\n def normalize_filters(value, branches = [])\n scope = Project.all\n scope = scope.where('description ILIKE ?', \"%#{value['description_contains']}%\") if value['description_contains']\n scope = scope.where('title ILIKE ?', \"%#{value['title_contains']}%\") if value['title_contains']\n branches I want to access current_user in the resolver so i can access current_user.projects not Project.all. I am very new to graphql and learning. \n\nEverything works but i just need to understand the whole flow on how i can get old of the ctx in the resolver.\n\n========================================\n\nCode:\n```text\nTypes::QueryType = GraphQL::ObjectType.define do\n name 'Query'\n\n field :allProjects, function: Resolvers::Projects\nend\n```\n\n```text\nrequire 'search_object/plugin/graphql'\n\nmodule Resolvers\n class Projects\n include SearchObject.module(:graphql)\n\n type !types[Types::ProjectType]\n\n scope { Project.all }\n\n ProjectFilter = GraphQL::InputObjectType.define do\n name 'ProjectFilter'\n\n argument :OR, -> { types[ProjectFilter] }\n argument :description_contains, types.String\n argument :title_contains, types.String\n end\n\n option :filter, type: ProjectFilter, with: :apply_filter\n option :first, type: types.Int, with: :apply_first\n option :skip, type: types.Int, with: :apply_skip\n\n def apply_first(scope, value)\n scope.limit(value)\n end\n\n def apply_skip(scope, value)\n scope.offset(value)\n end\n\n def apply_filter(scope, value)\n branches = normalize_filters(value).reduce { |a, b| a.or(b) }\n scope.merge branches\n end\n\n def normalize_filters(value, branches = [])\n scope = Project.all\n scope = scope.where('description ILIKE ?', \"%#{value['description_contains']}%\") if value['description_contains']\n scope = scope.where('title ILIKE ?', \"%#{value['title_contains']}%\") if value['title_contains']\n branches << scope\n\n value['OR'].reduce(branches) { |s, v| normalize_filters(v, s) } if value['OR'].present?\n branches\n end\n end\nend\n```\n\n```rb\nclass GraphqlController < ApplicationController\n before_action :authenticate_user!\n\n def execute\n variables = ensure_hash(params[:variables])\n query = params[:query]\n operation_name = params[:operationName]\n context = {\n current_user: current_user,\n }\n result = HabitTrackerSchema.execute(query, variables: variables, context: context, operation_name: operation_name)\n render json: result\n rescue => e\n raise e unless Rails.env.development?\n handle_error_in_development e\n end\n\n # ...\nend\n```\n\n```rb\ncontext[:current_user]\n```\n\n```rb\nmodule Types\n class BaseObject < GraphQL::Schema::Object\n field_class Types::BaseField\n\n def current_user\n context[:current_user]\n end\n end\nend\n```\n\n```text\ncurrent_user\n```\n\n```text\ncurrent_user\n```\n\n```text\ncurrent_user\n```\n\n```text\nTypes::BaseObject\n```\n\n```text\napp/graphql/types/base_object.rb\n```\n\n```text\ncurrent_user\n```\n\n```text\n#resolve\n```\n\n========================================\n\nComments:\n- Do you use anything authentification or authorization related?\n- Yes. I use Knock gem\n- @suyesh Did you find out how to do that? Use `current_user` in the resolver?\n- What is the best example to handle graphql to all the request\n- I'm not sure I understand your question. What exactly do you want to do?\n- was very helpful how you showed a good place to put the helper method inside of `Types::BaseObject`. I was wondering where the best place for this would be","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":196,"estimatedTokens":1153}}944{"id":"stack-64642948","source":"stackoverflow","questionId":64642948,"title":"Is there a way to name graphql requests in the devtool network tab?","tags":["graphql","apollo","apollo-client","devtools"],"text":"Title: Is there a way to name graphql requests in the devtool network tab?\nTags: graphql, apollo, apollo-client, devtools\nSource: Stack Overflow\n\nQuestion:\nI'm using apollo as my client and I run plenty of queries and mutations on my app. I was wondering if there is a way to have each of my query/mutation displayed by its name (eg. getProduct) instead of all showing as \"graph\" in my network tab? I'm on Brave (Chromium).\n\nIt would make debugging easier if I didn't have to click on each one and check the headers or the response to identify which query or mutation this request corresponds to.\n\nHere's how it currently shows in my devtools:\n\nnetwork tab screenshot\n\nThanks a lot!\n\n========================================\n\nTop Answer:\n`uri` prop of `HttpLink` can accept function which have `operation` as an arg\nso it can be done like this as well:\n\n```\nconst httpLink = new HttpLink({ uri: (operation) => `${MY_BASE_URL}?${operation.operationName}` });\n```\n\n========================================\n\nCode:\n```text\nimport {\n ApolloClient,\n ApolloLink,\n HttpLink,\n InMemoryCache,\n} from '@apollo/client';\n\nconst httpLink = new HttpLink({ uri: MY_BASE_URL });\n\nconst namedLink = new ApolloLink((operation, forward) => {\n operation.setContext(() => ({\n uri: `${MY_BASE_URL}?${operation.operationName}`,\n })\n );\n return forward ? forward(operation) : null;\n});\n\nexport const client = new ApolloClient({\n link: ApolloLink.from([namedLink, httpLink]),\n cache: new InMemoryCache(),\n});\n```\n\n```text\nimport { gql } from \"@apollo/client\";\n\nconst QUERY = gql`\n query QueryName {\n ...\n }\n`;\n```\n\n```text\nconst httpLink = new HttpLink({ uri: (operation) => `${MY_BASE_URL}?${operation.operationName}` });\n```\n\n```text\nuri\n```\n\n```text\nHttpLink\n```\n\n```text\noperation\n```\n\n========================================\n\nComments:\n- my company somehow implemented a requestAlias which makes the path look like v1 (requestAlias) still trying to figure out how to do this by default with my operationName by default...\n- This is setting up an implicit dependency on the server to ignore the query params. It is up to the server to interpret this request and may provide unexpected outputs.","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":549}}945{"id":"stack-52668154","source":"stackoverflow","questionId":52668154,"title":"GraphQL Dataloader vs Mongoose Populate","tags":["node.js","express","mongoose","graphql"],"text":"Title: GraphQL Dataloader vs Mongoose Populate\nTags: node.js, express, mongoose, graphql\nSource: Stack Overflow\n\nQuestion:\nIn order to perform a join-like operation, we can use both GraphQL and Mongoose to achieve that end. \n\nBefore asking any question, I would like to give the following example of Task/Activities (none of this code is tested, it is given just for the example's sake):\n\n```\nTask {\n _id,\n title,\n description,\n activities: [{ //Of Activity Type\n _id,\n title\n }]\n}\n```\n\nIn mongoose, we can retrieve the activities related to a task with the populate method, with something like this:\n\n```\nconst task = await TaskModel.findbyId(taskId).populate('activities');\n```\n\nUsing GraphQL and Dataloader, we can have the same result with something like:\n\n```\nconst DataLoader = require('dataloader');\nconst getActivitiesByTask = (taskId) => await ActivityModel.find({task: taskId});\nconst dataloaders = () => ({\n activitiesByTask: new DataLoader(getActivitiesByTask),\n});\n// ...\n// SET The dataloader in the context\n// ...\n\n//------------------------------------------\n// In another file\nconst resolvers = {\n Query: {\n Task: (_, { id }) => await TaskModel.findbyId(id),\n },\n Task: {\n activities: (task, _, context) => context.dataloaders.activitiesByTask.load(task._id),\n },\n};\n```\n\nI tried to see if there is any article that demonstrates which way is better regarding performance, resource exhaustion,...etc but I failed to find any comparison of the two methods.\n\nAny insight would be helpful, thanks!\n\n========================================\n\nCode:\n```text\nTask {\n _id,\n title,\n description,\n activities: [{ //Of Activity Type\n _id,\n title\n }]\n}\n```\n\n```text\nconst task = await TaskModel.findbyId(taskId).populate('activities');\n```\n\n```text\nconst DataLoader = require('dataloader');\nconst getActivitiesByTask = (taskId) => await ActivityModel.find({task: taskId});\nconst dataloaders = () => ({\n activitiesByTask: new DataLoader(getActivitiesByTask),\n});\n// ...\n// SET The dataloader in the context\n// ...\n\n//------------------------------------------\n// In another file\nconst resolvers = {\n Query: {\n Task: (_, { id }) => await TaskModel.findbyId(id),\n },\n Task: {\n activities: (task, _, context) => context.dataloaders.activitiesByTask.load(task._id),\n },\n};\n```\n\n```text\nactivities: (task, _, context) => Activity.find().where('id').in(task.activities)\n```\n\n```text\npopulate\n```\n\n```text\npopulate\n```\n\n```text\nactivities\n```\n\n```text\nactivities\n```\n\n```text\nactivities\n```\n\n```text\nactivities\n```\n\n```text\nactivities\n```\n\n```text\n$lookup\n```\n\n```text\npopulate\n```\n\n========================================\n\nComments:\n- I have to figure they are going to be more or less the same. There are probably more important things for you to worry about.\n- Thanks for your comment. Yes you are right, surely there is a lot of other aspects to care about. Regarding the previous methods, do you think specifically of any improvement or a better approach?\n- Lets say in a single request I would like to fetch array of tasks, where each activity field is populated. In this case, wouldnt it be better to use dataloader instead of populate? If I had 100 tasks, populate would request mongodb 100 times to fetch activities. But if I use a dataloader, it will hit the database only once. I know what you mean by your explanation on dataloaders for graphql. But I thought dataloaders could still benefit in non-graphql(express) apps, where populate(deep, with many arrays) is used heavily.\n- ok never mind. I did a test with `mongoose.set('debug', true)`. I thought mongoose will make unnecessary requests to database when using populate with deeply nested subdocuments. But just like dataloader the number of requests is minimal.(depth length == number of requests)","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":143,"estimatedTokens":951}}946{"id":"stack-61340137","source":"stackoverflow","questionId":61340137,"title":"Graphene Graphql - how to chain mutations","tags":["python-3.x","graphql","graphene-python","graphql-mutation"],"text":"Title: Graphene Graphql - how to chain mutations\nTags: python-3.x, graphql, graphene-python, graphql-mutation\nSource: Stack Overflow\n\nQuestion:\nI happened to send 2 separated requests to a Graphql API (Python3 + Graphene) in order to:\n\n- Create an object\n\n- Update another object so that it relates to the created one.\n\nI sensed this might not be in the \"spirit\" of Graphql, so I searched and read about nested migrations. Unforutnately, I also found that it was bad practice because nested migrations are not sequential and it might lead clients in hard to debug problems due to race conditions.\n\nI'm trying to use sequential root mutations in order to implement the use cases where nested migrations were considered. Allow me to present you a use case and a simple solution (but probably not good practice) I imagined. Sorry for the long post coming.\n\nLet's image I have User and Group entities, and I want, from the client form to update a group, to be able to not only add a user, but also create a user to be added in a group if the user does not exist. The users have ids named uid (user id) and groups gid (groupd id), just to highlight the difference. So using root mutations, I imagine doing a query like:\n\n```\nmutation {\n createUser(uid: \"b53a20f1b81b439\", username: \"new user\", password: \"secret\"){\n uid\n username\n }\n\n updateGroup(gid: \"group id\", userIds: [\"b53a20f1b81b439\", ...]){\n gid\n name\n }\n}\n```\n\nYou noticed that I provide the user id in the input of the `createUser` mutation. My problem is that to make the `updateGroup` mutation, I need the ID of the newly created user. I don't know a way to get that in graphene inside the mutate methods resolving `updateGroup`, so I imagined querying a UUID from the API while loading the client form data. So before sending the mutation above, at the initial loading of my client, I would do something like:\n\n```\nquery {\n uuid\n\n group (gid: \"group id\") {\n gid\n name\n }\n}\n```\n\nThen I would use the uuid from the response of this query in the mutation request (the value would be `b53a20f1b81b439`, as in the the first scriptlet above).\n\nWhat do you think about this process ? Is there a better way to do that ? Is Python `uuid.uuid4` safe to implement this ?\n\nThanks in advance.\n\n----- EDIT\n\nBased on a discussion in the comments, I should mention that the use case above is for illustration only. Indeed, a User entity might have an intrinsic unique key (email, username), as well as other entities might (ISBN for Book...). I'm looking for a general case solution, including for entities that might not exhibit such natural unique keys.\n\n========================================\n\nTop Answer:\nThere were a number of suggestions in the comments under the initial question. I'll come back to some at the end of this proposal.\n\nI have been thinking about this problem and also the fact that it seems to be a recurring question among developers. I have come to conclude that may we miss something in the way we want to edit our graph, namely edge operations. I think we try to do edges operations with node operations. To illustrate this, a graph creation in a language like dot (Graphviz) may look like:\n\n```\ndigraph D {\n\n /* Nodes */\n A \n B\n C\n\n /* Edges */\n\n A -> B\n A -> C\n A -> D\n\n}\n```\n\nFollowing this pattern, maybe the graphql mutation in the question should look like:\n\n```\nmutation {\n\n # Nodes\n\n n1: createUser(username: \"new user\", password: \"secret\"){\n uid\n username\n }\n\n n2: updateGroup(gid: \"group id\"){\n gid\n name\n }\n\n # Edges\n\n addUserToGroup(user: \"n1\", group: \"n2\"){\n status\n }\n}\n```\n\nThe inputs of the *\"edge operation\"* `addUserToGroup` would be the aliases of the previous nodes in the mutation query.\n\nThis would also allow to decorate edge operations with permission checks (permissions to create a relation may differ from permissions on each object).\n\nWe can definitely resolve a query like this already. What is less sure is if backend frameworks, Graphene-python in particular, provide mechanisms to allow the implementation of `addUserToGroup` (having the previous mutation results in the resolution context). I'm thinking of injecting a `dict` of the previous results in the Graphene context. I'll try and complete the answer with technical details if successful.\n\nMaybe there exist way to achieve something like this already, I will also look for that and complete the answer if found.\n\nIf it turns out the pattern above is not possible or found bad practice, I think I will stick to 2 separate mutations.\n\n### **EDIT 1: sharing results**\n\nI tested a way of resolving a query like above, using a Graphene-python middleware and a base mutation class to handle sharing the results. I created a one-file python program available on Github to test this. Or play with it on Repl.\n\nThe middleware is quite simple and adds a dict as `kwarg` parameter to the resolvers:\n\n```\nclass ShareResultMiddleware:\n\n shared_results = {}\n\n def resolve(self, next, root, info, **args):\n return next(root, info, shared_results=self.shared_results, **args)\n```\n\nThe base class is also quite simple and manages the insertion of results in the dictionary:\n\n```\nclass SharedResultMutation(graphene.Mutation):\n\n @classmethod\n def mutate(cls, root: None, info: graphene.ResolveInfo, shared_results: dict, *args, **kwargs):\n result = cls.mutate_and_share_result(root, info, *args, **kwargs)\n if root is None:\n node = info.path[0]\n shared_results[node] = result\n return result\n\n @staticmethod\n def mutate_and_share_result(*_, **__):\n return SharedResultMutation() # override\n```\n\nA node-like mutation that need to comply with the shared result pattern would inherit from `SharedResultMutation` in stead of `Mutation` and override `mutate_and_share_result` instead of `mutate`:\n\n```\nclass UpsertParent(SharedResultMutation, ParentType):\n class Arguments:\n data = ParentInput()\n\n @staticmethod\n def mutate_and_share_result(root: None, info: graphene.ResolveInfo, data: ParentInput, *___, **____):\n return UpsertParent(id=1, name=\"test\") # The edge-like mutations need to access the `shared_results` dict, so they override `mutate` directly:\n\n```\nclass AddSibling(SharedResultMutation):\n class Arguments:\n node1 = graphene.String(required=True)\n node2 = graphene.String(required=True)\n\n ok = graphene.Boolean()\n\n @staticmethod\n def mutate(root: None, info: graphene.ResolveInfo, shared_results: dict, node1: str, node2: str): # ISSUE: this breaks type awareness\n node1_ : ChildType = shared_results.get(node1)\n node2_ : ChildType = shared_results.get(node2)\n # do stuff\n return AddSibling(ok=True)\n```\n\nAnd that's basically it (the rest is common Graphene boilerplate and test mocks). We can now execute a query like:\n\n```\nmutation ($parent: ParentInput, $child1: ChildInput, $child2: ChildInput) {\n n1: upsertParent(data: $parent) {\n pk\n name\n }\n\n n2: upsertChild(data: $child1) {\n pk\n name\n }\n\n n3: upsertChild(data: $child2) {\n pk\n name\n }\n\n e1: setParent(parent: \"n1\", child: \"n2\") { ok }\n\n e2: setParent(parent: \"n1\", child: \"n3\") { ok }\n\n e3: addSibling(node1: \"n2\", node2: \"n3\") { ok }\n}\n```\n\nThe issue with this is that the edge-like mutation arguments do not satisfy the *type awareness* that GraphQL promotes: in the GraphQL spirit, `node1` and `node2` should be typed `graphene.Field(ChildType)`, instead of `graphene.String()` as in this implementation. **EDIT** Added basic type checking for edge-like mutation input nodes.\n\n### **EDIT 2: nesting creations**\n\nFor comparison, I also implemented a nesting pattern where only creations are resolved (it the only case where we cannot have the data in previous query), one-file program available on Github.\n\nIt is classic Graphene, except for the mutation `UpsertChild` were we add field to solve nested creations *and* their resolvers:\n\n```\nclass UpsertChild(graphene.Mutation, ChildType):\n class Arguments:\n data = ChildInput()\n\n create_parent = graphene.Field(ParentType, data=graphene.Argument(ParentInput))\n create_sibling = graphene.Field(ParentType, data=graphene.Argument(lambda: ChildInput))\n\n @staticmethod\n def mutate(_: None, __: graphene.ResolveInfo, data: ChildInput):\n return Child(\n pk=data.pk\n ,name=data.name\n ,parent=FakeParentDB.get(data.parent)\n ,siblings=[FakeChildDB[pk] for pk in data.siblings or []]\n ) # So the quantity of extra *stuff* is small compared to to the node+edge pattern. We can now execute a query like:\n\n```\nmutation ($parent: ParentInput, $child1: ChildInput, $child2: ChildInput) {\n n1: upsertChild(data: $child1) {\n pk\n name\n siblings { pk name }\n\n parent: createParent(data: $parent) { pk name }\n\n newSibling: createSibling(data: $child2) { pk name }\n }\n}\n```\n\nHowever, we can see that, in contrast to what was possible with the node+edge pattern,(shared_result_mutation.py) we cannot set the parent of the new sibling in the same mutation. The obvious reason is that we don't have its data (its pk in particular). The other reason is because order is not guaranteed for nested mutations. So cannot create, for example, a data-less mutation `assignParentToSiblings` that would set the parent of all siblings of the current *root* child, because the nested sibling may be created before the nested parent.\n\nIn some practical cases though, we just need to create a new object and\nand then link it to an exiting object. Nesting can satisfy these use cases.\n\nThere was a suggestion in the question's comments to use *nested data* for mutations. This actually was my first implementation of the feature, and I abandoned it because of security concerns. The permission checks use decorators and look like (I don't really have Book mutations):\n\n```\nclass UpsertBook(common.mutations.MutationMixin, graphene.Mutation, types.Book):\n class Arguments:\n data = types.BookInput()\n\n @staticmethod\n @authorize.grant(authorize.admin, authorize.owner, model=models.Book)\n def mutate(_, info: ResolveInfo, data: types.BookInput) -> 'UpsertBook':\n return UpsertBook(**data) # I don't think I should also make this check in another place, inside another mutation with nested data for example. Also, calling this method in another mutation would requires imports between mutation modules, which I don't think is a good idea. I really thought the solution should rely on GraphQL resolution capabilities, that's why I looked into nested mutations, which led me to ask the question of this post in the first place.\n\nAlso, I made more tests of the uuid idea from the question (with a unittest Tescase). It turns out that quick successive calls of python uuid.uuid4 can collide, so this option is discarded to me.\n\n========================================\n\nCode:\n```text\nmutation {\n createUser(uid: \"b53a20f1b81b439\", username: \"new user\", password: \"secret\"){\n uid\n username\n }\n\n updateGroup(gid: \"group id\", userIds: [\"b53a20f1b81b439\", ...]){\n gid\n name\n }\n}\n```\n\n```text\nquery {\n uuid\n\n group (gid: \"group id\") {\n gid\n name\n }\n}\n```\n\n```text\ncreateUser\n```\n\n```text\nupdateGroup\n```\n\n```text\nupdateGroup\n```\n\n```text\nb53a20f1b81b439\n```\n\n```text\nuuid.uuid4\n```\n\n```sh\npip install graphene-chain-mutation\n```\n\n```py\nimport graphene\n from graphene_chain_mutation import ShareResult\n from .types import ParentType, ParentInput, ChildType, ChildInput\n\n class CreateParent(ShareResult, graphene.Mutation, ParentType):\n class Arguments:\n data = ParentInput()\n\n @staticmethod\n def mutate(_: None, __: graphene.ResolveInfo,\n data: ParentInput = None) -> 'CreateParent':\n return CreateParent(**data.__dict__)\n\n class CreateChild(ShareResult, graphene.Mutation, ChildType):\n class Arguments:\n data = ChildInput()\n\n @staticmethod\n def mutate(_: None, __: graphene.ResolveInfo,\n data: ChildInput = None) -> 'CreateChild':\n return CreateChild(**data.__dict__)\n```\n\n```py\nimport graphene\n from graphene_chain_mutation import ParentChildEdgeMutation, SiblingEdgeMutation\n from .types import ParentType, ChildType\n from .fake_models import FakeChildDB\n\n class SetParent(ParentChildEdgeMutation):\n\n parent_type = ParentType\n child_type = ChildType\n\n @classmethod\n def set_link(cls, parent: ParentType, child: ChildType):\n FakeChildDB[child.pk].parent = parent.pk\n\n class AddSibling(SiblingEdgeMutation):\n\n node1_type = ChildType\n node2_type = ChildType\n\n @classmethod\n def set_link(cls, node1: ChildType, node2: ChildType):\n FakeChildDB[node1.pk].siblings.append(node2.pk)\n FakeChildDB[node2.pk].siblings.append(node1.pk)\n```\n\n```py\nclass Query(graphene.ObjectType):\n parent = graphene.Field(ParentType, pk=graphene.Int())\n parents = graphene.List(ParentType)\n child = graphene.Field(ChildType, pk=graphene.Int())\n children = graphene.List(ChildType)\n\n class Mutation(graphene.ObjectType):\n create_parent = CreateParent.Field()\n create_child = CreateChild.Field()\n set_parent = SetParent.Field()\n add_sibling = AddSibling.Field()\n\n schema = graphene.Schema(query=Query, mutation=Mutation)\n```\n\n```py\nresult = schema.execute(\n GRAPHQL_MUTATION\n ,variables = VARIABLES\n ,middleware=[ShareResultMiddleware()]\n )\n```\n\n```py\nGRAPHQL_MUTATION = \"\"\"\nmutation ($parent: ParentInput, $child1: ChildInput, $child2: ChildInput) {\n n1: upsertParent(data: $parent) {\n pk\n name\n }\n\n n2: upsertChild(data: $child1) {\n pk\n name\n }\n\n n3: upsertChild(data: $child2) {\n pk\n name\n }\n\n e1: setParent(parent: \"n1\", child: \"n2\") { ok }\n\n e2: setParent(parent: \"n1\", child: \"n3\") { ok }\n\n e3: addSibling(node1: \"n2\", node2: \"n3\") { ok }\n}\n\"\"\"\n\nVARIABLES = dict(\n parent = dict(\n name = \"Emilie\"\n )\n ,child1 = dict(\n name = \"John\"\n )\n ,child2 = dict(\n name = \"Julie\"\n )\n)\n```\n\n```text\nShareResult\n```\n\n```text\ngraphene.Muation\n```\n\n```text\nParentChildEdgeMutation\n```\n\n```text\nSiblingEdgeMutation\n```\n\n```text\nset_link\n```\n\n```text\nShareResultMiddleware\n```\n\n```text\nGRAPHQL_MUTATION\n```\n\n```text\ndigraph D {\n\n /* Nodes */\n A \n B\n C\n\n /* Edges */\n\n A -> B\n A -> C\n A -> D\n\n}\n```\n\n```text\nmutation {\n\n # Nodes\n\n n1: createUser(username: \"new user\", password: \"secret\"){\n uid\n username\n }\n\n n2: updateGroup(gid: \"group id\"){\n gid\n name\n }\n\n # Edges\n\n addUserToGroup(user: \"n1\", group: \"n2\"){\n status\n }\n}\n```\n\n```py\nclass ShareResultMiddleware:\n\n shared_results = {}\n\n def resolve(self, next, root, info, **args):\n return next(root, info, shared_results=self.shared_results, **args)\n```\n\n```py\nclass SharedResultMutation(graphene.Mutation):\n\n @classmethod\n def mutate(cls, root: None, info: graphene.ResolveInfo, shared_results: dict, *args, **kwargs):\n result = cls.mutate_and_share_result(root, info, *args, **kwargs)\n if root is None:\n node = info.path[0]\n shared_results[node] = result\n return result\n\n @staticmethod\n def mutate_and_share_result(*_, **__):\n return SharedResultMutation() # override\n```\n\n```py\nclass UpsertParent(SharedResultMutation, ParentType):\n class Arguments:\n data = ParentInput()\n\n @staticmethod\n def mutate_and_share_result(root: None, info: graphene.ResolveInfo, data: ParentInput, *___, **____):\n return UpsertParent(id=1, name=\"test\") # <-- example\n```\n\n```py\nclass AddSibling(SharedResultMutation):\n class Arguments:\n node1 = graphene.String(required=True)\n node2 = graphene.String(required=True)\n\n ok = graphene.Boolean()\n\n @staticmethod\n def mutate(root: None, info: graphene.ResolveInfo, shared_results: dict, node1: str, node2: str): # ISSUE: this breaks type awareness\n node1_ : ChildType = shared_results.get(node1)\n node2_ : ChildType = shared_results.get(node2)\n # do stuff\n return AddSibling(ok=True)\n```\n\n```text\nmutation ($parent: ParentInput, $child1: ChildInput, $child2: ChildInput) {\n n1: upsertParent(data: $parent) {\n pk\n name\n }\n\n n2: upsertChild(data: $child1) {\n pk\n name\n }\n\n n3: upsertChild(data: $child2) {\n pk\n name\n }\n\n e1: setParent(parent: \"n1\", child: \"n2\") { ok }\n\n e2: setParent(parent: \"n1\", child: \"n3\") { ok }\n\n e3: addSibling(node1: \"n2\", node2: \"n3\") { ok }\n}\n```\n\n```py\nclass UpsertChild(graphene.Mutation, ChildType):\n class Arguments:\n data = ChildInput()\n\n create_parent = graphene.Field(ParentType, data=graphene.Argument(ParentInput))\n create_sibling = graphene.Field(ParentType, data=graphene.Argument(lambda: ChildInput))\n\n @staticmethod\n def mutate(_: None, __: graphene.ResolveInfo, data: ChildInput):\n return Child(\n pk=data.pk\n ,name=data.name\n ,parent=FakeParentDB.get(data.parent)\n ,siblings=[FakeChildDB[pk] for pk in data.siblings or []]\n ) # <-- example\n\n @staticmethod\n def resolve_create_parent(child: Child, __: graphene.ResolveInfo, data: ParentInput):\n parent = UpsertParent.mutate(None, __, data)\n child.parent = parent.pk\n return parent\n\n @staticmethod\n def resolve_create_sibling(node1: Child, __: graphene.ResolveInfo, data: 'ChildInput'):\n node2 = UpsertChild.mutate(None, __, data)\n node1.siblings.append(node2.pk)\n node2.siblings.append(node1.pk)\n return node2\n```\n\n```text\nmutation ($parent: ParentInput, $child1: ChildInput, $child2: ChildInput) {\n n1: upsertChild(data: $child1) {\n pk\n name\n siblings { pk name }\n\n parent: createParent(data: $parent) { pk name }\n\n newSibling: createSibling(data: $child2) { pk name }\n }\n}\n```\n\n```py\nclass UpsertBook(common.mutations.MutationMixin, graphene.Mutation, types.Book):\n class Arguments:\n data = types.BookInput()\n\n @staticmethod\n @authorize.grant(authorize.admin, authorize.owner, model=models.Book)\n def mutate(_, info: ResolveInfo, data: types.BookInput) -> 'UpsertBook':\n return UpsertBook(**data) # <-- example\n```\n\n```text\naddUserToGroup\n```\n\n```text\naddUserToGroup\n```\n\n```text\ndict\n```\n\n```text\nkwarg\n```\n\n```text\nSharedResultMutation\n```\n\n```text\nMutation\n```\n\n```text\nmutate_and_share_result\n```\n\n```text\nmutate\n```\n\n```text\nshared_results\n```\n\n```text\nmutate\n```\n\n```text\nnode1\n```\n\n```text\nnode2\n```\n\n```text\ngraphene.Field(ChildType)\n```\n\n```text\ngraphene.String()\n```\n\n```text\nUpsertChild\n```\n\n```text\nassignParentToSiblings\n```\n\n========================================\n\nComments:\n- you have root mutations then order is guaranteed ... `const updateBook = (book, authorId) => {` gives a hint how to get id of the same args (used to creation)\n- @xadm do you mean getting the uuid in a previous query and using it in the mutations is ok, and because order is guaranteed I get the expected result ? (One of my main concerns is to know if it is fine to use a uui previously queried from the server, another is to know if Graphene (backend) offers an alternative)\n- `createUser(username=\"new user\", password=\"secret\"){..` ... `updateGroup(gid=\"group id\", username=\"new user\", password=\"secret\"){` ... second resolver can find inserted id by find using (username, password) ... you don't need to expose/use internals (uid) at all ... in this place\n- @xadm indeed some data will have intrinsic identifiers (User with email, Book with ISBN...), but other data might not have such functional unique keys. In an application, I have a Degree entity for example, and I don't think it has a field, expect an ID, that guarantees to retrieve a specific instance... maybe I should have found a better use case :)\n- nested data for mutation? insert inside insert/update mutation ... stackoverflow.com/a/61273760/6124657\n- I actually had* a first version with mutations including nested data to mutate related data. I abandoned that because it caused security issues (permission checks normally done on (root-)mutations would either be duplicated or not done). Maybe it was just bad coding of mine, I'll think about it again, thanks @xadm\n- PS: the solution to my security issue were to use nested mutations, so the mutation of related data would go through the process of resolving, thus permission checks. And... that led me to the question of this post :D\n- stackoverflow.com/a/49320606/6124657 ... and similar ... if you need to use result, use it in a separate query .... however you can try/check if you can pass data by context between mutations/resolvers .... duplicated permision checks ... resuse them (functions/annotations/etc.)?\n- @xadm was the first to suggest injecting mutation results in the context. I took inspiration from this to think a node+edge proposal\n- still only for root level mutations (guaranteed order), not deeper/nested (not preserving order) ?\n- @xadm yes, only for root mutations. The idea is to use only root mutations, as only them are guaranteed to be sequential, and yet being able to use the result of one such root mutation in another root mutation to mutate *\"edges\"*, links between the entities. -Edit: the initial question actually *\"how to chain mutations\"* (it wasn't really about nesting)\n- @xadm I wasn't sure I understood your question correctly, so I just tested referencing the result of a root mutation in nested mutation (using a resolver) and it works. I updated the Readme on Github and Pypi.\n- question was about non-root, between two sibbling nested mutations - use case from 'bad practice' link\n- @xadm I didn't tested that, but I guess you can, under the condition that you use resolvers and let them have the `shared_results` parameter. The initial issue remains though, nested operations have no guarantee of order. One would need to add the results of the nested operations in the sharing dict. A custom decorator can help automate that.","metadata":{"transformedAt":"2026-08-18T18:32:36.094Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":704,"estimatedTokens":5473}}947{"id":"stack-62457267","source":"stackoverflow","questionId":62457267,"title":"Remove all items in table with Prisma2 and Jest","tags":["node.js","graphql","prisma","prisma-graphql","prisma2"],"text":"Title: Remove all items in table with Prisma2 and Jest\nTags: node.js, graphql, prisma, prisma-graphql, prisma2\nSource: Stack Overflow\n\nQuestion:\nI would like to know how can I remove all items in table with Prisma2 and Jest ?\n\nI read the CRUD documentation and I try with this :\n\nuser.test.js\n\n```\n....\nimport { PrismaClient } from \"@prisma/client\"\n\nbeforeEach(async () => {\n const prisma = new PrismaClient()\n await prisma.user.deleteMany({})\n})\n...\n```\n\nBut I have an error :\n\n```\nInvalid `prisma.user.deleteMany()` invocation:\nThe change you are trying to make would violate the required relation 'PostToUser' between the `Post` and `User` models.\n```\n\nMy Database\n\n```\nCREATE TABLE User (\n id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,\n name VARCHAR(255),\n email VARCHAR(255) UNIQUE NOT NULL,\n password VARCHAR(255) NOT NULL\n);\n\nCREATE TABLE Post (\n id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,\n title VARCHAR(255) NOT NULL,\n createdAt TIMESTAMP NOT NULL DEFAULT now(),\n content TEXT,\n published BOOLEAN NOT NULL DEFAULT false,\n fk_user_id INTEGER NOT NULL,\n CONSTRAINT `fk_user_id` FOREIGN KEY (fk_user_id) REFERENCES User(id) ON DELETE CASCADE\n);\n```\n\nschema.prisma\n\n```\nmodel Post {\n content String?\n createdAt DateTime @default(now())\n fk_user_id Int\n id Int @default(autoincrement()) @id\n published Boolean @default(false)\n title String\n author User @relation(fields: [fk_user_id], references: [id])\n\n @@index([fk_user_id], name: \"fk_user_id\")\n}\n\nmodel User {\n email String @unique\n id Int @default(autoincrement()) @id\n name String?\n password String @default(\"\")\n Post Post[]\n Profile Profile?\n}\n```\n\n========================================\n\nTop Answer:\nAlternative solution:\n\nI found a guide from a medium article. But here's the code I'm using based from that article the only difference is the table names are dynamic.\n\nIt works well if you set cascade deletes on the tables properly. Either way, you can use the one from the article or maybe turn off foreign key checks instead\n\nYou can also create a separate function `truncateTable` and pass a table name or prisma model. Or maybe pass an array of tablenames to `refreshDatabase` instead.\n\n\r\n\r\n\n```\nimport prisma from .....\nimport {Prisma} from \".prisma/client\";\n\nconst tableNames = Object.values(Prisma.ModelName);\n\nexport default async function refreshDatabase() {\n for (const tableName of tableNames) {\n await prisma.$queryRawUnsafe(`TRUNCATE TABLE \"${tableName}\" RESTART IDENTITY CASCADE`)\n }\n}\n```\n\n========================================\n\nCode:\n```text\n....\nimport { PrismaClient } from \"@prisma/client\"\n\nbeforeEach(async () => {\n const prisma = new PrismaClient()\n await prisma.user.deleteMany({})\n})\n...\n```\n\n```text\nInvalid `prisma.user.deleteMany()` invocation:\nThe change you are trying to make would violate the required relation 'PostToUser' between the `Post` and `User` models.\n```\n\n```text\nCREATE TABLE User (\n id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,\n name VARCHAR(255),\n email VARCHAR(255) UNIQUE NOT NULL,\n password VARCHAR(255) NOT NULL\n);\n\nCREATE TABLE Post (\n id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,\n title VARCHAR(255) NOT NULL,\n createdAt TIMESTAMP NOT NULL DEFAULT now(),\n content TEXT,\n published BOOLEAN NOT NULL DEFAULT false,\n fk_user_id INTEGER NOT NULL,\n CONSTRAINT `fk_user_id` FOREIGN KEY (fk_user_id) REFERENCES User(id) ON DELETE CASCADE\n);\n```\n\n```text\nmodel Post {\n content String?\n createdAt DateTime @default(now())\n fk_user_id Int\n id Int @default(autoincrement()) @id\n published Boolean @default(false)\n title String\n author User @relation(fields: [fk_user_id], references: [id])\n\n @@index([fk_user_id], name: \"fk_user_id\")\n}\n\nmodel User {\n email String @unique\n id Int @default(autoincrement()) @id\n name String?\n password String @default(\"\")\n Post Post[]\n Profile Profile?\n}\n```\n\n```text\nbeforeEach(async () => {\n const prisma = new PrismaClient()\n await prisma.post.deleteMany({where: {...}}) //delete posts first\n await prisma.user.deleteMany({})\n})\n```\n\n```text\nPost\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nPosts\n```\n\n```text\nprisma.$executeRaw(`TRUNCATE TABLE \"${table}\" RESTART IDENTITY CASCADE;`)\n```\n\n```js\nimport prisma from .....\nimport {Prisma} from \".prisma/client\";\n\nconst tableNames = Object.values(Prisma.ModelName);\n\nexport default async function refreshDatabase() {\n for (const tableName of tableNames) {\n await prisma.$queryRawUnsafe(`TRUNCATE TABLE \"${tableName}\" RESTART IDENTITY CASCADE`)\n }\n}\n```\n\n```text\ntruncateTable\n```\n\n```text\nrefreshDatabase\n```\n\n========================================\n\nComments:\n- Thank you for your answer ! It's a bug with Prisma 2 github.com/prisma/prisma/issues/2810","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":216,"estimatedTokens":1191}}948{"id":"stack-58431224","source":"stackoverflow","questionId":58431224,"title":"How does Apollo-Client GraphQL refetchQueries works?","tags":["reactjs","graphql","apollo-client"],"text":"Title: How does Apollo-Client GraphQL refetchQueries works?\nTags: reactjs, graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nAny idea how do we get the response data from `refetchQueries`? I got the query response data from mutation.\n\n### Mutation\n\n```\nimport { gql } from 'apollo-boost';\n\nexport const DONE_TASK = gql`\n mutation DoneTask($taskId: ID!) {\n doneTask(input: {\n taskId: $taskId\n }) {\n task {\n id\n status\n }\n }\n }\n`;\n```\n\n### Query\n\n```\nimport { gql } from 'apollo-boost';\n\nexport const GET_TASKS_BY_STATUS = gql`\n query GetTasksByStatus($status: String!) {\n getTasksByStatus(status: $status) {\n edges {\n node {\n id\n status\n description\n }\n }\n }\n }\n`;\n```\n\n### Usage\n\n```\nconst response = await client.mutate({\n mutation: DONE_TASK,\n variables: {\n taskId: 1\n },\n refetchQueries: () => [{\n query: GET_TASKS_BY_STATUS,\n variables: { \n status: \"OPEN\"\n },\n }]\n});\n\nconsole.log(response);\n```\n\nOutput\n\n```\ndata: {\n doneTask: {\n task: { id: 1, status: 'DONE'}\n }\n}\n```\n\nBut I expect a response data from `GET_TASKS_BY_STATUS`. \n\nπ€ π\n\n========================================\n\nCode:\n```text\nimport { gql } from 'apollo-boost';\n\nexport const DONE_TASK = gql`\n mutation DoneTask($taskId: ID!) {\n doneTask(input: {\n taskId: $taskId\n }) {\n task {\n id\n status\n }\n }\n }\n`;\n```\n\n```text\nimport { gql } from 'apollo-boost';\n\nexport const GET_TASKS_BY_STATUS = gql`\n query GetTasksByStatus($status: String!) {\n getTasksByStatus(status: $status) {\n edges {\n node {\n id\n status\n description\n }\n }\n }\n }\n`;\n```\n\n```text\nconst response = await client.mutate({\n mutation: DONE_TASK,\n variables: {\n taskId: 1\n },\n refetchQueries: () => [{\n query: GET_TASKS_BY_STATUS,\n variables: { \n status: \"OPEN\"\n },\n }]\n});\n\nconsole.log(response);\n```\n\n```text\ndata: {\n doneTask: {\n task: { id: 1, status: 'DONE'}\n }\n}\n```\n\n```text\nrefetchQueries\n```\n\n```text\nGET_TASKS_BY_STATUS\n```\n\n```text\nconst { data } = useQuery(GET_TASKS_BY_STATUS, { variables: { status: 'OPEN' } })\nconst [mutate] = useMutation(DONE_TASK,{\n variables: {\n taskId: 1,\n },\n refetchQueries: () => [{\n query: GET_TASKS_BY_STATUS,\n variables: { \n status: 'OPEN',\n },\n }],\n})\n```\n\n```text\nrefetchQueries\n```\n\n```text\nuseQuery\n```\n\n```text\nQuery\n```\n\n```text\ngraphql\n```\n\n========================================\n\nComments:\n- Oh thanks for enlightenment, This is why there is no changes because the `client.query(GET_TASKS_BY_STATUS)` is placed in a different component.\n- @Roel As an aside, you should avoid using `client.query` unless you need to fetch a query exactly once. If you need the query data to update when the cache updates, use `useQuery`, the `Query` component or the `graphql` HOC as indicated in the answer.\n- I am still in development state. At my local, I use refetchQueries. So every time I add or update, my list is refetch again. My question is that on production, other user will see the latest record that another user added. I though that in memory cache is at the client side. So how the other user will get the late record.\n- @AlexAung did you remember how you fixed that? I'm facing exactly the same issue\n- Adding my two cents: for managed class-based components, one can use `fetchPolicy: 'network-only'` for direct server queries using `client.query`. The cache will be updated accordingly. This is most appropriate for *managed* situations (not for hooks). :)","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":189,"estimatedTokens":914}}949{"id":"stack-33235109","source":"stackoverflow","questionId":33235109,"title":"Is there way to use Relay without GraphQL?","tags":["reactjs","graphql","relayjs"],"text":"Title: Is there way to use Relay without GraphQL?\nTags: reactjs, graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nI'm trying Relay in my React application, and it uses GraphQL by default. It looks like this (`Score` is some React.js component):\n\n```\nScore = Relay.createContainer(Score, {\n fragments: {\n score: () => Relay.QL`\n fragment on Score {\n initials,\n score,\n }\n `,\n },\n});\n```\n\nThe question is: can I use custom API functions to return data into fragments? Like this:\n\n```\nScore = Relay.createContainer(Score, {\n fragments: {\n score: myCustomFunction(), // It will return a dataset.\n },\n});\n```\n\n========================================\n\nCode:\n```text\nScore = Relay.createContainer(Score, {\n fragments: {\n score: () => Relay.QL`\n fragment on Score {\n initials,\n score,\n }\n `,\n },\n});\n```\n\n```text\nScore = Relay.createContainer(Score, {\n fragments: {\n score: myCustomFunction(), // It will return a dataset.\n },\n});\n```\n\n```text\nScore\n```\n\n========================================\n\nComments:\n- Thank you for your answer! I thought there is too much complexity and redundant flexibility so I chose another way: creating a simple wrapper over React components by myself.","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":62,"estimatedTokens":316}}950{"id":"stack-60801861","source":"stackoverflow","questionId":60801861,"title":"GraphQL Mutation in Graphene for Object with Foreign Key Relation","tags":["python","django","graphql","graphene-django"],"text":"Title: GraphQL Mutation in Graphene for Object with Foreign Key Relation\nTags: python, django, graphql, graphene-django\nSource: Stack Overflow\n\nQuestion:\nI'm building a simple CRUD interface with Python, GraphQL (graphene-django) and Django. The CREATE mutation for an Object (`Ingredient`) that includes Foreign Key relations to another Object (`Category`) won't work. I want to give GraphQL the id of the CategoryObject and not a whole category instance. Then in the backend it should draw the relation to the Category object.\n\nIn the Django model the Ingredient Object contains an instance of the Foreign key Category Object (see code below). Is the whole Category Object needed here to draw the relation and to use `Ingredient.objects.select_related('category').all()`?\n\nThe create mutation expects `IngredientInput` that includes all properties and an integer field for the foreign key relation. So the graphQL mutation itself currently works as I want it to.\n\nMy question is similar if not the same as this one but these answers don't help me.\n\n**models.py:**\n\n```\nclass Category(models.Model):\n name = models.CharField(max_length=50, unique=True)\n notes = models.TextField()\n\n class Meta:\n verbose_name = u\"Category\"\n verbose_name_plural = u\"Categories\"\n ordering = (\"id\",)\n\n def __str__(self):\n return self.name\n\nclass Ingredient(models.Model):\n name = models.CharField(max_length=100)\n notes = models.TextField()\n category = models.ForeignKey(Category, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = u\"Ingredient\"\n verbose_name_plural = u\"Ingredients\"\n ordering = (\"id\",)\n\n def __str__(self):\n return self.name\n```\n\n**schema.py:**\n\n```\nclass CategoryType(DjangoObjectType):\n class Meta:\n model = Category\n\nclass CategoryInput(graphene.InputObjectType):\n name = graphene.String(required=True)\n notes = graphene.String()\n\nclass IngredientType(DjangoObjectType):\n class Meta:\n model = Ingredient\n\nclass IngredientInput(graphene.InputObjectType):\n name = graphene.String(required=True)\n notes = graphene.String()\n category = graphene.Int()\n\nclass CreateIngredient(graphene.Mutation):\n class Arguments:\n ingredientData = IngredientInput(required=True)\n\n ingredient = graphene.Field(IngredientType)\n\n @staticmethod\n def mutate(root, info, ingredientData):\n _ingredient = Ingredient.objects.create(**ingredientData)\n return CreateIngredient(ingredient=_ingredient)\n\nclass Mutation(graphene.ObjectType):\n create_category = CreateCategory.Field()\n create_ingredient = CreateIngredient.Field()\n```\n\n**graphql_query:**\n\n```\nmutation createIngredient($ingredientData: IngredientInput!) {\n createIngredient(ingredientData: $ingredientData) {\n ingredient {\n id\n name\n notes\n category{name}\n }\n```\n\n**graphql-variables:**\n\n```\n{\n \"ingredientData\": {\n \"name\": \"milk\",\n \"notes\": \"from cow\",\n \"category\": 8 # here I ant to insert the id of an existing category object\n }\n}\n```\n\n**error-message after executoin the query:**\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Cannot assign \\\"8\\\": \\\"Ingredient.category\\\" must be a \\\"Category\\\" instance.\",\n \"locations\": [\n {\n \"line\": 38,\n \"column\": 3\n }\n ],\n \"path\": [\n \"createIngredient\"\n ]\n }\n ],\n \"data\": {\n \"createIngredient\": null\n }\n}\n```\n\n========================================\n\nCode:\n```text\nclass Category(models.Model):\n name = models.CharField(max_length=50, unique=True)\n notes = models.TextField()\n\n class Meta:\n verbose_name = u\"Category\"\n verbose_name_plural = u\"Categories\"\n ordering = (\"id\",)\n\n def __str__(self):\n return self.name\n\n\nclass Ingredient(models.Model):\n name = models.CharField(max_length=100)\n notes = models.TextField()\n category = models.ForeignKey(Category, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = u\"Ingredient\"\n verbose_name_plural = u\"Ingredients\"\n ordering = (\"id\",)\n\n def __str__(self):\n return self.name\n```\n\n```text\nclass CategoryType(DjangoObjectType):\n class Meta:\n model = Category\n\n\nclass CategoryInput(graphene.InputObjectType):\n name = graphene.String(required=True)\n notes = graphene.String()\n\n\nclass IngredientType(DjangoObjectType):\n class Meta:\n model = Ingredient\n\n\nclass IngredientInput(graphene.InputObjectType):\n name = graphene.String(required=True)\n notes = graphene.String()\n category = graphene.Int()\n\n\nclass CreateIngredient(graphene.Mutation):\n class Arguments:\n ingredientData = IngredientInput(required=True)\n\n ingredient = graphene.Field(IngredientType)\n\n @staticmethod\n def mutate(root, info, ingredientData):\n _ingredient = Ingredient.objects.create(**ingredientData)\n return CreateIngredient(ingredient=_ingredient)\n\n\nclass Mutation(graphene.ObjectType):\n create_category = CreateCategory.Field()\n create_ingredient = CreateIngredient.Field()\n```\n\n```text\nmutation createIngredient($ingredientData: IngredientInput!) {\n createIngredient(ingredientData: $ingredientData) {\n ingredient {\n id\n name\n notes\n category{name}\n }\n```\n\n```text\n{\n \"ingredientData\": {\n \"name\": \"milk\",\n \"notes\": \"from cow\",\n \"category\": 8 # here I ant to insert the id of an existing category object\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Cannot assign \\\"8\\\": \\\"Ingredient.category\\\" must be a \\\"Category\\\" instance.\",\n \"locations\": [\n {\n \"line\": 38,\n \"column\": 3\n }\n ],\n \"path\": [\n \"createIngredient\"\n ]\n }\n ],\n \"data\": {\n \"createIngredient\": null\n }\n}\n```\n\n```text\nIngredient\n```\n\n```text\nCategory\n```\n\n```text\nIngredient.objects.select_related('category').all()\n```\n\n```text\nIngredientInput\n```\n\n```text\n_ingredient = Ingredient.objects.create(name=\"milk\", notes=\"from_cow\", category=8)\n```\n\n```text\ncategory_obj = Category.objects.get(id=8)\n_ingredient = Ingredient.objects.create(name=\"milk\", notes=\"from_cow\", category=category_obj)\n```\n\n```text\n_ingredient = Ingredient.objects.create(name=\"milk\", notes=\"from_cow\", category_id=8)\n```\n\n```text\nclass IngredientInput(graphene.InputObjectType):\n name = graphene.String(required=True)\n notes = graphene.String()\n category_id = graphene.Int()\n```\n\n```text\ncategory_id = graphene.Int(name=\"category\")\n```\n\n```text\nCannot assign \\\"8\\\": \\\"Ingredient.category\\\" must be a \\\"Category\\\" instance.\n```\n\n```text\n_id\n```\n\n```text\nInputObjectType\n```\n\n```text\ncategoryId\n```\n\n```text\ncategory\n```\n\n========================================\n\nComments:\n- Thanks for that very helpful and detailed answer!!\n- This is EXACTLY what I was looking for! I hope this is best practice though!","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":305,"estimatedTokens":1652}}951{"id":"stack-42781043","source":"stackoverflow","questionId":42781043,"title":"Clearing Node.js' cache when loading non-js files e.g. graphql language defenitions","tags":["node.js","babeljs","graphql"],"text":"Title: Clearing Node.js' cache when loading non-js files e.g. graphql language defenitions\nTags: node.js, babeljs, graphql\nSource: Stack Overflow\n\nQuestion:\nI want to clear Node's cache from my `graphql` defintions but nothing happens until I make a change to the file where the `require('my.graphql')` statement is. I think this question relates to this one and I've tried to do:\n\n```\nObject.keys(require.cache).forEach(function(key) {\n delete require.cache[key];\n});\n```\n\nBut it doesn't reload the code. There must be some other caching that is going on that I miss.\n\nSince the example would be a little long, I've forked this repo and created a graphql-branch that you can install and test adapting the `src/schema.graphql` file:\n\n```\ngit clone git@github.com:gforge/graphql-relay-mongodb-pagination.git\ncd graphql-relay-mongodb-pagination\ngit checkout git checkout mongoose-w-gql-lang \nnpm install\n```\n\nThe `require('my.graphql')` is mediated via babel-plugin-inline-import.\n\n========================================\n\nTop Answer:\nThe babel docs suggest \n\n```\nBABEL_CACHE_PATH=/foo/my-cache.json babel-node script.js # default in /tmp/\nBABEL_DISABLE_CACHE=1 babel-node script.js\nrequire('babel-register')({ cache: false });\n```\n\n- https://babeljs.io/docs/usage/babel-register/\n\nBut this doesn't work on Windows 7 when debugging in IntelliJ. After much googling I found where it really lives\n\n```\nC:\\Users\\username\\.babel.json\n%USERPROFILE%\\.babel.json \n$USERPROFILE/.babel.json # cygwin\n```\n\n- https://github.com/babel/babel/issues/1148\n\nYou can add a script to your package.json to do this for you\n\n```\n{\n \"scripts\": {\n \"clean\": \"del %USERPROFILE%/.babel.json\",\n \"clean\": \"bash -c 'rm -vf $USERPROFILE/.babel.json'\"\n }\n}\n```\n\nIf you are using webpack you can dynamically inject a cacheDirectory: parameter into .babelrc file for easier deletion\n\nbabel-node throws an error if you add it directly to the file\n\nwebpack.config.js\n\n```\nconst _ = require('lodash');\nconst JSON5 = require('json5');\n\nconst babelrc = _.extend(\n // WARNING: ./.babel-cache/ may occasionally get corrupted and need \"npm run clean\"\n // POSITIVE: ./.babel-cache/ provides a ~30% speed increase in recompile times\n { cacheDirectory: !argv.production && './.babel-cache' },\n JSON5.parse(fs.readFileSync('./.babelrc'))\n);\n```\n\n========================================\n\nCode:\n```text\nObject.keys(require.cache).forEach(function(key) {\n delete require.cache[key];\n});\n```\n\n```text\ngit clone git@github.com:gforge/graphql-relay-mongodb-pagination.git\ncd graphql-relay-mongodb-pagination\ngit checkout git checkout mongoose-w-gql-lang \nnpm install\n```\n\n```text\ngraphql\n```\n\n```text\nrequire('my.graphql')\n```\n\n```text\nsrc/schema.graphql\n```\n\n```text\nrequire('my.graphql')\n```\n\n```text\n...\n\"start\": \"babel-node ./src/index.js\",\n```\n\n```text\n...\n\"start\": \"BABEL_DISABLE_CACHE=1 babel-node ./src/index.js\",\n```\n\n```text\nBABEL_CACHE_PATH=/foo/my-cache.json babel-node script.js # default in /tmp/\nBABEL_DISABLE_CACHE=1 babel-node script.js\nrequire('babel-register')({ cache: false });\n```\n\n```text\nC:\\Users\\username\\.babel.json\n%USERPROFILE%\\.babel.json \n$USERPROFILE/.babel.json # cygwin\n```\n\n```text\n{\n \"scripts\": {\n \"clean\": \"del %USERPROFILE%/.babel.json\",\n \"clean\": \"bash -c 'rm -vf $USERPROFILE/.babel.json'\"\n }\n}\n```\n\n```text\nconst _ = require('lodash');\nconst JSON5 = require('json5');\n\nconst babelrc = _.extend(\n // WARNING: ./.babel-cache/ may occasionally get corrupted and need \"npm run clean\"\n // POSITIVE: ./.babel-cache/ provides a ~30% speed increase in recompile times\n { cacheDirectory: !argv.production && './.babel-cache' },\n JSON5.parse(fs.readFileSync('./.babelrc'))\n);\n```\n\n```sh\n$ rm -rf ./node_modules/.cache\n```\n\n========================================\n\nComments:\n- Why it returns `'BABEL_DISABLE_CACHE' is not recognized as an internal or external command`\n- R u using Linux? Windows probably requires a different syntax\n- I'm using Windows for development and Linux for production.\n- You should not use Babel node in production. The solution for windows is most likely to be different\n- ok, please guide me, how I run my `server.js` file in linux server, node can't understand `ES6` codes lile `import` or ``\n- you can see my `server.js` file in this repository: github.com/amerllica/simple-react-ssr-with-css-modules\n- Sorry, your setup is pretty different from mine. I suggest you create your own question and try to get an answer.\n- Thanks for your help, but I think using `babel-node` for production in some case like mine is necessary and a good approach.","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":168,"estimatedTokens":1148}}952{"id":"stack-78451117","source":"stackoverflow","questionId":78451117,"title":"graphql api fetching issue in next js getting ( Error: React functionality 'useContext' is not available in this environment. )","tags":["javascript","reactjs","next.js","graphql"],"text":"Title: graphql api fetching issue in next js getting ( Error: React functionality 'useContext' is not available in this environment. )\nTags: javascript, reactjs, next.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI have created a next js 14.2.3 app & I have graphql api end point(** which I replaced with localhost for stackOverflow )and I am using `\"@apollo/client\":\"^3.10.3\"`, `\"graphql\":\"^16.8.1\"`, for fetching data. I have created a product page path \"pages/products\".\n\n```\nimport { useQuery, gql } from \"@apollo/client\";\nimport { initializeApollo } from \"../lib/apollo-client\";\n\nconst PRODUCTS_QUERY = gql`\n query Products {\n products(first: 10, channel: \"default-channel\") {\n edges {\n node {\n id\n name\n }\n }\n }\n }\n`;\n\nfunction Products() {\n const apolloClient = initializeApollo();\n const { data, loading, error } = useQuery(PRODUCTS_QUERY, {\n client: apolloClient,\n });\n\n if (loading) return Loading...\n\n;\n if (error) return Error: {error.message}\n\n;\n\n return (\n \n \n\n### Products\n\n \n {data &&\n data.products.edges.map(({ node }) => (\n \n- {node.name}\n ))}\n \n \n );\n}\n\nexport default Products;\n```\n\nI have created a apollo-client,js file\n\n```\nimport { useMemo } from \"react\";\nimport { ApolloClient, HttpLink, InMemoryCache } from \"@apollo/client\";\n\nlet apolloClient;\n\nfunction createApolloClient() {\n return new ApolloClient({\n ssrMode: typeof window === \"undefined\",\n link: new HttpLink({\n uri: \"http://localhost:8000/graphql/\",\n }),\n cache: new InMemoryCache(),\n });\n}\n\nexport function initializeApollo(initialState = null) {\n const _apolloClient = apolloClient ?? createApolloClient();\n\n // If your page has Next.js data fetching methods that use Apollo Client, the initial\n state;\n // gets hydrated here\n if (initialState) {\n _apolloClient.cache.restore(initialState);\n }\n // For SSG and SSR always create a new Apollo Client\n if (typeof window === \"undefined\") return _apolloClient;\n // Create the Apollo Client once in the client\n if (!apolloClient) apolloClient = _apolloClient;\n\n return _apolloClient;\n}\n\nexport function useApollo(initialState) {\n const store = useMemo(() => initializeApollo(initialState), [initialState]);\n return store;\n}\n```\n\nso when I am routing http://localhost:3000/pages/products\n\ngetting error - https://i.sstatic.net/tC0aMaOy.png\n\n========================================\n\nTop Answer:\nRecently, I also came across with this error. I tried the first fix given by laroslav Sobolev but though I used \"use client\" on the top of the page, it was of no use, then I got to know the real reason of this error which was that the **provider of @apollo/client needs to be in the client environment.**\n\nHere is how to set up the Provider in client environment.\n\nFirst make a Provider.tsx file in the root or GraphQL folder.\n\n**provider.tsx**\n\n```\n\"use client\";\nimport React, { ReactNode } from \"react\";\nimport { ApolloClient, ApolloProvider, InMemoryCache } from \"@apollo/client\";\n\nexport const Provider = ({ children }: { children: ReactNode }) => {\n const client = new ApolloClient({\n uri: \"http://localhost:5050/graphql\",\n cache: new InMemoryCache(),\n });\n return {children};\n};\n```\n\nAnd now put this provider in the layout.tsx\n\n**layout.tsx**\n\n```\nimport type { Metadata } from \"next\";\nimport { Inter } from \"next/font/google\";\nimport \"./globals.css\";\nimport { Provider } from \"@/graphql/provider\";\n\nconst inter = Inter({ subsets: [\"latin\"] });\n\nexport const metadata: Metadata = {\n title: \"Create Next App\",\n description: \"Generated by create next app\",\n};\n\nexport default function RootLayout({\n children,\n}: Readonly) {\n return (\n \n \n {children}\n \n \n );\n}\n```\n\n========================================\n\nCode:\n```text\nimport { useQuery, gql } from \"@apollo/client\";\nimport { initializeApollo } from \"../lib/apollo-client\";\n\nconst PRODUCTS_QUERY = gql`\n query Products {\n products(first: 10, channel: \"default-channel\") {\n edges {\n node {\n id\n name\n }\n }\n }\n }\n`;\n\nfunction Products() {\n const apolloClient = initializeApollo();\n const { data, loading, error } = useQuery(PRODUCTS_QUERY, {\n client: apolloClient,\n });\n\n if (loading) return <p>Loading...</p>;\n if (error) return <p>Error: {error.message}</p>;\n\n return (\n <div>\n <h1>Products</h1>\n <ul>\n {data &&\n data.products.edges.map(({ node }) => (\n <li key={node.id}>{node.name}</li>\n ))}\n </ul>\n </div>\n );\n}\n\nexport default Products;\n```\n\n```text\nimport { useMemo } from \"react\";\nimport { ApolloClient, HttpLink, InMemoryCache } from \"@apollo/client\";\n\nlet apolloClient;\n\nfunction createApolloClient() {\n return new ApolloClient({\n ssrMode: typeof window === \"undefined\",\n link: new HttpLink({\n uri: \"http://localhost:8000/graphql/\",\n }),\n cache: new InMemoryCache(),\n });\n}\n\nexport function initializeApollo(initialState = null) {\n const _apolloClient = apolloClient ?? createApolloClient();\n\n // If your page has Next.js data fetching methods that use Apollo Client, the initial\n state;\n // gets hydrated here\n if (initialState) {\n _apolloClient.cache.restore(initialState);\n }\n // For SSG and SSR always create a new Apollo Client\n if (typeof window === \"undefined\") return _apolloClient;\n // Create the Apollo Client once in the client\n if (!apolloClient) apolloClient = _apolloClient;\n\n return _apolloClient;\n}\n\nexport function useApollo(initialState) {\n const store = useMemo(() => initializeApollo(initialState), [initialState]);\n return store;\n}\n```\n\n```text\n\"@apollo/client\":\"^3.10.3\"\n```\n\n```text\n\"graphql\":\"^16.8.1\"\n```\n\n```js\nimport { gql } from \"@apollo/client\";\nimport { initializeApollo } from \"../lib/apollo-client\";\n\nconst PRODUCTS_QUERY = gql`\n query Products {\n products(first: 10, channel: \"default-channel\") {\n edges {\n node {\n id\n name\n }\n }\n }\n }\n`;\n\nasync function Products() {\n const apolloClient = initializeApollo();\n const { data } = await apolloClient.query({\n query: PRODUCTS_QUERY,\n context: {},\n });\n\n return (\n <div>\n <h1>Products</h1>\n <ul>\n {data?.products?.edges?.map(({ node }) => (\n <li key={node.id}>{node.name}</li>\n ))}\n </ul>\n </div>\n );\n}\nexport default Products;\n```\n\n```text\n<Products />\n```\n\n```text\n\"use client\"\n```\n\n```text\npages/products\n```\n\n```text\n\"use client\";\nimport React, { ReactNode } from \"react\";\nimport { ApolloClient, ApolloProvider, InMemoryCache } from \"@apollo/client\";\n\nexport const Provider = ({ children }: { children: ReactNode }) => {\n const client = new ApolloClient({\n uri: \"http://localhost:5050/graphql\",\n cache: new InMemoryCache(),\n });\n return <ApolloProvider client={client}>{children}</ApolloProvider>;\n};\n```\n\n```text\nimport type { Metadata } from \"next\";\nimport { Inter } from \"next/font/google\";\nimport \"./globals.css\";\nimport { Provider } from \"@/graphql/provider\";\n\nconst inter = Inter({ subsets: [\"latin\"] });\n\nexport const metadata: Metadata = {\n title: \"Create Next App\",\n description: \"Generated by create next app\",\n};\n\nexport default function RootLayout({\n children,\n}: Readonly<{\n children: React.ReactNode;\n}>) {\n return (\n <html lang=\"en\">\n <body className={inter.className}>\n <Provider>{children}</Provider>\n </body>\n </html>\n );\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":340,"estimatedTokens":1828}}953{"id":"stack-51047735","source":"stackoverflow","questionId":51047735,"title":"GraphQL disable filtering if filter variable is empty","tags":["graphql","graphql-js","gatsby","contentful"],"text":"Title: GraphQL disable filtering if filter variable is empty\nTags: graphql, graphql-js, gatsby, contentful\nSource: Stack Overflow\n\nQuestion:\nI have a Gatsby GraphQL query for a list of posts ordered by date and filtered by category.\n\n```\n{\n posts: allContentfulPost(\n sort: {fields: [date], order: DESC},\n filter: {category: {slug: {eq: $slug}}}\n ) {\n edges {\n node {\n title {\n title\n }\n date\n }\n }\n }\n}\n```\n\nRight now when `$slug` is the empty string `\"\"`, I get\n\n```\n{\n \"data\": {\n \"posts\": null\n }\n}\n```\n\nIs there a way to get all posts instead?\n\n========================================\n\nTop Answer:\nIf anyone requires a solution for other systems than Gatsby this can be accomplished using `@skip` and `@include`.\n\n```\nfragment EventSearchResult on EventsConnection {\n edges {\n cursor\n node {\n id\n name\n }\n }\n totalCount\n}\n\nquery Events($organizationId: UUID!, $isSearch: Boolean!, $search: String!) {\n events(condition: { organizationId: $organizationId }, first: 100)\n @skip(if: $isSearch) {\n ...EventSearchResult\n }\n eventsSearch: events(\n condition: { organizationId: $organizationId }\n filter: { name: { likeInsensitive: $search } }\n first: 100\n ) @include(if: $isSearch) {\n ...EventSearchResult\n }\n}\n```\n\nThen in your client code you would provide search and isSearch to the query and get your events like:\n\n```\nconst events = data.eventsSearch || data.events\n```\n\n========================================\n\nCode:\n```text\n{\n posts: allContentfulPost(\n sort: {fields: [date], order: DESC},\n filter: {category: {slug: {eq: $slug}}}\n ) {\n edges {\n node {\n title {\n title\n }\n date\n }\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"posts\": null\n }\n}\n```\n\n```text\n$slug\n```\n\n```text\n\"\"\n```\n\n```text\nquery Posts($slugRegex: String = \"//\"){\n posts: allContentfulPost(\n sort: {fields: [date], order: DESC},\n filter: {category: {slug: {eq: $slugRegex}}}\n ) {\n # Rest of the query.\n }\n}\n```\n\n```js\n// gatsby-node.js\n\nexports.createPages = async ({ actions }) => {\n const { createPage } = actions\n\n // Create a page with only \"some-slug\" posts.\n createPage({\n // ...\n context: {\n slugRegex: \"/some-slug/\"\n }\n })\n\n // Create a page with all posts.\n createPage({\n // ...\n context: {\n // Nothing here. Or at least no `slugRegex`.\n }\n })\n}\n```\n\n```text\n$slugRegex\n```\n\n```text\n$slugRegex\n```\n\n```text\ngatsby-node.js\n```\n\n```text\nfragment EventSearchResult on EventsConnection {\n edges {\n cursor\n node {\n id\n name\n }\n }\n totalCount\n}\n\nquery Events($organizationId: UUID!, $isSearch: Boolean!, $search: String!) {\n events(condition: { organizationId: $organizationId }, first: 100)\n @skip(if: $isSearch) {\n ...EventSearchResult\n }\n eventsSearch: events(\n condition: { organizationId: $organizationId }\n filter: { name: { likeInsensitive: $search } }\n first: 100\n ) @include(if: $isSearch) {\n ...EventSearchResult\n }\n}\n```\n\n```js\nconst events = data.eventsSearch || data.events\n```\n\n```text\n@skip\n```\n\n```text\n@include\n```\n\n========================================\n\nComments:\n- Could you try setting `$slug` to `null` instead of `\"\"` in that case?\n- @FabianSchultz I did. Same result unfortunately, both with and without quotes around `null`.\n- did you found a solution to your problem?\n- Not really. It ceased to be a problem for me because for unrelated reasons I opted to always query all posts and do the filtering on the fly with JS.\n- Your answer helped me a lot figuring out a solution. In my case, I used a regex too but in the filter I've use the term `regex` instead of `eq`, so based on your example it's: `filter: {category: {slug: {regex: $slugRegex}}}`","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":206,"estimatedTokens":925}}954{"id":"stack-70693292","source":"stackoverflow","questionId":70693292,"title":"Github GraphQL API: This endpoint requires you to be authenticated","tags":["github","graphql","fetch-api"],"text":"Title: Github GraphQL API: This endpoint requires you to be authenticated\nTags: github, graphql, fetch-api\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a request with generated git token, but it seems like I'm making a wrong authentication, what am I doing wrong?\n\n```\nconst token = 'my github token'\n\n fetch('https://api.github.com/graphql', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': 'bearer' + token\n },\n body: JSON.stringify({ query: QUERY })\n })\n .then(res => res.json())\n .then(data => console.log(data))\n}\n```\n\nError message:\n\n{message: 'This endpoint requires you to be authenticated.'}\n\n========================================\n\nCode:\n```text\nconst token = 'my github token'\n\n fetch('https://api.github.com/graphql', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': 'bearer' + token\n },\n body: JSON.stringify({ query: QUERY })\n })\n .then(res => res.json())\n .then(data => console.log(data))\n}\n```\n\n```text\n'Authorization': 'bearer ' + token\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":49,"estimatedTokens":273}}955{"id":"stack-45199311","source":"stackoverflow","questionId":45199311,"title":"Show Apollo mutation error to user in Vue.js?","tags":["javascript","vue.js","graphql","apollo","vue-apollo"],"text":"Title: Show Apollo mutation error to user in Vue.js?\nTags: javascript, vue.js, graphql, apollo, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI am using Vue.js with Vue-Apollo and initiating a User mutation to sign in a user. I am using the graph.cool service.\n\nI have a request pipeline function setup to catch some errors, like an invalid email.\n\nWhen the request is made with bad / invalid input, my error `catch()` fires (as expected) and in the network tab I can see the JSON for the custom errors messages. But how do I access these errors / response from within the catch if an error is triggered from graph.cool?\n\n**Example:**\n\n```\nsignin () {\n const email = this.email\n const password = this.password\n\n this.$apollo.mutate({\n mutation: signinMutation,\n variables: {\n email,\n password\n }\n })\n .then((data) => {\n // This never fires on an error, so I can't \n // show the user the errors in the network repsonse.\n console.log(data) \n })\n .catch((error) => {\n // Error in this part fires in the console \n // but I'm unable to show the JSON response \n // errors because the 'then()' above doesn't execute.\n console.error(error)\n })\n}\n```\n\nI get the following error for an unrecognised user:\n\n Error: GraphQL error: No user found with that information\n at new ApolloError (eval at (app.js:956), :34:28)\n at eval (eval at (app.js:1353), :139:33)\n at \n\nAny idea how to show the errors in the response from within the `catch()`?\n\nI can literally see the errors I want to show to the user in the response on the network tab here:\n\nhttps://i.sstatic.net/UhcT6.png\n\n...but I can't figure out how to do it.\n\nAny help much appreciated! Thank you.\n\n========================================\n\nTop Answer:\nI may be misunderstanding your question so please comment and correct me if I am but it looks like you may be having trouble with Promises more than with Vue or GraphQL.\n\nJust like in a `try...catch` statement, once you catch an error, your program will continue to execute unless you re-throw the error. For example:\n\n**This Catches**\n\n```\ntry { \n codeThatThrowsAnError();\n} catch(e) {\n // Do Nothing\n}\n```\n\n**This re-throws**\n\n```\ntry { \n codeThatThrowsAnError();\n} catch(e) {\n throw new Error(\"Err 135: I failed\")\n}\n```\n\nSimilarly, in Promise land, you can either catch the error and move like you have in your example, or you can re-throw. What you may be missing is that anything you return from a catch statement will be used in the next `then`. For example:\n\n```\nsomethingReturningAFailedPromise()\n .then(doWork)\n .catch((err) => {\n return \"I'm a New Value\"\n })\n .then(console.log)\n\n//=> \"I'm a New Value\"\n```\n\nIt sounds to me like what you need is a data function that is more resilient to failure like the following:\n\n```\nconst getUserProfile = (id) => {\n return fetchUserData(id)\n .catch((err) => {\n logError(err);\n return {};\n })\n}\n```\n\n========================================\n\nCode:\n```text\nsignin () {\n const email = this.email\n const password = this.password\n\n this.$apollo.mutate({\n mutation: signinMutation,\n variables: {\n email,\n password\n }\n })\n .then((data) => {\n // This never fires on an error, so I can't \n // show the user the errors in the network repsonse.\n console.log(data) \n })\n .catch((error) => {\n // Error in this part fires in the console \n // but I'm unable to show the JSON response \n // errors because the 'then()' above doesn't execute.\n console.error(error)\n })\n}\n```\n\n```text\ncatch()\n```\n\n```text\ncatch()\n```\n\n```text\nerror.graphQLErrors[0]\n```\n\n```text\nsignin () {\n const email = this.email\n const password = this.password\n\n this.$apollo.mutate({\n mutation: signinMutation,\n variables: {\n email,\n password\n }\n })\n .then(data => {\n console.log(data)\n })\n .catch(error => {\n console.log(graphQLErrorMessages(error))\n })\n}\n```\n\n```text\nfunction graphQLErrorMessages (errorsFromCatch) {\n const errors = errorsFromCatch.graphQLErrors[0]\n const messages = []\n\n if (errors.hasOwnProperty('functionError')) {\n const customErrors = JSON.parse(errors.functionError)\n messages.push(...customErrors.errors)\n } else {\n messages.push(errors.message)\n }\n\n return messages\n}\n```\n\n```text\n.catch()\n```\n\n```text\nconsole.dir(error)\n```\n\n```text\ngraphQLErrorMessages()\n```\n\n```text\n.catch()\n```\n\n```text\ntry { \n codeThatThrowsAnError();\n} catch(e) {\n // Do Nothing\n}\n```\n\n```text\ntry { \n codeThatThrowsAnError();\n} catch(e) {\n throw new Error(\"Err 135: I failed\")\n}\n```\n\n```text\nsomethingReturningAFailedPromise()\n .then(doWork)\n .catch((err) => {\n return \"I'm a New Value\"\n })\n .then(console.log)\n\n//=> \"I'm a New Value\"\n```\n\n```text\nconst getUserProfile = (id) => {\n return fetchUserData(id)\n .catch((err) => {\n logError(err);\n return {};\n })\n}\n```\n\n```text\ntry...catch\n```\n\n```text\nthen\n```\n\n========================================\n\nComments:\n- I think you can add another `.then` after the `.catch`: stackoverflow.com/questions/35999072/…\n- Whilst that's true, I can't get hold of the 'data' in the actual response itself. :(\n- The Graphcool specific part is the property `functionError`, that only gets returned in a Graphcool Function when you want to return an error. Also, if the `catch` is active, there is no guarantee that `graphQLErrors` has an item. So you should first check if `graphQLErrors.length > 0`.\n- This is crazy that the official docs don't even mention this graphql error field at all! Took me too long to find this","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":254,"estimatedTokens":1372}}956{"id":"stack-57901668","source":"stackoverflow","questionId":57901668,"title":"How to understand null edges and nodes in GraphQL","tags":["null","graphql","nullable","relay"],"text":"Title: How to understand null edges and nodes in GraphQL\nTags: null, graphql, nullable, relay\nSource: Stack Overflow\n\nQuestion:\nThe *good practice* for relations in GraphQL is using the *connection* model with *edge* and *node* elements. The recommendation is also for both *edge* and *node* to be nullable. This is how e.g. graphene-sqlalchemy, that I use will map the SQL relations.\n\nMy question is: *why?* As far as my APIs that serve relational data from SQL database go I can't see any situation in which an edge or a node would be `null`. Thus, if I use statically-typed language on the frontend (like Typescript or Elm) I find myself writing a boilerplate that handles situations which will never occur.\n\nHow should I understand these `null`s in terms of abstract data model? βThere is nothing connectedβ for me would translate as a connection with no edges. Why do I need a `null` edge? The `null` node bothers me even more βThere is a connection, but there is nothing on the other endβ? Please explain to me the rationale here.\n\n========================================\n\nCode:\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\ndata\n```\n\n```text\nedges\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":37,"estimatedTokens":299}}957{"id":"stack-62052023","source":"stackoverflow","questionId":62052023,"title":"Type error initializing DataLoader with Typescript","tags":["typescript","graphql","dataloader"],"text":"Title: Type error initializing DataLoader with Typescript\nTags: typescript, graphql, dataloader\nSource: Stack Overflow\n\nQuestion:\nI'm trying to initialize an instance of DataLoader using the following code:\n\n```\nconst authorLoader = new DataLoader(async (keys:string[]) => {\n // Return an author for each book\n});\n```\n\nI'm getting the following error: \n\n```\nArgument of type '(keys: string[]) => Promise' is not assignable to parameter of type 'BatchLoadFn'.\nTypes of parameters 'keys' and 'keys' are incompatible.\nThe type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'\n```\n\nWhy am I getting this error and how do I fix it? I read up on `Generics` and the source code for dataloader but haven't found a solution.\n\nNote: `keys` is of type `string[]` and not `number[]` because I'm using `uuid`'s.\n\n========================================\n\nTop Answer:\nCheck the @InBatches lib, it makes it easier to implement dataloader using a decorator.\n\n```\nimport { InBatches } from 'inbatches';\n\nclass MyService {\n\n // (optional) overloaded method, where you define the keys as `number` and the return type as `string` for typings\n async fetch(keys: number): Promise;\n\n // in reality the Decorator will wrap this method and it will never be called with a single key :)\n @InBatches() // This method is now batch-enabled\n async fetch(keys: number | number[]): Promise {\n if (Array.isArray(keys)) {\n return this.db.getMany(keys);\n }\n\n // the Decorator will wrap this method and because of that it will never be called with a single key\n throw new Error('It will never be called with a single key π');\n }\n}\n```\n\nhttps://www.npmjs.com/package/inbatches\n\n========================================\n\nCode:\n```text\nconst authorLoader = new DataLoader(async (keys:string[]) => {\n // Return an author for each book\n});\n```\n\n```text\nArgument of type '(keys: string[]) => Promise<Author[]>' is not assignable to parameter of type 'BatchLoadFn<string, Author>'.\nTypes of parameters 'keys' and 'keys' are incompatible.\nThe type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'\n```\n\n```text\nGenerics\n```\n\n```text\nkeys\n```\n\n```text\nstring[]\n```\n\n```text\nnumber[]\n```\n\n```text\nuuid\n```\n\n```text\nconst authorLoader = new DataLoader(async (keys: readonly string[]) => {\n // Return an author for each book\n});\n```\n\n```text\nreadonly string[]\n```\n\n```text\nstring[]\n```\n\n```text\nimport { InBatches } from 'inbatches';\n\nclass MyService {\n\n // (optional) overloaded method, where you define the keys as `number` and the return type as `string` for typings\n async fetch(keys: number): Promise<string>;\n\n // in reality the Decorator will wrap this method and it will never be called with a single key :)\n @InBatches() // This method is now batch-enabled\n async fetch(keys: number | number[]): Promise<string | string[]> {\n if (Array.isArray(keys)) {\n return this.db.getMany(keys);\n }\n\n // the Decorator will wrap this method and because of that it will never be called with a single key\n throw new Error('It will never be called with a single key π');\n }\n}\n```\n\n========================================\n\nComments:\n- wow, I'm embarrassed to see the solution was so simple! thank you.\n- We've all been there!\n- I dont think many people have ever used readonly in the type for a function argument which is catches some of us out!","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":129,"estimatedTokens":850}}958{"id":"stack-54063090","source":"stackoverflow","questionId":54063090,"title":"react with GraphQL Clients","tags":["reactjs","graphql","react-apollo","apollo-client","apollo-boost"],"text":"Title: react with GraphQL Clients\nTags: reactjs, graphql, react-apollo, apollo-client, apollo-boost\nSource: Stack Overflow\n\nQuestion:\nUsing `React` with `GraphQL clients` like `Apollo Client` is a good idea? The same results i can achieve with `react` and new `Context API`. \n\nBasically i can consume `GraphQL API`s using `axios` or any other libraries like this. And for state management i can use react's new `Context API`s which is really simple.\n\n```\naxios.get('localhost://4000?qraphql').then((res)=>{\n\n//do something with the response.\n})\n```\n\nIs there still any Advantages to go with `Apollo Client`. Why would I really go for `Apollo client` when i can achieve the same without it. It will help me to reduce my `bundle` size.\n\n========================================\n\nCode:\n```text\naxios.get('localhost://4000?qraphql').then((res)=>{\n\n//do something with the response.\n})\n```\n\n```text\nReact\n```\n\n```text\nGraphQL clients\n```\n\n```text\nApollo Client\n```\n\n```text\nreact\n```\n\n```text\nContext API\n```\n\n```text\nGraphQL API\n```\n\n```text\naxios\n```\n\n```text\nContext API\n```\n\n```text\nApollo Client\n```\n\n```text\nApollo client\n```\n\n```text\nbundle\n```\n\n```text\napollo-link-error\n```\n\n```text\nloadMore\n```\n\n```text\napollo-link-ws\n```\n\n```text\napollo-link-state\n```\n\n```text\n@defer\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":91,"estimatedTokens":320}}959{"id":"stack-51579476","source":"stackoverflow","questionId":51579476,"title":"GraphQLError: Syntax Error: Cannot parse the unexpected character \"\\u00A0\"","tags":["reactjs","graphql","react-apollo","graphql-js"],"text":"Title: GraphQLError: Syntax Error: Cannot parse the unexpected character \"\\u00A0\"\nTags: reactjs, graphql, react-apollo, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI get an error when I make a query/mutation/subscription with gql (from 'graphql-tag').\n\nHas anyone had this error and know how to fix it ?\n\nHere is my code :\n\n```\nimport React from 'react';\nimport { Mutation } from 'react-apollo';\nimport MUTATION from './query.js';\nimport gql from 'graphql-tag';\n\nconst ADD_POST_MUTATION = gql`\n mutation addPost($content: String!, $author: String!)Β {\n addPost(content: $content, author: $author) {\n content\n author\n }\n }\n`;\n\nexport default class Tool extends React.Component {\n state = {\n content: '',\n author: localStorage.getItem('user') || ''\n };\n\n handleSubmit = (e, mutation) => {\n console.log(mutation);\n e.preventDefault();\n mutation({ variables: { content: this.state.content, author: this.state.author }})\n .then(res => console.log(res))\n .catch(e => console.log(e));\n }\n\n render() {\n return (\n \n {(addPost, { data }) => (\n \n Poster un commentaire\n this.handleSubmit(e, addPost)}>\n this.setState({ content: e.target.value })}>\n Poster\n \n \n )}\n \n );\n }\n};\n```\n\nThe error occurs again for this query:\n\n```\nconst FETCH_POST_QUERY = gql`\n query {\n getPost {\n id\n content\n author\n }\n }\n`;\n```\n\nAnd I got this error :\n\nhttps://i.sstatic.net/MIsY0.png\n\n========================================\n\nTop Answer:\ncopy your GQL code and use another editor like TextEdit to and paste as plain Text then copy the plain text and paste back in VSCode.\n\n========================================\n\nCode:\n```text\nimport React from 'react';\nimport { Mutation } from 'react-apollo';\nimport MUTATION from './query.js';\nimport gql from 'graphql-tag';\n\nconst ADD_POST_MUTATION = gql`\n mutation addPost($content: String!, $author: String!)Β {\n addPost(content: $content, author: $author) {\n content\n author\n }\n }\n`;\n\nexport default class Tool extends React.Component {\n state = {\n content: '',\n author: localStorage.getItem('user') || ''\n };\n\n handleSubmit = (e, mutation) => {\n console.log(mutation);\n e.preventDefault();\n mutation({ variables: { content: this.state.content, author: this.state.author }})\n .then(res => console.log(res))\n .catch(e => console.log(e));\n }\n\n render() {\n return (\n <Mutation mutation={MUTATION}>\n {(addPost, { data }) => (\n <div>\n <div>Poster un commentaire</div>\n <form onSubmit={e => this.handleSubmit(e, addPost)}>\n <textarea onChange={e => this.setState({ content: e.target.value })}></textarea>\n <button type='submit'>Poster</button>\n </form>\n </div>\n )}\n </Mutation>\n );\n }\n};\n```\n\n```text\nconst FETCH_POST_QUERY = gql`\n query {\n getPost {\n id\n content\n author\n }\n }\n`;\n```\n\n========================================\n\nComments:\n- As per SO guidelines, all text, code, error messages & data must be typed in as text, not posted in image form. Please edit your question replacing the images with text. Text allows visitors to efficiently copy-paste exact error messages, code, & data into their editors & search engines to efficiently & without introducing more typos. Also, text in images can be difficult to read, especially on mobile devices, and images are not accessibility friendly. Thanks, all the best.\n- Pasting from Notepad and notepad2 didn't work. Typing GQL again worked","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":148,"estimatedTokens":870}}960{"id":"stack-53952480","source":"stackoverflow","questionId":53952480,"title":"GitHub GraphQL fetch repositories that are not archived","tags":["graphql","github-api","github-graphql"],"text":"Title: GitHub GraphQL fetch repositories that are not archived\nTags: graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nIs there a way to fetch only the repos that are not archived? \n\n```\n{\n user(login: \"SrikanthBandaru\") {\n id\n email\n isHireable\n name\n repositories(first: 100) { # fetch only the repos that are not archived\n edges {\n node {\n name\n isArchived\n shortDescriptionHTML\n description\n descriptionHTML\n repositoryTopics(first: 10) {\n edges {\n node {\n topic {\n name\n }\n }\n }\n }\n homepageUrl\n url\n }\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou can run the query below to filter out archived repository in the Github org; I used the pageInfo request to get the endcursor for paginating into the next page.\n\n\r\n\r\n\n```\nquery {\n organization(login: \"orgname\") {\n repositories(isArchived:false, first: 100) { # adjust this value based on your needs\n edges {\n node {\n name\n vulnerabilityAlerts(first: 100) { # adjust this value based on your needs\n edges {\n node {\n id\n securityVulnerability {\n package {\n name\n ecosystem\n }\n severity\n updatedAt\n }\n vulnerableRequirements\n }\n }\n }\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n } \n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n user(login: \"SrikanthBandaru\") {\n id\n email\n isHireable\n name\n repositories(first: 100) { # fetch only the repos that are not archived\n edges {\n node {\n name\n isArchived\n shortDescriptionHTML\n description\n descriptionHTML\n repositoryTopics(first: 10) {\n edges {\n node {\n topic {\n name\n }\n }\n }\n }\n homepageUrl\n url\n }\n }\n }\n }\n}\n```\n\n```graphql\n{\n user: user(login: \"simon04\") {\n id\n email\n isHireable\n name\n }\n repos: search(query: \"user:simon04 fork:true archived:false\", type: REPOSITORY, first: 100) {\n repositoryCount\n edges {\n node {\n ... on Repository {\n nameWithOwner\n name\n isArchived\n shortDescriptionHTML\n description\n descriptionHTML\n repositoryTopics(first: 10) {\n edges {\n node {\n topic {\n name\n }\n }\n }\n }\n homepageUrl\n url\n }\n }\n }\n }\n}\n```\n\n```text\nfork:true\n```\n\n```html\nquery {\n organization(login: \"orgname\") {\n repositories(isArchived:false, first: 100) { # adjust this value based on your needs\n edges {\n node {\n name\n vulnerabilityAlerts(first: 100) { # adjust this value based on your needs\n edges {\n node {\n id\n securityVulnerability {\n package {\n name\n ecosystem\n }\n severity\n updatedAt\n }\n vulnerableRequirements\n }\n }\n }\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n } \n }\n }\n}\n```\n\n========================================\n\nComments:\n- ahh..!! Thank you!!","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":197,"estimatedTokens":822}}961{"id":"stack-70672470","source":"stackoverflow","questionId":70672470,"title":"Npm dependency conflict - how to solve it?","tags":["npm","graphql"],"text":"Title: Npm dependency conflict - how to solve it?\nTags: npm, graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to install graphql-iso-date. Can someone tell me how to fix this?\n\n```\nnpm ERR! code ERESOLVE \nnpm ERR! ERESOLVE unable to resolve dependency tree \nnpm ERR! \nnpm ERR! While resolving: undefined@undefined\nnpm ERR! Found: graphql@16.2.0\nnpm ERR! node_modules/graphql\nnpm ERR! graphql@\"^16.2.0\" from the root project\nnpm ERR!\nnpm ERR! Could not resolve dependency:\nnpm ERR! peer graphql@\"^0.5.0 || ^0.6.0 || ^0.7.0 || ^0.8.0-b || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0\" from graphql-iso-date@3.6.1\nnpm ERR! node_modules/graphql-iso-date\nnpm ERR! graphql-iso-date@\"*\" from the root project\nnpm ERR!\nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force, or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\nnpm ERR!\nnpm ERR! See C:\\Users\\Simon\\AppData\\Local\\npm-cache\\eresolve-report.txt for a full report.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! C:\\Users\\Simon\\AppData\\Local\\npm-cache\\_logs\\2022-01-11T19_26_53_815Z-debug-0.log\n```\n\n========================================\n\nTop Answer:\nPlease be careful to run the `npm install ` with `--force`, or `--legacy-peer-deps` option, it will cause potentially broken. Instead, we should fix the version compatibility issues between dependent packages.\n\nLet's check the `peerDependencies` of `graphql-iso-date@3.6.1` package.\n\n```\n$ npm view graphql-iso-date@3.6.1 peerDependencies\n{\n graphql: '^0.5.0 || ^0.6.0 || ^0.7.0 || ^0.8.0-b || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0'\n}\n```\n\nThis means it demands the `graphql` package as its peer dependency with these compatibility versions.\n\nObviously, the `graphql@16.2.0` version is not on the list. That's why you got the warning.\n\nThe safe solution is to downgrade the `graphql` package to the compatibility version.\n\nLet's check the all 14.x versions of `graphql` package:\n\n```\n$ npm view graphql@14 version\ngraphql@14.0.0 '14.0.0'\ngraphql@14.0.1 '14.0.1'\ngraphql@14.0.2 '14.0.2'\ngraphql@14.1.0 '14.1.0'\ngraphql@14.1.1 '14.1.1'\ngraphql@14.2.0 '14.2.0'\ngraphql@14.2.1 '14.2.1'\ngraphql@14.3.0 '14.3.0'\ngraphql@14.3.1 '14.3.1'\ngraphql@14.4.0 '14.4.0'\ngraphql@14.4.1 '14.4.1'\ngraphql@14.4.2 '14.4.2'\ngraphql@14.5.0 '14.5.0'\ngraphql@14.5.1 '14.5.1'\ngraphql@14.5.2 '14.5.2'\ngraphql@14.5.3 '14.5.3'\ngraphql@14.5.4 '14.5.4'\ngraphql@14.5.5 '14.5.5'\ngraphql@14.5.6 '14.5.6'\ngraphql@14.5.7 '14.5.7'\ngraphql@14.5.8 '14.5.8'\ngraphql@14.6.0 '14.6.0'\ngraphql@14.7.0 '14.7.0'\n```\n\nWe can use the last version of 14.x, it's compatible with `^14.0.0`. Now let's downgrade the version of `graphql` package and install `graphql-iso-date` package\n\n```\n$ npm i graphql@^14.7.0 -S\n\nadded 1 package, changed 1 package, and audited 3 packages in 26s\n\nfound 0 vulnerabilities\n$ npm i graphql-iso-date -S\n\nadded 1 package, and audited 4 packages in 8s\n\nfound 0 vulnerabilities\n```\n\nList the installed packages:\n\n```\n$ npm ls --depth 0\npeer-deps-issue@ /home/lindu/workspace/peer-deps-issue\nβββ graphql-iso-date@3.6.1\nβββ graphql@14.7.0\n```\n\nThe warning is gone. Further reading npm-v7-series-beta-release-and-semver-major\n\n========================================\n\nCode:\n```text\nnpm ERR! code ERESOLVE \nnpm ERR! ERESOLVE unable to resolve dependency tree \nnpm ERR! \nnpm ERR! While resolving: undefined@undefined\nnpm ERR! Found: graphql@16.2.0\nnpm ERR! node_modules/graphql\nnpm ERR! graphql@\"^16.2.0\" from the root project\nnpm ERR!\nnpm ERR! Could not resolve dependency:\nnpm ERR! peer graphql@\"^0.5.0 || ^0.6.0 || ^0.7.0 || ^0.8.0-b || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0\" from graphql-iso-date@3.6.1\nnpm ERR! node_modules/graphql-iso-date\nnpm ERR! graphql-iso-date@\"*\" from the root project\nnpm ERR!\nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force, or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\nnpm ERR!\nnpm ERR! See C:\\Users\\Simon\\AppData\\Local\\npm-cache\\eresolve-report.txt for a full report.\n\nnpm ERR! A complete log of this run can be found in:\nnpm ERR! C:\\Users\\Simon\\AppData\\Local\\npm-cache\\_logs\\2022-01-11T19_26_53_815Z-debug-0.log\n```\n\n```text\nnpm install graphql-iso-date --legacy-peer-deps\n```\n\n```text\n--legacy-peer-deps\n```\n\n```text\nnpm i -g npm@next-7\n```\n\n```text\n$ npm view graphql-iso-date@3.6.1 peerDependencies\n{\n graphql: '^0.5.0 || ^0.6.0 || ^0.7.0 || ^0.8.0-b || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0'\n}\n```\n\n```text\n$ npm view graphql@14 version\ngraphql@14.0.0 '14.0.0'\ngraphql@14.0.1 '14.0.1'\ngraphql@14.0.2 '14.0.2'\ngraphql@14.1.0 '14.1.0'\ngraphql@14.1.1 '14.1.1'\ngraphql@14.2.0 '14.2.0'\ngraphql@14.2.1 '14.2.1'\ngraphql@14.3.0 '14.3.0'\ngraphql@14.3.1 '14.3.1'\ngraphql@14.4.0 '14.4.0'\ngraphql@14.4.1 '14.4.1'\ngraphql@14.4.2 '14.4.2'\ngraphql@14.5.0 '14.5.0'\ngraphql@14.5.1 '14.5.1'\ngraphql@14.5.2 '14.5.2'\ngraphql@14.5.3 '14.5.3'\ngraphql@14.5.4 '14.5.4'\ngraphql@14.5.5 '14.5.5'\ngraphql@14.5.6 '14.5.6'\ngraphql@14.5.7 '14.5.7'\ngraphql@14.5.8 '14.5.8'\ngraphql@14.6.0 '14.6.0'\ngraphql@14.7.0 '14.7.0'\n```\n\n```text\n$ npm i graphql@^14.7.0 -S\n\nadded 1 package, changed 1 package, and audited 3 packages in 26s\n\nfound 0 vulnerabilities\n$ npm i graphql-iso-date -S\n\nadded 1 package, and audited 4 packages in 8s\n\nfound 0 vulnerabilities\n```\n\n```text\n$ npm ls --depth 0\npeer-deps-issue@ /home/lindu/workspace/peer-deps-issue\nβββ graphql-iso-date@3.6.1\nβββ graphql@14.7.0\n```\n\n```text\nnpm install <package>\n```\n\n```text\n--force\n```\n\n```text\n--legacy-peer-deps\n```\n\n```text\npeerDependencies\n```\n\n```text\ngraphql-iso-date@3.6.1\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql@16.2.0\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql\n```\n\n```text\n^14.0.0\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql-iso-date\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.095Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":246,"estimatedTokens":1476}}962{"id":"stack-54047369","source":"stackoverflow","questionId":54047369,"title":"Prisma API returns relation but client returns \"cannot return null for non-nullable field..\"","tags":["javascript","graphql","prisma"],"text":"Title: Prisma API returns relation but client returns \"cannot return null for non-nullable field..\"\nTags: javascript, graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nWhen I try to return fields from a one-to-many relation in Prisma client playground it returns the following error:\n\n Cannot return null for non-nullable field DeviceConfig.device.\n\nWhat in my resolver or client could be causing this?\n\nWhen running the following query on the backend Prisma API playground it does return the correct data so that tells me my mutations and relationship is good.\n\n**Datamodel**\n\n```\ntype Device {\n ...\n model: String! @unique\n ...\n configs: [DeviceConfig] @relation(name: \"DeviceConfigs\", onDelete: CASCADE)\n}\n\ntype DeviceConfig {\n id: ID! @unique\n device: Device! @relation(name: \"DeviceConfigs\", onDelete: SET_NULL)\n name: String!\n ...\n}\n```\n\n**Resolver**\n\n```\ndeviceConfig: async (parent, { id }, context, info) => context.prisma.deviceConfig({ id }, info)\n```\n\n**Query**\n\n```\n{\n deviceConfig(id:\"cjqigyian00ef0d206tg116k5\"){\n name\n id\n device{\n model\n }\n }\n}\n```\n\n**Result**\n\n```\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field DeviceConfig.device.\",\n \"locations\": [\n {\n \"line\": 5,\n \"column\": 5\n }\n ],\n \"path\": [\n \"deviceConfig\",\n \"device\"\n ]\n }\n ]\n}\n```\n\nI expect the query to return the model of the device like the backend Prisma API server does\n**Query**\n\n```\n{\n deviceConfig(where:{id:\"cjqigyian00ef0d206tg116k5\"}){\n name\n id\n device{\n id\n model\n }\n }\n}\n```\n\n**Result**\n\n```\n{\n \"data\": {\n \"deviceConfig\": {\n \"name\": \"Standard\",\n \"id\": \"cjqigyian00ef0d206tg116k5\",\n \"device\": {\n \"id\": \"cjqigxzs600e60d20sdw38x7p\",\n \"model\": \"7530\"\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nI think you are mixing Prisma Bindings syntax with Prisma Client syntax. \n\nThe `info` object is something you pass to the bindings to return what the user is asking for. However, this feature is not available in the Prisma Client, which you seem to be using. If you need that feature then you could try Prisma Bindings. \n\nOtherwise, modify your code to something like `context.prisma.deviceConfig({ id }).device()`. I think it can also accept a fragment `context.prisma.deviceConfig({ id }).$fragment('fragment configWithDevice on DeviceConfig { id name device { id model } }')`.\n\n========================================\n\nCode:\n```text\ntype Device {\n ...\n model: String! @unique\n ...\n configs: [DeviceConfig] @relation(name: \"DeviceConfigs\", onDelete: CASCADE)\n}\n\ntype DeviceConfig {\n id: ID! @unique\n device: Device! @relation(name: \"DeviceConfigs\", onDelete: SET_NULL)\n name: String!\n ...\n}\n```\n\n```text\ndeviceConfig: async (parent, { id }, context, info) => context.prisma.deviceConfig({ id }, info)\n```\n\n```text\n{\n deviceConfig(id:\"cjqigyian00ef0d206tg116k5\"){\n name\n id\n device{\n model\n }\n }\n}\n```\n\n```text\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field DeviceConfig.device.\",\n \"locations\": [\n {\n \"line\": 5,\n \"column\": 5\n }\n ],\n \"path\": [\n \"deviceConfig\",\n \"device\"\n ]\n }\n ]\n}\n```\n\n```text\n{\n deviceConfig(where:{id:\"cjqigyian00ef0d206tg116k5\"}){\n name\n id\n device{\n id\n model\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"deviceConfig\": {\n \"name\": \"Standard\",\n \"id\": \"cjqigyian00ef0d206tg116k5\",\n \"device\": {\n \"id\": \"cjqigxzs600e60d20sdw38x7p\",\n \"model\": \"7530\"\n }\n }\n }\n}\n```\n\n```text\nconst resolvers = {\n // Relationship resolvers\n Device: {\n configs: (parent, args, context) => context.prisma.device({ id: parent.id }).configs(),\n },\n DeviceConfig: {\n device: (parent, args, context) => context.prisma.deviceConfig({ id: parent.id }).device(),\n },\n Query: {\n ...User.Query,\n ...Device.Query,\n ...DeviceConfig.Query,\n },\n Mutation: {\n ...User.Mutation,\n ...Device.Mutation,\n ...DeviceConfig.Mutation,\n },\n};\n```\n\n```text\ninfo\n```\n\n```text\ncontext.prisma.deviceConfig({ id }).device()\n```\n\n```text\ncontext.prisma.deviceConfig({ id }).$fragment('fragment configWithDevice on DeviceConfig { id name device { id model } }')\n```\n\n========================================\n\nComments:\n- Your correct I am migrating from Prisma binding and missed that detail. I tried `context.prisma.deviceConfig({ id }).device()` and got back the following error `Cannot return null for non-nullable field DeviceConfig.name.`. It would be nice to get this to work so I don't have to use the fragment solution. But the fragment worked! Is there a way to request all the fields without having to populate the fragment with all the fields?\n- Looks like the first syntax only returns \"device by deviceConfig\" (like posts by user), but not the device config itself. Perhaps the fragment syntax is the only possibility :/\n- That makes sense, Thank you for the help.","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":240,"estimatedTokens":1233}}963{"id":"stack-65381211","source":"stackoverflow","questionId":65381211,"title":"Passing Objects as Argument to GraphQL Mutation (graphql-request)","tags":["javascript","graphql","graphql-js","express-graphql","graphql-mutation"],"text":"Title: Passing Objects as Argument to GraphQL Mutation (graphql-request)\nTags: javascript, graphql, graphql-js, express-graphql, graphql-mutation\nSource: Stack Overflow\n\nQuestion:\nI have a very basic graphql mutation in the frontend that I send to my backend. I am using this code on the by `graphql-request` as a guide.\n\nWith primitives it works:\n\n```\nconst mutation = gql`\n mutation EditArticle($id: ID!, $title: String) {\n editArticle(id: $id, title: $title) {\n id\n }\n }\n `\n```\n\nNow I'd like to also be able to mutate some meta data about the article, stored in a `meta` object inside the article:\n\n```\n...,\ntitle: \"Hello World\",\nmeta: {\n author: \"John\",\n age: 32,\n ...\n}\n```\n\nSo my question is: *How do I pass over non-primitive object types as arguments to mutations when making the request from the frontend, using graphql-request?*\n\nI tried something like this already:\n\n```\nconst Meta = new GraphQLObjectType({\n name: \"Meta\",\n fields: () => ({\n id: { type: GraphQLID },\n name: { type: GraphQLString },\n age ....\n }),\n })\n \nconst mutation = gql`\n mutation EditArticle($id: ID!, $title: String, $meta: Meta) { //??? I don't seem to get what goes here? \n editArticle(id: $id, title: $title, meta: $meta) {\n id\n }\n }\n `\n```\n\nI also tried it with `GraphQLObjectType`, but I think I am going wrong here (since this is the frontend).\n\nPS: I looked at this answer, but I didn't understand / believe the solution there might be incomplete.\n\n========================================\n\nCode:\n```text\nconst mutation = gql`\n mutation EditArticle($id: ID!, $title: String) {\n editArticle(id: $id, title: $title) {\n id\n }\n }\n `\n```\n\n```text\n...,\ntitle: \"Hello World\",\nmeta: {\n author: \"John\",\n age: 32,\n ...\n}\n```\n\n```text\nconst Meta = new GraphQLObjectType({\n name: \"Meta\",\n fields: () => ({\n id: { type: GraphQLID },\n name: { type: GraphQLString },\n age ....\n }),\n })\n \nconst mutation = gql`\n mutation EditArticle($id: ID!, $title: String, $meta: Meta) { //??? I don't seem to get what goes here? \n editArticle(id: $id, title: $title, meta: $meta) {\n id\n }\n }\n `\n```\n\n```text\ngraphql-request\n```\n\n```text\nmeta\n```\n\n```text\nGraphQLObjectType\n```\n\n```text\ninput MetaInput {\n name: String\n author: String\n release: Date\n}\n```\n\n```text\nextend type Mutation {\n editArticle(id: ID!, title: String, meta: MetaInput): Article\n}\n```\n\n```text\neditArticle\n```\n\n```text\nMetaInput\n```\n\n```text\nmutation EditArticle\n```\n\n========================================\n\nComments:\n- Look in your schema what the types of the `editArticle` arguments are. Most likely it should be something like `MetaInput`. It needs to be an `input` type, not an output one.\n- Thanks a lot, I think I understand now. So the MetaInput type is something I define on the server, but on the client I can just write that it's of the type `MetaInput` and there's no need to define this again on the client, as I understand now?\n- Yes, if you're using `express-graphql`, though of course the server side is implementation dependent (and you don't necessarily need to construct a `new GraphQLInputObjectType` yourself - you might just parse a schema definition or something). But on the frontend, where you're defining the query, you'd just refer to it by name, you don't have to do anything extra.\n- Ok, I think this was the bit that had me confused!! Thank you (so!) much. If you just write that as an answer, I would definitely accept that :)\n- Thanks a lot, that's very helpful!","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":146,"estimatedTokens":877}}964{"id":"stack-60013899","source":"stackoverflow","questionId":60013899,"title":"Send 2 identical Graphql queries in one call but with different variables","tags":["reactjs","angular","graphql","apollo","apollo-client"],"text":"Title: Send 2 identical Graphql queries in one call but with different variables\nTags: reactjs, angular, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have a search query which takes an variable and searches based on that.\n\nOn my home page I'd like to send this query 3 times with 3 different variables.\n\nBut if I do as above I can't get the results.\n\nHere is the query:\n\n```\nconst TOP_TEACHER_QUERY= gql`\n query topTeachers {\n searchBasicTeachersByRating(rating: 3) {\n id\n name\n title\n }\n searchBasicTeachersByRating(rating: 4) {\n id\n name\n title\n isNew\n }\n }\n}\n```\n\nand this is the function\n\n```\nallQueries() {\n return this.apollo\n .watchQuery({\n query: TOP_TEACHER_QUERY,\n })\n .valueChanges;\n}\n```\n\n**NOTE :**\n\nI have tried adding an interface and define the desired response data, but it has no effect\n\n```\ninterface Response {\n searchBasicTeachersByRatingMedium: Student[];\n searchBasicTeachersByRatingHigh: Student[];\n}\n\nallQueries() {\n return this.apollo\n .watchQuery({\n query: TOP_TEACHER_QUERY,\n })\n .valueChanges;\n}\n```\n\n*THE DATA IS ONLY CONTAINING A LIST NAMED AFTER THE QUERY (searchBasicTeachersByRating)*\n\nI have tried the following query in graphql playground and it returns 2 arrays\nbut in Angular I can only get one\n\nAs a work around I created new queries at back-end, or sent 2 different queries.\n\nBut I want a solution for this approach.\n\nThanks in advance\n\n========================================\n\nCode:\n```text\nconst TOP_TEACHER_QUERY= gql`\n query topTeachers {\n searchBasicTeachersByRating(rating: 3) {\n id\n name\n title\n }\n searchBasicTeachersByRating(rating: 4) {\n id\n name\n title\n isNew\n }\n }\n}\n```\n\n```text\nallQueries() {\n return this.apollo\n .watchQuery<any>({\n query: TOP_TEACHER_QUERY,\n })\n .valueChanges;\n}\n```\n\n```text\ninterface Response {\n searchBasicTeachersByRatingMedium: Student[];\n searchBasicTeachersByRatingHigh: Student[];\n}\n\nallQueries() {\n return this.apollo\n .watchQuery<any>({\n query: TOP_TEACHER_QUERY,\n })\n .valueChanges;\n}\n```\n\n```text\nsearchBasicTeachersByRatingMedium: searchBasicTeachersByRating(rating: 3) {\n id\n name\n title\n}\nsearchBasicTeachersByRatingHigh: searchBasicTeachersByRating(rating: 4) {\n id\n name\n title\n isNew\n}\n```\n\n```text\ndata\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":136,"estimatedTokens":604}}965{"id":"stack-60219418","source":"stackoverflow","questionId":60219418,"title":"React.js Log all GraphQL queries in Sentry","tags":["reactjs","graphql","sentry","react-error-boundary"],"text":"Title: React.js Log all GraphQL queries in Sentry\nTags: reactjs, graphql, sentry, react-error-boundary\nSource: Stack Overflow\n\nQuestion:\nI have a **React** application which I've surrounded with an `ErrorBoundary` that sends errors to Sentry and it works fine. I would like to log all my GraphQL query errors into Sentry as well but my problem now is for all my GraphQL queries, I have a catch block where I dispatch an action for the failed query. \nWhen I remove the catch blocks, the errors are logged into Sentry but I'm unable to trigger the failed query action. \n\nMy solution now is to put `Sentry.captureException()` into each catch block of a GraphQL query which is very repetitive. \n\nIs there a way to allow the `ErrorBoundary` to still catch GraphQL errors even if the query has it's own catch block?\n\n```\nfunction getEmployee() {\n return function(dispatch) {\n dispatch(requestEmployeeInformation());\n\n GraphqlClient.query({ query: EmployeeQuery, fetchPolicy: 'network-only' })\n .then((response) => {\n dispatch(receiveEmployeeInformation(response.data));\n })\n .catch((error) => {\n /* temporary solution. This sends error to sentry but is very repetitive because\n it has to be added to every single action with a graphql query \n */\n Sentry.captureException(error)\n\n //dispatch this action if the query failed\n dispatch(failGetEmployee(error));\n });\n };\n}\n```\n\n========================================\n\nCode:\n```text\nfunction getEmployee() {\n return function(dispatch) {\n dispatch(requestEmployeeInformation());\n\n GraphqlClient.query({ query: EmployeeQuery, fetchPolicy: 'network-only' })\n .then((response) => {\n dispatch(receiveEmployeeInformation(response.data));\n })\n .catch((error) => {\n /* temporary solution. This sends error to sentry but is very repetitive because\n it has to be added to every single action with a graphql query \n */\n Sentry.captureException(error)\n\n //dispatch this action if the query failed\n dispatch(failGetEmployee(error));\n });\n };\n}\n```\n\n```text\nErrorBoundary\n```\n\n```text\nSentry.captureException()\n```\n\n```text\nErrorBoundary\n```\n\n```text\nimport { onError } from '@apollo/client/link/error'\n\nconst link = onError(({ graphQLErrors, networkError, response }) => {\n if (graphQLErrors)\n graphQLErrors.map(({ message, locations, path }) =>\n Sentry.captureMessage(message)\n )\n if (networkError) {\n Sentry.captureException(networkError)\n }\n \n // Optionally, set response.errors to null to ignore the captured errors\n // at the component level. Omit this if you still want component-specific handling\n response.errors = null\n});\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":88,"estimatedTokens":690}}966{"id":"stack-72230166","source":"stackoverflow","questionId":72230166,"title":"Generate the correct type instead of a union in GraphQL codegen","tags":["typescript","graphql","code-generation","graphql-codegen"],"text":"Title: Generate the correct type instead of a union in GraphQL codegen\nTags: typescript, graphql, code-generation, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nI am trying to migrate a setup which generates all the types exactly like what the server has into something which is based on just the document nodes that we've written.\n\nI currenly have this configuration in `.graphqlrc.js`\n\n```\n/** @type {import('graphql-config').IGraphQLConfig} */\nconst graphqlConfig = {\n schema: process.env.NEXT_PUBLIC_API_URL,\n documents: './src/graphql/**/*.ts',\n extensions: {\n codegen: {\n hooks: {\n afterAllFileWrite: ['prettier --write'],\n },\n generates: {\n './src/__generated__/graphql.ts': {\n plugins: [\n 'typescript',\n 'typescript-operations',\n {\n add: {\n content: '/* eslint-disable */',\n },\n },\n ],\n config: {\n disableDescriptions: true,\n },\n },\n './src/__generated__/introspection-result.ts': {\n plugins: ['fragment-matcher'],\n config: {\n useExplicitTyping: true,\n },\n },\n },\n },\n },\n}\n```\n\nand this generates something like below\n\n```\nexport type QueryName = {\n __typename?: 'Query'\n resource?:\n | { __typename?: 'A' }\n | { __typename?: 'B' }\n | {\n __typename?: 'C'\n id: string\n prop1: any\n prop2: any\n }\n}\n```\n\nthat is not exactly what I was expecting to be generated. I am expecting something like\n\n```\nexport type QueryName = {\n __typename?: 'Query'\n resource?: {\n __typename?: 'C'\n id: string\n prop1: any\n prop2: any\n }\n}\n```\n\nas I am only querying for `C`. The types that is currently getting generated will affect a lot of codes whereas if I could output what I want to achieve, we only need to change the types.\n\nI've tried playing with the config found here but could not find a solution. Please let me know if this is possible or if there's something I could take a look at to solve this.\n\nThanks in advance!\n\n========================================\n\nTop Answer:\nThere is a pretty good solution!\n\nFor example you have something like this:\n\n```\nexport type GetProductQuery = {\n __typename?: 'Query'\n product?:\n | { __typename: 'NotFound'; message: string }\n | {\n __typename: 'Product'\n id: string\n title: string\n currentPrice: number\n }\n | null\n}\n```\n\nThen, you can use the Extract utility type\n\n```\ntype QueryProductData = Extract\ntype QueryNotFoundData = Extract\n```\n\nFrom these types, you can construct any type in the future.\n\n========================================\n\nCode:\n```js\n/** @type {import('graphql-config').IGraphQLConfig} */\nconst graphqlConfig = {\n schema: process.env.NEXT_PUBLIC_API_URL,\n documents: './src/graphql/**/*.ts',\n extensions: {\n codegen: {\n hooks: {\n afterAllFileWrite: ['prettier --write'],\n },\n generates: {\n './src/__generated__/graphql.ts': {\n plugins: [\n 'typescript',\n 'typescript-operations',\n {\n add: {\n content: '/* eslint-disable */',\n },\n },\n ],\n config: {\n disableDescriptions: true,\n },\n },\n './src/__generated__/introspection-result.ts': {\n plugins: ['fragment-matcher'],\n config: {\n useExplicitTyping: true,\n },\n },\n },\n },\n },\n}\n```\n\n```js\nexport type QueryName = {\n __typename?: 'Query'\n resource?:\n | { __typename?: 'A' }\n | { __typename?: 'B' }\n | {\n __typename?: 'C'\n id: string\n prop1: any\n prop2: any\n }\n}\n```\n\n```js\nexport type QueryName = {\n __typename?: 'Query'\n resource?: {\n __typename?: 'C'\n id: string\n prop1: any\n prop2: any\n }\n}\n```\n\n```text\n.graphqlrc.js\n```\n\n```text\nC\n```\n\n```js\nconst {data} = useUserQuery({variables: {id}});\n\n// more codes here...\n\ninvariant(data.user.__typename === \"User\");\n\n// now we should get the type that we want here\n```\n\n```text\nif (data.user.__typename === \"User\") { ... };\n```\n\n```text\nexport type GetProductQuery = {\n __typename?: 'Query'\n product?:\n | { __typename: 'NotFound'; message: string }\n | {\n __typename: 'Product'\n id: string\n title: string\n currentPrice: number\n }\n | null\n}\n```\n\n```text\ntype QueryProductData = Extract<GetProductQuery['product'], { __typename: 'Product' }>\ntype QueryNotFoundData = Extract<GetProductQuery['product'], { __typename: 'NotFound' }>\n```\n\n========================================\n\nComments:\n- I tried to make a helper function: `function ensureType(graphqlObject, expectedTypeName) { invariant(graphqlObject.__typename === expectedTypeName, `Expected graphql object to be type of ${expectedTypeName}; got ${graphqlObject.__typename}`); }` Any idea how to make it work?\n- Why use tiny-invariant? You can do the same thing with an if statement","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":228,"estimatedTokens":1186}}967{"id":"stack-56345757","source":"stackoverflow","questionId":56345757,"title":"\"cannot query field 'id' on type CreateUser\" with official Graphql tutorial","tags":["graphql","graphene-python","graphql-python"],"text":"Title: \"cannot query field 'id' on type CreateUser\" with official Graphql tutorial\nTags: graphql, graphene-python, graphql-python\nSource: Stack Overflow\n\nQuestion:\nI am following the graphql-python tutorial on https://www.howtographql.com/graphql-python/4-authentication/. However, I get 3 errors saying \"Cannot query field \\\"id\\\" on type \\\"CreateUser\\\".\" I basically copied all source code in the tutorial and I double-checked my Python code before posting here. And I used the same versions of Django, Graphene and other packages. I use Windows 10 and Python3.7. How can I pass the error?\n\nMutation:\n\n```\nmutation {\n createUser (\n username: \"abc\",\n email: \"abc@example.com\",\n password: \"123456\"\n ){\n id\n username\n password\n }\n}\n```\n\nResponse:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Cannot query field \\\"id\\\" on type \\\"CreateUser\\\".\",\n \"locations\": [\n {\n \"line\": 7,\n \"column\": 5\n }\n ]\n },\n {\n \"message\": \"Cannot query field \\\"username\\\" on type \\\"CreateUser\\\". Did you mean \\\"user\\\"?\",\n \"locations\": [\n {\n \"line\": 8,\n \"column\": 5\n }\n ]\n },\n {\n \"message\": \"Cannot query field \\\"password\\\" on type \\\"CreateUser\\\".\",\n \"locations\": [\n {\n \"line\": 9,\n \"column\": 5\n }\n ]\n }\n ]\n}\n```\n\n========================================\n\nCode:\n```text\nmutation {\n createUser (\n username: \"abc\",\n email: \"abc@example.com\",\n password: \"123456\"\n ){\n id\n username\n password\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Cannot query field \\\"id\\\" on type \\\"CreateUser\\\".\",\n \"locations\": [\n {\n \"line\": 7,\n \"column\": 5\n }\n ]\n },\n {\n \"message\": \"Cannot query field \\\"username\\\" on type \\\"CreateUser\\\". Did you mean \\\"user\\\"?\",\n \"locations\": [\n {\n \"line\": 8,\n \"column\": 5\n }\n ]\n },\n {\n \"message\": \"Cannot query field \\\"password\\\" on type \\\"CreateUser\\\".\",\n \"locations\": [\n {\n \"line\": 9,\n \"column\": 5\n }\n ]\n }\n ]\n}\n```\n\n```text\nmutation {\n createUser (\n username: \"abc\",\n email: \"abc@example.com\",\n password: \"123456\"\n ){\n user {\n id\n username\n password\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":125,"estimatedTokens":538}}968{"id":"stack-59842182","source":"stackoverflow","questionId":59842182,"title":"How to call useQuery as an async task","tags":["react-native","graphql","react-hooks","apollo","apollo-client"],"text":"Title: How to call useQuery as an async task\nTags: react-native, graphql, react-hooks, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am new to `React Native` and `Apollo-Client`. In my Screen there are three tabs and individual tabs is calling its own data. But due to `useQuery` UI is completely freezing and giving a very bad experience.\n\nIs there any other way that I can call the `useQuery` in async manner or in any background task?\n\n**EDIT**\n\n```\nfunction PlayerList(props) {\n\n const [loading , setloading] = useState(true)\n const [data, setData] = useState()\n const [loadData, { tempLoading, tempError, tempData }] = useLazyQuery(query);\n \n\n async function getData(){\n loadData()\n }\n\n useEffect(() => {\n\n if (tempData == undefined) {\n getData()\n }\n\n })\n\n if(tempLoading){\n return \n ....\n }\n if(tempData) {\n return ( ... ) }\n\n }\n```\n\nPlease find the above code for better understanding.\n\n========================================\n\nCode:\n```text\nfunction PlayerList(props) {\n\n const [loading , setloading] = useState(true)\n const [data, setData] = useState()\n const [loadData, { tempLoading, tempError, tempData }] = useLazyQuery(query);\n \n\n async function getData(){\n loadData()\n }\n\n useEffect(() => {\n\n if (tempData == undefined) {\n getData()\n }\n\n })\n\n if(tempLoading){\n return \n <View >....</View>\n }\n if(tempData) {\n return ( <View> ... </View>) }\n\n }\n```\n\n```text\nReact Native\n```\n\n```text\nApollo-Client\n```\n\n```text\nuseQuery\n```\n\n```text\nuseQuery\n```\n\n```text\nconst { data, loading } = useQuery(query)\nif (loading) {\n return <View>....</View>\n}\nreturn <View>...</View>\n```\n\n```text\nuseLazyQuery\n```\n\n```text\ntempLoading\n```\n\n```text\ntempError\n```\n\n```text\ntempData\n```\n\n```text\ntempData\n```\n\n```text\nuseEffect\n```\n\n```text\nloadData\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nuseQuery\n```\n\n========================================\n\nComments:\n- Apollo Client uses fetch under the hood, which is always asynchronous. It sounds like something else is going on. You should edit your question to include the relevant code.\n- @DanielRearden , please look the edited one.\n- Thanks for updating about Apollo Client being the asynchronous. My issue was my UI was not getting updated properly after fetching the data.","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":142,"estimatedTokens":581}}969{"id":"stack-65533359","source":"stackoverflow","questionId":65533359,"title":"Good use of FetchMore GQL for infinite scroll pagination ListView with Flutter","tags":["flutter","graphql"],"text":"Title: Good use of FetchMore GQL for infinite scroll pagination ListView with Flutter\nTags: flutter, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a ListView of elements comming from a GraphQL API with graphql-flutter library.\n\nThe build of the first page is OK. Then when I start to scroll, the result will be good, my ListView show the second page, then third ect ... correctly.\n\nThe problem is, from the second page loading, there is a problem. FetchMore function seems to build multiple request at each page loading. It's like all previous page ever load are load again, more and more.\n\nStrangely as I said, the result of the displayed list is correct for several pages, then suddenly the list loops back from a previous page, then resumes further ...\n\nThis is my Query widget:\n\n```\nQuery(\n options: QueryOptions(\n document: gql(getHistory),\n variables: {\n 'pubkey': this.pubkey,\n 'number': nRepositories,\n 'cursor': null\n },\n ),\n builder: (QueryResult result, {refetch, FetchMore fetchMore}) {\n if (result.isLoading && result.data == null) {\n return const Center(\n child: CircularProgressIndicator(),\n );\n }\n\n if (result.hasException) {\n return Text('\\nErrors: \\n ' + result.exception.toString());\n }\n\n if (result.data == null && result.exception.toString() == null) {\n return const Text('Both data and errors are null');\n }\n\n final List blockchainTX =\n (result.data['txsHistoryBc']['both']['edges'] as List);\n\n final Map pageInfo =\n result.data['txsHistoryBc']['both']['pageInfo'];\n\n final String fetchMoreCursor =\n pageInfo['endCursor'];\n\n FetchMoreOptions opts = FetchMoreOptions(\n variables: {'cursor': fetchMoreCursor},\n updateQuery: (previousResultData, fetchMoreResultData) {\n final List repos = [\n ...previousResultData['txsHistoryBc']['both']['edges']\n as List,\n ...fetchMoreResultData['txsHistoryBc']['both']['edges']\n as List\n ];\n\n fetchMoreResultData['txsHistoryBc']['both']['edges'] = repos;\n return fetchMoreResultData;\n },\n );\n\n _scrollController\n ..addListener(() {\n if (_scrollController.position.pixels ==\n _scrollController.position.maxScrollExtent) {\n if (!result.isLoading) {\n print(\n \"DEBUG fetchMoreCursor in scrollController: $fetchMoreCursor\");\n fetchMore(opts);\n }\n }\n });\n\n print(\n \"###### DEBUG Parse blockchainTX list. Cursor: $fetchMoreCursor ######\");\n List _transBC = parseHistory(blockchainTX);\n\n return Expanded(\n child: HistoryListView(\n scrollController: _scrollController,\n transBC: _transBC,\n historyData: result),\n );\n },\n),\n```\n\nThen the Widget `HistoryListView` build the list from `transBC` data.\nThis is the print result of `DEBUG` lines *(see the code above)* for just one page loading, from the start of the app:\n\n```\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8 ######\nI/flutter ( 8745): DEBUG fetchMoreCursor in scrollController: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8 ######\nI/flutter ( 8745): DEBUG fetchMoreCursor in scrollController: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8 ######\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 384695:4BF72317A538FB37F71C0A8D5CC36F319F87B7421260F128EFFF75B9A17C2CC7 ######\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 384695:4BF72317A538FB37F71C0A8D5CC36F319F87B7421260F128EFFF75B9A17C2CC7 ######\n```\n\nNote that the `scrollController` function is executed twice, with the first cursor as the same value.\nAnd the `parseHistory` function is then executed 3 times! I just scrolled to load 1 page here.\n\nI really don't understand this behavior ...\nI've been working on it for a week now, if developers of this library could explain it to me that would be fantastic.\n\nI am using version 4.0.0-beta.6 of the `graphql_flutter` library.\n\nEdit: This is the UI asociate for this test: https://i.sstatic.net/FUuPS.png\n\nThe value of `nRepository` here is `3`.\n\n========================================\n\nTop Answer:\nI am using notification listener for capturing scroll reaching to the bottom event and it is working. And if you wanna make sure to keep the scroll position after fetching more, be sure to add key in the listview.\n\n```\nreturn NotificationListener(\n onNotification: (t) {\n if (t is ScrollEndNotification && _scrollController.position.pixels >= _scrollController.position.maxScrollExtent * 0.7) {\n fetchMore(_fetchMoreOptions);\n }\n return true;\n },\n child: ListView.builder(\n key: const PageStorageKey('uniqueString'),\n controller: _scrollController,\n ...\n ),\n);\n```\n\n========================================\n\nCode:\n```text\nQuery(\n options: QueryOptions(\n document: gql(getHistory),\n variables: <String, dynamic>{\n 'pubkey': this.pubkey,\n 'number': nRepositories,\n 'cursor': null\n },\n ),\n builder: (QueryResult result, {refetch, FetchMore fetchMore}) {\n if (result.isLoading && result.data == null) {\n return const Center(\n child: CircularProgressIndicator(),\n );\n }\n\n if (result.hasException) {\n return Text('\\nErrors: \\n ' + result.exception.toString());\n }\n\n if (result.data == null && result.exception.toString() == null) {\n return const Text('Both data and errors are null');\n }\n\n final List<dynamic> blockchainTX =\n (result.data['txsHistoryBc']['both']['edges'] as List<dynamic>);\n\n final Map pageInfo =\n result.data['txsHistoryBc']['both']['pageInfo'];\n\n final String fetchMoreCursor =\n pageInfo['endCursor'];\n\n FetchMoreOptions opts = FetchMoreOptions(\n variables: {'cursor': fetchMoreCursor},\n updateQuery: (previousResultData, fetchMoreResultData) {\n final List<dynamic> repos = [\n ...previousResultData['txsHistoryBc']['both']['edges']\n as List<dynamic>,\n ...fetchMoreResultData['txsHistoryBc']['both']['edges']\n as List<dynamic>\n ];\n\n fetchMoreResultData['txsHistoryBc']['both']['edges'] = repos;\n return fetchMoreResultData;\n },\n );\n\n _scrollController\n ..addListener(() {\n if (_scrollController.position.pixels ==\n _scrollController.position.maxScrollExtent) {\n if (!result.isLoading) {\n print(\n \"DEBUG fetchMoreCursor in scrollController: $fetchMoreCursor\");\n fetchMore(opts);\n }\n }\n });\n\n print(\n \"###### DEBUG Parse blockchainTX list. Cursor: $fetchMoreCursor ######\");\n List _transBC = parseHistory(blockchainTX);\n\n return Expanded(\n child: HistoryListView(\n scrollController: _scrollController,\n transBC: _transBC,\n historyData: result),\n );\n },\n),\n```\n\n```text\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8 ######\nI/flutter ( 8745): DEBUG fetchMoreCursor in scrollController: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8 ######\nI/flutter ( 8745): DEBUG fetchMoreCursor in scrollController: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 386237:8A98F83A120EF89FC65CF43BEE77068F3DA5734340B7987FA059D582A06934F8 ######\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 384695:4BF72317A538FB37F71C0A8D5CC36F319F87B7421260F128EFFF75B9A17C2CC7 ######\nI/flutter ( 8745): ###### DEBUG Parse blockchainTX list. Cursor: 384695:4BF72317A538FB37F71C0A8D5CC36F319F87B7421260F128EFFF75B9A17C2CC7 ######\n```\n\n```text\nHistoryListView\n```\n\n```text\ntransBC\n```\n\n```text\nDEBUG\n```\n\n```text\nscrollController\n```\n\n```text\nparseHistory\n```\n\n```text\ngraphql_flutter\n```\n\n```text\nnRepository\n```\n\n```text\n3\n```\n\n```text\n_scrollController.addListener()\n```\n\n```text\nbuild\n```\n\n```text\nfetchMore(opts)\n```\n\n```text\nmaxScrollExtent\n```\n\n```text\naddListener\n```\n\n```text\ninitState\n```\n\n```text\nNotificationListener<ScrollUpdateNotification>\n```\n\n```dart\nreturn NotificationListener(\n onNotification: (t) {\n if (t is ScrollEndNotification && _scrollController.position.pixels >= _scrollController.position.maxScrollExtent * 0.7) {\n fetchMore(_fetchMoreOptions);\n }\n return true;\n },\n child: ListView.builder(\n key: const PageStorageKey<String>('uniqueString'),\n controller: _scrollController,\n ...\n ),\n);\n```\n\n========================================\n\nComments:\n- Thank you, I try to understand where to put my `addListener()` to call `fetchMore(opts)`, or how to use `NotificationListener` ...\n- @poka Did you find any solution\n- @Shaon Yes, I dont use `addListener` anymore, and use `NotificationListener` widget; like @micimize , as you can see here: git.duniter.org/clients/gecko/-/blob/master/lib/screens/… Everything is working fine this way.","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":306,"estimatedTokens":2313}}970{"id":"stack-62717215","source":"stackoverflow","questionId":62717215,"title":"How do I pass two parameters to GraphQLHttpClient in c#?","tags":["c#","graphql"],"text":"Title: How do I pass two parameters to GraphQLHttpClient in c#?\nTags: c#, graphql\nSource: Stack Overflow\n\nQuestion:\nI am having a problem similar to this. I have updated my GraphQLHttpClient and now I need to supply an extra parameter, solution give is:\n\n```\nGraphQLHttpClient gql = new GraphQLHttpClient(o => {\no.EndPoint = _config[\"API:Endpoint\"];\no.JsonSerializer = new NewtonsoftJsonSerializer();\n});\n```\n\nbut this tells me:\n`Error CS1729 'GraphQLHttpClient' does not contain a constructor that takes 1 arguments`\nI have also tried:\n\n```\nusing Newtonsoft.Json\nGraphQLHttpClient gql = new GraphQLHttpClient(_options.Url, new Newtonsoft.Json.JsonSerializer());\n```\n\nwhich gives `Error CS1503 Argument 2: cannot convert from 'Newtonsoft.Json.JsonSerializer' to 'GraphQL.Client.Abstractions.Websocket.IGraphQLWebsocketJsonSerializer'`\n\nI know very little c# so I'd be grateful for any pointers.\n\n========================================\n\nCode:\n```text\nGraphQLHttpClient gql = new GraphQLHttpClient(o => {\no.EndPoint = _config[\"API:Endpoint\"];\no.JsonSerializer = new NewtonsoftJsonSerializer();\n});\n```\n\n```text\nusing Newtonsoft.Json\nGraphQLHttpClient gql = new GraphQLHttpClient(_options.Url, new Newtonsoft.Json.JsonSerializer());\n```\n\n```text\nError CS1729 'GraphQLHttpClient' does not contain a constructor that takes 1 arguments\n```\n\n```text\nError CS1503 Argument 2: cannot convert from 'Newtonsoft.Json.JsonSerializer' to 'GraphQL.Client.Abstractions.Websocket.IGraphQLWebsocketJsonSerializer'\n```\n\n```text\nGraphQLHttpClient gql = new GraphQLHttpClient(_options.Url, new NewtonsoftJsonSerializer());\n```\n\n```text\nNewtonsoftJsonSerializer\n```\n\n```text\nIGraphQLWebsocketJsonSerializer\n```\n\n```text\nNewtonsoft.Json.JsonSerializer\n```\n\n```text\nIGraphQLWebsocketJsonSerializer\n```\n\n```text\nIGraphQLWebsocketJsonSerializer\n```\n\n========================================\n\nComments:\n- Thank you, but that gives me `Error\tCS0234\tThe type or namespace name 'NewtonsoftJsonSerializer' does not exist in the namespace` how do I get that one?\n- I had to get nuget package: `GraphQL.Client.Serializer.Newtonsoft`.\n- @schoon yep, I was just about to update this answer with exactly that. Well done!","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":80,"estimatedTokens":548}}971{"id":"stack-60827105","source":"stackoverflow","questionId":60827105,"title":"Wrapping graphQL(appsync) with REST API using Amazon api gateway","tags":["amazon-web-services","graphql","aws-appsync","aws-api-gateway"],"text":"Title: Wrapping graphQL(appsync) with REST API using Amazon api gateway\nTags: amazon-web-services, graphql, aws-appsync, aws-api-gateway\nSource: Stack Overflow\n\nQuestion:\nI have a graphQL server deployed with aws appsync. The thing is that our customers prefer a standard REST API. I'm looking for the simplest way to wrap graphQL query with REST API.\n\nI'm considering using Amazon api gateway to make a REST endpoint, and integrate lambda behind the api gateway. In that way I can let lambda functions to send a fixed graphQL query/mutations and modify the response.\n\nHowever as you can see from below image, I found AWS Service integration option in Amazon API gateway. I'm wondering whether I can integrate appsync to api gateway directly without using lambda. I searched it from aws documents but couldn't find any related information.\n\nAmazon api gateway setup capture:\n\n- Is it possible to wrap graphQL API with REST API by integrating appsync to api gateway without using lambda? Just like what I found from the captured image?\n\n- If yes, is there any examples or tutorials?\n\n- If not, should I just integrate lambda? Is there any better ideas or tips?\n\n========================================\n\nTop Answer:\nIn case someone using OpenAPI spec for defining APIGW, use the following:\n\n```\n/graphql:\n post:\n x-amazon-apigateway-integration:\n type: \"AWS\"\n httpMethod: \"POST\"\n uri: arn:aws:apigateway::.appsync-api:path/graphql\n credentials: \n```\n\nhttps://docs.aws.amazon.com/general/latest/gr/appsync.html#appsync_region_data_plane\nhttps://docs.aws.amazon.com/apigateway/api-reference/resource/integration/#type\n\n========================================\n\nCode:\n```text\n/graphql:\n post:\n x-amazon-apigateway-integration:\n type: \"AWS\"\n httpMethod: \"POST\"\n uri: arn:aws:apigateway:<APIGW_REGION>:<APPSYNC_URL_ID>.appsync-api:path/graphql\n credentials: <INVOCATION_ROLE_ARN>\n```\n\n```text\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": \"apigateway.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRole\",\n \"Condition\": {}\n }\n ]\n}\n```\n\n```text\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": [\n \"appsync:GraphQL\"\n ],\n \"Resource\": [\n \"arn:aws:appsync:us-east-1:{AWS-Account-Number}:apis/{AppSync-API-ID}/*\"\n ],\n \"Effect\": \"Allow\"\n }\n ]\n}\n```\n\n```text\nquery MyQuery {\n foo(request: {bar: \"abc123\", baz: \"xyz\"}) {\n a\n b\n c\n }\n}\n```\n\n```text\n{\n \"query\": \"query MyQuery {foo(request: {bar: \\\"abc123\\\", baz: \\\"xyz\\\"}) {a b c} }\"\n}\n```\n\n========================================\n\nComments:\n- Hi @BSD, Can you pls the execution role you created? I tried your steps and created an execution role(from another Medium post - medium.com/@aswinkumar4018/…) as below - { \"Version\": \"2012-10-17\", \"Statement\": [ { \"Action\": [ \"appsync:GraphQL\" ], \"Resource\": [ \"arn:aws:appsync:us-east-1:{AWS-Account-Number}:apis/{AppSyn‌​c-API-ID}/*\" ], \"Effect\": \"Allow\" } ] }\n- but I get error - Execution failed due to configuration error: API Gateway does not have permission to assume the provided role\n- @csharpnewbie make sure the role has enough permissions to call appsync\n- @BSD how do format the request for the rest api? wouldn't the body be the same as a graphql query? If so what is the point in creating a proxy rather than just making the appsync public\n- I can't seem to figure out how to construct the uri for OpenAPI Spec. Is there a way to get this dynamically in terraform? e.g. aws_appsync_graphql_api.mygraphql.arn did not work","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":107,"estimatedTokens":917}}972{"id":"stack-57836075","source":"stackoverflow","questionId":57836075,"title":"How do I update the grapqhl cache with urql upon a mutation, where the initial query response does not include the required __typename?","tags":["javascript","reactjs","caching","graphql","urql"],"text":"Title: How do I update the grapqhl cache with urql upon a mutation, where the initial query response does not include the required __typename?\nTags: javascript, reactjs, caching, graphql, urql\nSource: Stack Overflow\n\nQuestion:\nMy situation has 4 components nested within each other in this order: `Products` (page), `ProductList`, `ProductListItem`, and `CrossSellForm`.\n\n`Products` executes a graphql query (using urql) as such:\n\n```\nconst productsQuery = `\n query {\n products {\n id\n title\n imageSrc\n crossSells {\n id\n type\n title\n }\n }\n }\n`;\n\n...\n\nconst [response] = useQuery({\n query: productsQuery,\n });\n const { data: { products = [] } = {}, fetching, error } = response;\n\n...\n\n \n```\n\n`products` returns an array of `Products` that contains a field, `crossSells`, that returns an array of `CrossSells`. `Products` is propagated downwards to `CrossSellForm`, which contains a mutation query that returns an array of `CrossSells`.\n\nThe problem is that when I submit the crossSellForm the request goes through successfully but the `crossSells` up in `Products` does not update, and the UI reflects stale data. This only happens when the initial fetch up in `Products` contains no `crossSells`, so the initial response looks something like this:\n\n```\n{\ndata: {\n products: [\n {\n id: '123123',\n title: 'Nice',\n imageSrc: 'https://image.com',\n crossSells: [],\n __typename: \"Product\"\n },\n ...\n ]\n }\n}\n}\n```\n\nIf there is an existing `crossSell`, there is no problem, the ui updates properly and the response looks like this:\n\n```\n{\n data: {\n products: [\n {\n id: '123123',\n title: 'Nice',\n imageSrc: 'https://image.com',\n crossSells: [\n {\n id: 40,\n title: 'Nice Stuff',\n type: 'byVendor',\n __typename: 'CrossSell'\n }\n ],\n __typename: \"Product\"\n },\n ...\n ]\n }\n }\n}\n```\n\nI read up a bit on urql's caching mechanism at https://formidable.com/open-source/urql/docs/basics/ and from what I understand it uses a document cache, so it caches the document based on `__typename`. If a query requests something with a the same `__typename` it will pull it from the cache. If a `mutation` occurs with the same `__typename` it will invalidate all objects in the cache with that `__typename` so the next time the user fetches an object with that `__typename` it will execute a network request instead of cache. \n\nWhat I think is going on is in the initial situation where there are `products` but no `crossSells` the form submission is successful but the `Products` page does not update because there is no reference to an object with `__typename` of `CrossSell`, but in the second situation there is so it busts the cache and executes the query again, refreshes products and cross-sells and the UI is properly updated.\n\nI've really enjoyed the experience of using urql hooks with React components and want to continue but I'm not sure how I can fix this problem without reaching for another tool. \n\nI've tried to force a re-render upon form submission using tips from: How can I force component to re-render with hooks in React? but it runs into the same problem where `Products` will fetch from the cache again and `crossSells` will return an empty array. I thought about modifying urql's RequestPolicy to network only, along with the forced re-render, but I thought that would be unnecessarily expensive to re-fetch every single time. The solution I'm trying out now is to move all the state into redux, a single source of truth so that any update to `crossSells` will propagate properly, and although I'm sure it will work it will also mean I'll trade in a lot of the convenience I had with hooks for standard redux boilerplate. \n\nHow can I gracefully update `Products` with `crossSells` upon submitting the form within `CrossSellForm`, while still using urql and hooks?\n\n========================================\n\nCode:\n```text\nconst productsQuery = `\n query {\n products {\n id\n title\n imageSrc\n crossSells {\n id\n type\n title\n }\n }\n }\n`;\n\n...\n\nconst [response] = useQuery({\n query: productsQuery,\n });\n const { data: { products = [] } = {}, fetching, error } = response;\n\n...\n\n <ProductList products={products} />\n```\n\n```text\n{\ndata: {\n products: [\n {\n id: '123123',\n title: 'Nice',\n imageSrc: 'https://image.com',\n crossSells: [],\n __typename: \"Product\"\n },\n ...\n ]\n }\n}\n}\n```\n\n```text\n{\n data: {\n products: [\n {\n id: '123123',\n title: 'Nice',\n imageSrc: 'https://image.com',\n crossSells: [\n {\n id: 40,\n title: 'Nice Stuff',\n type: 'byVendor',\n __typename: 'CrossSell'\n }\n ],\n __typename: \"Product\"\n },\n ...\n ]\n }\n }\n}\n```\n\n```text\nProducts\n```\n\n```text\nProductList\n```\n\n```text\nProductListItem\n```\n\n```text\nCrossSellForm\n```\n\n```text\nProducts\n```\n\n```text\nproducts\n```\n\n```text\nProducts\n```\n\n```text\ncrossSells\n```\n\n```text\nCrossSells\n```\n\n```text\nProducts\n```\n\n```text\nCrossSellForm\n```\n\n```text\nCrossSells\n```\n\n```text\ncrossSells\n```\n\n```text\nProducts\n```\n\n```text\nProducts\n```\n\n```text\ncrossSells\n```\n\n```text\ncrossSell\n```\n\n```text\n__typename\n```\n\n```text\n__typename\n```\n\n```text\nmutation\n```\n\n```text\n__typename\n```\n\n```text\n__typename\n```\n\n```text\n__typename\n```\n\n```text\nproducts\n```\n\n```text\ncrossSells\n```\n\n```text\nProducts\n```\n\n```text\n__typename\n```\n\n```text\nCrossSell\n```\n\n```text\nProducts\n```\n\n```text\ncrossSells\n```\n\n```text\ncrossSells\n```\n\n```text\nProducts\n```\n\n```text\ncrossSells\n```\n\n```text\nCrossSellForm\n```\n\n========================================\n\nComments:\n- I dug a bit more and found a similar issue in the repo's github: github.com/FormidableLabs/urql/issues/212 There seems to be a normalized cache exchange under development that can replace the default one in urql: github.com/FormidableLabs/urql-exchange-graphcache. I briefly looked into it but it seemed to require a bit more configuration out of the box for my use-case and I decided that using redux would be simpler.","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":37,"totalLines":310,"estimatedTokens":1523}}973{"id":"stack-48696210","source":"stackoverflow","questionId":48696210,"title":"Invoke-WebRequest failed - \"Problems parsing json\" with GitHub api","tags":["json","powershell","curl","github","graphql"],"text":"Title: Invoke-WebRequest failed - \"Problems parsing json\" with GitHub api\nTags: json, powershell, curl, github, graphql\nSource: Stack Overflow\n\nQuestion:\nI am attempting to communicate with the `Graphql` api through powershell. According to Github, one must first do the following `curl` call.\n\n```\ncurl -H \"Authorization: bearer token\" -X POST -d \" \\\n { \\\n \\\"query\\\": \\\"query { viewer { login }}\\\" \\\n } \\\n\" https://api.github.com/graphql\n```\n\nUsing **GitHub Enterprise**, on powershell I do the following calls:\n\n```\n$url = \"http://github.company.com/api/graphql\" # note that it's http, not https\n\n$body = \"`\"query`\":`\"query { viewer { login }}`\"\" #`\n\n$headers = New-Object \"System.Collections.Generic.Dictionary[[String],[String]]\"\n\n$headers.Add(\"content-type\",\"application/json\")\n\n$headers.Add(\"Authorization\",\"bearer myTokenNumber\")\n\n$response = Invoke-WebRequest -Uri $url -Method POST -Body $body -Headers $headers\n```\n\nI keep getting the same error message, that there are problems parsing JSON.\n\nI assume the error is with the `body` tag, but I can't see how. \n\n`echo $body` gives `\"query\":\"query { viewer { login }}\"`\n\nWhat is the issue here?\n\nExact error message:\n\n```\nInvoke-WebRequest : {\"message\":\"Problems parsing JSON\",\"documentation_url\":\"https://developer.github.com/v3\"}\nAt line:1 char:13\n+ $response = Invoke-WebRequest -Uri $url -Method POST -Body $body -Headers $heade ...\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc\n eption\n + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand\n```\n\n========================================\n\nTop Answer:\nHere is the working program. Thanks to those who answered:\n\n```\n$url = \"https://api.github.com/graphql\" # regular github\n# for enterprise it will be http(s)://[hostname]/api/graphql where hostname is \n# usually github.company.com ... try with both http and https\n\n$body = @'\n{ \"query\": \"query { viewer { login } }\" }\n'@\n\n$headers = @{\n \"content-type\" = \"application/json\"\n \"Authorization\" = \"bearer tokenCode\"\n}\n\n$response = Invoke-WebRequest -Uri $url -Method POST -Body $body -Headers $headers\nWrite-Host $response\n```\n\nOutput: `{\"data\":{\"viewer\":{\"login\":\"yourGithubUsername\"}}}`\n\n========================================\n\nCode:\n```text\ncurl -H \"Authorization: bearer token\" -X POST -d \" \\\n { \\\n \\\"query\\\": \\\"query { viewer { login }}\\\" \\\n } \\\n\" https://api.github.com/graphql\n```\n\n```text\n$url = \"http://github.company.com/api/graphql\" # note that it's http, not https\n\n$body = \"`\"query`\":`\"query { viewer { login }}`\"\" #`\n\n$headers = New-Object \"System.Collections.Generic.Dictionary[[String],[String]]\"\n\n$headers.Add(\"content-type\",\"application/json\")\n\n$headers.Add(\"Authorization\",\"bearer myTokenNumber\")\n\n$response = Invoke-WebRequest -Uri $url -Method POST -Body $body -Headers $headers\n```\n\n```text\nInvoke-WebRequest : {\"message\":\"Problems parsing JSON\",\"documentation_url\":\"https://developer.github.com/v3\"}\nAt line:1 char:13\n+ $response = Invoke-WebRequest -Uri $url -Method POST -Body $body -Headers $heade ...\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc\n eption\n + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand\n```\n\n```text\nGraphql\n```\n\n```text\ncurl\n```\n\n```text\nbody\n```\n\n```text\necho $body\n```\n\n```text\n\"query\":\"query { viewer { login }}\"\n```\n\n```text\n$body = @'\n{ \"query\": \"query { viewer { login } }\" }\n'@\n```\n\n```text\n$headers = @{\n \"content-type\" = \"application/json\"\n \"Authorization\" = \"bearer myTokenNumber\"\n}\n```\n\n```text\n$body\n```\n\n```text\n{ ... }\n```\n\n```text\n$url = \"https://api.github.com/graphql\" # regular github\n# for enterprise it will be http(s)://[hostname]/api/graphql where hostname is \n# usually github.company.com ... try with both http and https\n\n$body = @'\n{ \"query\": \"query { viewer { login } }\" }\n'@\n\n$headers = @{\n \"content-type\" = \"application/json\"\n \"Authorization\" = \"bearer tokenCode\"\n}\n\n$response = Invoke-WebRequest -Uri $url -Method POST -Body $body -Headers $headers\nWrite-Host $response\n```\n\n```text\n{\"data\":{\"viewer\":{\"login\":\"yourGithubUsername\"}}}\n```\n\n========================================\n\nComments:\n- Can you please the exact error message?\n- Please check now\n- Have you tested your token and Query in GitHub's GraphQL Explorer Interface ?\n- Works perfectly there\n- Is there a reason why you have to use the `http` version?\n- For a certain reason, `https` does not with github enterprise when I do it, but regardless, I tried this at home using `https` (normal git), and still the same error\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":184,"estimatedTokens":1231}}974{"id":"stack-58166982","source":"stackoverflow","questionId":58166982,"title":"Graphql returns null id for mongoose aggregation query","tags":["mongodb","mongoose","graphql","aggregation-framework","apollo-server"],"text":"Title: Graphql returns null id for mongoose aggregation query\nTags: mongodb, mongoose, graphql, aggregation-framework, apollo-server\nSource: Stack Overflow\n\nQuestion:\nGraphql returns null id for mongoose aggregation query, but works ok other mongoose queries.\n\nHere is my mongoose schema:\n\n```\nconst { Schema } = mongoose;\nconst ObjectId = Schema.Types.ObjectId;\n\nconst productSchema = new Schema({\n _id: ObjectId,\n price: Number\n})\n\nconst Product = mongoose.model('Product', productSchema, 'Product')\n```\n\nHere is my Graphql schema:\n\n```\ntype Product {\n id: ID\n price: String\n}\n```\n\nGraphql normal query:\n\n```\ncontext.Product.findOne()\n```\n\nResult with console.log:\n\n```\n[ {\n price: 10, \n _id: 5d7f8efebff791dcd3bb1b69\n}]\n```\n\nResult with graphql:\n\n```\n\"getSearch\": [\n {\n \"id\": \"5d7f8efebff791dcd3bb1b69\",\n \"price\": 10,\n }]\n```\n\nEverything is fine here. \n**Now the problem is with aggregation query:**\n\nGraphQL query:\n\n```\ncontext.Product.aggregate(\n [\n { $sample: { size: 1 } }\n ]\n )\n```\n\nResult with console.log:\n\n```\n[ { _id: 5d7f8f23bff791dcd3bb1da3,\n price: 5\n}]\n```\n\nResult with GraphQL:\n\n```\n\"test\": [\n {\n \"id\": null\",\n \"price\": 7,\n }]\n```\n\nThe problem here is: \n\n- the id is null\n\n- the responses from console.log and graphql are different objects\n\n========================================\n\nTop Answer:\nAdding `id` element to the result works fine to mine\n\n```\nconst res = await Product.aggregate(\n [\n { $sample: { size: 1 } }\n ]\n )\n res.forEach(element => {\n element.id = element._id \n });\n return res;\n```\n\n========================================\n\nCode:\n```text\nconst { Schema } = mongoose;\nconst ObjectId = Schema.Types.ObjectId;\n\nconst productSchema = new Schema({\n _id: ObjectId,\n price: Number\n})\n\nconst Product = mongoose.model('Product', productSchema, 'Product')\n```\n\n```text\ntype Product {\n id: ID\n price: String\n}\n```\n\n```text\ncontext.Product.findOne()\n```\n\n```text\n[ {\n price: 10, \n _id: 5d7f8efebff791dcd3bb1b69\n}]\n```\n\n```text\n\"getSearch\": [\n {\n \"id\": \"5d7f8efebff791dcd3bb1b69\",\n \"price\": 10,\n }]\n```\n\n```text\ncontext.Product.aggregate(\n [\n { $sample: { size: 1 } }\n ]\n )\n```\n\n```text\n[ { _id: 5d7f8f23bff791dcd3bb1da3,\n price: 5\n}]\n```\n\n```text\n\"test\": [\n {\n \"id\": null\",\n \"price\": 7,\n }]\n```\n\n```text\nfunction resolve (parent, args, context, info) {\n return parent.id || parent._id\n}\n```\n\n```text\nid\n```\n\n```text\n_id\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\nfind\n```\n\n```text\nfindOne\n```\n\n```text\naggregate\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\n_id\n```\n\n```js\ntype Product {\n id: ID\n _id: ID\n price: String\n}\n```\n\n```text\n@Prop()//remove this\n @Field(() => ID,{ nullable: true })\n _id: string;\n```\n\n```text\nnest js\n```\n\n```text\nGraphQL\n```\n\n```text\nid\n```\n\n```text\n_id\n```\n\n```text\n@prop\n```\n\n```text\nconst res = await Product.aggregate(\n [\n { $sample: { size: 1 } }\n ]\n )\n res.forEach(element => {\n element.id = element._id \n });\n return res;\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- There's no reason this would somehow interfere with Apollo Client's cacheRedirects. If it does, then it's an issue with how you're implementing cacheRedirects.","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":272,"estimatedTokens":820}}975{"id":"stack-45263838","source":"stackoverflow","questionId":45263838,"title":"Can apollo-android be used as a java client?","tags":["java","spring-boot","graphql","apollo-android"],"text":"Title: Can apollo-android be used as a java client?\nTags: java, spring-boot, graphql, apollo-android\nSource: Stack Overflow\n\nQuestion:\nI'm working on a spring boot app that needs to talk to the Github GraphQl API. Can apollo-android be used for this purpose? Since all of it's scarce documentation available as well as the sample project is written with android in mind, I'm not sure.\n\n========================================\n\nTop Answer:\nFound this maven plugin. It would be nice if you could make a sample project that uses apollo-android in spring boot.\n\n========================================\n\nComments:\n- The Android-specific references appear to be isolated in the `apollo-android-support` module. I do not know how easy it is to fork this project and create a replacement module that does not use Android APIs.\n- Did you ever figure out how to use in spring boot?","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":17,"estimatedTokens":219}}976{"id":"stack-47972196","source":"stackoverflow","questionId":47972196,"title":"What is the use of `schema` typedef in GraphQL?","tags":["node.js","graphql","apollo"],"text":"Title: What is the use of `schema` typedef in GraphQL?\nTags: node.js, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm getting started on GraphQL with Apollo + Express and I see that the example adds a `schema` name at the bottom of the typedefs:\n\n```\nlet typeDefs = [`\ntype Query {\n hello: String\n}\n\nschema {\n query: Query\n}`];\n```\n\nAnd after defining the resolvers it generates the schema with `makeExecutableSchema`:\n\n```\nlet schema = makeExecutableSchema({typeDefs, resolvers});\n```\n\nHowever if I remove the `schema` part of the typedefs I can still use my endpoint normally, e.g.: \n\n```\nhttp://localhost:3000/graphql/?query={hello}\n```\n\nreturns:\n\n```\n{\"data\":{\"hello\":\"world\"}}\n```\n\nBut if I change the query part for something else, the server fails:\n\n```\nlet typeDefs = [`\ntype Query {\n hello: String\n}\n\nschema {\n testquery: Query\n}`];\n```\n\n GraphQLError: Syntax Error: Unexpected Name \"testquery\"\n\nI have read through Apollo's tutorial pages and also the How To GraphQL tutorial for Node.js + GraphQL but can't find reference to that `schema` part.\n\nWhat is it used for?\n\n========================================\n\nCode:\n```text\nlet typeDefs = [`\ntype Query {\n hello: String\n}\n\nschema {\n query: Query\n}`];\n```\n\n```text\nlet schema = makeExecutableSchema({typeDefs, resolvers});\n```\n\n```text\nhttp://localhost:3000/graphql/?query={hello}\n```\n\n```text\n{\"data\":{\"hello\":\"world\"}}\n```\n\n```text\nlet typeDefs = [`\ntype Query {\n hello: String\n}\n\nschema {\n testquery: Query\n}`];\n```\n\n```text\nschema\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nschema\n```\n\n```text\nschema\n```\n\n```text\n# Doesn't need further specification, Query is the default name\ntype Query {\n # ...\n}\n```\n\n```text\n# Non standard query type name\ntype MyQuery {\n # ...\n}\n\nschema {\n # Needs to be defined in the schema declaration\n query: MyQuery\n}\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nSubscription\n```\n\n```text\nschema\n```\n\n========================================\n\nComments:\n- apollographql.com/blog/…","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":147,"estimatedTokens":501}}977{"id":"stack-70448483","source":"stackoverflow","questionId":70448483,"title":"Correct value for `startCursor` and `endCursor` in `PageInfo` when there are 0 items/edges? Is the Relay pagination spec incorrect?","tags":["graphql","pagination","relay"],"text":"Title: Correct value for `startCursor` and `endCursor` in `PageInfo` when there are 0 items/edges? Is the Relay pagination spec incorrect?\nTags: graphql, pagination, relay\nSource: Stack Overflow\n\nQuestion:\nThe Relay pagination specification says the following about `PageInfo`:\n\nIt must also contain fields `startCursor` and `endCursor`, both of which return non-null opaque strings.\n\n[...]\n\n`startCursor` and `endCursor` must be the cursors corresponding to the first and last nodes in edges, respectively.\n\nBut what if I want to return zero items? There are lots of reason why a request to that specific endpoint would return an empty connection.\n\nI don't see what values `startCursor` and `endCursor` should have in that case. The obvious answer is `null`, but the spec explicitly says \"non-null\". What's up with that?\n\nFor what it's worth, I looked at roughly 15 articles about the topic of \"graphql pagination\" and all of those either ignore the issue or assign `null` in the case of an empty list. So at this point it seems that the spec is just wrong or incompatible with the real world?\n\n========================================\n\nCode:\n```text\nPageInfo\n```\n\n```text\nstartCursor\n```\n\n```text\nendCursor\n```\n\n```text\nstartCursor\n```\n\n```text\nendCursor\n```\n\n```text\nstartCursor\n```\n\n```text\nendCursor\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- did you find out anything yet (I'm running into the same issue)\n- @pvgoddijn Nope, unfortunately not. In my project, I proceeded by making them nullable, but I'm still hoping for a proper answer to this.\n- i'm currently going for returning the 'from' cursor from the request (since that is where they are coming from so I sort of makes some sense but still feels ugly). But this is a gap in the spec IMHO,\n- @pvgoddijn But the `from` cursor is usually an optional parameter, right? So what do you do if it is not specified and you still want to return 0 items, because e.g. the database is empty?\n- i didnt think about that edge case yet...\n- filed a bug with the relay github: github.com/facebook/relay/issues/3708 returning null seems tp be connonical","metadata":{"transformedAt":"2026-08-18T18:32:36.096Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":67,"estimatedTokens":539}}978{"id":"stack-64826080","source":"stackoverflow","questionId":64826080,"title":"How can I get Absinthe and Dataloader to work together?","tags":["graphql","elixir","ecto","dataloader","absinthe"],"text":"Title: How can I get Absinthe and Dataloader to work together?\nTags: graphql, elixir, ecto, dataloader, absinthe\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQL API that works just fine using conventional resolve functions. My goal is to eliminate the N+1 problem.\n\nTo do so I've decided to use the Dataloader. I've done these steps to supposedly make the app run:\n\n- I added these two functions to my context module:\n\n```\ndefmodule Project.People do\n # CRUD...\n\n def data, do: Dataloader.Ecto.new(Repo, query: &query/2)\n\n def query(queryable, _params) do\n queryable\n end\nend\n```\n\n- I added `context/1` and `plugins/0` to the Schema module and updated the resolvers for queries:\n\n```\ndefmodule ProjectWeb.GraphQL.Schema do\n use Absinthe.Schema\n\n import Absinthe.Resolution.Helpers, only: [dataloader: 1]\n\n alias ProjectWeb.GraphQL.Schema\n alias Project.People\n\n import_types(Schema.Types)\n\n query do\n @desc \"Get a list of all people.\"\n field :people, list_of(:person) do\n resolve(dataloader(People))\n end\n\n # Other queries...\n end\n\n def context(context) do\n loader =\n Dataloader.new()\n |> Dataloader.add_source(People, People.data())\n\n Map.put(context, :loader, loader)\n end\n\n def plugins, do: [Absinthe.Middleware.Dataloader | Absinthe.Plugin.defaults()]\nend\n```\n\nNo other steps are given in the official tutorials. My `:person` object looks like this:\n\n```\n@desc \"An object that defines a person.\"\n object :person do\n field :id, :id\n field :birth_date, :date\n field :first_name, :string\n field :last_name, :string\n field :pesel, :string\n field :second_name, :string\n field :sex, :string\n\n # field :addresses, list_of(:address) do\n # resolve(fn parent, _, _ ->\n # addresses = Project.Repo.all(Ecto.assoc(parent, :addresses))\n\n # {:ok, addresses}\n # end)\n # description(\"List of addresses that are assigned to this person.\")\n # end\n\n # field :contacts, list_of(:contact) do\n # resolve(fn parent, _, _ ->\n # contacts = Project.Repo.all(Ecto.assoc(parent, :contacts))\n\n # {:ok, contacts}\n # end)\n # description(\"List of contacts that are assigned to this person.\")\n # end\n end\n```\n\nThe commented part is the resolver that works without `dataloader` and doesn't cause the problem.\n\nWhen I try to query:\n\n```\n{\n people { \n id\n }\n}\n```\n\nI get this:\n\n```\nRequest: POST /graphiql\n** (exit) an exception was raised:\n ** (Dataloader.GetError) The given atom - :people - is not a module.\n\n This can happen if you intend to pass an Ecto struct in your call to\n `dataloader/4` but pass something other than a struct.\n```\n\nI don't fully comprehend the error message since I pass a module to the `dataloader/1` and cannot find the solution. What might be the case?\n\n========================================\n\nCode:\n```elixir\ndefmodule Project.People do\n # CRUD...\n\n def data, do: Dataloader.Ecto.new(Repo, query: &query/2)\n\n def query(queryable, _params) do\n queryable\n end\nend\n```\n\n```elixir\ndefmodule ProjectWeb.GraphQL.Schema do\n use Absinthe.Schema\n\n import Absinthe.Resolution.Helpers, only: [dataloader: 1]\n\n alias ProjectWeb.GraphQL.Schema\n alias Project.People\n\n import_types(Schema.Types)\n\n query do\n @desc \"Get a list of all people.\"\n field :people, list_of(:person) do\n resolve(dataloader(People))\n end\n\n # Other queries...\n end\n\n def context(context) do\n loader =\n Dataloader.new()\n |> Dataloader.add_source(People, People.data())\n\n Map.put(context, :loader, loader)\n end\n\n def plugins, do: [Absinthe.Middleware.Dataloader | Absinthe.Plugin.defaults()]\nend\n```\n\n```elixir\n@desc \"An object that defines a person.\"\n object :person do\n field :id, :id\n field :birth_date, :date\n field :first_name, :string\n field :last_name, :string\n field :pesel, :string\n field :second_name, :string\n field :sex, :string\n\n # field :addresses, list_of(:address) do\n # resolve(fn parent, _, _ ->\n # addresses = Project.Repo.all(Ecto.assoc(parent, :addresses))\n\n # {:ok, addresses}\n # end)\n # description(\"List of addresses that are assigned to this person.\")\n # end\n\n # field :contacts, list_of(:contact) do\n # resolve(fn parent, _, _ ->\n # contacts = Project.Repo.all(Ecto.assoc(parent, :contacts))\n\n # {:ok, contacts}\n # end)\n # description(\"List of contacts that are assigned to this person.\")\n # end\n end\n```\n\n```json\n{\n people { \n id\n }\n}\n```\n\n```text\nRequest: POST /graphiql\n** (exit) an exception was raised:\n ** (Dataloader.GetError) The given atom - :people - is not a module.\n\n This can happen if you intend to pass an Ecto struct in your call to\n `dataloader/4` but pass something other than a struct.\n```\n\n```text\ncontext/1\n```\n\n```text\nplugins/0\n```\n\n```text\n:person\n```\n\n```text\ndataloader\n```\n\n```text\ndataloader/1\n```\n\n```elixir\ndefmodule ProjectWeb.GraphQL.Schema do\n use Absinthe.Schema\n\n import Absinthe.Resolution.Helpers, only: [dataloader: 1]\n\n alias ProjectWeb.GraphQL.Schema\n alias Project.People\n\n import_types(Schema.Types)\n\n query do\n @desc \"Get a list of all people.\"\n field :people, list_of(:person) do\n resolve(&StandardPerson.resolver/2)\n end\n\n # Other queries...\n end\n\n def context(context) do\n loader =\n Dataloader.new()\n |> Dataloader.add_source(People, People.data())\n\n Map.put(context, :loader, loader)\n end\n\n def plugins, do: [Absinthe.Middleware.Dataloader | Absinthe.Plugin.defaults()]\nend\n```\n\n```elixir\n@desc \"An object that defines a person.\"\n object :person do\n field :id, :id\n field :birth_date, :date\n field :first_name, :string\n field :last_name, :string\n field :pesel, :string\n field :second_name, :string\n field :sex, :string\n\n field :addresses, list_of(:address) do\n resolve(dataloader(People))\n description(\"List of addresses that are assigned to this person.\")\n end\n\n field :contacts, list_of(:contact) do\n resolve(dataloader(People))\n description(\"List of contacts that are assigned to this person.\")\n end\n end\n```\n\n```text\ndataloader\n```\n\n```text\ndataloader(People)\n```\n\n```text\nobject\n```\n\n```text\nquery\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":300,"estimatedTokens":1524}}979{"id":"stack-53461426","source":"stackoverflow","questionId":53461426,"title":"How to readQuery() and writeQuery() from Vue-Apollo Store?","tags":["vue.js","graphql","apollo","apollo-client","vue-apollo"],"text":"Title: How to readQuery() and writeQuery() from Vue-Apollo Store?\nTags: vue.js, graphql, apollo, apollo-client, vue-apollo\nSource: Stack Overflow\n\nQuestion:\nI want to edit some data in the cache manually.\n\nHow can I `readQuery()` and `writeQuery()` in vue-apollo directly from a method of a Vue component? Im looking for something like `this.$apollo.readQuery(...)`, which does not work. Where do I get the `store` instance from?\n\nI mean the store instance from `update()` method in e.g. `this.$apollo.mutate`.\n\n========================================\n\nCode:\n```text\nreadQuery()\n```\n\n```text\nwriteQuery()\n```\n\n```text\nthis.$apollo.readQuery(...)\n```\n\n```text\nstore\n```\n\n```text\nupdate()\n```\n\n```text\nthis.$apollo.mutate\n```\n\n```text\nmethods: {\n async doQuery (my_data) {\n const apolloClient = this.$apollo.provider.defaultClient\n apolloClient.writeQuery({\n query: QUERY,\n data: {\n data: my_data,\n },\n })\n },\n```\n\n```text\nthis.$apollo.provider.defaultClient\n```\n\n========================================\n\nComments:\n- If you want to use another client: `this.$apollo.provider.clients.yourClientName`","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":59,"estimatedTokens":288}}980{"id":"stack-38240599","source":"stackoverflow","questionId":38240599,"title":"graphql-java cyclic types dependencies","tags":["java","graphql","graphql-java"],"text":"Title: graphql-java cyclic types dependencies\nTags: java, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\ni've hit a brick wall while trying to construct types that depend on each other, here is the code:\n\n```\nimport graphql.schema.GraphQLObjectType;\nimport static graphql.schema.GraphQLObjectType.newObject;\n\nimport static graphql.Scalars.*;\nimport graphql.schema.GraphQLFieldDefinition;\nimport graphql.schema.GraphQLList;\n\nimport static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;\n\npublic class GraphQLTypes {\n\n private GraphQLObjectType studentType;\n private GraphQLObjectType classType;\n\n public GraphQLTypes() {\n\n createStudentType();\n createClassType();\n }\n\n void createStudentType() {\n studentType = newObject().name(\"Student\")\n .field(newFieldDefinition().name(\"name\").type(GraphQLString).build())\n .field(newFieldDefinition().name(\"currentClass\").type(classType).build())\n .build();\n }\n\n void createClassType() {\n classType = newObject().name(\"Class\")\n .field(newFieldDefinition().name(\"name\").type(GraphQLString).build())\n .field(newFieldDefinition().name(\"students\").type(new GraphQLList(studentType)).build())\n .build();\n }\n\n}\n```\n\nits impossible to intantiate this class, as i get this exception\n\n```\nCaused by: graphql.AssertException: type can't be null\nat graphql.Assert.assertNotNull(Assert.java:10)\nat graphql.schema.GraphQLFieldDefinition.(GraphQLFieldDefinition.java:23)\nat graphql.schema.GraphQLFieldDefinition$Builder.build(GraphQLFieldDefinition.java:152)\nat graphql_types.GraphQLTypes.createStudentType(GraphQLTypes.java:26)\nat graphql_types.GraphQLTypes.(GraphQLTypes.java:19)\n```\n\nobviously classType is not yet intantiated at the point createStudentType() is referencing it. How to i get around this problem?\n\n========================================\n\nTop Answer:\nDid you try to use `new GraphQLTypeReference(\"ForwardType\")`? I'm talking about this one https://github.com/graphql-java/graphql-java#recursive-type-references\n\n========================================\n\nCode:\n```text\nimport graphql.schema.GraphQLObjectType;\nimport static graphql.schema.GraphQLObjectType.newObject;\n\nimport static graphql.Scalars.*;\nimport graphql.schema.GraphQLFieldDefinition;\nimport graphql.schema.GraphQLList;\n\nimport static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;\n\npublic class GraphQLTypes {\n\n private GraphQLObjectType studentType;\n private GraphQLObjectType classType;\n\n public GraphQLTypes() {\n\n createStudentType();\n createClassType();\n }\n\n void createStudentType() {\n studentType = newObject().name(\"Student\")\n .field(newFieldDefinition().name(\"name\").type(GraphQLString).build())\n .field(newFieldDefinition().name(\"currentClass\").type(classType).build())\n .build();\n }\n\n void createClassType() {\n classType = newObject().name(\"Class\")\n .field(newFieldDefinition().name(\"name\").type(GraphQLString).build())\n .field(newFieldDefinition().name(\"students\").type(new GraphQLList(studentType)).build())\n .build();\n }\n\n}\n```\n\n```text\nCaused by: graphql.AssertException: type can't be null\nat graphql.Assert.assertNotNull(Assert.java:10)\nat graphql.schema.GraphQLFieldDefinition.<init>(GraphQLFieldDefinition.java:23)\nat graphql.schema.GraphQLFieldDefinition$Builder.build(GraphQLFieldDefinition.java:152)\nat graphql_types.GraphQLTypes.createStudentType(GraphQLTypes.java:26)\nat graphql_types.GraphQLTypes.<init>(GraphQLTypes.java:19)\n```\n\n```text\nimport graphql.schema.GraphQLList;\nimport graphql.schema.GraphQLObjectType;\nimport graphql.schema.GraphQLTypeReference;\n\nimport static graphql.Scalars.GraphQLString;\nimport static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;\nimport static graphql.schema.GraphQLObjectType.newObject;\n\npublic class GraphQLTypes {\n\n private GraphQLObjectType studentType;\n private GraphQLObjectType classType;\n\n public GraphQLTypes() {\n createStudentType();\n createClassType();\n }\n\n void createStudentType() {\n studentType = newObject().name(\"Student\")\n .field(newFieldDefinition().name(\"name\").type(GraphQLString).build())\n .field(newFieldDefinition().name(\"currentClass\").type(new GraphQLTypeReference(\"Class\")).build())\n .build();\n }\n\n void createClassType() {\n classType = newObject().name(\"Class\")\n .field(newFieldDefinition().name(\"name\").type(GraphQLString).build())\n .field(newFieldDefinition().name(\"students\").type(new GraphQLList(studentType)).build())\n .build();\n }\n\n}\n```\n\n```text\nnew GraphQLTypeReference(\"ForwardType\")\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":152,"estimatedTokens":1174}}981{"id":"stack-52781291","source":"stackoverflow","questionId":52781291,"title":"How to use GraphQL queries in a container class component","tags":["javascript","reactjs","graphql","gatsby"],"text":"Title: How to use GraphQL queries in a container class component\nTags: javascript, reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nπ\n\nMy current **GatsbyJS** project is a one pager with a carousel and some other content. \n\n**Background**\n\nThe carousel should be filled with information about some products. My goal is to let the carousel build itself by iterating through all markdown files, picking the ones with these three lines at the top of the file:\n\n```\n---\ntype: product\n---\n```\n\nSo I've created a `CarouselContainer` (class component) and a `Carousel` component (functional component). The Container should load the markdown via GraphQL query and pass the resulting products object to it's nested component. Then the component should map over the object and create the carousel.\n\nBut there are also other markdown files for menu lists, text modals and so on. They have the `type: page`. I thought preparing a few GraphQL queries would be the solution. But it turned out to be more difficult than expected... \n\nThe container component is a class component, so I am not able to call the query directly in it (https://github.com/gatsbyjs/gatsby/issues/3991#issuecomment-364939030).\n\nThen I thought putting multiple queries into the `pages/index.js` could be the solution. \n\n```\nexport const indexQuery = graphql`\nquery IndexQuery {\n allMarkdownRemark(filter: {frontmatter: {type: {eq: \"page\"}}}) {\n edges {\n node {\n frontmatter {\n title\n text\n }\n }\n }\n }\n}\n`\n\nexport const productsQuery = graphql`\nquery ProductsQuery {\n allMarkdownRemark(filter: {frontmatter: {type: {eq: \"product\"}}}) {\n edges {\n node {\n id\n frontmatter {\n title\n content\n }\n }\n }\n }\n}\n`\n```\n\nNope again. Using GraphQL fragments should be a solution... \n\n**Q** Can someone tell me how to prepare fragments for that purpose **and/or** have another idea how to get the markdown content right into my container?\n\nThanks for reading.\n\n========================================\n\nCode:\n```text\n---\ntype: product\n---\n```\n\n```js\nexport const indexQuery = graphql`\nquery IndexQuery {\n allMarkdownRemark(filter: {frontmatter: {type: {eq: \"page\"}}}) {\n edges {\n node {\n frontmatter {\n title\n text\n }\n }\n }\n }\n}\n`\n\nexport const productsQuery = graphql`\nquery ProductsQuery {\n allMarkdownRemark(filter: {frontmatter: {type: {eq: \"product\"}}}) {\n edges {\n node {\n id\n frontmatter {\n title\n content\n }\n }\n }\n }\n}\n`\n```\n\n```text\nCarouselContainer\n```\n\n```text\nCarousel\n```\n\n```text\ntype: page\n```\n\n```text\npages/index.js\n```\n\n```text\nexport const query = graphql`\n {\n products: allMarkdownRemark(\n filter: { frontmatter: { type: { eq: \"product\" } } }\n ) {\n edges {\n # ...\n }\n }\n\n pages: allMarkdownRemark(\n filter: { frontmatter: { type: { eq: \"pages\" } } }\n ) {\n edges {\n # ...\n }\n }\n }\n`\n```\n\n```text\nexport const query = graphql`\n fragment Products on Query {\n products: allMarkdownRemark(\n filter: { frontmatter: { type: { eq: \"product\" } } }\n ) {\n edges {\n # ...\n }\n }\n }\n`\n```\n\n```text\nexport const query = graphql`\n {\n pages: allMarkdownRemark(\n filter: { frontmatter: { type: { eq: \"pages\" } } }\n ) {\n edges {\n # ...\n }\n }\n\n ...Products\n }\n`\n```\n\n```text\nimport React from \"react\";\nimport { graphql, StaticQuery } from \"gatsby\";\n\nclass Carousel extends React.Component {\n // ...\n}\n\nexport default props => (\n <StaticQuery\n query={graphql`\n products: allMarkdownRemark(\n filter: { frontmatter: { type: { eq: \"product\" } } }\n ) {\n edges {\n # ...\n }\n }\n `}\n render={({ products }) => <Carousel products={products} {...props} />}\n />\n);\n```\n\n```text\nallMarkdownRemark\n```\n\n```text\ndata.products\n```\n\n```text\ndata.pages\n```\n\n```text\ndefault\n```\n\n```text\nproducts\n```\n\n```text\nCarousel\n```\n\n```text\ncarousel.js\n```\n\n```text\non Query\n```\n\n```text\non RootQueryType\n```\n\n========================================\n\nComments:\n- Thank you, it worked! The first way with the aliases worked very well. StaticQuery is the preferred way. Didn't know about that feature before, because I started a few weeks ago with v1.\n- For others reading this question: I can't claim to fully understand this, but this solution worked for me only when I removed the `{}` surrounding `products` in the `render=` line. In my case the working code was `render={( settings_query ) => }`. So if you're having trouble, might be worth a go.\n- @RobinL That bit is destructuring the `product` property of the props object.","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":242,"estimatedTokens":1165}}982{"id":"stack-57552296","source":"stackoverflow","questionId":57552296,"title":"Size limit for GraphQL scalar String","tags":["graphql"],"text":"Title: Size limit for GraphQL scalar String\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI want to send images as Base64 encoded strings. However, the size of each generated string turns out to be very large. My question is therefore, does GraphQL restrict the scalar `String` to a certain length, i.e. is it possible for me to send my images as strings using GraphQL?\n\n========================================\n\nCode:\n```text\nString\n```\n\n```text\nString\n```\n\n```text\nString\n```\n\n========================================\n\nComments:\n- I have tried it with a 30MB image file converted to base64 string. It's working fine. Thank you.","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":26,"estimatedTokens":158}}983{"id":"stack-53466486","source":"stackoverflow","questionId":53466486,"title":"Split the graphql resolvers file into seperatefiles","tags":["graphql","apollo"],"text":"Title: Split the graphql resolvers file into seperatefiles\nTags: graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm working with GraphQL and have a **resolvers.js** file that looks like this:\n\n```\nconst User = require(\"../models/User\");\nconst Post = require(\"../models/Post\");\n\nmodule.exports = {\n Query: {\n async users(){...},\n async user(){...},\n async posts(){...},\n async post(){...},\n },\n User: {...},\n Post: {...},\n Mutation: {\n createUser(){...},\n login(){...},\n createPost(){...},\n },\n}\n```\n\nBut if I have more models, queries and mutations the file is gonna be very long. How can I split this into seperate files? One for user queries and mutations, one for posts and so. Or is that not possible? Maybe there's a way to combine this with the **schema.js** file? So that I can split the schema too and put schema/resolver from User into a file. I'm still a beginner in coding.\n\n========================================\n\nTop Answer:\nJust in case somebody is looking for an answer in 2020,\n\nI had the similar issue,\nand I tried to adapt the method mentioned,\nbut found an easier way to solve the problem.\n\nI used `graphql-tools`'s `mergeResolvers` to solve the issue - https://www.graphql-tools.com/docs/merge-resolvers/\n\nExample code would be like this\n\n```\nconst { mergeResolvers } = require('@graphql-tools/merge');\nconst clientResolver = require('./clientResolver');\nconst productResolver = require('./productResolver');\n\nconst resolvers = [\n clientResolver,\n productResolver,\n];\n\nmodule.exports mergeResolvers(resolvers);\n```\n\nThe `lodash` `merge` would not differentiate `Query` and `Mutation`,\nthus throwing an error in my case.\n\n========================================\n\nCode:\n```text\nconst User = require(\"../models/User\");\nconst Post = require(\"../models/Post\");\n\nmodule.exports = {\n Query: {\n async users(){...},\n async user(){...},\n async posts(){...},\n async post(){...},\n },\n User: {...},\n Post: {...},\n Mutation: {\n createUser(){...},\n login(){...},\n createPost(){...},\n },\n}\n```\n\n```text\nconst { merge } = require(\"lodash\");\n\nmodule.exports = makeExecutableSchema({\n typeDefs: [typeDefs, userTypeDefs],\n resolvers: merge(resolvers, userResolvers)\n});\n```\n\n```text\nimport { DateBidListResolvers } from \"../../types/generated\";\n\nexport const DateBidList: DateBidListResolvers.Type = {\n ...DateBidListResolvers.defaultResolvers,\n\n list: (_, __) => { // This is an example resolver of Type DateBidList\n throw new Error(\"Resolver not implemented\");\n }\n};\n```\n\n```text\nimport { Resolvers } from \"../../types/generated\";\n\nimport { Query } from \"./Query\";\nimport { User } from \"./User\";\nimport { DateBid } from \"./DateBid\";\nimport { DateItem } from \"./DateItem\";\nimport { Match } from \"./Match\";\nimport { Mutation } from \"./Mutation\";\nimport { Subscription } from \"./Subscription\";\nimport { DateBidList } from \"./DateBidList\";\nimport { DateList } from \"./DateList\";\nimport { Following } from \"./Following\";\nimport { MatchList } from \"./MatchList\";\nimport { Message } from \"./Message\";\nimport { MessageItem } from \"./MessageItem\";\nimport { Queue } from \"./Queue\";\n\nexport const resolvers: Resolvers = {\n DateBid,\n DateBidList,\n DateItem,\n DateList,\n Following,\n Match,\n MatchList,\n Message,\n MessageItem,\n Mutation,\n Query,\n Queue,\n Subscription,\n User\n};\n```\n\n```text\nimport { resolvers } from './resolvers/index';\n\n// ... other imports here\n\nexport const server = {\n typeDefs,\n resolvers,\n playground,\n context,\n dataSources,\n};\n\nexport default new ApolloServer(server);\n```\n\n```text\nconst { mergeResolvers } = require('@graphql-tools/merge');\nconst clientResolver = require('./clientResolver');\nconst productResolver = require('./productResolver');\n\nconst resolvers = [\n clientResolver,\n productResolver,\n];\n\nmodule.exports mergeResolvers(resolvers);\n```\n\n```text\ngraphql-tools\n```\n\n```text\nmergeResolvers\n```\n\n```text\nlodash\n```\n\n```text\nmerge\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n========================================\n\nComments:\n- Never worked with Typescript. Will take a look at how to use it. Thanks.\n- You don't need Typescript to do this. It was just to note on some of the lingo in the code. I would appreciate it if you would select my answer rather than yours so I get the points.\n- blog.apollographql.com/… supplies this solution if anyone wants more detail.","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":199,"estimatedTokens":1091}}984{"id":"stack-51927420","source":"stackoverflow","questionId":51927420,"title":"How to use (opaque) cursors in GraphQL / Relay when using filter arguments and order by","tags":["graphql","relayjs","relay"],"text":"Title: How to use (opaque) cursors in GraphQL / Relay when using filter arguments and order by\nTags: graphql, relayjs, relay\nSource: Stack Overflow\n\nQuestion:\nImagine the following GraphQL request:\n\n```\n{\n books(\n first:10,\n filter: [{field: TITLE, contains: \"Potter\"}],\n orderBy: [{sort: PRICE, direction: DESC}, {sort: TITLE}]\n )\n}\n```\n\nThe result will return a connection with the Relay cursor information.\n\nShould the cursor contain the `filter` and `orderBy` details?\n\nMeaning querying the next set of data would only mean:\n\n```\n{\n books(first:10, after:\"opaque-cursor\")\n}\n```\n\nOr should the `filter` and `orderBy` be repeated? \n\nIn the latter case the user can specify different `filter` and/or `orderBy` details which would make the opaque cursor invalid.\n\nI can't find anything in the Relay spec about this.\n\n========================================\n\nTop Answer:\nI came across the same question / problem, and came to the same conclusion as @Dan Crews. The cursor must contain everything you need to execute the database query, except for `LIMIT`.\n\nWhen your initial query is something like\n\n```\nSELECT *\nFROM DataTable\nWHERE filterField = 42\nORDER BY sortingField,ASC\nLIMIT 10\n-- with implicit OFFSET 0\n```\n\nthen you could basically *(**don't** do this in a real app, because of SQL Injections!)* use exactly this query as your cursor. You just have to remove `LIMIT x` and append `OFFSET y` for every node.\n\nResponse:\n\n```\n{\n edges: [\n {\n cursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 0\",\n node: { ... }\n },\n {\n cursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 1\",\n node: { ... }\n },\n ...,\n {\n cursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 9\",\n node: { ... }\n }\n ]\n pageInfo: {\n startCursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 0\"\n endCursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 9\"\n }\n}\n```\n\nThe next request will then use `after: CURSOR, first: 10`. Then you'll take the `after` argument and set the `LIMIT` and `OFFSET`:\n\n- `LIMIT = first`\n\n- `OFFSET = OFFSET + 1`\n\nThen the resulting database query would be this when using `after = endCursor`:\n\n```\nSELECT *\nFROM DataTable\nWHERE filterField = 42\nORDER BY sortingField,ASC\nLIMIT 10\nOFFSET 10\n```\n\nAs already mentioned above: **This is only an example, and it's highly vulnerable to SQL Injections!**\n\nIn a real world app, you could simply encode the provided `filter` and `orderBy` arguments within the cursor, and add `offset` as well:\n\n```\nfunction handleGraphQLRequest(first, after, filter, orderBy) {\n let offset = 0; // initial offset, if after isn't provided\n\n if(after != null) {\n // combination of after + filter/orderBy is not allowed!\n if(filter != null || orderBy != null) {\n throw new Error(\"You can't combine after with filter and/or orderBy\");\n }\n\n // parse filter, orderBy, offset from after cursor\n cursorData = fromBase64String(after);\n filter = cursorData.filter;\n orderBy = cursorData.orderBy;\n offset = cursorData.offset;\n }\n\n const databaseResult = executeDatabaseQuery(\n filter, // = WHERE ...\n orderBy, // = ORDER BY ...\n first, // = LIMIT ...\n offset // = OFFSET ...\n );\n\n const edges = []; // this is the resulting edges array\n let currentOffset = offset; // this is used to calc the offset for each node\n for(let node of databaseResult.nodes) { // iterate over the database results\n currentOffset++;\n const currentCursor = createCursorForNode(filter, orderBy, currentOffset);\n edges.push({\n cursor = currentCursor,\n node = node\n });\n }\n\n return {\n edges: edges,\n pageInfo: buildPageInfo(edges, totalCount, offset) // instead of\n // of providing totalCount, you could also fetch (limit+1) from\n // database to check if there is a next page available\n }\n}\n\n// this function returns the cursor string\nfunction createCursorForNode(filter, orderBy, offset) {\n return toBase64String({\n filter: filter,\n orderBy: orderBy,\n offset: offset\n });\n}\n\n// function to build pageInfo object\nfunction buildPageInfo(edges, totalCount, offset) {\n return {\n startCursor: edges.length ? edges[0].cursor : null,\n endCursor: edges.length ? edges[edges.length - 1].cursor : null,\n hasPreviousPage: offset > 0 && totalCount > 0,\n hasNextPage: offset + edges.length The content of `cursor` depends mainly on your database and you database layout.\n\nThe code above emulates a simple pagination with limit and offset. But you could (if supported by your database) of course use something else.\n\n========================================\n\nCode:\n```text\n{\n books(\n first:10,\n filter: [{field: TITLE, contains: \"Potter\"}],\n orderBy: [{sort: PRICE, direction: DESC}, {sort: TITLE}]\n )\n}\n```\n\n```text\n{\n books(first:10, after:\"opaque-cursor\")\n}\n```\n\n```text\nfilter\n```\n\n```text\norderBy\n```\n\n```text\nfilter\n```\n\n```text\norderBy\n```\n\n```text\nfilter\n```\n\n```text\norderBy\n```\n\n```sql\nSELECT *\nFROM DataTable\nWHERE filterField = 42\nORDER BY sortingField,ASC\nLIMIT 10\n-- with implicit OFFSET 0\n```\n\n```js\n{\n edges: [\n {\n cursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 0\",\n node: { ... }\n },\n {\n cursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 1\",\n node: { ... }\n },\n ...,\n {\n cursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 9\",\n node: { ... }\n }\n ]\n pageInfo: {\n startCursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 0\"\n endCursor: \"SELECT ... WHERE ... ORDER BY ... OFFSET 9\"\n }\n}\n```\n\n```sql\nSELECT *\nFROM DataTable\nWHERE filterField = 42\nORDER BY sortingField,ASC\nLIMIT 10\nOFFSET 10\n```\n\n```js\nfunction handleGraphQLRequest(first, after, filter, orderBy) {\n let offset = 0; // initial offset, if after isn't provided\n\n if(after != null) {\n // combination of after + filter/orderBy is not allowed!\n if(filter != null || orderBy != null) {\n throw new Error(\"You can't combine after with filter and/or orderBy\");\n }\n\n // parse filter, orderBy, offset from after cursor\n cursorData = fromBase64String(after);\n filter = cursorData.filter;\n orderBy = cursorData.orderBy;\n offset = cursorData.offset;\n }\n\n const databaseResult = executeDatabaseQuery(\n filter, // = WHERE ...\n orderBy, // = ORDER BY ...\n first, // = LIMIT ...\n offset // = OFFSET ...\n );\n\n const edges = []; // this is the resulting edges array\n let currentOffset = offset; // this is used to calc the offset for each node\n for(let node of databaseResult.nodes) { // iterate over the database results\n currentOffset++;\n const currentCursor = createCursorForNode(filter, orderBy, currentOffset);\n edges.push({\n cursor = currentCursor,\n node = node\n });\n }\n\n return {\n edges: edges,\n pageInfo: buildPageInfo(edges, totalCount, offset) // instead of\n // of providing totalCount, you could also fetch (limit+1) from\n // database to check if there is a next page available\n }\n}\n\n// this function returns the cursor string\nfunction createCursorForNode(filter, orderBy, offset) {\n return toBase64String({\n filter: filter,\n orderBy: orderBy,\n offset: offset\n });\n}\n\n// function to build pageInfo object\nfunction buildPageInfo(edges, totalCount, offset) {\n return {\n startCursor: edges.length ? edges[0].cursor : null,\n endCursor: edges.length ? edges[edges.length - 1].cursor : null,\n hasPreviousPage: offset > 0 && totalCount > 0,\n hasNextPage: offset + edges.length < totalCount\n }\n}\n```\n\n```text\nLIMIT\n```\n\n```text\nLIMIT x\n```\n\n```text\nOFFSET y\n```\n\n```text\nafter: CURSOR, first: 10\n```\n\n```text\nafter\n```\n\n```text\nLIMIT\n```\n\n```text\nOFFSET\n```\n\n```text\nLIMIT = first\n```\n\n```text\nOFFSET = OFFSET + 1\n```\n\n```text\nafter = endCursor\n```\n\n```text\nfilter\n```\n\n```text\norderBy\n```\n\n```text\noffset\n```\n\n```text\ncursor\n```\n\n```text\nfilter\n```\n\n```text\norderBy\n```\n\n```text\ncursor\n```\n\n```text\nfilter\n```\n\n```text\norderBy\n```\n\n```text\nprice\n```\n\n```text\ntitle\n```\n\n```text\nid\n```\n\n```text\n{ id, price, title }\n```\n\n```text\nfilter\n```\n\n```text\norderBy\n```\n\n```text\nfilter\n```\n\n```text\norderBy\n```\n\n```text\nfilter\n```\n\n```text\norderBy\n```\n\n```text\nlimit\n```\n\n```text\npointer\n```\n\n```text\ncursor\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":44,"totalLines":437,"estimatedTokens":2006}}985{"id":"stack-48255251","source":"stackoverflow","questionId":48255251,"title":"How to query review requests by user, using Github's v4 GraphQL API?","tags":["github","graphql","github-api","github-graphql"],"text":"Title: How to query review requests by user, using Github's v4 GraphQL API?\nTags: github, graphql, github-api, github-graphql\nSource: Stack Overflow\n\nQuestion:\nGiven a user's id, I want to get all pull requests where they are a requested reviewer.\n\nThe following won't work as it only allows me to get pull requests *opened* by that user:\n\n```\nquery {\n node(id: \"$user\") {\n ... on User {\n pullRequests(first: 100) {\n nodes {\n reviewRequests(first: 100) {\n nodes {\n requestedReviewer {\n ... on User {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\nIs there a way to do this?\n\nThanks!\n\n========================================\n\nCode:\n```text\nquery {\n node(id: \"$user\") {\n ... on User {\n pullRequests(first: 100) {\n nodes {\n reviewRequests(first: 100) {\n nodes {\n requestedReviewer {\n ... on User {\n id\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```graphql\n{\n node(id: \"MDQ6VXNlcjk2OTQ3\") {\n ... on User {\n login\n }\n }\n}\n```\n\n```graphql\n{\n search(query: \"type:pr state:open review-requested:refack\", type: ISSUE, first: 100) {\n issueCount\n pageInfo {\n endCursor\n startCursor\n }\n edges {\n node {\n ... on PullRequest {\n repository {\n nameWithOwner\n }\n number\n url\n }\n }\n }\n }\n}\n```\n\n```text\nreview-requested\n```\n\n========================================\n\nComments:\n- Beautiful! Thank you.","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":101,"estimatedTokens":379}}986{"id":"stack-63081532","source":"stackoverflow","questionId":63081532,"title":"Nestjs GraphQL subscriptions onConnect & onDisconnect callbacks","tags":["graphql","nestjs","apollo-server"],"text":"Title: Nestjs GraphQL subscriptions onConnect & onDisconnect callbacks\nTags: graphql, nestjs, apollo-server\nSource: Stack Overflow\n\nQuestion:\nIs there an approach to hook into the onConnect and onDisconnect lifecycle-events in Nestjs?\n\n========================================\n\nTop Answer:\nIt turns out you can provide them in the subscriptions portion of the graphql configuration\n\n```\nsubscriptions: {\n keepAlive: subscriptionsTimeout,\n onConnect: (connectionParams, websocket, context) => {\n console.log(`connectionParams: ${connectionParams}, websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);\n },\n onDisconnect: ( websocket, context) => {\n console.log(`websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);\n }\n },\n```\n\n========================================\n\nCode:\n```text\nsubscriptions: {\n 'graphql-ws': true\n}\n```\n\n```text\nsubscriptions: {\n 'graphql-ws': {\n onConnect: (context: Context) => {\n const { connectionParams, subscriptions } = context;\n console.log(\n `connectionParams: ${connectionParams}, subscriptions: ${JSON.stringify(\n subscriptions,\n )}}, context ${JSON.stringify(context)}`,\n );\n },\n onDisconnect: (context: Context) => {\n const { connectionParams, subscriptions } = context;\n console.log(\n `connectionParams: ${JSON.stringify(\n connectionParams,\n )}}, subscriptions: ${JSON.stringify(\n subscriptions,\n )}, context ${JSON.stringify(context)}`,\n );\n },\n```\n\n```text\ngraph-ws\n```\n\n```text\ngraphql-ws\n```\n\n```text\nsubscriptions: {\n keepAlive: subscriptionsTimeout,\n onConnect: (connectionParams, websocket, context) => {\n console.log(`connectionParams: ${connectionParams}, websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);\n },\n onDisconnect: ( websocket, context) => {\n console.log(`websocket: ${JSON.stringify(websocket)}}, context ${JSON.stringify(context)}`);\n }\n },\n```\n\n========================================\n\nComments:\n- This approach worked for me up until NestJS 8.\n- Thanks. This works perfectly for NestJS 8.","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":571}}987{"id":"stack-66970321","source":"stackoverflow","questionId":66970321,"title":"GraphQL .NET - AutoRegisteringObjectGraphType error on schema loading: Unable to register GraphType","tags":["c#",".net","graphql"],"text":"Title: GraphQL .NET - AutoRegisteringObjectGraphType error on schema loading: Unable to register GraphType\nTags: c#, .net, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a CustomerDetails class:\n\n```\npublic record CustomerDetails{\n public string? Code { get; init; }\n public string? Name { get; init; }\n public string? Notes { get; init; }\n}\n```\n\nOn GraphQL side I have the following:\n\nOn queries side:\n\n```\npublic class CustomerDetailsGraphType : AutoRegisteringObjectGraphType { }\n```\n\nOn mutations side:\n\n```\npublic class CustomerDetailsInputGraphType : AutoRegisteringInputObjectGraphType {}\n```\n\nWhen I run this and try to see the schema into Altair it gives me an error of type:\n\n```\n\"message\": \"GraphQL.Execution.UnhandledError: Error executing document.\\r\\n ---> System.InvalidOperationException: Unable to register GraphType 'MyProject.Customers.Mutations.ContactDetailsInputGraphType' with the name 'ContactDetails';\\nthe name 'ContactDetails' is already registered to 'MyProject.Customers.Query.ContactDetailsGraphType'.\\r\\n...\"\n```\n\nI don't understand why is that happening?\n\n========================================\n\nCode:\n```text\npublic record CustomerDetails{\n public string? Code { get; init; }\n public string? Name { get; init; }\n public string? Notes { get; init; }\n}\n```\n\n```text\npublic class CustomerDetailsGraphType : AutoRegisteringObjectGraphType<CustomerDetails> { }\n```\n\n```text\npublic class CustomerDetailsInputGraphType : AutoRegisteringInputObjectGraphType<CustomerDetails> {}\n```\n\n```text\n\"message\": \"GraphQL.Execution.UnhandledError: Error executing document.\\r\\n ---> System.InvalidOperationException: Unable to register GraphType 'MyProject.Customers.Mutations.ContactDetailsInputGraphType' with the name 'ContactDetails';\\nthe name 'ContactDetails' is already registered to 'MyProject.Customers.Query.ContactDetailsGraphType'.\\r\\n...\"\n```\n\n```text\npublic class CustomerDetailsGraphType : AutoRegisteringObjectGraphType<CustomerDetails> \n{\n public CustomerDetailsGraphType()\n {\n Name = \"CustomerDetailsGraphType\"; // or any other name you consider\n }\n\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":70,"estimatedTokens":534}}988{"id":"stack-49162247","source":"stackoverflow","questionId":49162247,"title":"How to pass multiple queries into refetchQueries in apollo/graphql","tags":["reactjs","graphql","apollo","react-apollo","apollo-client"],"text":"Title: How to pass multiple queries into refetchQueries in apollo/graphql\nTags: reactjs, graphql, apollo, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI have a mutation named `deleteSong`. I was wondering after the mutation has passed through how can I pass multiple queries into `refetchQueries`?\n\n```\nthis.props\n .deleteSong({\n variables: { id },\n refetchQueries: [{ query: fetchSongs }] // {})\n .catch(err => {\n this.setState({ err });\n });\n```\n\n========================================\n\nCode:\n```text\nthis.props\n .deleteSong({\n variables: { id },\n refetchQueries: [{ query: fetchSongs }] //<-- I only know how to pass 1 query\n })\n .then(() => {})\n .catch(err => {\n this.setState({ err });\n });\n```\n\n```text\ndeleteSong\n```\n\n```text\nrefetchQueries\n```\n\n```text\nthis.props\n .deleteSong({\n variables: { id },\n refetchQueries: [{ query: FETCH_SONGS }, { query: FETCH_FOLLOWERS }]\n })\n .then(() => {})\n .catch(err => {\n this.setState({ err });\n });\n```\n\n```text\nrefetchQueries()\n```\n\n```text\nFETCH_SONG\n```\n\n```text\nFETCH_FOLLOWERS\n```\n\n========================================\n\nComments:\n- it's an array, no reasons you would not be able to pass multiples : `refetchQueries: [{ query: fetchSongs }, {query: fetchStuff}, {query: etc}]`\n- \"With refetchQueries you can specify **one or more queries** that you want to run after a mutation is completed\" github.com/apollographql/apollo-client/blob/master/docs/sour‌​ce/…\n- @Ben have you tested this? I am on my phone atm and can't test till later. It makes since though, but if you have tested please put this as an answer so I can give you credit.\n- I have't experienced that much apollo, but looking at your example and looking at the docs, it looked so obvious (you pass an array of hashes)","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":71,"estimatedTokens":450}}989{"id":"stack-62806312","source":"stackoverflow","questionId":62806312,"title":"Gatsby GraphQL cannot query field \"url\" on type \"File\" of Strapi","tags":["graphql","gatsby","strapi"],"text":"Title: Gatsby GraphQL cannot query field \"url\" on type \"File\" of Strapi\nTags: graphql, gatsby, strapi\nSource: Stack Overflow\n\nQuestion:\nI'm making a blog with Gatsby front-end, Strapi back-end. I made a query in component with StaticQuery\n\n```\nquery={graphql`\n query {\n allStrapiArticle {\n edges {\n node {\n strapiId\n title\n category {\n name\n }\n image {\n url\n }\n }\n }\n }\n }\n `}\n```\n\nAll of field is work fine without `image{url}`. I got error: `error Cannot query field \"url\" on type \"File\" graphql/template-strings`. How can I fix it? Thanks!\n\n========================================\n\nTop Answer:\nI have faced this problem too. Tutorial on Strapi suggest to query with 'url' but it's wrong.\n\nThe right way to query is to do:\n\n```\nallStrapiArticle {\n edges {\n node {\n strapiId\n title\n category {\n name\n }\n image {\n publicURL\n }\n }\n }\n }\n```\n\nIn order to display image, don't forget to swap **url** into **publicURL** like that:\n\n```\n\n```\n\n========================================\n\nCode:\n```text\nquery={graphql`\n query {\n allStrapiArticle {\n edges {\n node {\n strapiId\n title\n category {\n name\n }\n image {\n url\n }\n }\n }\n }\n }\n `}\n```\n\n```text\nimage{url}\n```\n\n```text\nerror Cannot query field \"url\" on type \"File\" graphql/template-strings\n```\n\n```text\nsingleImage {\n publicURL\n }\n multipleImages {\n localFile {\n publicURL\n }\n }\n```\n\n```text\nimage {\n childImageSharp {\n fluid(maxWidth: 960) {\n ...GatsbyImageSharpFluid\n }\n }\n }\n```\n\n```text\n<Img fluid={data.allStrapiArticle.edges[position].index.image.childImageSharp.fluid} />\n```\n\n```text\nurl\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\nurl\n```\n\n```text\npublicURL\n```\n\n```text\nurl\n```\n\n```text\nlocalhost:8000/___graphql\n```\n\n```text\ngatsby-image\n```\n\n```text\ngatsby-image\n```\n\n```text\nallStrapiArticle {\n edges {\n node {\n strapiId\n title\n category {\n name\n }\n image {\n publicURL\n }\n }\n }\n }\n```\n\n```text\n<img\n src={article.node.image.publicURL}\n alt={article.node.image.publicURL}\n height=\"100\"\n />\n```\n\n========================================\n\nComments:\n- Does the field exist?\n- Yes, of course, I added a field with Image type, single Image, required. Also create a article with image\n- You should probably query by `publicURL` instead of `url` inside the `image` object.","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":180,"estimatedTokens":659}}990{"id":"stack-58771868","source":"stackoverflow","questionId":58771868,"title":"Invariant violation when using react apollo hooks alongside query components","tags":["graphql","react-hooks","apollo","react-apollo","apollo-client"],"text":"Title: Invariant violation when using react apollo hooks alongside query components\nTags: graphql, react-hooks, apollo, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm beginning our migration from Apollo Client 2.x to 3.x beta, and I'm having trouble using both the apollo hooks and the now deprecated query/mutation components.\n\nI'm using the packages:\n\n```\n@apollo/client: 3.0.0-beta.4\n@apollo/react-components: 3.1.3\n```\n\nUsing the apollo hooks works fine in this case, but using the query component, I get the following error:\n\n Invariant Violation\n Could not find \"client\" in the context or passed in as an option.\n Wrap the root component in an , or pass an ApolloClient instance in via options.\n\nI've created a codesandbox that shows this issue here:\nhttps://codesandbox.io/s/react-example-9p9ym\n\nI think the issue is with the source of the `ApolloProvider` I'm using, but not sure which package to get that from if I want to use the new beta, while still using the query components.\n\n========================================\n\nCode:\n```text\n@apollo/client: 3.0.0-beta.4\n@apollo/react-components: 3.1.3\n```\n\n```text\nApolloProvider\n```\n\n```text\nimport {\n ApolloProvider as ApolloProvider2,\n Query,\n} from '@apollo/react-components'\nimport {\n ApolloProvider,\n ApolloClient,\n HttpLink,\n InMemoryCache,\n useQuery,\n gql,\n} from '@apollo/client'\n\n<ApolloProvider2 client={client}>\n <ApolloProvider client={client}>\n <App/>\n </ApolloProvider>\n</ApolloProvider2>\n```\n\n```text\nApolloProvider\n```\n\n```text\nApolloProvider\n```\n\n```text\nreact-apollo\n```\n\n```text\nApolloProvider\n```\n\n```text\nQuery\n```\n\n```text\nuseQuery\n```\n\n```text\nApolloProvider\n```\n\n```text\nQuery\n```\n\n```text\nuseQuery\n```\n\n```text\n@apollo/client\n```\n\n```text\nApolloProvider\n```\n\n```text\nuseQuery\n```\n\n```text\ngraphql\n```\n\n```text\nQuery\n```\n\n```text\nuseQuery\n```\n\n```text\nQuery\n```\n\n```text\n@apollo/react-components\n```\n\n```text\nApolloProvider\n```\n\n```text\ngql\n```\n\n```text\napollo@client\n```\n\n========================================\n\nComments:\n- This worked perfectly, thank you. I had thought that the deprecation would have still meant they were compatible with the same Provider until they were removed, but I see that's not the case. Thanks!\n- Bear in mind the incompatibility comes from the fact you're using different packages, because of the way context works. You'd have the same issue using, for example, two different redux packages that each required a context provider.","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":143,"estimatedTokens":619}}991{"id":"stack-75153941","source":"stackoverflow","questionId":75153941,"title":"why instaling type-graphql, @apollo/server and graphql together showing dependency error","tags":["graphql","apollo-server","typegraphql"],"text":"Title: why instaling type-graphql, @apollo/server and graphql together showing dependency error\nTags: graphql, apollo-server, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI have been trying to install typegraphql with apollo/server in typescript node template but it showing dependency error, I don't know why all new version is not compatible with each other.\n\n```\nnpm ERR! ERESOLVE could not resolve\nnpm ERR! \nnpm ERR! While resolving: server@1.0.0\nnpm ERR! Found: graphql@16.6.0\nnpm ERR! node_modules/graphql\nnpm ERR! graphql@\"*\" from the root project\nnpm ERR! peer graphql@\"^16.6.0\" from @apollo/server@4.3.0\nnpm ERR! node_modules/@apollo/server\nnpm ERR! @apollo/server@\"*\" from the root project\nnpm ERR! \nnpm ERR! Could not resolve dependency:\nnpm ERR! type-graphql@\"*\" from the root project\nnpm ERR! \nnpm ERR! Conflicting peer dependency: graphql@15.8.0\nnpm ERR! node_modules/graphql\nnpm ERR! peer graphql@\"^15.3.0\" from type-graphql@1.1.1\nnpm ERR! node_modules/type-graphql\nnpm ERR! type-graphql@\"*\" from the root project\nnpm ERR! \nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\n\n$ npm i @apollo/server express graphql reflect-metadata type-graphql\n```\n\nshould forcing it works or will it lead to data-leaks and all?\nThanks in advance for replying\n\n========================================\n\nCode:\n```text\nnpm ERR! ERESOLVE could not resolve\nnpm ERR! \nnpm ERR! While resolving: server@1.0.0\nnpm ERR! Found: graphql@16.6.0\nnpm ERR! node_modules/graphql\nnpm ERR! graphql@\"*\" from the root project\nnpm ERR! peer graphql@\"^16.6.0\" from @apollo/server@4.3.0\nnpm ERR! node_modules/@apollo/server\nnpm ERR! @apollo/server@\"*\" from the root project\nnpm ERR! \nnpm ERR! Could not resolve dependency:\nnpm ERR! type-graphql@\"*\" from the root project\nnpm ERR! \nnpm ERR! Conflicting peer dependency: graphql@15.8.0\nnpm ERR! node_modules/graphql\nnpm ERR! peer graphql@\"^15.3.0\" from type-graphql@1.1.1\nnpm ERR! node_modules/type-graphql\nnpm ERR! type-graphql@\"*\" from the root project\nnpm ERR! \nnpm ERR! Fix the upstream dependency conflict, or retry\nnpm ERR! this command with --force or --legacy-peer-deps\nnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.\n\n\n\n$ npm i @apollo/server express graphql reflect-metadata type-graphql\n```\n\n```bash\nnpm uninstall type-graphql\nnpm install type-graphql@next\n```\n\n```text\ntype-graphql\n```\n\n```text\ngraphql\n```\n\n```text\n^15.5.0\n```\n\n```text\n@apollo/server\n```\n\n```text\ngraphql\n```\n\n```text\n>= 16\n```\n\n```text\ntype-graphql\n```\n\n```text\n2.0.0\n```\n\n```text\nnext\n```\n\n```text\nnpm\n```\n\n```text\ntype-graphql\n```\n\n```text\nnext\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":121,"estimatedTokens":687}}992{"id":"stack-53468410","source":"stackoverflow","questionId":53468410,"title":"Rails Graphql resolve error: wrong number of arguments (given 1, expected 3)","tags":["ruby-on-rails","ruby","graphql"],"text":"Title: Rails Graphql resolve error: wrong number of arguments (given 1, expected 3)\nTags: ruby-on-rails, ruby, graphql\nSource: Stack Overflow\n\nQuestion:\nI created fresh rails app with `graphql`, but had a lot of problems agains guides aged 6+ months. I suspect that `graphql-ruby` changing quite fast.\n\nSo my last issue in `resolve` method:\n\n```\nmodule Types\n class QueryType (_obj, _args, _ctx) { Product.all }\n end\n end\nend\n```\n\nError:\n\n```\nwrong number of arguments (given 1, expected 3)\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:430:in `resolve'\n/Users/alder/Projects/_apps/service_exchange/any-do-api/app/graphql/types/query_type.rb:7:in `block in '\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:222:in `instance_eval'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:222:in `initialize'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/member/accepts_definition.rb:142:in `initialize'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:88:in `new'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:88:in `from_options'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/member/has_fields.rb:52:in `field'\n/Users/alder/Projects/_apps/service_exchange/any-do-api/app/graphql/types/query_type.rb:6:in `'\n/Users/alder/Projects/_apps/service_exchange/any-do-api/app/graphql/types/query_type.rb:2:in `'\n/Users/alder/Projects/_apps/service_exchange/any-do-api/app/graphql/types/query_type.rb:1:in `'\n```\n\nFull log\n\nYou can check out the full project here\n\nI'm using the latest version:\n\n```\ngem \"graphql\", \"~> 1.9.0.pre1\"\n```\n\nBut the same error with `1.8.*`\n\n========================================\n\nCode:\n```text\nmodule Types\n class QueryType < Types::BaseObject\n graphql_name \"Root Query\"\n description \"The query root of this schema\"\n\n field :allProducts, [ProductType], null: false do\n resolve ->(_obj, _args, _ctx) { Product.all }\n end\n end\nend\n```\n\n```text\nwrong number of arguments (given 1, expected 3)\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:430:in `resolve'\n/Users/alder/Projects/_apps/service_exchange/any-do-api/app/graphql/types/query_type.rb:7:in `block in <class:QueryType>'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:222:in `instance_eval'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:222:in `initialize'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/member/accepts_definition.rb:142:in `initialize'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:88:in `new'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/field.rb:88:in `from_options'\n/usr/local/var/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/graphql-1.9.0.pre1/lib/graphql/schema/member/has_fields.rb:52:in `field'\n/Users/alder/Projects/_apps/service_exchange/any-do-api/app/graphql/types/query_type.rb:6:in `<class:QueryType>'\n/Users/alder/Projects/_apps/service_exchange/any-do-api/app/graphql/types/query_type.rb:2:in `<module:Types>'\n/Users/alder/Projects/_apps/service_exchange/any-do-api/app/graphql/types/query_type.rb:1:in `<main>'\n```\n\n```text\ngem \"graphql\", \"~> 1.9.0.pre1\"\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql-ruby\n```\n\n```text\nresolve\n```\n\n```text\n1.8.*\n```\n\n```text\nclass QueryType < Types::BaseObject\n graphql_name \"RootQuery\"\n\n field :categories, [Types::CategoryType], null: false\n\n def categories\n Category.all\n end\nend\n```\n\n```text\nresolve\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":112,"estimatedTokens":1007}}993{"id":"stack-58941500","source":"stackoverflow","questionId":58941500,"title":"Inline images not loading from body of the markdown file in GatsbyJS","tags":["javascript","reactjs","graphql","markdown","gatsby"],"text":"Title: Inline images not loading from body of the markdown file in GatsbyJS\nTags: javascript, reactjs, graphql, markdown, gatsby\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to use inline images in my markdown file using gatsby-remark-images. Unfortunately, the image won't load on my local host. I don't know if it's simply erroneous syntax or I am missing something drastic.\n\nHere's the config: (I have a suspicion that I've done something wrong somewhere, it's here.)\n\n```\nmodule.exports = {\n siteMetadata: {\n title: ``,\n description: `A blog where code is written about`,\n author: `@wesley`,\n },\n\n plugins: [\n `gatsby-plugin-sass`,\n `gatsby-plugin-styled-components`,\n `gatsby-plugin-react-helmet`,\n `gatsby-plugin-catch-links`,\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/images`,\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/pages`,\n },\n },\n `gatsby-transformer-sharp`,\n `gatsby-plugin-sharp`,\n {\n resolve: `gatsby-transformer-remark`,\n options: {\n plugins: [\n {\n resolve: `gatsby-remark-images`,\n options: {\n // It's important to specify the maxWidth (in pixels) of\n // the content container as this plugin uses this as the\n // base for generating different widths of each image.\n maxWidth: 1200,\n },\n },\n ],\n },\n },\n\n `gatsby-transformer-remark`,\n {\n resolve: `gatsby-plugin-manifest`,\n options: {\n name: `gatsby-starter-default`,\n short_name: `starter`,\n start_url: `/`,\n background_color: `#663399`,\n theme_color: `#663399`,\n display: `minimal-ui`,\n icon: `src/images/mt.png`, // This path is relative to the root of the site.\n },\n },\n // this (optional) plugin enables Progressive Web App + Offline functionality\n // To learn more, visit: https://gatsby.dev/offline\n // `gatsby-plugin-offline`,\n ],\n};\n```\n\nI've pored over the poor documentation on Gatsby over and over. I am confounded. Anyone have an idea as to what's going on? I was able to get the featured image to work, but that's not what I want. \n\n**package.json:**\n\n**Path in markdown file is right (I believe):**\n\n**Screenshot of what I'm getting:**\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n siteMetadata: {\n title: ``,\n description: `A blog where code is written about`,\n author: `@wesley`,\n },\n\n plugins: [\n `gatsby-plugin-sass`,\n `gatsby-plugin-styled-components`,\n `gatsby-plugin-react-helmet`,\n `gatsby-plugin-catch-links`,\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/images`,\n },\n },\n {\n resolve: `gatsby-source-filesystem`,\n options: {\n path: `${__dirname}/src/pages`,\n },\n },\n `gatsby-transformer-sharp`,\n `gatsby-plugin-sharp`,\n {\n resolve: `gatsby-transformer-remark`,\n options: {\n plugins: [\n {\n resolve: `gatsby-remark-images`,\n options: {\n // It's important to specify the maxWidth (in pixels) of\n // the content container as this plugin uses this as the\n // base for generating different widths of each image.\n maxWidth: 1200,\n },\n },\n ],\n },\n },\n\n `gatsby-transformer-remark`,\n {\n resolve: `gatsby-plugin-manifest`,\n options: {\n name: `gatsby-starter-default`,\n short_name: `starter`,\n start_url: `/`,\n background_color: `#663399`,\n theme_color: `#663399`,\n display: `minimal-ui`,\n icon: `src/images/mt.png`, // This path is relative to the root of the site.\n },\n },\n // this (optional) plugin enables Progressive Web App + Offline functionality\n // To learn more, visit: https://gatsby.dev/offline\n // `gatsby-plugin-offline`,\n ],\n};\n```\n\n```js\nmodule.exports = {\n plugins: [\n // ... other plugins\n {\n resolve: `gatsby-transformer-remark`,\n options: {\n plugins: [\n {\n resolve: `gatsby-remark-images`,\n options: {\n // It's important to specify the maxWidth (in pixels) of\n // the content container as this plugin uses this as the\n // base for generating different widths of each image.\n maxWidth: 1200,\n },\n },\n ],\n },\n },\n\n // `gatsby-transformer-remark`, // remove this as it will override previous configuration \n ]\n};\n```\n\n```text\ngatsby-remark-images\n```\n\n```text\n../../images/train.png\n```\n\n========================================\n\nComments:\n- welcome to SO. Please copy/paste your text instead of using screenshots when possible. 1- better accessibility 2- easier SEO\n- wow that totally solved my problem, thanks! I'd recently added support for embedded youtube videos, and didn't realise I'd now added a 2nd `gatsby-transformer-remark`\n- I understand this isn't the best use of a comment, but this answer saved me from hours of confusing investigation. Much appreciated.","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":188,"estimatedTokens":1242}}994{"id":"stack-52101534","source":"stackoverflow","questionId":52101534,"title":"How to declare a module to do named imports?","tags":["typescript","module","graphql","graphql-tag"],"text":"Title: How to declare a module to do named imports?\nTags: typescript, module, graphql, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nI'm using graphql-tag. My files are like that.\n\n./operation.graphql\n\n```\nQuery User {\n ...\n}\n```\n\n./test.ts\n\n```\nimport { User } from './operation.graphql'; /// Module ''*.graphql'' has no exported member 'User'.\n```\n\n./index.d.ts\n\n```\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql';\n\n const value:DocumentNode;\n\n export default value;\n}\n```\n\nA application is work well, but I want to prevent that error.\n\nWhen I do default import is work well, but as you see, I got an error at named imports.\n\nHow to declare this? Thanks. :)\n\n========================================\n\nCode:\n```text\nQuery User {\n ...\n}\n```\n\n```text\nimport { User } from './operation.graphql'; /// Module ''*.graphql'' has no exported member 'User'.\n```\n\n```text\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql';\n\n const value:DocumentNode;\n\n export default value;\n}\n```\n\n```text\ndeclare module 'operation.graphql' {\n import { DocumentNode } from 'graphql';\n\n export const User: DocumentNode;\n}\n```\n\n```text\ndeclare module '*.graphql';\n```\n\n```text\nbaseUrl\n```\n\n```text\npaths\n```\n\n```text\nd.ts\n```\n\n```text\ndeclare module\n```\n\n```text\nany\n```\n\n========================================\n\nComments:\n- Thanks. :) it's helpful!\n- I ran into this today, and ended up using @graphql-codegen/typescript-graphql-files-modules to generate the types, with named exports, from the gql docs.","metadata":{"transformedAt":"2026-08-18T18:32:36.097Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":99,"estimatedTokens":385}}995{"id":"stack-54947891","source":"stackoverflow","questionId":54947891,"title":"Can I add data to a GraphQL edge?","tags":["graphql"],"text":"Title: Can I add data to a GraphQL edge?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI'm playing around with GraphQL, and I've run across the concept of connections and edges.\n\nFrom what I understand it's not uncommon to see metadata on the connection, like the `totalCount` property in the following snippet.\n\n```\ntype UserFriendsConnection {\n pageInfo: PageInfo!\n edges: [UserFriendsEdge]\n totalCount: Int\n}\n```\n\nMy questions is whether it's OK to put arbitrary metadata on the edge also, and if the following would be a decent way to do that.\n\nI felt like a query and a response would best illustrate what I'm looking for. It's the `role` property I want to place somewhere that makes sense.\n\nI feel like it doesn't belong in the `User` type since the role describes the type of connection/relationship the `User` has with a `Group`.\n\n```\n# Query\n\n{\n me {\n id\n name\n groupsConnection {\n edges {\n node {\n id\n name\n membersConnection {\n edges {\n node {\n id\n name\n }\n role <--- HERE\n }\n }\n }\n role <--- HERE\n }\n }\n }\n}\n```\n\n```\n# Response\n\n{\n \"data\": {\n \"me\": {\n \"id\": \"1Edj3hZFg\",\n \"name\": \"John Doe\",\n \"groupsConnection\": {\n \"edges\": [\n {\n \"node\": {\n \"id\": \"bpQgdZweQE\",\n \"name\": \"Fishing Team\",\n \"membersConnection\": {\n \"edges\": [\n {\n \"node\": {\n \"id\": \"1Edj3hZFg\",\n \"name\": \"John Doe\"\n },\n \"role\": \"ADMINISTRATOR\" <--- HERE\n },\n {\n \"node\": {\n \"id\": \"7dj37dH2d\",\n \"name\": \"Rebecca Anderson\"\n },\n \"role\": \"MEMBER\" <--- HERE\n }\n ]\n }\n },\n \"role\": \"ADMINISTRATOR\" <--- HERE\n }\n ]\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\ntype UserFriendsConnection {\n pageInfo: PageInfo!\n edges: [UserFriendsEdge]\n totalCount: Int\n}\n```\n\n```text\n# Query\n\n{\n me {\n id\n name\n groupsConnection {\n edges {\n node {\n id\n name\n membersConnection {\n edges {\n node {\n id\n name\n }\n role <--- HERE\n }\n }\n }\n role <--- HERE\n }\n }\n }\n}\n```\n\n```text\n# Response\n\n{\n \"data\": {\n \"me\": {\n \"id\": \"1Edj3hZFg\",\n \"name\": \"John Doe\",\n \"groupsConnection\": {\n \"edges\": [\n {\n \"node\": {\n \"id\": \"bpQgdZweQE\",\n \"name\": \"Fishing Team\",\n \"membersConnection\": {\n \"edges\": [\n {\n \"node\": {\n \"id\": \"1Edj3hZFg\",\n \"name\": \"John Doe\"\n },\n \"role\": \"ADMINISTRATOR\" <--- HERE\n },\n {\n \"node\": {\n \"id\": \"7dj37dH2d\",\n \"name\": \"Rebecca Anderson\"\n },\n \"role\": \"MEMBER\" <--- HERE\n }\n ]\n }\n },\n \"role\": \"ADMINISTRATOR\" <--- HERE\n }\n ]\n }\n }\n }\n}\n```\n\n```text\ntotalCount\n```\n\n```text\nrole\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nGroup\n```\n\n```text\ntype UserConnection {\n pageInfo: PageInfo!\n egdes: [UserEdge!]!\n}\n\ntype UserEdge {\n cursor: String!\n edge: User!\n}\n```\n\n```text\ntype Query {\n allUsers: UserConnection!\n # other fields\n}\n\ntype Group {\n members: UserConnection!\n # other fields\n}\n\ntype User {\n coworkers: UserConnection!\n # other fields\n}\n```\n\n```text\ntype GroupUserConnection {\n pageInfo: PageInfo!\n egdes: [GroupUserEdge!]!\n}\n\ntype GroupUserEdge {\n cursor: String!\n edge: User!\n role: Role!\n}\n```\n\n```text\nUser\n```\n\n```text\nUserConnection\n```\n\n```text\nUserEdge\n```\n\n```text\nrole\n```\n\n```text\nUserEdge\n```\n\n```text\nmembers\n```\n\n```text\nGroup\n```\n\n```text\nUserConnection\n```\n\n```text\nrole\n```\n\n========================================\n\nComments:\n- Fantastic! Thank you so much for clarifying this for me. I was planning on having separate connection types to make sure relationship-dependent stuff only exists where it makes sense. So, thanks for adding that part of your answer too.","metadata":{"transformedAt":"2026-08-18T18:32:36.098Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":278,"estimatedTokens":1023}}996{"id":"stack-54004551","source":"stackoverflow","questionId":54004551,"title":"How do I implement auth directive for mutations with Apollo?","tags":["javascript","authentication","graphql","apollo","apollo-server"],"text":"Title: How do I implement auth directive for mutations with Apollo?\nTags: javascript, authentication, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am trying to set up an Apollo backend for a project I'm working on, where I'm attempting to implement schema directives. However, I am not able to add my schema directive to mutations. So to my main question: How do I implement an auth directive for mutations?\n\nI have added `@auth(requires: ADMIN)` to the end of my users query, which is working fine. Apollo will then require a bearer token with admin access for performing the users query.\n\n```\nextend type Query {\n user(id: ID!): User\n users: [User!]! @auth(requires: ADMIN)\n}\n```\n\nWhen I tried to do it in the same way for the editMyUser mutation, the auth directive seems to be enforced for all the mutations, instead of just the one I wanted. Even the signUp mutation will give \"not authorized\" error, when I add the @auth part to the editMyUser mutation. Even though there is no relation between them.\n\nThe role field which is supposed to be passed to the auth directive when invoked is logging out empty.\n\n```\nextend type Mutation {\n signUp(\n username: String!\n firstName: String\n lastName: String\n password: String!\n isAdmin: Boolean\n isActive: Boolean): User!\n login(\n username: String!\n password: String!): User!\n editMyUser(\n id: ID!\n firstName: String\n lastName: String\n password: String): User! @auth(requires: USER)\n adminEditUser(\n id: ID!\n firstName: String\n lastName: String\n password: String\n isActive: Boolean\n isAdmin: Boolean\n isBanned: Boolean): User!\n}\n```\n\nThis is how I implemented the schema directive\n\n```\nexport default gql`\ndirective @auth(requires: Role = ADMIN) on OBJECT | FIELD_DEFINITION\n\nenum Role {\n ADMIN\n USER\n}\n```\n\nhttps://github.com/jwhenshaw/graphql-directives-auth\nThis is the Auth Directive I've implemented in my code for reference. \n\nSo to summarise, when I implement auth directives for mutations they are implemented for all mutations, instead of just the one, and it is not even working correctly, as roles are not passed on to the directive.\n\nI would love to get some help with this. Thanks!\n\n========================================\n\nTop Answer:\nThe issue here is that the referenced implementation throws an error when the wrapping resolver does not find any required roles (neither for the object type nor the field in question) in these lines of code. \n\nThe logic is that as you use the directive for some field of an object type, you also need to provide a requirement for the type itself. In my opinion this logic isn't too bad and is as the code comment suggests to be on the safe side. The author of that implementation probably focused on usage of the directive for actual data types, not for queries or mutations.\n\nLet me be even a little more specific: What you and I do (as I am trying to accomplish the same thing as you today), when using the directive for one or several queries/mutations is actually applying the directive on the fields of the schema types `Query` and `Mutation`. So if we don't want a minimum requirement for all queries and/or mutations of our schema, the code should not throw an error in that condition I linked above, but it should call the wrapped resolver just as if the requirements were met (because there are none).\n\nExample:\n\n```\nif (!requiredRole) {\n // No auth required, just call the resolver\n return resolve.apply(this, args);\n}\n```\n\nI hope this helps! π\n\n========================================\n\nCode:\n```text\nextend type Query {\n user(id: ID!): User\n users: [User!]! @auth(requires: ADMIN)\n}\n```\n\n```text\nextend type Mutation {\n signUp(\n username: String!\n firstName: String\n lastName: String\n password: String!\n isAdmin: Boolean\n isActive: Boolean): User!\n login(\n username: String!\n password: String!): User!\n editMyUser(\n id: ID!\n firstName: String\n lastName: String\n password: String): User! @auth(requires: USER)\n adminEditUser(\n id: ID!\n firstName: String\n lastName: String\n password: String\n isActive: Boolean\n isAdmin: Boolean\n isBanned: Boolean): User!\n}\n```\n\n```text\nexport default gql`\ndirective @auth(requires: Role = ADMIN) on OBJECT | FIELD_DEFINITION\n\nenum Role {\n ADMIN\n USER\n}\n```\n\n```text\n@auth(requires: ADMIN)\n```\n\n```text\nAuthDirective\n```\n\n```text\nobjectType\n```\n\n```text\nensureFieldWrapped\n```\n\n```text\neditMyUser\n```\n\n```text\nMutation\n```\n\n```text\nMutation\n```\n\n```text\nUser\n```\n\n```text\nAuthDirective\n```\n\n```text\nFieldAuthDirective\n```\n\n```text\nObjectAuthDirective\n```\n\n```text\nif (!requiredRole) {\n // No auth required, just call the resolver\n return resolve.apply(this, args);\n}\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.098Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":193,"estimatedTokens":1209}}997{"id":"stack-46656426","source":"stackoverflow","questionId":46656426,"title":"Apollo and GraphQL CORS","tags":["ruby-on-rails","reactjs","cors","graphql","react-apollo"],"text":"Title: Apollo and GraphQL CORS\nTags: ruby-on-rails, reactjs, cors, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nRunning into a frustrating issue with Apollo getting content from a Rails backend. The issue seems to be resolving around the use of CORS in my Apollo project.\n\n**Tech**\n\n- apollo-client: 1.9.3\n\n- graphql: 0.11.7\n\n- react: 15.6.1\n\n- react-apollo: 1.4.16\n\n**cors.rb**\n\n```\nRails.application.config.middleware.insert_before 0, Rack::Cors do\n allow do\n origins `*`\n\n resource '*',\n headers: :any,\n methods: [:get, :post, :put, :patch, :delete, :options, :head]\n end\nend\n```\n\n*rails is running on port 3001* `rails s -p 3001`\n\nWith this backend you can make `curl` requests and everything works as expected\n\n**Working Curl**\n\n```\ncurl -X POST -H \"Content-Type: application/json\" -d '{\"query\": \"{users{first_name}}\"}' http://localhost:3001/graphql\n```\n\nThis returns back expected data\n\nSo this is all pointing to an issue with Apollo and the frontend of the application. \n\n**index.jsx**\n\n```\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport ApolloClient from 'apollo-client';\nimport { ApolloProvider, createNetworkInterface } from 'react-apollo';\n\nimport App from './containers/App.jsx';\n\nconst client = new ApolloClient({\n networkInterface: createNetworkInterface({\n uri: 'http://localhost:3001/graphql', \n \n ,\n document.getElementById('root')\n);\n```\n\n**App.jsx**\n\n```\nimport React, { Component } from 'react';\nimport gql from 'graphql-tag';\nimport { graphql } from 'react-apollo';\n\nclass App extends Component {\n render() {\n console.log(this.props);\n return (\n Application\n );\n }\n}\n\nconst query = gql`\n {\n users {\n first_name\n }\n }\n`;\n\nexport default graphql(query)(App);\n```\n\nThis returns the error \n\n Failed to load http://localhost:3001/graphql: Response to preflight\n request doesn't pass access control check: No\n 'Access-Control-Allow-Origin' header is present on the requested\n resource. Origin 'http://localhost:8080' is therefore not allowed\n access. If an opaque response serves your needs, set the request's\n mode to 'no-cors' to fetch the resource with CORS disabled.\n\n**app.jsx (change mode)**\n\n```\nconst client = new ApolloClient({\n networkInterface: createNetworkInterface({\n uri: 'http://localhost:3001/graphql',\n opts: {\n mode: 'no-cors'\n }\n })\n});\n```\n\nThis returns the error\n\n Unhandled (in react-apollo) Error: Network error: Network request\n failed with status 0 - \"\"`\n\nLooking at the request:\n\nGENERAL\n\n```\nRequest URL:http://localhost:3001/graphql\nRequest Method:POST\nStatus Code:200 OK\nRemote Address:[::1]:3001\nReferrer Policy:no-referrer-when-downgrade\n```\n\nRESPONSE HEADERS\n\nCache-Control:max-age=0, private, must-revalidate\nContent-Type:application/json; charset=utf-8\nTransfer-Encoding:chunked\nVary:Origin\n\nREQUEST HEADERS\n\n```\nAccept:*/*\nConnection:keep-alive\nContent-Length:87\nContent-Type:text/plain;charset=UTF-8 REQUEST PAYLOAD\n\n```\n{query: \"{β΅ users {β΅ first_nameβ΅ __typenameβ΅ }β΅}β΅\", operationName: null}\noperationName\n:\nnull\nquery\n:\n\"{β΅ users {β΅ first_nameβ΅ __typenameβ΅ }β΅}β΅\"\n```\n\nSo what I did to get some sort of response was to install the Chrome Extension Allow-Control-Allow-Origin: *\n\nIf `mode: 'no-cors'` is removed and this extension is active, data can be retrieved.\n\nIn looking through the Apollo docs I'm unable to find much on this topic. I tried implementing the Apollo Auth Header but this simply produced the same errors as above. \n\nWhat in my Apollo code could be causing these errors? And what steps are there to fix the problem?\n\nSearching over GitHub issues and other Google searches are either for much-older versions of Apollo in which issues \"have been addressed\" or do not work when implemented.\n\n**Edit**\n\nAdding Ruby on Rails tag just in case there is more configuration needed in Rails. Upon researching the Apollo Client issues found Network error: Network request failed with status 0 - \"\" This issued was resolved by the OP because of an issue on the backend.\n\n========================================\n\nCode:\n```text\nRails.application.config.middleware.insert_before 0, Rack::Cors do\n allow do\n origins `*`\n\n resource '*',\n headers: :any,\n methods: [:get, :post, :put, :patch, :delete, :options, :head]\n end\nend\n```\n\n```text\ncurl -X POST -H \"Content-Type: application/json\" -d '{\"query\": \"{users{first_name}}\"}' http://localhost:3001/graphql\n```\n\n```text\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport ApolloClient from 'apollo-client';\nimport { ApolloProvider, createNetworkInterface } from 'react-apollo';\n\nimport App from './containers/App.jsx';\n\nconst client = new ApolloClient({\n networkInterface: createNetworkInterface({\n uri: 'http://localhost:3001/graphql', <<<<< There is a different endpoint then the standard 'graphql' which is why this is declared\n })\n});\n\nReactDOM.render(\n <ApolloProvider client={client}>\n <App />\n </ApolloProvider>,\n document.getElementById('root')\n);\n```\n\n```text\nimport React, { Component } from 'react';\nimport gql from 'graphql-tag';\nimport { graphql } from 'react-apollo';\n\nclass App extends Component {\n render() {\n console.log(this.props);\n return (\n <div>Application</div>\n );\n }\n}\n\nconst query = gql`\n {\n users {\n first_name\n }\n }\n`;\n\nexport default graphql(query)(App);\n```\n\n```text\nconst client = new ApolloClient({\n networkInterface: createNetworkInterface({\n uri: 'http://localhost:3001/graphql',\n opts: {\n mode: 'no-cors'\n }\n })\n});\n```\n\n```none\nRequest URL:http://localhost:3001/graphql\nRequest Method:POST\nStatus Code:200 OK\nRemote Address:[::1]:3001\nReferrer Policy:no-referrer-when-downgrade\n```\n\n```none\nAccept:*/*\nConnection:keep-alive\nContent-Length:87\nContent-Type:text/plain;charset=UTF-8 <<< I'm wondering if this needs to be application/json?\nHost:localhost:3001\nOrigin:http://localhost:8080\nReferer:http://localhost:8080/\nUser-Agent:Chrome/61\n```\n\n```none\n{query: \"{β΅ users {β΅ first_nameβ΅ __typenameβ΅ }β΅}β΅\", operationName: null}\noperationName\n:\nnull\nquery\n:\n\"{β΅ users {β΅ first_nameβ΅ __typenameβ΅ }β΅}β΅\"\n```\n\n```text\nrails s -p 3001\n```\n\n```text\ncurl\n```\n\n```text\nmode: 'no-cors'\n```\n\n```text\nRails.application.config.middleware.insert_before 0, Rack::Cors do\n allow do\n origins `*`\n\n resource '*',\n headers: :any,\n methods: [:get, :post, :put, :patch, :delete, :options, :head]\n end\nend\n```\n\n```text\norigins '*'\n```\n\n```text\nopts\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.098Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":306,"estimatedTokens":1603}}998{"id":"stack-34492614","source":"stackoverflow","questionId":34492614,"title":"RelayJS: How to set initialVariables via props","tags":["reactjs","relayjs","graphql","graphql-js"],"text":"Title: RelayJS: How to set initialVariables via props\nTags: reactjs, relayjs, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nLets say I have a GraphQL type `Echo` that echo whatever I query with some decorations. On the other hand, I have a React component that echo `message` passed to it with some decorations determined by `Echo` type. How can I set `initialVariables` for the `Echo` component?\n\nI read that setting props sets `initialVariables`, however that does not work. I have tried `componentDidMount`, but that does not work too.\n\nThis Relay Playground shows that message is not being displayed correctly.\n\nFor context,\n\n```\n// This component consumes `Echo` type\nclass Echo extends React.Component {\n componentDidMount() {\n let {relay, message} = this.props; \n\n relay.setVariables({\n message\n });\n }\n\n render() {\n let name = '';\n if (this.props.echo) {\n name = this.props.echo.name;\n }\n\n return (\n \n- Message: {name}\n );\n }\n}\n\nEcho = Relay.createContainer(Echo, {\n // By default `message` is null\n initialVariables: {\n message: null\n },\n\n fragments: {\n echo: () => Relay.QL`\n fragment on Echo {\n name(message: $message)\n }\n `,\n },\n});\n```\n\nThis is the type that resolve with an echo\n\n```\nlet EchoType = new GraphQLObjectType({\n name: 'Echo',\n fields: () => ({\n name: {\n type: GraphQLString,\n args: {\n message: {\n type: GraphQLString\n }\n },\n resolve: (echo, {message}) => `Hello, ${message}!`\n }\n })\n});\n```\n\n========================================\n\nCode:\n```jsx\n// This component consumes `Echo` type\nclass Echo extends React.Component {\n componentDidMount() {\n let {relay, message} = this.props; \n\n relay.setVariables({\n message\n });\n }\n\n render() {\n let name = '';\n if (this.props.echo) {\n name = this.props.echo.name;\n }\n\n return (\n <li>Message: {name}</li>\n );\n }\n}\n\nEcho = Relay.createContainer(Echo, {\n // By default `message` is null\n initialVariables: {\n message: null\n },\n\n fragments: {\n echo: () => Relay.QL`\n fragment on Echo {\n name(message: $message)\n }\n `,\n },\n});\n```\n\n```js\nlet EchoType = new GraphQLObjectType({\n name: 'Echo',\n fields: () => ({\n name: {\n type: GraphQLString,\n args: {\n message: {\n type: GraphQLString\n }\n },\n resolve: (echo, {message}) => `Hello, ${message}!`\n }\n })\n});\n```\n\n```text\nEcho\n```\n\n```text\nmessage\n```\n\n```text\nEcho\n```\n\n```text\ninitialVariables\n```\n\n```text\nEcho\n```\n\n```text\ninitialVariables\n```\n\n```text\ncomponentDidMount\n```\n\n```js\n<Echo echo={this.props.viewer.echo} defaultMessage=\"Default\"/>\n```\n\n```js\ncomponentDidMount() {\n let {relay, defaultMessage} = this.props; \n\n relay.setVariables({\n message: defaultMessage\n });\n}\n```\n\n```js\nclass Echo extends React.Component {\n componentDidMount() {\n let {relay, defaultMessage} = this.props; \n\n relay.setVariables({\n message: defaultMessage\n });\n }\n\n render() {\n let name = '';\n if (this.props.echo) {\n name = this.props.echo.name;\n }\n\n return (\n <li>Message: {name}</li>\n );\n }\n}\nEcho = Relay.createContainer(Echo, {\n initialVariables: {\n message: \"\"\n },\n fragments: {\n echo: () => Relay.QL`\n fragment on Echo {\n name(message: $message)\n }\n `,\n },\n});\n\nclass EchoApp extends React.Component {\n render() {\n return <ul>\n <Echo echo={this.props.viewer.echo} defaultMessage=\"Default\"/>\n </ul>;\n }\n}\nEchoApp = Relay.createContainer(EchoApp, {\n fragments: {\n viewer: () => Relay.QL`\n fragment on Viewer {\n echo { ${Echo.getFragment('echo')} },\n }\n `,\n },\n});\n\nclass EchoRoute extends Relay.Route {\n static routeName = 'Home';\n static queries = {\n viewer: (Component) => Relay.QL`\n query {\n viewer { ${Component.getFragment('viewer')} },\n }\n `,\n };\n}\n\nReactDOM.render(\n <Relay.RootContainer\n Component={EchoApp}\n route={new EchoRoute()}\n />,\n mountNode\n);\n```\n\n```text\nmessage\n```\n\n```text\nEcho\n```\n\n```text\nEcho\n```\n\n```text\ncomponentDidMount\n```\n\n========================================\n\nComments:\n- That is exactly what I wanted! It feels like a workaround of what Relay is missing anyway :)\n- Thank you! This is an absolute farce. I thought the whole point was that you passed the variables to set as props, not that you had to pass slightly differently named props and set them yourself (you're right, there's some sort of shadowing going on). I've wasted hours on this :-(\n- @jbrown I thought that too β and what makes even less sense is that if you do it like that, I can see that `this.props.relay.variables.message` is the prop that's passed into the component, and yet the component doesn't display the data I expect; `this.props.echo` is undefined.\n- @MichelleTilley Yeah that was the part that was confusing me most.","metadata":{"transformedAt":"2026-08-18T18:32:36.098Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":267,"estimatedTokens":1205}}999{"id":"stack-44213536","source":"stackoverflow","questionId":44213536,"title":"GraphQL: Many small mutations, or one bulk mutation?","tags":["graphql","relay","apollo"],"text":"Title: GraphQL: Many small mutations, or one bulk mutation?\nTags: graphql, relay, apollo\nSource: Stack Overflow\n\nQuestion:\nLet's say I am a user and I am editing my profile on some arbitrary app. The app let's me make a bunch of changes, and when I'm done, I click on \"Save\" and my profile gets updated.\n\nWhat is the recommended best practice in GraphQL to handle a large update like this? As I see it, there are a few options:\n\nA) **Many small mutations**. If the user changed 5 things (i.e., name, email, username, image, bio) the client could fire off 5 mutations to the server.\n\nPros: smaller, more isolated operations.\n\nCons: Doesn't this defeat the purpose of \"one round trip to the server\" in GraphQL, as it would require... 5?\n\nB) **Many small mutations, called server-side**. Rather than calling 5 mutations from the client, requiring 5 round trips, you could post a data blob to the server and have a function that parses it, and runs individual mutations on the data it finds.\n\nPros: One round trip\n\nCons: We have to add another layer to the app to handle this. The new function would get messy, be hard to test, and hard to maintain over time.\n\nC) **One large mutation**. The user sends the data blob to the server via a single mutation, which sets the new data in bulk on the document rather than running individual mutations on each field.\n\nPros: DX; one round trip.\n\nCons: Since fields are being passed in as arguments, this open the application to attack. A malicious user could try passing in arbitrary fields, setting fields that shouldn't be changed (i.e. an `isAdmin` field), etc. The mutation would have to be smart to know which fields are allowed to be updated, and reject / ignore the rest.\n\nI can't find much on the web about which way is the \"right way\" to do this kind of thing in GraphQL. Hoping to find some answers / feedback here. Thanks!\n\n========================================\n\nTop Answer:\nI'd go with the third solution, **one large mutation**. I'm not sure I understand your point about malicious users passing arbitrary fields : they wouldn't be able to pass fields that are not defined in your schema.\n\nAs for the server side logic, you'd have to put those smart checks anyway : you can never trust the client!\n\n========================================\n\nCode:\n```text\nisAdmin\n```\n\n```text\nmutation {\n setUserName(name: \"new_name\") { ok }\n setUserEmail(email: \"new_email\") { ok }\n}\n```\n\n========================================\n\nComments:\n- One round trip to the server is really for queries, not mutations.\n- I think you're overthinking it. The ways 1 and 3 are both correct ways to solve this problem depending on what you need. I would go with 3 it is probably the most robust way in most cases.\n- Thank you! I was definitely overthinking the security aspect of it. I hadn't realized that you can't pass in arbitrary values to a mutation to try and trick it, you can only supply the exact fields specified in your schema and they MUST be of expected type. So that means the more work you can get out of a single mutation, the better. So larger, more generic mutations it is!","metadata":{"transformedAt":"2026-08-18T18:32:36.098Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":56,"estimatedTokens":780}}1000{"id":"stack-55622941","source":"stackoverflow","questionId":55622941,"title":"Generate a schema.json with graphql-ruby","tags":["javascript","reactjs","graphql","graphql-ruby"],"text":"Title: Generate a schema.json with graphql-ruby\nTags: javascript, reactjs, graphql, graphql-ruby\nSource: Stack Overflow\n\nQuestion:\nHow can I generate a schema.json like the code in the links?\n\nhttps://github.com/exAspArk/graphql-on-rails/blob/master/schema.json\nhttps://github.com/Shopify/graphql-js-client/blob/master/schema.json\n\n========================================\n\nCode:\n```text\nGraphQL::RakeTask\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.220Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":16,"estimatedTokens":103}}1001{"id":"stack-64553202","source":"stackoverflow","questionId":64553202,"title":"Prisma doesn't generate files when running prisma init","tags":["docker","docker-compose","graphql","prisma","prisma-graphql"],"text":"Title: Prisma doesn't generate files when running prisma init\nTags: docker, docker-compose, graphql, prisma, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nRunning prisma init does not generate files. It not generates the 3 files below.\n\n- datamodel.graphql\n\n- docker-compose.yml\n\n- prisma.yml\n\nend up getting this error:-\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Project not found: 'graphiql@default'\",\n \"code\": 3016,\n \"requestId\": \"local:api:cjh3r908l000s0834adw100sj\"\n }\n ] \n}\n```\n\n========================================\n\nCode:\n```text\n{\n \"errors\": [\n {\n \"message\": \"Project not found: 'graphiql@default'\",\n \"code\": 3016,\n \"requestId\": \"local:api:cjh3r908l000s0834adw100sj\"\n }\n ] \n}\n```\n\n```text\n$ nvm install 12.19.1\n$ nvm use 12.19.1\n$ node -v // Check and confirm your node version\n\n$ prisma init <project_name>\n```\n\n```text\nNode v14.x.x.\n```\n\n```text\n$ prisma init <project_name>\n```\n\n```text\nv12.x.x\n```\n\n```text\nv.12.19.1\n```\n\n```text\nNode v12.19.1\n```\n\n```text\nv14.x.x\n```\n\n```text\nnvm\n```\n\n========================================\n\nComments:\n- Prisma 1 is an older version. As you're getting started, go for Prisma 2 prisma.io/docs/getting-started/quickstart-node","metadata":{"transformedAt":"2026-08-18T18:32:36.220Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":82,"estimatedTokens":307}}1002{"id":"stack-35713889","source":"stackoverflow","questionId":35713889,"title":"Handling errors in mutations","tags":["graphql","graphql-js"],"text":"Title: Handling errors in mutations\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nLet's say I'm trying to create a bike as a mutation\n\n```\nvar createBike = (wheelSize) => {\n if (!factoryHasEnoughMetal(wheelSize)) {\n return supplierError('Not enough metal');\n }\n return factoryBuild(wheelSize);\n}\n```\n\nWhat happens when there's not enough steel for them shiny wheels? We'll probably need an error for the client side. How do I get that to them from my graphQL server with the below mutation: \n\n```\n// Mutations\nmutation: new graphql.GraphQLObjectType({\n name: 'BikeMutation',\n fields: () => ({\n createBike: {\n type: bikeType,\n args: {\n wheelSize: {\n description: 'Wheel size',\n type: new graphql.GraphQLNonNull(graphql.Int)\n },\n },\n resolve: (_, args) => createBike(args.wheelSize)\n }\n })\n})\n```\n\nIs it as simple as returning some error type which the server/I have defined?\n\n========================================\n\nCode:\n```text\nvar createBike = (wheelSize) => {\n if (!factoryHasEnoughMetal(wheelSize)) {\n return supplierError('Not enough metal');\n }\n return factoryBuild(wheelSize);\n}\n```\n\n```text\n// Mutations\nmutation: new graphql.GraphQLObjectType({\n name: 'BikeMutation',\n fields: () => ({\n createBike: {\n type: bikeType,\n args: {\n wheelSize: {\n description: 'Wheel size',\n type: new graphql.GraphQLNonNull(graphql.Int)\n },\n },\n resolve: (_, args) => createBike(args.wheelSize)\n }\n })\n})\n```\n\n```text\n{\n \"data\": {\n \"createBike\": null\n },\n \"errors\": [\n {\n \"message\": \"Not enough metal\",\n \"originalError\": {}\n }\n ]\n}\n```\n\n```text\nif (res.errors) {res.errors[0].message}\n```\n\n```text\nthrow new Errors(JSON.stringify({\n code:409, \n message:\"Duplicate request......\"\n}))\n```\n\n========================================\n\nComments:\n- Haha, it's so simple! Thanks for the clear response and graphql-errors\n- Is the norm always to return localized messages directly from the API rather than error keys letting the client handle the translation as it pleases?","metadata":{"transformedAt":"2026-08-18T18:32:36.220Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":100,"estimatedTokens":517}}1003{"id":"stack-33143704","source":"stackoverflow","questionId":33143704,"title":"graphQL multiple mutations transaction","tags":["python","database","node.js","scala","graphql"],"text":"Title: graphQL multiple mutations transaction\nTags: python, database, node.js, scala, graphql\nSource: Stack Overflow\n\nQuestion:\nApparently graphQL mutations are executed one by one sequentially.\n\nSource :\n\n- https://learngraphql.com/basics/invoking-mutations/4\n\n In GraphQL, mutations are executed as a sequence. Otherwise, it's hard\n to detect errors like adding the same author again and again.\n\n \n It's totally up to the GraphQL server implementation to implement\n mutations like this. Reference NodeJS implementation and other\n community implementations for Python and Scala this.\n\nIf I understand it right, this does this prevent :\n\n- executing the requests in parallel\n\n- the use of transactions over multiple requests\n\nWhat is the rationale behind this design decision ?\nAre there other projects that do it differently ?\n\n========================================\n\nComments:\n- So in other words, two requests each containing one mutation can be executed in parallel, but when the two mutations are batched in one request, it is executed serially?\n- Sorry to respond to this so late, I am not exactly sure. I've never run two mutations batched into one request. If that was occurring, I'd probably just make a new mutation to perform both resolvers however I'd prefer and just call that.","metadata":{"transformedAt":"2026-08-18T18:32:36.220Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":33,"estimatedTokens":323}}1004{"id":"stack-71178814","source":"stackoverflow","questionId":71178814,"title":"How to pass object type argument in query in GraphQL?","tags":["graphql","graphql-js","graphql-java","express-graphql"],"text":"Title: How to pass object type argument in query in GraphQL?\nTags: graphql, graphql-js, graphql-java, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI got this type of query\n\n```\nquery {\n searchRandom (param : MyObjectClass){\n city\n }\n}\n```\n\nHow may I set param with the type of `MyObjectClass` and pass it in the query? To be able to test here?\n\nhttps://i.sstatic.net/CQ05p.png\n\n========================================\n\nCode:\n```text\nquery {\n searchRandom (param : MyObjectClass){\n city\n }\n}\n```\n\n```text\nMyObjectClass\n```\n\n```text\nquery getData($param: MyObjectClass){\n searchRandom(param: $param)\n city\n}\n```\n\n```text\n{\n \"param\": {\"country\": \"England\", \"population\": \"High\" }\n}\n```\n\n```text\ninput MyObjectClass {\n country: String\n population: String\n}\n```\n\n```js\nconst resolvers = {\n Query: {\n searchRandom: (parent, { param }) => {\n var query_data = param\n ...//your code\n return city_name;\n },\n },\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.220Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":64,"estimatedTokens":243}}1005{"id":"stack-66799844","source":"stackoverflow","questionId":66799844,"title":"What is the \"Merge\" Button in GraphiQL?","tags":["graphql","graphiql"],"text":"Title: What is the \"Merge\" Button in GraphiQL?\nTags: graphql, graphiql\nSource: Stack Overflow\n\nQuestion:\nWhat is the purpose of the `Merge` button in GraphiQL UI. It seems to be doing the same thing as the `Prettify` button.\n\nPlease provide an example\n\n========================================\n\nCode:\n```text\nMerge\n```\n\n```text\nPrettify\n```\n\n```text\nquery {\n test {\n person {\n name\n age\n ...friendNames\n }\n }\n}\n\nfragment friendNames on Person {\n friends {\n name\n }\n}\n```\n\n```text\n{\n test {\n person {\n name\n age\n friends {\n name\n }\n }\n }\n}\n```\n\n```text\nMerge\n```\n\n```text\nMerge\n```\n\n========================================\n\nComments:\n- Thank you very much! Very clear and understandable answer.","metadata":{"transformedAt":"2026-08-18T18:32:36.220Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":64,"estimatedTokens":190}}1006{"id":"stack-69449574","source":"stackoverflow","questionId":69449574,"title":"How to pass variables to metafieldsSet mutation in Shopify Api Node js Grahql client?","tags":["node.js","graphql","shopify"],"text":"Title: How to pass variables to metafieldsSet mutation in Shopify Api Node js Grahql client?\nTags: node.js, graphql, shopify\nSource: Stack Overflow\n\nQuestion:\nI was trying to use the `metafieldsSet` mutation to update metafields in `Shopify` with the following code:\n\n```\nconst client = new Shopify.Clients.Graphql(\n process.env.SHOP,\n process.env.PASSWORD\n )\n try {\n const metafields = await client.query({\n data: `mutation metafieldsSet($metafields: [MetafieldsSetInput!]!) {\n metafieldsSet(metafields: $metafields) {\n userErrors {\n field\n message\n }\n metafields {\n key\n value\n }\n }\n } \n `,\n query: {\n metafields: [\n {\n key: 'cb_inventory',\n namespace: 'my_fields',\n ownerId: 'gid://shopify/ProductVariant/40576138313890',\n type: 'number_integer',\n value: '25',\n },\n ],\n },\n })\n console.log(metafields)\n res.status(200).json({ values: metafields })\n } catch (error) {\n console.log(error)\n res.status(500).json(error)\n }\n```\n\nHowever, the above mutation returns the following error:\n\n```\nExpected value to not be null\nVariable $metafields of type [MetafieldsSetInput!]! was provided invalid value\n```\n\nI assume the variable `metafields` failed to pass into the mutation because when I run the exact same mutation in the `Shopify Admin API GraphiQL explorer`, there was no error\nShopify Admin API GraphiQL explorer mutation result\n\nI have also looked into the github repo of @shopify/shopify-api. In my understanding, variables are added to the `query` object.\n\nWhat am I missing?\n\nThanks,\n\nHoward\n\nEnvironment: Next js 11.1.2,\n\nDependencies: `@shopify/shopify-api` 1.4.1\n\n========================================\n\nCode:\n```text\nconst client = new Shopify.Clients.Graphql(\n process.env.SHOP,\n process.env.PASSWORD\n )\n try {\n const metafields = await client.query({\n data: `mutation metafieldsSet($metafields: [MetafieldsSetInput!]!) {\n metafieldsSet(metafields: $metafields) {\n userErrors {\n field\n message\n }\n metafields {\n key\n value\n }\n }\n } \n `,\n query: {\n metafields: [\n {\n key: 'cb_inventory',\n namespace: 'my_fields',\n ownerId: 'gid://shopify/ProductVariant/40576138313890',\n type: 'number_integer',\n value: '25',\n },\n ],\n },\n })\n console.log(metafields)\n res.status(200).json({ values: metafields })\n } catch (error) {\n console.log(error)\n res.status(500).json(error)\n }\n```\n\n```text\nExpected value to not be null\nVariable $metafields of type [MetafieldsSetInput!]! was provided invalid value\n```\n\n```text\nmetafieldsSet\n```\n\n```text\nShopify\n```\n\n```text\nmetafields\n```\n\n```text\nShopify Admin API GraphiQL explorer\n```\n\n```text\nquery\n```\n\n```text\n@shopify/shopify-api\n```\n\n```text\nconst metafields = await client.query({\n data: {\n query: `mutation metafieldsSet($metafields: [MetafieldsSetInput!]!) {\n metafieldsSet(metafields: $metafields) {\n userErrors {\n field\n message\n }\n metafields {\n key\n value\n }\n }\n }`,\n variables: {\n metafields: [\n {\n key: 'cb_inventory',\n namespace: 'my_fields',\n ownerId: 'gid://shopify/ProductVariant/40576138313890',\n type: 'number_integer',\n value: '25',\n },\n ],\n },\n },\n})\n```\n\n```text\nShopify.Context.initialize({\n API_KEY,\n API_SECRET_KEY,\n SCOPES: ['read_products', 'write_products'],\n HOST_NAME: HOST,\n API_VERSION: '2021-10',\n})\n```\n\n```text\nvariables\n```\n\n```text\nquery\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.220Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":188,"estimatedTokens":1004}}1007{"id":"stack-57109680","source":"stackoverflow","questionId":57109680,"title":"How to use mutations in react-apollo-hooks and formik?","tags":["reactjs","graphql","react-hooks","formik","react-apollo-hooks"],"text":"Title: How to use mutations in react-apollo-hooks and formik?\nTags: reactjs, graphql, react-hooks, formik, react-apollo-hooks\nSource: Stack Overflow\n\nQuestion:\nIn my many attempts, I've tried to use react-apollo-hooks and formik together but it seems impossible. The data from the forms is only available in the `` tag, and is otherwise inaccessible outside of it. Also I can't call my `useMutation` hook and pass arguments to it at the same time:\n\n```\nconst SignUp = () => {\n const classes = useStyles();\n // The react-apollo-hook for useMutation\n // Its not hard to call this, but it seems impossible to call it,\n // with any sort of arguments.\n // It seems pointless not being able to pass in data from the form\n const [createUser, { loading }] = useMutation(CREATE_USER_MUTATION, {\n variables: {\n firstName: '???',\n lastName: '???',\n email: '???',\n password: '???',\n },\n });\n // Formik stuff goes down here. It's impossible to call `useMutation` \n // with the argument of `values`\n return (\n createUser}\n render={({submitForm, isSubmitting, values, setFieldValue}) => (\n \n \n\n### Sign up for a new account\n\n \n \n \n \n Sign Up\n \n \n )}\n />\n );\n\n};\n```\n\nSo how would I somehow be able to pass arguments to the `useMutation` part at the top, from `onSubmit`? It seems impossible to pass arguments to the hook. I don't think I can add any other data outside of the query name `CREATE_USER_MUTATION` and the objects which has the settings.\n\n========================================\n\nCode:\n```text\nconst SignUp = () => {\n const classes = useStyles();\n // The react-apollo-hook for useMutation\n // Its not hard to call this, but it seems impossible to call it,\n // with any sort of arguments.\n // It seems pointless not being able to pass in data from the form\n const [createUser, { loading }] = useMutation(CREATE_USER_MUTATION, {\n variables: {\n firstName: '???',\n lastName: '???',\n email: '???',\n password: '???',\n },\n });\n // Formik stuff goes down here. It's impossible to call `useMutation` \n // with the argument of `values`\n return (\n <Formik\n initialValues={{\n firstName: '',\n lastName: '',\n email: '',\n password: '',\n showPassword: false,\n }}\n // This is the part that calls the hook.\n // I see no way of passing arguments to `useMutation` from here\n onSubmit={(values, { setSubmitting }) => createUser}\n render={({submitForm, isSubmitting, values, setFieldValue}) => (\n <div>\n <h1>Sign up for a new account</h1>\n <Form className={classes.container}>\n <Field\n className={classes.textField}\n name=\"firstName\"\n type=\"text\"\n label=\"First name\"\n margin=\"dense\"\n variant=\"outlined\"\n component={TextField}\n />\n </Form>\n <Button\n variant=\"contained\"\n color=\"primary\"\n margin=\"dense\"\n className={classes.button}\n disabled={isSubmitting}\n onClick={submitForm}\n >\n Sign Up\n </Button>\n </div>\n )}\n />\n );\n\n};\n```\n\n```text\n<Formik>\n```\n\n```text\nuseMutation\n```\n\n```text\nuseMutation\n```\n\n```text\nonSubmit\n```\n\n```text\nCREATE_USER_MUTATION\n```\n\n```text\nconst [createUser, { loading }] = useMutation(CREATE_USER_MUTATION)\n```\n\n```text\nonSubmit={(values, { setSubmitting }) => createUser({ variables: values })}\n```\n\n```text\nuseMutation\n```\n\n```text\ncreateUser\n```\n\n========================================\n\nComments:\n- I found a workaround earlier, which relied on something inefficient that relied on using React `useState`, setting all the fields in an onSubmit function, and using `useEffect` to call `createUser` only after all the fields have been updated (since its async). But its obviously inefficient and requires lots of lines of code. Your solution is much more cleaner and simple!","metadata":{"transformedAt":"2026-08-18T18:32:36.220Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":152,"estimatedTokens":988}}1008{"id":"stack-54732818","source":"stackoverflow","questionId":54732818,"title":"How do I wait until a cookie is set?","tags":["javascript","cookies","cucumber","graphql","cypress"],"text":"Title: How do I wait until a cookie is set?\nTags: javascript, cookies, cucumber, graphql, cypress\nSource: Stack Overflow\n\nQuestion:\nI am writing the acceptance tests for my application's login feature. At some point, I want to double-check the cookie's expiry time. \n\nUpon clicking on the \"Login\" button, a graphql query is sent to my server which responds with a Jwt. Upon reception of the jwt, the application sets the cookie with \n\n```\ndocument.cookie = ...\n```\n\nIn my Cypress test, I check the token in the following way:\n\n```\nThen(\"sa session s'ouvre pour {SessionDurationType}\", expectedDuration => {\n cy.get('@graphql').then(() => {\n cy.wait(1000)\n cy.getCookie('token').then(cookie => {\n const tokenDuration = getTokenDuration(cookie.value)\n expect(tokenDuration.asSeconds()).to.equal(expectedDuration.asSeconds())\n })\n })\n})\n```\n\nWith `cy.get('@graphql')`, I am waiting for the graphql query to return a response. The alias is defined like this:\n\n```\ncy.stub(win, 'fetch', fetch).as('graphql')\n```\n\nUpon reception, the application sets the cookie. \n\nMy problem is that I am not fond of the following call:\n\n```\ncy.wait(1000)\n```\n\nWithout that call, I always get an undefined cookie. \n\nIs there a way to get that cookie within some time that might be much less than 1000 ms? I tried many things without success...\n\n========================================\n\nTop Answer:\nI dont like the timeout in this i have to say for dom changes. I have come up with this solution based on @NoriSte Answer together with DomMutation Observers.\n\n\r\n\r\n\n```\ngetFileUploadItem().get(\".upload-item--state i\")\r\n .should(\"have.class\", \"ngx-fileupload-icon--start\")\r\n .then(item => {\r\n const iconEl = item.get(0);\r\n const states: string[] = [];\r\n\r\n return new Promise((resolve, reject) => {\r\n const observer = new MutationObserver((mutations: MutationRecord[]) => {\r\n const mutationEl = mutations[0].target as HTMLElement;\r\n const className = mutationEl.getAttribute(\"class\");\r\n\r\n states.push(className);\r\n\r\n if (className === \"ngx-fileupload-icon--uploaded\") {\r\n resolve(states);\r\n }\r\n });\r\n\r\n observer.observe(iconEl, {\r\n subtree: true,\r\n attributes: true,\r\n attributeFilter: [\"class\"]\r\n });\r\n });\r\n })\r\n .then((value) => expect(value).to.deep.equal(\r\n [\"ngx-fileupload-icon--progress\", \"ngx-fileupload-icon--uploaded\"])\r\n );\n```\n\n========================================\n\nCode:\n```text\ndocument.cookie = ...\n```\n\n```text\nThen(\"sa session s'ouvre pour {SessionDurationType}\", expectedDuration => {\n cy.get('@graphql').then(() => {\n cy.wait(1000)\n cy.getCookie('token').then(cookie => {\n const tokenDuration = getTokenDuration(cookie.value)\n expect(tokenDuration.asSeconds()).to.equal(expectedDuration.asSeconds())\n })\n })\n})\n```\n\n```text\ncy.stub(win, 'fetch', fetch).as('graphql')\n```\n\n```text\ncy.wait(1000)\n```\n\n```text\ncy.get('@graphql')\n```\n\n```text\nfunction checkCookie() {\n // cy.getCookie returns a thenebale\n return cy.getCookie('token').then(cookie => {\n const tokenDuration = getTokenDuration(cookie.value);\n // it checks the seconds right now, without unnecessary waitings\n if(tokenDuration.asSeconds() !== expectedDuration.asSeconds()) {\n // waits for a fixed milliseconds amount\n cy.wait(100);\n // returns the same function recursively, the next `.then()` will be the checkCookie function itself\n return checkCookie();\n }\n // only when the condition passes returns a resolving promise\n return Promise.resolve(tokenDuration.asSeconds());\n })\n}\n\nThen(\"sa session s'ouvre pour {SessionDurationType}\", expectedDuration => {\n cy.get('@graphql').then(() => {\n checkCookie()\n .then(seconds => {\n expect(seconds).to.equal(expectedDuration.asSeconds())\n })\n })\n})\n```\n\n```text\nexpectedDuration\n```\n\n```text\nfunction awaitNonNullToken(elapsedTimeInMs = 0) {\n let timeDeltaInMs = 10\n\n if (elapsedTimeInMs > Cypress.env('timeoutInMs')) {\n return Promise.reject(new Error('Awaiting token timeout'))\n }\n\n return getTokenCookie().then(cookie => {\n if (cookie === null) {\n cy.wait(timeDeltaInMs)\n elapsedTimeInMs += timeDeltaInMs\n return awaitNonNullToken(elapsedTimeInMs)\n }\n return Promise.resolve(cookie.value)\n })\n}\n```\n\n```text\nclass TokenHandler {\n constructor () {\n this.TIME_DELTA_IN_MS = Cypress.env('timeDeltaInMs')\n this.TIMEOUT_IN_MS = Cypress.env('timeoutInMs')\n this.elapsedTimeInMs = 0\n }\n\n getToken () {\n if (this.elapsedTimeInMs > this.TIMEOUT_IN_MS) {\n return Promise.reject(new Error('Awaiting token timeout'))\n }\n return getTokenCookie().then(cookie => {\n if (cookie === null) {\n cy.wait(this.TIME_DELTA_IN_MS)\n this.elapsedTimeInMs += this.TIME_DELTA_IN_MS\n return this.getToken()\n }\n return Promise.resolve(cookie.value)\n })\n }\n}\n```\n\n```text\ncy.get('@graphql').then(() => {\n const handler = new TokenHandler\n handler.getToken().then(token => {\n const tokenDuration = getTokenDuration(token)\n expect(tokenDuration.asSeconds()).to.equal(expectedDuration.asSeconds())\n })\n})\n```\n\n```js\ngetFileUploadItem().get(\".upload-item--state i\")\n .should(\"have.class\", \"ngx-fileupload-icon--start\")\n .then(item => {\n const iconEl = item.get(0);\n const states: string[] = [];\n\n return new Promise((resolve, reject) => {\n const observer = new MutationObserver((mutations: MutationRecord[]) => {\n const mutationEl = mutations[0].target as HTMLElement;\n const className = mutationEl.getAttribute(\"class\");\n\n states.push(className);\n\n if (className === \"ngx-fileupload-icon--uploaded\") {\n resolve(states);\n }\n });\n\n observer.observe(iconEl, {\n subtree: true,\n attributes: true,\n attributeFilter: [\"class\"]\n });\n });\n })\n .then((value) => expect(value).to.deep.equal(\n [\"ngx-fileupload-icon--progress\", \"ngx-fileupload-icon--uploaded\"])\n );\n```\n\n========================================\n\nComments:\n- Sorry, I'm beginner in JS. I want to understand - what if in recursive function our `if` statement will never give `false` then it means that we are in infinite loop ?\n- You're right, the code is not complete, and that's why I suggest using `waitUntil` that abstracts away the problem.","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":235,"estimatedTokens":1592}}1009{"id":"stack-56911431","source":"stackoverflow","questionId":56911431,"title":"Graphql-config does not recognize Apollo Graphql @client directive","tags":["intellij-idea","graphql","apollo-client","graphql-tag"],"text":"Title: Graphql-config does not recognize Apollo Graphql @client directive\nTags: intellij-idea, graphql, apollo-client, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nI'm using Apollo Client with React, graphql-tag loaded with Webpack, and graphql-config to maintain the schema on the client.\n\nThere is a file `./myclient/src/features/stats/graphql/getStart.graphql`\n\n```\nquery GetStart {\n start @client\n}\n```\n\nwhere `start` and `@client` don't validate with the IDE graphql plugin because they are not included in the auto generated schema.\n\nThe `./myclient/.graphqlconfig` file\n\n```\n{\n \"projects\": {\n \"client\": {\n \"schemaPath\": \"schema.graphql\",\n \"extensions\": {\n \"endpoints\": {\n \"dev\": \"http://localhost:3000/graphql\"\n }\n }\n }\n }\n}\n```\n\nWebpack is configured to load the graphql schema on the client with\n\n```\n{\n test: /\\.(graphql|gql)$/,\n exclude: /node_modules/,\n use: 'graphql-tag/loader',\n},\n```\n\nIt will load the server schema correctly. But, how do I configure it to validate or ignore the `start @client` which is causing `Unknown field \"start\" on object \"Query\"` and `Unknown directive \"@client\"` errors?\n\n========================================\n\nCode:\n```text\nquery GetStart {\n start @client\n}\n```\n\n```text\n{\n \"projects\": {\n \"client\": {\n \"schemaPath\": \"schema.graphql\",\n \"extensions\": {\n \"endpoints\": {\n \"dev\": \"http://localhost:3000/graphql\"\n }\n }\n }\n }\n}\n```\n\n```text\n{\n test: /\\.(graphql|gql)$/,\n exclude: /node_modules/,\n use: 'graphql-tag/loader',\n},\n```\n\n```text\n./myclient/src/features/stats/graphql/getStart.graphql\n```\n\n```text\nstart\n```\n\n```text\n@client\n```\n\n```text\n./myclient/.graphqlconfig\n```\n\n```text\nstart @client\n```\n\n```text\nUnknown field \"start\" on object \"Query\"\n```\n\n```text\nUnknown directive \"@client\"\n```\n\n```text\ndirective @client on FIELD\n\ntype RestParams {\n limit: Int\n page: Int\n}\n\nextend type Query {\n restParams: RestParams\n}\n```\n\n```text\nimport { ApolloClient } from 'apollo-client';\nimport { ApolloLink } from 'apollo-link';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\n\nimport TYPE_DEFS from './graphql/typeDefs.graphql';\nimport createHttpLink from './links/httpLink';\nimport createErrorLink from './links/errorLink';\nimport createAuthLink from './links/authLink';\n\nconst errorLink = createErrorLink();\nconst httpLink = createHttpLink();\nconst authLink = createAuthLink();\n\nconst cache = new InMemoryCache({});\n\nconst client = new ApolloClient({\n cache,\n link: ApolloLink.from([\n authLink,\n errorLink,\n httpLink,\n ]),\n // resolves,\n typeDefs: TYPE_DEFS,\n connectToDevTools: true,\n});\n\nexport default client;\n```\n\n```text\n./src/apollo/graphql/typeDefs.graphql\n```\n\n```text\ntypeDefs.graphql\n```\n\n```text\nclient.js\n```\n\n```text\ntypeDefs\n```\n\n```text\nApolloClient\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":169,"estimatedTokens":699}}1010{"id":"stack-39578852","source":"stackoverflow","questionId":39578852,"title":"How can I extract data from a list of dicts using graphene's mutation method?","tags":["graphql","flask-graphql"],"text":"Title: How can I extract data from a list of dicts using graphene's mutation method?\nTags: graphql, flask-graphql\nSource: Stack Overflow\n\nQuestion:\nIβm trying to created a list of objects using `graphql mutation`, but have been unsuccessful. I've identified the error, please see code snippets and comment on where the error is propagating.\n\n**Note: I'm using Graphene on Flask with Python 2.7**\n\nHereβs an example payload:\n\n```\nmutation UserMutation {\n createUser(\n phones: [\n {\n βnumberβ: β609-777-7777β,\n βlabelβ: βhome\" \n },\n {\n βnumberβ: β609-777-7778β,\n βlabelβ: βmobile\" \n }\n ]\n )\n}\n```\n\nOn the schema, I have the following:\n\n```\nclass CreateUser(graphene.Mutation):\n ok = graphene.Boolean()\n ...\n phones = graphene.List(graphene.String()) # this is a list of string but what I need is a list of dicts!\n```\n\n========================================\n\nCode:\n```text\nmutation UserMutation {\n createUser(\n phones: [\n {\n βnumberβ: β609-777-7777β,\n βlabelβ: βhome\" \n },\n {\n βnumberβ: β609-777-7778β,\n βlabelβ: βmobile\" \n }\n ]\n )\n}\n```\n\n```text\nclass CreateUser(graphene.Mutation):\n ok = graphene.Boolean()\n ...\n phones = graphene.List(graphene.String()) # this is a list of string but what I need is a list of dicts!\n```\n\n```text\ngraphql mutation\n```\n\n```text\nclass PhoneInput(graphene.InputObjectType):\n number = graphene.String()\n label = graphene.String()\n\nclass CreateUser(graphene.Mutation):\n class Input:\n phones = graphene.List(PhoneInput)\n ok = graphene.Boolean()\n\nclass Mutation(graphene.ObjectType):\n create_user = CreateUser.Field()\n```\n\n```text\nInputObjectType\n```\n\n```text\nInputObjectType\n```\n\n```text\n1.0\n```\n\n========================================\n\nComments:\n- Hi Syrus, how to save the phones into db. I use the document code but the database is not affected","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":98,"estimatedTokens":485}}1011{"id":"stack-60575891","source":"stackoverflow","questionId":60575891,"title":"How do I update subscription variables in a useSubscription hook - Apollo v3","tags":["reactjs","graphql","react-hooks","apollo"],"text":"Title: How do I update subscription variables in a useSubscription hook - Apollo v3\nTags: reactjs, graphql, react-hooks, apollo\nSource: Stack Overflow\n\nQuestion:\nI am currently trying to update a GraphQL subscription using the useSubscription hook from apollo v3 in a useEffect hook:\n\n```\nlet containerSubscription = useSubscription(\n gql(containerUpdatedOnCreatedDate),\n {\n variables: { createdDate: selectedDate },\n shouldResubscribe: true, // is this needed?\n },\n);\n\n// update subscription on date change\nReact.useEffect(() => {\n // how do I update the subscription here?\n // setting containerSubscription.variables = ... does not change the subscription\n}, [selectedDate]);\n```\n\nI could not find any solution in the apollo docs on how to address this problem.\n\nAny help would be appreciated!\n\n========================================\n\nCode:\n```js\nlet containerSubscription = useSubscription<CreatedDateSubscription, CreatedDateSubscriptionVariables>(\n gql(containerUpdatedOnCreatedDate),\n {\n variables: { createdDate: selectedDate },\n shouldResubscribe: true, // is this needed?\n },\n);\n\n// update subscription on date change\nReact.useEffect(() => {\n // how do I update the subscription here?\n // setting containerSubscription.variables = ... does not change the subscription\n}, [selectedDate]);\n```\n\n```text\nuseEffect\n```\n\n```text\nselectedDate\n```\n\n========================================\n\nComments:\n- Maybe you're not supposed to do that, I didn't find any documentation on that either, perhaps because you need to unsubscribe and resubscribe with new variables\n- @Arman thank you, I thought about that. But then, I could find any documentation on how to unsubscribe and resubscribe in the docs\n- Didn't think about that, thank you! It finally worked when i omitted the `shouldResubscribe` option","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":60,"estimatedTokens":454}}1012{"id":"stack-64441761","source":"stackoverflow","questionId":64441761,"title":"Postgress tries to return a column that does not exist in my model","tags":["node.js","postgresql","graphql","sequelize.js","database-migration"],"text":"Title: Postgress tries to return a column that does not exist in my model\nTags: node.js, postgresql, graphql, sequelize.js, database-migration\nSource: Stack Overflow\n\nQuestion:\nI use graphql API and try to insert data into Postgress table and got an error:\n\n```\n\"message\": \"column \\\"UserId\\\" does not exist\",\n```\n\nand my raw query:\n\n```\nExecuting (default): INSERT INTO \"Recipes\" \n(\"id\",\"title\",\"ingredients\",\"direction\",\"createdAt\",\"updatedAt\",\"userId\") VALUES \n(DEFAULT,$1,$2,$3,$4,$5,$6) \n RETURNING \n\"id\",\"title\",\"ingredients\",\"direction\",\"createdAt\",\"updatedAt\",\"userId\",\"UserId\";\n```\n\nthe problem is that a column **UserId** isn't in my model but **userId** is ! And i don't know why Postgres trying to return UserId column.\nMy Models.\nUser:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n class User extends Model {\n static associate(models) {\n User.hasMany(models.Recipe)\n }\n };\n User.init({\n name: {\n type: DataTypes.STRING,\n allowNull: false\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false\n },\n password: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n sequelize,\n modelName: 'User',\n });\n return User;\n};\n```\n\nRecipe:\n\n```\nmodule.exports = (sequelize, DataTypes) => {\n class Recipe extends Model {\n static associate(models) {\n Recipe.belongsTo(models.User, { foreignKey: 'userId' })\n }\n };\n Recipe.init({\n title: {\n type: DataTypes.STRING,\n allowNull: false\n },\n ingredients: {\n type: DataTypes.STRING,\n allowNull: false\n },\n direction: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n sequelize,\n modelName: 'Recipe',\n });\n return Recipe;\n};\n```\n\nmy graphql schema:\n\n```\nconst typeDefs = gql`\n type User {\n id: Int!\n name: String!\n email: String!\n recipes: [Recipe!]!\n }\n\n type Recipe {\n id: Int!\n title: String!\n ingredients: String!\n direction: String!\n user: User!\n }\n\n type Query {\n user(id: Int!): User\n allRecipes: [Recipe!]!\n recipe(id: Int!): Recipe\n }\n\n type Mutation {\n createUser(name: String!, email: String!, password: String!): User!\n createRecipe(\n userId: Int!\n title: String!\n ingredients: String!\n direction: String!\n ): Recipe!\n }\n`\n```\n\ngraphql reslover:\n\n```\nMutation: {\n async createRecipe (root, { userId, title, ingredients, direction }, { models }) {\n return models.Recipe.create({ userId, title, ingredients, direction })\n }\n }\n```\n\nand my grapql request:\n\n```\nmutation {\n createRecipe(\n userId: 1\n title: \"Sample 2\"\n ingredients: \"Salt, Pepper\"\n direction: \"Add salt, Add pepper\"\n ) {\n id\n title\n ingredients\n direction\n }\n}\n```\n\n========================================\n\nCode:\n```text\n\"message\": \"column \\\"UserId\\\" does not exist\",\n```\n\n```text\nExecuting (default): INSERT INTO \"Recipes\" \n(\"id\",\"title\",\"ingredients\",\"direction\",\"createdAt\",\"updatedAt\",\"userId\") VALUES \n(DEFAULT,$1,$2,$3,$4,$5,$6) \n RETURNING \n\"id\",\"title\",\"ingredients\",\"direction\",\"createdAt\",\"updatedAt\",\"userId\",\"UserId\";\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n class User extends Model {\n static associate(models) {\n User.hasMany(models.Recipe)\n }\n };\n User.init({\n name: {\n type: DataTypes.STRING,\n allowNull: false\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false\n },\n password: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n sequelize,\n modelName: 'User',\n });\n return User;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n class Recipe extends Model {\n static associate(models) {\n Recipe.belongsTo(models.User, { foreignKey: 'userId' })\n }\n };\n Recipe.init({\n title: {\n type: DataTypes.STRING,\n allowNull: false\n },\n ingredients: {\n type: DataTypes.STRING,\n allowNull: false\n },\n direction: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n sequelize,\n modelName: 'Recipe',\n });\n return Recipe;\n};\n```\n\n```text\nconst typeDefs = gql`\n type User {\n id: Int!\n name: String!\n email: String!\n recipes: [Recipe!]!\n }\n\n type Recipe {\n id: Int!\n title: String!\n ingredients: String!\n direction: String!\n user: User!\n }\n\n type Query {\n user(id: Int!): User\n allRecipes: [Recipe!]!\n recipe(id: Int!): Recipe\n }\n\n type Mutation {\n createUser(name: String!, email: String!, password: String!): User!\n createRecipe(\n userId: Int!\n title: String!\n ingredients: String!\n direction: String!\n ): Recipe!\n }\n`\n```\n\n```text\nMutation: {\n async createRecipe (root, { userId, title, ingredients, direction }, { models }) {\n return models.Recipe.create({ userId, title, ingredients, direction })\n }\n }\n```\n\n```text\nmutation {\n createRecipe(\n userId: 1\n title: \"Sample 2\"\n ingredients: \"Salt, Pepper\"\n direction: \"Add salt, Add pepper\"\n ) {\n id\n title\n ingredients\n direction\n }\n}\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n\nclass User extends Model {\n static associate(models) {\n User.hasMany(models.Recipe, {as: 'recipes', foreignKey:'userId'})\n }\n };\n User.init({\n name: {\n type: DataTypes.STRING,\n allowNull: false\n },\n email: {\n type: DataTypes.STRING,\n allowNull: false\n },\n password: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n sequelize,\n modelName: 'User',\n });\n return User;\n};\n```\n\n```text\nmodule.exports = (sequelize, DataTypes) => {\n class Recipe extends Model {\n static associate(models) {\n Recipe.belongsTo(models.User, { foreignKey: 'userId' })\n }\n };\n Recipe.init({\n title: {\n type: DataTypes.STRING,\n allowNull: false\n },\n ingredients: {\n type: DataTypes.STRING,\n allowNull: false\n },\n direction: {\n type: DataTypes.STRING,\n allowNull: false\n }\n }, {\n sequelize,\n modelName: 'Recipe',\n });\n return Recipe;\n};\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":334,"estimatedTokens":1491}}1013{"id":"stack-63705056","source":"stackoverflow","questionId":63705056,"title":"GraphQL query access parameter object values","tags":["graphql","apollo-client"],"text":"Title: GraphQL query access parameter object values\nTags: graphql, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI would like to create a parameter object on the client side, so I dont need too many parameters.\n\nI want to do something like this:\n\n```\ninput Options {\n option1: String\n option2: String\n}\n\nquery test($param: Options) {\n test(option1: $param.option1, option2: $param.option2) {\n id\n }\n}\n```\n\n$param.option1 is not supported. Is there any way to access attributes of an object parameter?\n\n========================================\n\nCode:\n```text\ninput Options {\n option1: String\n option2: String\n}\n\nquery test($param: Options) {\n test(option1: $param.option1, option2: $param.option2) {\n id\n }\n}\n```\n\n```text\ntype Query {\n test(options: OptionsInput): SomeType\n}\n\ninput OptionsInput {\n option1: String\n option2: String\n}\n```\n\n```text\ntest\n```\n\n========================================\n\nComments:\n- Thank you very much! I was afraid of this answer :D","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":59,"estimatedTokens":247}}1014{"id":"stack-60915530","source":"stackoverflow","questionId":60915530,"title":"How to add headers in login.vue?","tags":["android","vue.js","graphql","nativescript-vue","vue-apollo"],"text":"Title: How to add headers in login.vue?\nTags: android, vue.js, graphql, nativescript-vue, vue-apollo\nSource: Stack Overflow\n\nQuestion:\n### How to update headers of apolloProvider?\n\nPlease check out nativescript-vue app repo: \n\nhttps://github.com/kaanguru/vue-apollo-login\n\nI can not explain properly so please check out the app. **I don't know how to update appolloClient headers.**\n\nApp repo has it's own comments and directives. It's easy to install and see by your self.\n\n### Current Structure of code:\n\nPost request submits the user's identifier and password credentials for authentication and **gets token** in login page.\n\nApollo needs to place the jwt token into an Authorization header.\n\nMain.js: Start apollo client if there is JWT start with headers\n\nGoto login if there is no JWT\n\nGoto birds list if there is JWT\n\nLogin : get jwt from server and write it to local storage\n\n- Go to birds list *(does not show data because apollo initilised in main js)*\n\nhttps://i.sstatic.net/1Gdm2.jpg\n\n```\nimport ApolloClient from 'apollo-boost'\nimport VueApollo from 'vue-apollo'\n\nVue.use(VueApollo)\n\nconst apolloClient = new ApolloClient({\n uri: 'http://sebapi.com/graphql',\n\n// HEADERS WORK FINE IF TOKEN WAS IN MAIN\n// headers: {\n// authorization: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTg2MzU2NzM2LCJleHAiOjE1ODg5NDg3MzZ9.wpyhPTWuqxrDgezDXJqIOaAIaocpM8Ehd3BhQUWKK5Q`,\n// }\n\n})\nconst apolloProvider = new VueApollo({\n defaultClient: apolloClient,\n})\n```\n\n LOGIN.VUE\n\n```\n.then(\n (response) => {\n const result = response.content.toJSON();\n console.log(\"Result from Server: \", result);\n const token = result.jwt;\n\n // HOW TO ADD HEADERS TO APOLLOCLIENT this.$apollo.provider.defaultClient\n\n // this.$apollo.provider.defaultClient({\n // request: (operation) => {\n // operation.setContext({\n // headers: {\n // authorization: `Bearer ${result.jwt}` ,\n // },\n // });\n // },\n // });\n\n },\n```\n\nThank you for your interest.\n\n**NOTE**: Please comment for more details. sebapi.com backend is a strapi graphql server.\n\n**Related Docs:** \n\nApollo authentication\n\nApollo link composition\n\nVue apolloProvider Usage\n\n========================================\n\nCode:\n```js\nimport ApolloClient from 'apollo-boost'\nimport VueApollo from 'vue-apollo'\n\nVue.use(VueApollo)\n\nconst apolloClient = new ApolloClient({\n uri: 'http://sebapi.com/graphql',\n\n// HEADERS WORK FINE IF TOKEN WAS IN MAIN\n// headers: {\n// authorization: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTg2MzU2NzM2LCJleHAiOjE1ODg5NDg3MzZ9.wpyhPTWuqxrDgezDXJqIOaAIaocpM8Ehd3BhQUWKK5Q`,\n// }\n\n})\nconst apolloProvider = new VueApollo({\n defaultClient: apolloClient,\n})\n```\n\n```js\n.then(\n (response) => {\n const result = response.content.toJSON();\n console.log(\"Result from Server: \", result);\n const token = result.jwt;\n\n // HOW TO ADD HEADERS TO APOLLOCLIENT this.$apollo.provider.defaultClient\n\n // this.$apollo.provider.defaultClient({\n // request: (operation) => {\n // operation.setContext({\n // headers: {\n // authorization: `Bearer ${result.jwt}` ,\n // },\n // });\n // },\n // });\n\n },\n```\n\n```text\nimport { setContext } from 'apollo-link-context'\n\nconst authLink = setContext((_, { headers }) => {\n // get the authentication token from ApplicationSettings if it exists\n const token = ApplicationSettings.getString(\"token\");\n\n // return the headers to the context so HTTP link can read them\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : null\n }\n }\n})\n\n// update apollo client as below\nconst apolloClient = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache() // If you want to use then \n})\n```\n\n```text\n.then(\n (response) => {\n const result = response.content.toJSON();\n console.log(\"Result from Server: \", result);\n const token = result.jwt;\n // Set token using setString\n ApplicationSettings.setString(\"token\", result.jwt);\n},\n```\n\n```text\napollo-link-context\n```\n\n```text\napollo-link-context\n```\n\n```text\nsetContext\n```\n\n========================================\n\nComments:\n- Is there a way to extend Apollo provider\n- apollographql.com/docs/link/links/context I red apollo-link-context documentation. But my token is inside Vuex state. How can I set headers?\n- should I use vue-apollo local state instead of vuex state? Or can I pass Vuex.store state data to Vue Apollo Local State?\n- Have you tried initiating your the client in a diffrent file where you import the store instead?\n- If I will initialize the client from somewhere other than main file, then there will be two copies of **apollo client** one in main file *handling auto-login* and another one in the component which will *handle ordinary log in*.\n- I don't really understand the structure of your project. I personally have a client initalized at one point which I import throughout the project, as for login scenarios, I have a singular login function, and then, if I need to autologin (let's say using the authkey in cookies) I do it using a lifecycle hook of the authpage itself.. but the function used remains the same, so does the client..\n- Why would you have any business logic at all in your main.js file? Just initialize your apolloClient there (or in a diffrent file and export) In your app.vue file (which will initaially show the auth components), use the client in a lifcycle hook to autologin and if it fails, just stay on the login page, if it suceeds, goto the home page.\n- @bhaskar I will give your offer a try and let you know. For now, I don't know if I can initialize apollo in the main file then add headers in login file.\n- You have store the token and use it in main.js. The thing which you need to pass the token is apollo-link-context. I'm not having android so I said it won't work in my Mac.\n- @cemkaan I have added the updated answer to how you can store the token and retrieve it in middleware. Hope this is clear now.\n- Did you check? It will take as all requests are passing through it. don't think about it is in the main.js file so it won't work. For every request you make, it will bypass through apollo-link-context and add headers if the token exists.","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":194,"estimatedTokens":1595}}1015{"id":"stack-52173791","source":"stackoverflow","questionId":52173791,"title":"Correct way to declare fields for Prisma provided by GraphQL Yoga but not required in resolver","tags":["graphql","prisma"],"text":"Title: Correct way to declare fields for Prisma provided by GraphQL Yoga but not required in resolver\nTags: graphql, prisma\nSource: Stack Overflow\n\nQuestion:\nI've been trying to find some documentation on this on the Prisma websites but to be honest it's a bit difficult to find very detailed use cases there, especially when the problem is as difficult to describe as this one is.\n\nI have the situation where my front end sends a mutation request to `createPosting` on my GraphQL-Yoga server with the fields `positionTitle, employmentType, description, requirements, customId, expiresAt` (I have thoroughly tested that this works as expected). I want to add a `createdAt` field before creating the node on the Prisma service.\n\nIn my GraphQL-Yoga server I have a datamodel.graphql that includes the following:\n\n```\ntype Posting {\n id: ID! @unique\n customId: String! @unique\n offeredBy: Employer!\n postingTitle: String!\n positionTitle: String!\n employmentType: EmploymentType!\n status: PostingStatus!\n description: String\n requirements: String\n applications: [Application!]!\n createdAt: DateTime!\n expiresAt: DateTime!\n}\n```\n\nMy schema.graphql has this under Mutations:\n\n```\ncreatePosting(postingTitle: String!,\n positionTitle: String!,\n employmentType: String!,\n description: String!,\n requirements: String!,\n customId: String!,\n expiresAt: DateTime!,\n status: PostingStatus): Posting!\n```\n\nFinally in my createPosting resolver I attempt to mutate the Prisma backend like this:\n\n```\nconst result = await context.prisma.mutation.createPosting({\n data: {\n offeredBy: { connect: { name: context.req.name} },\n postingTitle: args.postingTitle,\n positionTitle: args.positionTitle,\n employmentType: args.employmentType,\n description: args.description,\n requirements: args.requirements,\n customId: args.customId,\n createdAt: new Date().toISOString(),\n expiresAt: expiresAt,\n status: args.status || 'UPCOMING'\n }\n })\n```\n\nWhen I try to run this from my front-end I get the following error on the server: \n\n`Error: Variable '$_v0_data' expected value of type 'PostingCreateInput!' but got: {\"customId\":\"dwa\",\"postingTitle\":\"da\",\"positionTitle\":\"da\",\"employmentType\":\"PART_TIME\",\"status\":\"UPCOMING\",\"description\":\"dada\",\"requirements\":\"dadada\",\"expiresAt\":\"2018-09-27T00:00:00.000Z\",\"createdAt\":\"2018-09-04T20:29:10.745Z\",\"offeredBy\":{\"connect\":{\"name\":\"NSB\"}}}. Reason: 'createdAt' Field 'createdAt' is not defined in the input type 'PostingCreateInput'.`\n\nFrom this error message I would assume that my Prisma service for some reason does not know about createdAt, as I recently added this field, but when I inspect the type Posting and the PostingCreateInput in the GraphQL playground on the Prisma host I find the field createdAt! in both those places.\n\nI tried deleting the generated prisma.graphql and deploying again for a fresh file but that did not work. And when I inspected prisma.graphql, PostingCreateInput did indeed miss the createdAt field, even though the Prisma server seems to have it.\n\nIf anyone can point me in the right direction as to what is wrong, or give me a better idea of how to set up variables that should be stored in the database but created in my Yoga-server as opposed to in front-end I would be very appreciative :)\n\nAlthough this question might seem a bit specific I believe the idea of creating data for the fields during on the server should be possible before creating nodes, but at the moment I'm struggling with wrapping my head around how to do it.\n\nTLDR; Want to create a `createdAt:DateTime` field on my GraphQL-Yoga server on a resolver before sending a create request to my Prisma service.\n\n========================================\n\nCode:\n```text\ntype Posting {\n id: ID! @unique\n customId: String! @unique\n offeredBy: Employer!\n postingTitle: String!\n positionTitle: String!\n employmentType: EmploymentType!\n status: PostingStatus!\n description: String\n requirements: String\n applications: [Application!]!\n createdAt: DateTime!\n expiresAt: DateTime!\n}\n```\n\n```text\ncreatePosting(postingTitle: String!,\n positionTitle: String!,\n employmentType: String!,\n description: String!,\n requirements: String!,\n customId: String!,\n expiresAt: DateTime!,\n status: PostingStatus): Posting!\n```\n\n```text\nconst result = await context.prisma.mutation.createPosting({\n data: {\n offeredBy: { connect: { name: context.req.name} },\n postingTitle: args.postingTitle,\n positionTitle: args.positionTitle,\n employmentType: args.employmentType,\n description: args.description,\n requirements: args.requirements,\n customId: args.customId,\n createdAt: new Date().toISOString(),\n expiresAt: expiresAt,\n status: args.status || 'UPCOMING'\n }\n })\n```\n\n```text\ncreatePosting\n```\n\n```text\npositionTitle, employmentType, description, requirements, customId, expiresAt\n```\n\n```text\ncreatedAt\n```\n\n```text\nError: Variable '$_v0_data' expected value of type 'PostingCreateInput!' but got: {\"customId\":\"dwa\",\"postingTitle\":\"da\",\"positionTitle\":\"da\",\"employmentType\":\"PART_TIME\",\"status\":\"UPCOMING\",\"description\":\"dada\",\"requirements\":\"dadada\",\"expiresAt\":\"2018-09-27T00:00:00.000Z\",\"createdAt\":\"2018-09-04T20:29:10.745Z\",\"offeredBy\":{\"connect\":{\"name\":\"NSB\"}}}. Reason: 'createdAt' Field 'createdAt' is not defined in the input type 'PostingCreateInput'.\n```\n\n```text\ncreatedAt:DateTime\n```\n\n```text\ncreatedAt\n```\n\n```text\ncreatedDate\n```\n\n```text\ncreatedAt\n```\n\n```text\norderBy\n```\n\n```text\nReason: 'createdAt' Field 'createdAt' is not defined in the input type 'PostingCreateInput'.\n```\n\n```text\ncreatedAt\n```\n\n========================================\n\nComments:\n- saved me, dude!\n- @Aquib glad to hear! I would have preferred it if the library threw an error or warning @_@","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":171,"estimatedTokens":1441}}1016{"id":"stack-46615798","source":"stackoverflow","questionId":46615798,"title":"A better way to check for authorization of API requests using Express JS","tags":["node.js","express","jwt","graphql","restful-authentication"],"text":"Title: A better way to check for authorization of API requests using Express JS\nTags: node.js, express, jwt, graphql, restful-authentication\nSource: Stack Overflow\n\nQuestion:\nI have a super redundant server.js file, since nearly every method in it belonging to the REST API starts like that, as I have to check at the API requests whether the client is authorized to ask for the particular thing.\n\n```\nvar jwt = require('jsonwebtoken');\n\n// ...\n\napp.get('/getsomething', function(req, res) {\n \"use strict\";\n var token = req.headers[tokenName];\n if (token) {\n jwt.verify(token, app.get('some_secret'), {\n ignoreExpiration: false\n }, function(err, decoded) {\n if (err || typeof decoded === \"undefined\") {\n res.json({\n status: 401,\n message: \"unauthorized\"\n });\n }\n else { // actual code starts here...\n```\n\nWhat would be a better way?\n\n========================================\n\nCode:\n```text\nvar jwt = require('jsonwebtoken');\n\n// ...\n\napp.get('/getsomething', function(req, res) {\n \"use strict\";\n var token = req.headers[tokenName];\n if (token) {\n jwt.verify(token, app.get('some_secret'), {\n ignoreExpiration: false\n }, function(err, decoded) {\n if (err || typeof decoded === \"undefined\") {\n res.json({\n status: 401,\n message: \"unauthorized\"\n });\n }\n else { // actual code starts here...\n```\n\n```text\n// AUTHENTICATION\napp.use(async (req) => {\n try {\n const token = req.headers.authorization\n const { person } = await jwt.verify(token, SECRET)\n req.person = person\n return req.next()\n } catch (e) {\n return req.next()\n }\n})\n```\n\n```text\njwt.sign({\n person: 'some unique identifier'\n}, 'secret', { expiresIn: '1y' })\n```\n\n```text\nconst decodedJWT = await jwt.verify(token, SECRET)\nconst person = decodedJWT.person\n```\n\n```text\n// PROTECTED\napp.get('/radical', async (req, res, next) => {\n try {\n // If req.person is falsy, the user is not logged in\n if (!req.person) return res.status(403).render('error/403')\n // Otherwise, the user is logged in, allow him/her to continue\n // Replace res.render() with res.json() in your case.\n return res.render('radical/template', {\n person: req.person\n })\n } catch (e) {\n return next(e)\n }\n})\n```\n\n```text\n// SPLAT ROUTE\napp.get('*', (req, res, next) => {\n return res.status(404).render('error/404')\n})\n\n// ERRORS\napp.use((err, req, res, next) => {\n res.status(500).render('error/500')\n throw err\n})\n```\n\n```text\n// GRAPHQL\napp.use('/graphql', bodyParser.json(), graphqlExpress((req) => {\n const context = {\n person: req.person\n }\n return {\n schema,\n context,\n rootValue: null,\n formatError: (error) => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack,\n path: error.path\n }),\n debug: true\n }\n}))\n```\n\n```text\nreq.person\n```\n\n```text\nasync\n```\n\n```text\nawait\n```\n\n```text\njwt.verify()\n```\n\n```text\nperson\n```\n\n```text\nreq.person\n```\n\n```text\nperson\n```\n\n```text\njwt.sign()\n```\n\n```text\nreq.person\n```\n\n```text\nconst { person } = await jwt.verify(token, SECRET)\n```\n\n```text\nerr\n```\n\n```text\nnext()\n```\n\n```text\nnext('Error happened')\n```\n\n```text\ncontext.person\n```\n\n========================================\n\nComments:\n- If anyone has any questions, let me know. I will expand on any reasoning or syntax usage.\n- It seems to be a very nice solution and thank you for your devotion! I need some time to implement this because the concept is still new for me. I will check back a bit later and ask if something's not clear.\n- This is a good resource about const and let: wesbos.com/let-vs-const . It will take you some time to harness async/await because it involves promises, but you should definitely examine them. We also used destructuring which is that `const { person } =` part. Basically, there are lots of articles out there about ES6 aka ES 2015 syntax, and I think you will enjoy what you find if you start utilizing any/all of it.\n- So, I needed some time and I'm still learning and experimenting with it, but I already have a working instance of your code in my app and it's doing its job very well! Thank you!\n- Good to hear. That will treat you well and be very scalable. I recommend reading through the Express docs also now that you have it working. You will learn all kinds of little tricks. Their docs are amazing, very well put together. The sections on middlewares and error handling will show you everything I said. I recommend reading about `next()` everywhere in those docs until you feel comfortable understanding how it works. It is the perfect candidate to show you how middleware works and why we might care about higher-order components. Unrelated, but anything async/await is worth study time.\n- The short and dirty on what you did was create an authentication middleware that runs before every request. You could add more such as one that logs request data on every request or increases a view counter or other usage statistics every request.","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":195,"estimatedTokens":1281}}1017{"id":"stack-57542305","source":"stackoverflow","questionId":57542305,"title":"How to display images without cropping using gatsby-image?","tags":["javascript","reactjs","graphql","gatsby"],"text":"Title: How to display images without cropping using gatsby-image?\nTags: javascript, reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nLive example (images might load slowly): https://suhadolnik-photo.surge.sh/portreti\n\nI'm making a photography site with GatsbyJS and using the following template as a base site that I've been changing: https://github.com/LekoArts/gatsby-starter-portfolio-emilia\n\nBeing really new to graphql I've run into a problem displaying images after a user clicks on the card to show the 'Portraits' subpage. The images are all displayed with a fixed width and height which I don't want. I need to display them with their native width and height, just resized to fit into the grid.\n\nI've tried changing the graphql query in the `project.js` file, where you set the `maxWidth: 1600` to no avail, as well as the `resize(width: 800)` further down the query. Later I found out that changing the `margin` on `gatsby-image-wrapper` through dev tools gave me the expected results, but that required changing the core `gatsby-image` plugin and having to manually change the `margin` for every image separately which isn't the solution.\n\n`project.js`\n\n```\nimport React from 'react'\nimport Img from 'gatsby-image'\nimport PropTypes from 'prop-types'\nimport { graphql } from 'gatsby'\nimport styled from 'styled-components'\n\nimport { Layout, ProjectHeader, ProjectPagination, SEO } from '../components'\nimport config from '../../config/site'\n\nconst BG = styled.div`\n background-color: ${props => props.theme.colors.bg};\n position: relative;\n padding: 2rem 0 0 0;\n`\n\nconst OuterWrapper = styled.div`\n padding: 0 ${props => props.theme.contentPadding};\n margin: -10rem auto 0 auto;\n`\n\nconst InnerWrapper = styled.div`\n position: relative;\n max-width: ${props => `${props.theme.maxWidths.project}px`};\n margin: 0 auto;\n`\n\nconst Grid = styled.div`\n display: grid;\n grid-template-columns: repeat(${props => props.theme.gridColumnsProject}, 1fr);\n grid-gap: 20px;\n\n @media (max-width: 768px) {\n grid-template-columns: 1fr;\n }\n`\n\nconst Project = ({ pageContext: { slug, prev, next }, data: { project: postNode, images } }) => {\n const project = postNode.frontmatter\n\n return (\n \n \n \n \n \n \n \n {images.nodes.map(image => (\n \n ))}\n \n \n \n \n \n \n )\n}\n\nexport default Project\n\nProject.propTypes = {\n pageContext: PropTypes.shape({\n slug: PropTypes.string.isRequired,\n next: PropTypes.object,\n prev: PropTypes.object,\n }),\n data: PropTypes.shape({\n project: PropTypes.object.isRequired,\n images: PropTypes.object.isRequired,\n }).isRequired,\n}\n\nProject.defaultProps = {\n pageContext: PropTypes.shape({\n next: null,\n prev: null,\n }),\n}\n\nexport const pageQuery = graphql`\n query($slug: String!, $absolutePathRegex: String!) {\n images: allFile(\n filter: {\n absolutePath: { regex: $absolutePathRegex }\n extension: { regex: \"/(jpg)|(png)|(tif)|(tiff)|(webp)|(jpeg)/\" }\n }\n sort: { fields: name, order: ASC }\n ) {\n nodes {\n name\n childImageSharp {\n fluid(maxWidth: 1600, quality: 90) {\n ...GatsbyImageSharpFluid_withWebp\n }\n }\n }\n }\n project: mdx(fields: { slug: { eq: $slug } }) {\n body\n excerpt\n parent {\n ... on File {\n mtime\n birthtime\n }\n }\n frontmatter {\n cover {\n childImageSharp {\n resize(width: 800) {\n src\n }\n }\n }\n date(formatString: \"DD.MM.YYYY\")\n title\n areas\n }\n }\n }\n`\n```\n\n`Card.js` the parent component:\n\n```\nimport React from 'react'\nimport styled from 'styled-components'\nimport PropTypes from 'prop-types'\nimport { useSpring, animated, config } from 'react-spring'\nimport { rgba } from 'polished'\nimport Img from 'gatsby-image'\nimport { Link } from 'gatsby'\n\nconst CardItem = styled(Link)`\n min-height: 500px;\n position: relative;\n box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3), 0 15px 12px rgba(0, 0, 0, 0.2);\n display: flex;\n flex-direction: column;\n justify-content: flex-end;\n color: ${props => props.theme.colors.color};\n transition: all 0.3s ease-in-out;\n\n &:hover {\n color: white;\n transform: translateY(-6px);\n }\n\n @media (max-width: ${props => props.theme.breakpoints.s}) {\n min-height: 300px;\n }\n`\n\nconst Cover = styled.div`\n width: 100%;\n height: 100%;\n position: absolute;\n`\n\nconst Content = styled.div`\n padding: 1rem;\n position: relative;\n transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);\n opacity: 0;\n background: ${props => rgba(props.theme.colors.link, 0.65)};\n height: 0;\n\n ${CardItem}:hover & {\n opacity: 1;\n height: 120px;\n }\n`\n\nconst Bottom = styled.div`\n margin-top: 0.5rem;\n display: flex;\n align-items: center;\n font-size: 0.85rem;\n div:first-child {\n margin-right: 1rem;\n }\n`\n\nconst Name = styled.h2`\n margin-bottom: 0;\n margin-top: 0;\n`\n\nconst Card = ({ path, cover, date, areas, title, delay }) => {\n const springProps = useSpring({\n config: config.slow,\n delay: 200 * delay,\n from: { opacity: 0, transform: 'translate3d(0, 30px, 0)' },\n to: { opacity: 1, transform: 'translate3d(0, 0, 0)' },\n })\n\n return (\n \n \n \n \n \n \n {title}\n \n {date}\n \n {areas.map((area, index) => (\n \n {index > 0 && ', '}\n {area}\n \n ))}\n \n \n \n \n \n )\n}\n\nexport default Card\n\nCard.propTypes = {\n path: PropTypes.string.isRequired,\n cover: PropTypes.object.isRequired,\n date: PropTypes.string.isRequired,\n areas: PropTypes.array.isRequired,\n title: PropTypes.string.isRequired,\n delay: PropTypes.number.isRequired,\n}\n```\n\nI expect the images to show in their native width and height, but resized to fit the grid. Providing visual representation below on how it looks now and what the expected result is.\nCurrent result and expected result\n\nCheers!\n\n========================================\n\nCode:\n```js\nimport React from 'react'\nimport Img from 'gatsby-image'\nimport PropTypes from 'prop-types'\nimport { graphql } from 'gatsby'\nimport styled from 'styled-components'\n\nimport { Layout, ProjectHeader, ProjectPagination, SEO } from '../components'\nimport config from '../../config/site'\n\nconst BG = styled.div`\n background-color: ${props => props.theme.colors.bg};\n position: relative;\n padding: 2rem 0 0 0;\n`\n\nconst OuterWrapper = styled.div`\n padding: 0 ${props => props.theme.contentPadding};\n margin: -10rem auto 0 auto;\n`\n\nconst InnerWrapper = styled.div`\n position: relative;\n max-width: ${props => `${props.theme.maxWidths.project}px`};\n margin: 0 auto;\n`\n\nconst Grid = styled.div`\n display: grid;\n grid-template-columns: repeat(${props => props.theme.gridColumnsProject}, 1fr);\n grid-gap: 20px;\n\n @media (max-width: 768px) {\n grid-template-columns: 1fr;\n }\n`\n\nconst Project = ({ pageContext: { slug, prev, next }, data: { project: postNode, images } }) => {\n const project = postNode.frontmatter\n\n return (\n <Layout customSEO>\n <SEO postPath={slug} postNode={postNode} postSEO />\n <ProjectHeader\n name={config.name}\n date={project.date}\n title={project.title}\n areas={project.areas}\n text={postNode.body}\n />\n <BG>\n <OuterWrapper>\n <InnerWrapper>\n <Grid>\n {images.nodes.map(image => (\n <Img\n alt={image.name}\n key={image.childImageSharp.fluid.src}\n fluid={image.childImageSharp.fluid}\n style={{ margin: '2rem 0' }}\n />\n ))}\n </Grid>\n </InnerWrapper>\n <ProjectPagination next={next} prev={prev} />\n </OuterWrapper>\n </BG>\n </Layout>\n )\n}\n\nexport default Project\n\nProject.propTypes = {\n pageContext: PropTypes.shape({\n slug: PropTypes.string.isRequired,\n next: PropTypes.object,\n prev: PropTypes.object,\n }),\n data: PropTypes.shape({\n project: PropTypes.object.isRequired,\n images: PropTypes.object.isRequired,\n }).isRequired,\n}\n\nProject.defaultProps = {\n pageContext: PropTypes.shape({\n next: null,\n prev: null,\n }),\n}\n\nexport const pageQuery = graphql`\n query($slug: String!, $absolutePathRegex: String!) {\n images: allFile(\n filter: {\n absolutePath: { regex: $absolutePathRegex }\n extension: { regex: \"/(jpg)|(png)|(tif)|(tiff)|(webp)|(jpeg)/\" }\n }\n sort: { fields: name, order: ASC }\n ) {\n nodes {\n name\n childImageSharp {\n fluid(maxWidth: 1600, quality: 90) {\n ...GatsbyImageSharpFluid_withWebp\n }\n }\n }\n }\n project: mdx(fields: { slug: { eq: $slug } }) {\n body\n excerpt\n parent {\n ... on File {\n mtime\n birthtime\n }\n }\n frontmatter {\n cover {\n childImageSharp {\n resize(width: 800) {\n src\n }\n }\n }\n date(formatString: \"DD.MM.YYYY\")\n title\n areas\n }\n }\n }\n`\n```\n\n```js\nimport React from 'react'\nimport styled from 'styled-components'\nimport PropTypes from 'prop-types'\nimport { useSpring, animated, config } from 'react-spring'\nimport { rgba } from 'polished'\nimport Img from 'gatsby-image'\nimport { Link } from 'gatsby'\n\nconst CardItem = styled(Link)`\n min-height: 500px;\n position: relative;\n box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3), 0 15px 12px rgba(0, 0, 0, 0.2);\n display: flex;\n flex-direction: column;\n justify-content: flex-end;\n color: ${props => props.theme.colors.color};\n transition: all 0.3s ease-in-out;\n\n &:hover {\n color: white;\n transform: translateY(-6px);\n }\n\n @media (max-width: ${props => props.theme.breakpoints.s}) {\n min-height: 300px;\n }\n`\n\nconst Cover = styled.div`\n width: 100%;\n height: 100%;\n position: absolute;\n`\n\nconst Content = styled.div`\n padding: 1rem;\n position: relative;\n transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);\n opacity: 0;\n background: ${props => rgba(props.theme.colors.link, 0.65)};\n height: 0;\n\n ${CardItem}:hover & {\n opacity: 1;\n height: 120px;\n }\n`\n\nconst Bottom = styled.div`\n margin-top: 0.5rem;\n display: flex;\n align-items: center;\n font-size: 0.85rem;\n div:first-child {\n margin-right: 1rem;\n }\n`\n\nconst Name = styled.h2`\n margin-bottom: 0;\n margin-top: 0;\n`\n\nconst Card = ({ path, cover, date, areas, title, delay }) => {\n const springProps = useSpring({\n config: config.slow,\n delay: 200 * delay,\n from: { opacity: 0, transform: 'translate3d(0, 30px, 0)' },\n to: { opacity: 1, transform: 'translate3d(0, 0, 0)' },\n })\n\n return (\n <animated.div style={springProps}>\n <CardItem to={path}>\n <Cover>\n <Img fluid={cover} />\n </Cover>\n <Content>\n <Name>{title}</Name>\n <Bottom>\n <div>{date}</div>\n <div>\n {areas.map((area, index) => (\n <React.Fragment key={area}>\n {index > 0 && ', '}\n {area}\n </React.Fragment>\n ))}\n </div>\n </Bottom>\n </Content>\n </CardItem>\n </animated.div>\n )\n}\n\nexport default Card\n\nCard.propTypes = {\n path: PropTypes.string.isRequired,\n cover: PropTypes.object.isRequired,\n date: PropTypes.string.isRequired,\n areas: PropTypes.array.isRequired,\n title: PropTypes.string.isRequired,\n delay: PropTypes.number.isRequired,\n}\n```\n\n```text\nproject.js\n```\n\n```text\nmaxWidth: 1600\n```\n\n```text\nresize(width: 800)\n```\n\n```text\nmargin\n```\n\n```text\ngatsby-image-wrapper\n```\n\n```text\ngatsby-image\n```\n\n```text\nmargin\n```\n\n```text\nproject.js\n```\n\n```text\nCard.js\n```\n\n```text\nconst Cover = styled.div`\n width: 100%;\n`\n```\n\n```text\n| style | object | Spread into the default styles of the wrapper element | \n| imgStyle | object | Spread into the default styles of the actual img element |\n| placeholderStyle | object | Spread into the default styles of the placeholder img element |\n```\n\n```text\n<Img\n alt={image.name}\n key={image.childImageSharp.fluid.src}\n fluid={image.childImageSharp.fluid}\n imgStyle={{ objectFit: 'contain' }}\n/>\n```\n\n```text\nheight:100%\n```\n\n```text\nposition:absolute\n```\n\n```text\nstyle\n```\n\n```text\nimgStyle\n```\n\n========================================\n\nComments:\n- Do you have a working example?\n- Best I can provide is the demo page for the template I've used: emilia.lekoarts.de\n- Haven't you made some changes though?\n- I've added a live demo: suhadolnik-photo.surge.sh/portreti\n- This only fixes the issue on the home page, not on the individual projects pages.\n- Adding the `imgStyle={{ objectFit: 'contain' }}` fixed the issue. Also I wasn't aware the image could take styles so thank you for that aswell!\n- Cool. Yeah, It's buried right at the bottom of the docs, so it's usually not something that many ever find out about `gatsby-image`.","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":587,"estimatedTokens":3139}}1018{"id":"stack-54232556","source":"stackoverflow","questionId":54232556,"title":"Graphql contentful query with error 'cannot query field'","tags":["graphql","gatsby","contentful"],"text":"Title: Graphql contentful query with error 'cannot query field'\nTags: graphql, gatsby, contentful\nSource: Stack Overflow\n\nQuestion:\nI'm using gatsbyJS with contentful. When I start to query any contentful content I donΒ΄t get the support from graphql. When I start to type \"allContentful*\" no contentful stuff appears:\n\nhttps://i.sstatic.net/6318s.png\n\nWhen i do a query, the **query works**. But the underline is red and i have no chance to see which types are available:\n\nhttps://i.sstatic.net/wYlVt.png\n\n========================================\n\nTop Answer:\nhttps://i.sstatic.net/ElaLN.png\n\nJust to be 100% clear, for anyone else who gets this issue...\n\nThis is the cache which I needed to clear / delete.\n\nOnce removed, the new GraphiQL interface / types loaded\n\n========================================\n\nComments:\n- Oh my dear. Thanks a lot. In webdevelopment it is always the cache^^\n- Wow. Cache indeed. Opening in incognito window fixed it for me.","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":29,"estimatedTokens":239}}1019{"id":"stack-48763497","source":"stackoverflow","questionId":48763497,"title":"GraphQL Schema for Nested JSON?","tags":["json","schema","graphql"],"text":"Title: GraphQL Schema for Nested JSON?\nTags: json, schema, graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to use GraphQL to deal with some JSON data. I can retrieve fields from the top level no problem. I can associate separate JSON objects also no problem. My problems are occurring trying to get at data one level down. So, I have defined a type in my schema for staff. The json looks like this:\n\n```\n\"staff\": [\n {\n \"id\": 123,\n \"name\": \"fred\",\n \"role\" : \"designer\",\n \"address\": {\n \"street\": \"main street\",\n \"town\": \"Springfield\"\n }\n },\n ...\n]\n```\n\nand the corresponding type in the schema looks like this so far:\n\n```\nconst StaffType = new GraphQLObjectType({\n name: 'Staff',\n fields: {\n id: {type: GraphQLInt},\n name: {type: GraphQLString},\n role: {type: GraphQLString}\n }\n})\n```\n\nThis works fine as far as retrieving the id, name and role goes. My question is how can I extend `StaffType` to also retrieve `street` and `town` from the `address` field in the original JSON?\n\nThanks\n\n========================================\n\nCode:\n```text\n\"staff\": [\n {\n \"id\": 123,\n \"name\": \"fred\",\n \"role\" : \"designer\",\n \"address\": {\n \"street\": \"main street\",\n \"town\": \"Springfield\"\n }\n },\n ...\n]\n```\n\n```text\nconst StaffType = new GraphQLObjectType({\n name: 'Staff',\n fields: {\n id: {type: GraphQLInt},\n name: {type: GraphQLString},\n role: {type: GraphQLString}\n }\n})\n```\n\n```text\nStaffType\n```\n\n```text\nstreet\n```\n\n```text\ntown\n```\n\n```text\naddress\n```\n\n```text\nconst StaffType = new GraphQLObjectType({\n name: 'Staff',\n fields: {\n id: {type: GraphQLInt},\n name: {type: GraphQLString},\n role: {type: GraphQLString},\n address: {type: AddressType}\n }\n})\n\nconst AddressType = new GraphQLObjectType({\n name: 'Address',\n fields: {\n street: {type: GraphQLString},\n town: {type: GraphQLString}\n }\n})\n```\n\n========================================\n\nComments:\n- If you are still active. I am facing this issue now, any additional assistance you could provide would be helpful.\n- Hi @Shawn, what worked for me was defining a separate type for Address and then referring to that in the StaffType. I've edited my answer above to show an example.\n- Thanks @Drum. I asked a new question just in-case and also received helpful advice - stackoverflow.com/questions/50440547/…. Thank you for your response.\n- Hi, how do you handle the resolving afterward? Doesn't this schema means that you need 2 resolvers, one for Staff and one for Address now ?","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":111,"estimatedTokens":631}}1020{"id":"stack-46062915","source":"stackoverflow","questionId":46062915,"title":"How do you unsubscribe to apollo observable in angular?","tags":["angular","rxjs","graphql","apollo"],"text":"Title: How do you unsubscribe to apollo observable in angular?\nTags: angular, rxjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm building an angular (4.x) application using apollo-angular, and I'm wondering how to unsubscribe from apollo observables (if you need to at all). \n\nI'm trying to the guidance in this response by creating a query: \n\n```\nthis.query = this.apollo.watchQuery({\n fetchPolicy: 'network-only',\n query: myQuery\n});\n```\n\nAssigning a new subject:\n\n```\nprivate ngUnsubscribe: Subject = new Subject();\n```\n\nSubscribing to the query:\n\n```\nthis.query.takeUntil(this.ngUnsubscribe).subscribe(({ data }) => {...}\n```\n\nand then destroying all active observables on a `onDestroy` event cycle with something like:\n\n```\nngOnDestroy() {\n this.ngUnsubscribe.next();\n this.ngUnsubscribe.complete();\n }\n```\n\nAfter adding the `.takeUntil(this.ngUnsubscribe)`, I run into lint errors like: \n\n Argument of type 'Subject' is not assignable to parameter of type 'Observable'.\n\nOr when I try to manually unsubscribe to the ApolloQueryObservable, I get:\n\n Property 'unsubscribe' does not exist on type 'ApolloQueryObservable'. Did you mean 'subscribe'?\n\nIs unsubscribing necessary for apollo observables?\n\n========================================\n\nTop Answer:\nAlthough the question is answering this is a more specific scenario that explains more to this question, so adding this below blog link here.\nhttps://www.digitalocean.com/community/tutorials/angular-takeuntil-rxjs-unsubscribe\n\n========================================\n\nCode:\n```text\nthis.query = this.apollo.watchQuery<LatestReportQueryResponse>({\n fetchPolicy: 'network-only',\n query: myQuery\n});\n```\n\n```text\nprivate ngUnsubscribe: Subject<void> = new Subject<void>();\n```\n\n```text\nthis.query.takeUntil(this.ngUnsubscribe).subscribe(({ data }) => {...}\n```\n\n```text\nngOnDestroy() {\n this.ngUnsubscribe.next();\n this.ngUnsubscribe.complete();\n }\n```\n\n```text\nonDestroy\n```\n\n```text\n.takeUntil(this.ngUnsubscribe)\n```\n\n```text\nthis.query.takeUntil(this.ngUnsubscribe).subscribe(...)\n```\n\n```text\nthis.unsubscribe = this.query.takeUntil(this.ngUnsubscribe).subscribe(...)\n```\n\n```text\nonDestroy\n```\n\n```text\nthis.unsubscribe()\n```\n\n```text\nimport { from, Subscription } from 'rxjs';\n\nexport class CalendarWeekViewStdComponent implements OnInit, OnDestroy, AfterViewInit {\nprivate subscriptionName: Subscription;\n\nngOnInit() {\nthis.subscriptionName = this.settingService.diarySettings.subscribe(settings => {\n\n });\n}\n ngOnDestroy(): void {\nif (this.subscriptionName) {\n this.subscriptionName.unsubscribe();\n }\n}\n}\n```\n\n```text\nimport { from, Subscription } from 'rxjs';\n\nprivate subscriptions: Subscription[] = [];\nngOnInit() {\nthis.subscriptions.push( this.settingService.diarySettings.subscribe(settings => {\n\n }));\n}\nngOnDestroy(): void {\n this.subscriptions.forEach(sub => sub.unsubscribe());\n }\n```\n\n```text\nngUnsubscribe\n```\n\n```text\nSubscription\n```\n\n========================================\n\nComments:\n- Thanks for the response! I currently have the setup you described-- however, when I however over the \"this.query\" (before the takeunti()) typescript complains with: \"The 'this' context of type 'ApolloQueryObservable' is not assignable to method's 'this' of type Observable>'. Is there any way to confirm that an observable is completed/destroyed?\n- Sorry, i'm not sure if it can be confirmed. Maybe it is written in the API\n- This is wrong. You don't need to unsubscribe if you have a takeUntil. Once the takeUntil meets its callback, it auto unsubs. You could just set `this.ngUnsubscribe = false;` in your answer, `this.unsubscribe()` would fail as it's not a function.\n- Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.\n- This is the correct way to do it but one small change. `private subscriptions: Subscription = new Subscription();` instead of setting it to an array, and `this.subscriptions.add` instead of `.push`. then you don't have to forEach, you just say `this.subscriptions.unsubscribe();` and it will unsub to all.","metadata":{"transformedAt":"2026-08-18T18:32:36.221Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":151,"estimatedTokens":1035}}1021{"id":"stack-48375644","source":"stackoverflow","questionId":48375644,"title":"GraphQL] The type of [...] must be Output Type but got: undefined","tags":["node.js","graphql","object-type"],"text":"Title: GraphQL] The type of [...] must be Output Type but got: undefined\nTags: node.js, graphql, object-type\nSource: Stack Overflow\n\nQuestion:\nI'm having troubles with referencing to other GraphQLObjectTypes inside a GraphQLObjectType.\nI keep getting the following error:\n\n \"message\": \"The type of getBooks.stores must be Output Type but got:\n undefined.\"\n\nI thought that using a resolve inside books.stores would help fixing the issue, but it doesn't. Can someone help me out?\n\n**Code**\n\n```\nvar express = require('express');\nvar graphqlHTTP = require('express-graphql');\nvar graphql = require('graphql');\n\nvar { buildSchema, GraphQLSchema, GraphQLObjectType,GraphQLString,GraphQLList } = require('graphql');\n\nvar books = new GraphQLObjectType({\n name:'getBooks',\n fields: {\n isbn: { type: GraphQLString},\n stores: {\n type: stores,\n resolve: function(){\n var store = [];\n store.storeName = \"this will contain the name of a shop\";\n return store;\n }\n }\n }\n});\n\nvar stores = new GraphQLObjectType({\n name:'storeList',\n fields: {\n storeName: { type: GraphQLString}\n }\n});\n\nvar queryType = new GraphQLObjectType({\n name: 'Query',\n fields: {\n books: {\n type: books,\n // `args` describes the arguments that the `user` query accepts\n args: {\n id: { type: new GraphQLList(GraphQLString) }// graphql.GraphQLStringj\n },\n resolve: function (_, {id}) {\n var data = [];\n data.isbn = '32131231';\n return data;\n }\n }\n }\n});\n\nvar schema = new GraphQLSchema({query: queryType});\n\nvar app = express();\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n graphiql: true,\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at localhost:4000/graphql');\n```\n\n========================================\n\nTop Answer:\nOr you can just make the field a function type so that it can wrap type relations\nFor example\n\n```\nfields: () => ({\n\n //Enter Your Code\n\n})\n```\n\n========================================\n\nCode:\n```text\nvar express = require('express');\nvar graphqlHTTP = require('express-graphql');\nvar graphql = require('graphql');\n\nvar { buildSchema, GraphQLSchema, GraphQLObjectType,GraphQLString,GraphQLList } = require('graphql');\n\nvar books = new GraphQLObjectType({\n name:'getBooks',\n fields: {\n isbn: { type: GraphQLString},\n stores: {\n type: stores,\n resolve: function(){\n var store = [];\n store.storeName = \"this will contain the name of a shop\";\n return store;\n }\n }\n }\n});\n\nvar stores = new GraphQLObjectType({\n name:'storeList',\n fields: {\n storeName: { type: GraphQLString}\n }\n});\n\n\nvar queryType = new GraphQLObjectType({\n name: 'Query',\n fields: {\n books: {\n type: books,\n // `args` describes the arguments that the `user` query accepts\n args: {\n id: { type: new GraphQLList(GraphQLString) }// graphql.GraphQLStringj\n },\n resolve: function (_, {id}) {\n var data = [];\n data.isbn = '32131231';\n return data;\n }\n }\n }\n});\n\nvar schema = new GraphQLSchema({query: queryType});\n\nvar app = express();\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n graphiql: true,\n}));\napp.listen(4000);\nconsole.log('Running a GraphQL API server at localhost:4000/graphql');\n```\n\n```text\nfields: () => ({\n\n //Enter Your Code\n\n})\n```\n\n========================================\n\nComments:\n- Adding on, the arrow function allows it so you don't have to worry about the order of the store's type. Also, this way it will allow you to modulize your schemas, so in case your app gets large, it'll be cleaner to look for specific schemas in specific folder/files.","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":161,"estimatedTokens":891}}1022{"id":"stack-57740389","source":"stackoverflow","questionId":57740389,"title":"PHP Laravel GraphQL Query Declaration Incompatibility issue","tags":["php","laravel","graphql"],"text":"Title: PHP Laravel GraphQL Query Declaration Incompatibility issue\nTags: php, laravel, graphql\nSource: Stack Overflow\n\nQuestion:\nI followed the following article to setup laravel with graphql on my local machine:\n\nhttps://auth0.com/blog/developing-and-securing-graphql-apis-with-laravel\n\nI following the complete article step by step without any issue. But when I run my app using \n\n```\nphp artisan serve\n```\n\nand hit the endpoint `localhost:8000/graphql`, I get the following error.\n\n [Sat Aug 31 23:09:20 2019] PHP Fatal error: Declaration of App\\GraphQL\\Queries\\WineQuery::type() must be compatible with \n Rebing\\GraphQL\\Support\\Field::type(): GraphQL\\Type\\Definition\\Type \n in /Users/sushilsingh/Projects/winestore/app/GraphQL/Queries/WineQuery.php on line 9\n\nHere is my WineQuery.php\n\n```\n 'wine',\n ];\n\n public function type()\n {\n return GraphQL::type('Wine');\n }\n\n public function args()\n {\n return [\n 'id' => [\n 'name' => 'id',\n 'type' => Type::int(),\n 'rules' => ['required']\n ],\n ];\n }\n\n public function resolve($root, $args)\n {\n return Wine::findOrFail($args['id']);\n }\n}\n```\n\nHere is graphql.php\n\n```\n 'graphql',\n\n // The routes to make GraphQL request. Either a string that will apply\n // to both query and mutation or an array containing the key 'query' and/or\n // 'mutation' with the according Route\n //\n // Example:\n //\n // Same route for both query and mutation\n //\n // 'routes' => 'path/to/query/{graphql_schema?}',\n //\n // or define each route\n //\n // 'routes' => [\n // 'query' => 'query/{graphql_schema?}',\n // 'mutation' => 'mutation/{graphql_schema?}',\n // ]\n //\n 'routes' => '{graphql_schema?}',\n\n // The controller to use in GraphQL request. Either a string that will apply\n // to both query and mutation or an array containing the key 'query' and/or\n // 'mutation' with the according Controller and method\n //\n // Example:\n //\n // 'controllers' => [\n // 'query' => '\\Rebing\\GraphQL\\GraphQLController@query',\n // 'mutation' => '\\Rebing\\GraphQL\\GraphQLController@mutation'\n // ]\n //\n 'controllers' => \\Rebing\\GraphQL\\GraphQLController::class.'@query',\n\n // Any middleware for the graphql route group\n 'middleware' => [],\n\n // Additional route group attributes\n //\n // Example:\n //\n // 'route_group_attributes' => ['guard' => 'api']\n //\n 'route_group_attributes' => [],\n\n // The name of the default schema used when no argument is provided\n // to GraphQL::schema() or when the route is used without the graphql_schema\n // parameter.\n 'default_schema' => 'default',\n\n // The schemas for query and/or mutation. It expects an array of schemas to provide\n // both the 'query' fields and the 'mutation' fields.\n //\n // You can also provide a middleware that will only apply to the given schema\n //\n // Example:\n //\n // 'schema' => 'default',\n //\n // 'schemas' => [\n // 'default' => [\n // 'query' => [\n // 'users' => 'App\\GraphQL\\Query\\UsersQuery'\n // ],\n // 'mutation' => [\n //\n // ]\n // ],\n // 'user' => [\n // 'query' => [\n // 'profile' => 'App\\GraphQL\\Query\\ProfileQuery'\n // ],\n // 'mutation' => [\n //\n // ],\n // 'middleware' => ['auth'],\n // ],\n // 'user/me' => [\n // 'query' => [\n // 'profile' => 'App\\GraphQL\\Query\\MyProfileQuery'\n // ],\n // 'mutation' => [\n //\n // ],\n // 'middleware' => ['auth'],\n // ],\n // ]\n //\n // 'schemas' => [\n // 'default' => [\n // 'query' => [\n // // 'example_query' => ExampleQuery::class,\n // ],\n // 'mutation' => [\n // // 'example_mutation' => ExampleMutation::class,\n // ],\n // 'middleware' => [],\n // 'method' => ['get', 'post'],\n // ],\n // ],\n 'schemas' => [\n 'default' => [\n 'query' => [\n 'wine' => App\\GraphQL\\Queries\\WineQuery::class,\n 'wines' => App\\GraphQL\\Queries\\WinesQuery::class,\n ]\n ],\n ],\n\n // The types available in the application. You can then access it from the\n // facade like this: GraphQL::type('user')\n //\n // Example:\n //\n // 'types' => [\n // 'user' => 'App\\GraphQL\\Type\\UserType'\n // ]\n //\n 'types' => [\n // 'example' => ExampleType::class,\n // 'relation_example' => ExampleRelationType::class,\n // \\Rebing\\GraphQL\\Support\\UploadType::class,\n 'Wine' => App\\GraphQL\\Types\\WineType::class,\n ],\n\n // The types will be loaded on demand. Default is to load all types on each request\n // Can increase performance on schemes with many types\n // Presupposes the config type key to match the type class name property\n 'lazyload_types' => false,\n\n // This callable will be passed the Error object for each errors GraphQL catch.\n // The method should return an array representing the error.\n // Typically:\n // [\n // 'message' => '',\n // 'locations' => []\n // ]\n 'error_formatter' => ['\\Rebing\\GraphQL\\GraphQL', 'formatError'],\n\n /*\n * Custom Error Handling\n *\n * Expected handler signature is: function (array $errors, callable $formatter): array\n *\n * The default handler will pass exceptions to laravel Error Handling mechanism\n */\n 'errors_handler' => ['\\Rebing\\GraphQL\\GraphQL', 'handleErrors'],\n\n // You can set the key, which will be used to retrieve the dynamic variables\n 'params_key' => 'variables',\n\n /*\n * Options to limit the query complexity and depth. See the doc\n * @ https://github.com/webonyx/graphql-php#security\n * for details. Disabled by default.\n */\n 'security' => [\n 'query_max_complexity' => null,\n 'query_max_depth' => null,\n 'disable_introspection' => false,\n ],\n\n /*\n * You can define your own pagination type.\n * Reference \\Rebing\\GraphQL\\Support\\PaginationType::class\n */\n 'pagination_type' => \\Rebing\\GraphQL\\Support\\PaginationType::class,\n\n /*\n * Config for GraphiQL (see (https://github.com/graphql/graphiql).\n */\n 'graphiql' => [\n 'prefix' => '/graphiql',\n 'controller' => \\Rebing\\GraphQL\\GraphQLController::class.'@graphiql',\n 'middleware' => [],\n 'view' => 'graphql::graphiql',\n 'display' => env('ENABLE_GRAPHIQL', true),\n ],\n\n /*\n * Overrides the default field resolver\n * See http://webonyx.github.io/graphql-php/data-fetching/#default-field-resolver\n *\n * Example:\n *\n * ```php\n * 'defaultFieldResolver' => function ($root, $args, $context, $info) {\n * },\n * ```\n * or\n * ```php\n * 'defaultFieldResolver' => [SomeKlass::class, 'someMethod'],\n * ```\n */\n 'defaultFieldResolver' => null,\n\n /*\n * Any headers that will be added to the response returned by the default controller\n */\n 'headers' => [],\n\n /*\n * Any JSON encoding options when returning a response from the default controller\n * See http://php.net/manual/function.json-encode.php for the full list of options\n */\n 'json_encoding_options' => 0,\n];\n```\n\n========================================\n\nCode:\n```sh\nphp artisan serve\n```\n\n```php\n<?php\n\nnamespace App\\GraphQL\\Queries;\n\nuse App\\Wine;\nuse GraphQL\\Type\\Definition\\Type;\nuse Rebing\\GraphQL\\Support\\Query;\n\nclass WineQuery extends Query\n{\n protected $attributes = [\n 'name' => 'wine',\n ];\n\n public function type()\n {\n return GraphQL::type('Wine');\n }\n\n public function args()\n {\n return [\n 'id' => [\n 'name' => 'id',\n 'type' => Type::int(),\n 'rules' => ['required']\n ],\n ];\n }\n\n public function resolve($root, $args)\n {\n return Wine::findOrFail($args['id']);\n }\n}\n```\n\n```php\n<?php\n\ndeclare(strict_types=1);\n\nuse example\\Type\\ExampleType;\nuse example\\Query\\ExampleQuery;\nuse example\\Mutation\\ExampleMutation;\nuse example\\Type\\ExampleRelationType;\n\nreturn [\n\n // The prefix for routes\n 'prefix' => 'graphql',\n\n // The routes to make GraphQL request. Either a string that will apply\n // to both query and mutation or an array containing the key 'query' and/or\n // 'mutation' with the according Route\n //\n // Example:\n //\n // Same route for both query and mutation\n //\n // 'routes' => 'path/to/query/{graphql_schema?}',\n //\n // or define each route\n //\n // 'routes' => [\n // 'query' => 'query/{graphql_schema?}',\n // 'mutation' => 'mutation/{graphql_schema?}',\n // ]\n //\n 'routes' => '{graphql_schema?}',\n\n // The controller to use in GraphQL request. Either a string that will apply\n // to both query and mutation or an array containing the key 'query' and/or\n // 'mutation' with the according Controller and method\n //\n // Example:\n //\n // 'controllers' => [\n // 'query' => '\\Rebing\\GraphQL\\GraphQLController@query',\n // 'mutation' => '\\Rebing\\GraphQL\\GraphQLController@mutation'\n // ]\n //\n 'controllers' => \\Rebing\\GraphQL\\GraphQLController::class.'@query',\n\n // Any middleware for the graphql route group\n 'middleware' => [],\n\n // Additional route group attributes\n //\n // Example:\n //\n // 'route_group_attributes' => ['guard' => 'api']\n //\n 'route_group_attributes' => [],\n\n // The name of the default schema used when no argument is provided\n // to GraphQL::schema() or when the route is used without the graphql_schema\n // parameter.\n 'default_schema' => 'default',\n\n // The schemas for query and/or mutation. It expects an array of schemas to provide\n // both the 'query' fields and the 'mutation' fields.\n //\n // You can also provide a middleware that will only apply to the given schema\n //\n // Example:\n //\n // 'schema' => 'default',\n //\n // 'schemas' => [\n // 'default' => [\n // 'query' => [\n // 'users' => 'App\\GraphQL\\Query\\UsersQuery'\n // ],\n // 'mutation' => [\n //\n // ]\n // ],\n // 'user' => [\n // 'query' => [\n // 'profile' => 'App\\GraphQL\\Query\\ProfileQuery'\n // ],\n // 'mutation' => [\n //\n // ],\n // 'middleware' => ['auth'],\n // ],\n // 'user/me' => [\n // 'query' => [\n // 'profile' => 'App\\GraphQL\\Query\\MyProfileQuery'\n // ],\n // 'mutation' => [\n //\n // ],\n // 'middleware' => ['auth'],\n // ],\n // ]\n //\n // 'schemas' => [\n // 'default' => [\n // 'query' => [\n // // 'example_query' => ExampleQuery::class,\n // ],\n // 'mutation' => [\n // // 'example_mutation' => ExampleMutation::class,\n // ],\n // 'middleware' => [],\n // 'method' => ['get', 'post'],\n // ],\n // ],\n 'schemas' => [\n 'default' => [\n 'query' => [\n 'wine' => App\\GraphQL\\Queries\\WineQuery::class,\n 'wines' => App\\GraphQL\\Queries\\WinesQuery::class,\n ]\n ],\n ],\n\n // The types available in the application. You can then access it from the\n // facade like this: GraphQL::type('user')\n //\n // Example:\n //\n // 'types' => [\n // 'user' => 'App\\GraphQL\\Type\\UserType'\n // ]\n //\n 'types' => [\n // 'example' => ExampleType::class,\n // 'relation_example' => ExampleRelationType::class,\n // \\Rebing\\GraphQL\\Support\\UploadType::class,\n 'Wine' => App\\GraphQL\\Types\\WineType::class,\n ],\n\n // The types will be loaded on demand. Default is to load all types on each request\n // Can increase performance on schemes with many types\n // Presupposes the config type key to match the type class name property\n 'lazyload_types' => false,\n\n // This callable will be passed the Error object for each errors GraphQL catch.\n // The method should return an array representing the error.\n // Typically:\n // [\n // 'message' => '',\n // 'locations' => []\n // ]\n 'error_formatter' => ['\\Rebing\\GraphQL\\GraphQL', 'formatError'],\n\n /*\n * Custom Error Handling\n *\n * Expected handler signature is: function (array $errors, callable $formatter): array\n *\n * The default handler will pass exceptions to laravel Error Handling mechanism\n */\n 'errors_handler' => ['\\Rebing\\GraphQL\\GraphQL', 'handleErrors'],\n\n // You can set the key, which will be used to retrieve the dynamic variables\n 'params_key' => 'variables',\n\n /*\n * Options to limit the query complexity and depth. See the doc\n * @ https://github.com/webonyx/graphql-php#security\n * for details. Disabled by default.\n */\n 'security' => [\n 'query_max_complexity' => null,\n 'query_max_depth' => null,\n 'disable_introspection' => false,\n ],\n\n /*\n * You can define your own pagination type.\n * Reference \\Rebing\\GraphQL\\Support\\PaginationType::class\n */\n 'pagination_type' => \\Rebing\\GraphQL\\Support\\PaginationType::class,\n\n /*\n * Config for GraphiQL (see (https://github.com/graphql/graphiql).\n */\n 'graphiql' => [\n 'prefix' => '/graphiql',\n 'controller' => \\Rebing\\GraphQL\\GraphQLController::class.'@graphiql',\n 'middleware' => [],\n 'view' => 'graphql::graphiql',\n 'display' => env('ENABLE_GRAPHIQL', true),\n ],\n\n /*\n * Overrides the default field resolver\n * See http://webonyx.github.io/graphql-php/data-fetching/#default-field-resolver\n *\n * Example:\n *\n * ```php\n * 'defaultFieldResolver' => function ($root, $args, $context, $info) {\n * },\n * ```\n * or\n * ```php\n * 'defaultFieldResolver' => [SomeKlass::class, 'someMethod'],\n * ```\n */\n 'defaultFieldResolver' => null,\n\n /*\n * Any headers that will be added to the response returned by the default controller\n */\n 'headers' => [],\n\n /*\n * Any JSON encoding options when returning a response from the default controller\n * See http://php.net/manual/function.json-encode.php for the full list of options\n */\n 'json_encoding_options' => 0,\n];\n```\n\n```text\nlocalhost:8000/graphql\n```\n\n```text\n<?php\nnamespace App\\GraphQL\\Types;\n\nuse App\\Wine;\nuse GraphQL\\Type\\Definition\\Type;\nuse Rebing\\GraphQL\\Support\\Type as GraphQLType;\n\nclass WineType extends GraphQLType\n{\n protected $attributes = [\n 'name' => 'Wine',\n 'description' => 'Details about a wine',\n 'model' => Wine::class\n ];\n\n public function fields(): array\n {\n return [\n 'id' => [\n 'type' => Type::nonNull(Type::int()),\n 'description' => 'Id of the wine',\n ],\n 'name' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The name of the wine',\n ],\n 'description' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'Short description of the wine',\n ],\n 'color' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The color of the wine',\n ],\n 'grape_variety' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The grape variety of the wine',\n ],\n 'country' => [\n 'type' => Type::nonNull(Type::string()),\n 'description' => 'The country of origin of the wine',\n ]\n ];\n }\n}\n```\n\n```text\n<?php\n\nnamespace App\\GraphQL\\Queries;\n\nuse App\\Wine;\nuse GraphQL\\Type\\Definition\\Type;\nuse Rebing\\GraphQL\\Support\\Facades\\GraphQL;\nuse Rebing\\GraphQL\\Support\\Query;\n\nclass WineQuery extends Query\n{\n protected $attributes = [\n 'name' => 'wine',\n ];\n\n public function type(): Type\n {\n return GraphQL::type('Wine');\n }\n\n public function args():array\n {\n return [\n 'id' => [\n 'name' => 'id',\n 'type' => Type::int(),\n 'rules' => ['required']\n ],\n ];\n }\n\n public function resolve($root, $args)\n {\n return Wine::findOrFail($args['id']);\n }\n}\n```\n\n```text\n<?php\nnamespace App\\GraphQL\\Queries;\n\nuse App\\Wine;\nuse GraphQL\\Type\\Definition\\Type;\nuse Rebing\\GraphQL\\Support\\Facades\\GraphQL;\nuse Rebing\\GraphQL\\Support\\Query;\n\nclass WinesQuery extends Query\n{\n protected $attributes = [\n 'name' => 'wines',\n ];\n\n public function type(): Type\n {\n return Type::listOf(GraphQL::type('Wine'));\n }\n\n public function resolve($root, $args)\n {\n return Wine::all();\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks for help @MaartenDev. I also figured it out later. Forgot to update here.\n- Thanks @MaartenDev in GraphQL example argument is missing.","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":652,"estimatedTokens":4107}}1023{"id":"stack-52767366","source":"stackoverflow","questionId":52767366,"title":"How can I resolve custom fields for django models using django_graphene?","tags":["python","django","graphql","graphene-python"],"text":"Title: How can I resolve custom fields for django models using django_graphene?\nTags: python, django, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nLooking at graphene_django, I see they have a bunch of resolvers picking up django model fields mapping them to graphene types.\n\nI have a subclass of JSONField I'd also like to be picked up.\n\n:\n\n```\n# models\nclass Recipe(models.Model):\n name = models.CharField(max_length=100)\n instructions = models.TextField()\n ingredients = models.ManyToManyField(\n Ingredient, related_name='recipes'\n )\n custom_field = JSONFieldSubclass(....)\n\n# schema\nclass RecipeType(DjangoObjectType):\n class Meta:\n model = Recipe\n\n custom_field = ???\n```\n\nI know I could write a separate field and resolver pair for a Query, but I'd prefer it to be available as part of the schema for that model.\n\nWhat I realize I could do:\n\n```\nclass RecipeQuery:\n custom_field = graphene.JSONString(id=graphene.ID(required=True))\n\n def resolve_custom_field(self, info, **kwargs):\n id = kwargs.get('id')\n instance = get_item_by_id(id)\n return instance.custom_field.to_json()\n```\n\nBut -- this means a separate round trip, to get the id then get the custom_field for that item, right?\n\nIs there a way I could have it seen as part of the RecipeType schema?\n\n========================================\n\nCode:\n```text\n# models\nclass Recipe(models.Model):\n name = models.CharField(max_length=100)\n instructions = models.TextField()\n ingredients = models.ManyToManyField(\n Ingredient, related_name='recipes'\n )\n custom_field = JSONFieldSubclass(....)\n\n\n# schema\nclass RecipeType(DjangoObjectType):\n class Meta:\n model = Recipe\n\n custom_field = ???\n```\n\n```text\nclass RecipeQuery:\n custom_field = graphene.JSONString(id=graphene.ID(required=True))\n\n def resolve_custom_field(self, info, **kwargs):\n id = kwargs.get('id')\n instance = get_item_by_id(id)\n return instance.custom_field.to_json()\n```\n\n```text\n# schema\nclass RecipeType(DjangoObjectType):\n class Meta:\n model = Recipe\n\n custom_field = graphene.JSONString(resolver=lambda my_obj, resolve_obj: my_obj.custom_field.to_json())\n```\n\n```text\ncustom_field\n```\n\n```text\nto_json\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":95,"estimatedTokens":555}}1024{"id":"stack-34905474","source":"stackoverflow","questionId":34905474,"title":"Why the \"graph\" in GraphQL?","tags":["graph","graphql"],"text":"Title: Why the \"graph\" in GraphQL?\nTags: graph, graphql\nSource: Stack Overflow\n\nQuestion:\nMaybe I'm missing something, but I don't know why GraphQL has *graph* in the title. \n\nI'm guessing it is something to do with Graph Theory and graph and can see some sort of connection but it would be great if someone can explain it in simple terms.","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":8,"estimatedTokens":85}}1025{"id":"stack-37106285","source":"stackoverflow","questionId":37106285,"title":"Returning results from mutations","tags":["graphql","graphql-js"],"text":"Title: Returning results from mutations\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nMy immediate question is why don't the query resolve functions get called?\n\nMy suspicion is that there is a problem with the return value from the mutation resolve function (which works). So, what should the return values look like?\n\nA higher level question is: is there a standard way in GraphQL to register a new user and handle the case of the user already existing?\n\nThe approach below is to have all the data about the user in the session data and pass back only the data the front end needs.\n\n```\n/**\n * graphQL.js\n *\n * Created by jrootham on 18/04/16.\n *\n * Copyright Β© 2016 Jim Rootham\n */\n\nimport graphqlHTTP from \"express-graphql\";\nimport {\n graphql,\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLString,\n GraphQLNonNull,\n GraphQLBoolean\n} from 'graphql';\nimport {hash} from \"bcrypt\"\nimport {connect, User} from \"../database/defineDB\";\n\nconst GraphUser = new GraphQLObjectType({\n name: \"GraphUser\",\n description: \"A user object\",\n fields: () => {\n return {\n name: {\n type: GraphQLString,\n resolve: (_, __, session) => {\n console.log(\"resolve name\", session);\n let name = \"\";\n if (session.signedOn) {\n return User.findById(session.userId).then (user => {\n return user.name;\n });\n }\n\n console.log(\"name\", name);\n return name;\n }\n },\n signedOn: {\n type: GraphQLBoolean,\n resolve: (_, __, session) => {\n return session.signedOn;\n }\n },\n existed: {\n type: GraphQLBoolean,\n resolve: (_, __, session) => {\n return session.existed;\n }\n }\n }\n }\n});\n\nconst query = new GraphQLObjectType({\n name: 'Queries',\n fields: () => {\n return {\n graphUser: {\n type: GraphUser\n }\n }\n }\n});\n\nconst mutation = new GraphQLObjectType({\n name: 'Mutations',\n description: \"Modification actions\",\n fields() {\n return {\n registerUser: {\n type: GraphUser,\n args: {\n name: {\n type: new GraphQLNonNull(GraphQLString)\n },\n password: {\n type: new GraphQLNonNull(GraphQLString)\n }\n },\n resolve(_, args, session) {\n console.log(\"resolve\", args);\n User.findOne({where:{name:args.name}}).then(user => {\n console.log(\"After find\", user);\n if (user === null) {\n const getHash = new Promise(\n resolve => {\n hash(args.password, 10, (err, hash) => {\n resolve(hash);\n });\n }\n );\n\n const result = getHash.then(hash => {\n connect.models.user.create({\n name: args.name,\n password: hash\n }).then(user => {\n session.userId = user.id;\n session.signedOn = true;\n session.existed = false;\n\n console.log(\"session user\", session.userId);\n return user;\n });\n\n console.log(result);\n return result;\n });\n }\n else {\n session.userId = 0;\n session.signedOn = false;\n session.existed = true;\n console.log(\"existed\");\n return GraphUser;\n }\n });\n }\n }\n }\n }\n});\n\nconst schema = new GraphQLSchema({\n query: query,\n mutation: mutation\n});\n\nexport const useGraphQL = app => {\n app.use('/graphql', graphqlHTTP(request =>({\n schema: schema,\n context: request.session,\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack\n }),\n graphiql:true\n })));\n};\n```\n\n========================================\n\nTop Answer:\n**why don't the query resolve functions get called?**\n\nYour root query field `graphUser` doesn't get resolved.\n\n```\nconst query = new GraphQLObjectType({\n name: 'Queries',\n fields: () => {\n return {\n graphUser: {\n type: GraphUser\n // TODO Add a resolve function here\n }\n }\n }\n});\n```\n\n**My suspicion is that there is a problem with the return value from the mutation resolve function (which works). So, what should the return values look like?**\n\nIf you use `Promise`, Your mutation's `resolve` function should return a Promise (it doesn't return now) and should use `resolve(result)` instead of `return result`. If user already exists, just return the existing user *object* instead of *type* `GraphUser`.\n\n**A higher level question is: is there a standard way in GraphQL to register a new user and handle the case of the user already existing?**\n\nGraphQL itself does not have a standard way of handling user registration. You just need a mutation for user registration. In the mutation's resolve function, whether the user already exists is checked. If exists, the mutation can return error. Otherwise, the user is registered and the newly created user object is returned.\n\n========================================\n\nCode:\n```text\n/**\n * graphQL.js\n *\n * Created by jrootham on 18/04/16.\n *\n * Copyright Β© 2016 Jim Rootham\n */\n\nimport graphqlHTTP from \"express-graphql\";\nimport {\n graphql,\n GraphQLSchema,\n GraphQLObjectType,\n GraphQLString,\n GraphQLNonNull,\n GraphQLBoolean\n} from 'graphql';\nimport {hash} from \"bcrypt\"\nimport {connect, User} from \"../database/defineDB\";\n\nconst GraphUser = new GraphQLObjectType({\n name: \"GraphUser\",\n description: \"A user object\",\n fields: () => {\n return {\n name: {\n type: GraphQLString,\n resolve: (_, __, session) => {\n console.log(\"resolve name\", session);\n let name = \"\";\n if (session.signedOn) {\n return User.findById(session.userId).then (user => {\n return user.name;\n });\n }\n\n console.log(\"name\", name);\n return name;\n }\n },\n signedOn: {\n type: GraphQLBoolean,\n resolve: (_, __, session) => {\n return session.signedOn;\n }\n },\n existed: {\n type: GraphQLBoolean,\n resolve: (_, __, session) => {\n return session.existed;\n }\n }\n }\n }\n});\n\nconst query = new GraphQLObjectType({\n name: 'Queries',\n fields: () => {\n return {\n graphUser: {\n type: GraphUser\n }\n }\n }\n});\n\nconst mutation = new GraphQLObjectType({\n name: 'Mutations',\n description: \"Modification actions\",\n fields() {\n return {\n registerUser: {\n type: GraphUser,\n args: {\n name: {\n type: new GraphQLNonNull(GraphQLString)\n },\n password: {\n type: new GraphQLNonNull(GraphQLString)\n }\n },\n resolve(_, args, session) {\n console.log(\"resolve\", args);\n User.findOne({where:{name:args.name}}).then(user => {\n console.log(\"After find\", user);\n if (user === null) {\n const getHash = new Promise(\n resolve => {\n hash(args.password, 10, (err, hash) => {\n resolve(hash);\n });\n }\n );\n\n const result = getHash.then(hash => {\n connect.models.user.create({\n name: args.name,\n password: hash\n }).then(user => {\n session.userId = user.id;\n session.signedOn = true;\n session.existed = false;\n\n console.log(\"session user\", session.userId);\n return user;\n });\n\n console.log(result);\n return result;\n });\n }\n else {\n session.userId = 0;\n session.signedOn = false;\n session.existed = true;\n console.log(\"existed\");\n return GraphUser;\n }\n });\n }\n }\n }\n }\n});\n\nconst schema = new GraphQLSchema({\n query: query,\n mutation: mutation\n});\n\nexport const useGraphQL = app => {\n app.use('/graphql', graphqlHTTP(request =>({\n schema: schema,\n context: request.session,\n formatError: error => ({\n message: error.message,\n locations: error.locations,\n stack: error.stack\n }),\n graphiql:true\n })));\n};\n```\n\n```text\nconst query = new GraphQLObjectType({\n name: 'Queries',\n fields: () => {\n return {\n graphUser: {\n type: GraphUser\n // TODO Add a resolve function here\n }\n }\n }\n});\n```\n\n```text\ngraphUser\n```\n\n```text\nPromise\n```\n\n```text\nresolve\n```\n\n```text\nresolve(result)\n```\n\n```text\nreturn result\n```\n\n```text\nGraphUser\n```\n\n========================================\n\nComments:\n- @ OP, you shouldn't change the question to the extent that it changes the context. Mutation code has been changed?\n- The root query was just a place holder. Resolving it has no effect.\n- The Promise part of the answer was a clue, but not complete, see below.\n- Re: root query, it's not a mere placeholder. Unless you resolve it, you can't make query on it.\n- Re: promise part, only you can know the complete implementation depending on your business logic. I tried to point you in the right direction. You had 3 questions in total :-)","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":383,"estimatedTokens":2399}}1026{"id":"stack-45458428","source":"stackoverflow","questionId":45458428,"title":"Fragment composition with Apollo client: convention and boilerplate","tags":["reactjs","graphql","apollo","react-apollo"],"text":"Title: Fragment composition with Apollo client: convention and boilerplate\nTags: reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nIn an Apollo app (but also GraphQL/Relay), one can choose to colocate data requirements to components, or eventually assemble big GraphQL queries himself. We have choosen to colocate data requirements to components because we expect better maintainability on the long terme, as you don't need to look at the whole component tree or your page to see all the data requirements, and can add new requirements locally.\n\nI'd like to know better how to compose GraphQL fragments with Apollo client. I know how to do it, but I'd like to know how can I do it better.\n\nCurrently, composing my fragments involve quite a bunch of boilerplate, particularly when I have components that just pass down the properties untouched.\n\n### Fragment declaration convention?\n\nFirst, let's take a simple component:\n\n```\nexport const User = ({\n user: {\n firstName,\n lastName,\n job,\n email,\n pictureUrl,\n color\n },\n ...props\n}) => (\n \n \n \n \n \n {(firstName || lastName) &&\n \n {firstName}\n {\" \"}\n {lastName}\n {\" \"}\n {email && {email}}\n }\n {job && {job}}\n \n \n);\nUser.fragments = {\n user: gql`\n fragment User on User {\n id\n firstName\n lastName\n pictureUrl: avatar\n job\n color\n email\n }\n `,\n};\n```\n\nHere are some choices to be made. It seems there is some kind of convention used in most examples, but this convention is not explicit in the doc.\n\nThe key used on the `User.fragments`. Does it make sense to name it exactly like the propName `user` of the component? \n\nThe name of the fragment: it seems by convention people name it with the name of the component, and if useful, suffix them by the GraphQL type on which is the fragment. (here `UserUser` would probably be overkill suffixing).\n\nI think it is good to the same convention across the same app, so that all fragment declarations are consistant. So, can someone more experienced help me clarify this convention that seems used in many Apollo examples?\n\n### Reducing fragment composition boilerplate ?\n\nLets consider now a `Relationship` component following the convention we've set up.\n\n```\nconst Relationship = ({ user1, user2 }) => (\n \n \n \n \n \n \n \n \n);\nRelationship.fragments = {\n user1: gql`\n fragment RelationshipUser1User on User {\n ...User\n }\n ${User.fragments.user}\n `,\n user2: gql`\n fragment RelationshipUser2User on User {\n ...User\n }\n ${User.fragments.user}\n `,\n};\n```\n\nNote that here I'm declaring 2 fragments that look the same. I think it's necessary because there are 2 props and you should not necessarily assume that the data requirement on both props are the same. We could easily imagine a component with `me` props, and `friend` props, where you would receive more data for the `me` props.\n\nThis works fine but it quite a lot of boilerplate and intermediate fragments that look quite unnecessary. Also it's not always convenient because from a component user point of view, you have to be aware of the 2 fragment names to be able to use it.\n\nI tried to simplify this with the following\n\n```\nRelationship.fragments = {\n user1: User.fragments.user,\n user2: User.fragments.user,\n};\n```\n\nThis can work, but if you do this, then the fragment names are not anymore `RelationshipUserXUser`, but `User` instead, this means it breaks the encapsulation and that somehow you need to be aware that internally, the `Relationship` component is using the `User` component.\n\nIf one day, the `Relationship` component switch to using an alternative representation like `UserAlt`, this would require refactoring from all components using the Relationship fragments, which is something I'd like to avoid. I think in such a case, the modifications should only have to happen in the `Relationship` component.\n\n### Conclusion\n\nI'd like to know the best practices to compose fragments with Apollo, so that components remain truly encapsulated, and preferably without involving too much boilerplate.\n\nAm I already doing the right thing? \n\nIs all this boilerplate unavoidable if I really want to compose queries?\n\n========================================\n\nCode:\n```text\nexport const User = ({\n user: {\n firstName,\n lastName,\n job,\n email,\n pictureUrl,\n color\n },\n ...props\n}) => (\n <UserWrapper {...props}>\n <UserAvatarWrapper>\n <Avatar\n firstName={firstName}\n lastName={lastName}\n color={color}\n src={pictureUrl}\n />\n </UserAvatarWrapper>\n <UserContentWrapper>\n {(firstName || lastName) &&\n <UserName>\n {firstName}\n {\" \"}\n {lastName}\n {\" \"}\n {email && <UserEmailInline>{email}</UserEmailInline>}\n </UserName>}\n {job && <UserJob>{job}</UserJob>}\n </UserContentWrapper>\n </UserWrapper>\n);\nUser.fragments = {\n user: gql`\n fragment User on User {\n id\n firstName\n lastName\n pictureUrl: avatar\n job\n color\n email\n }\n `,\n};\n```\n\n```text\nconst Relationship = ({ user1, user2 }) => (\n <RelationshipContainer>\n <RelationshipUserContainer>\n <User user={user1} />\n </RelationshipUserContainer/>\n <RelationshipUserContainer>\n <User user={user2} />\n </RelationshipUserContainer/>\n </RelationshipContainer>\n);\nRelationship.fragments = {\n user1: gql`\n fragment RelationshipUser1User on User {\n ...User\n }\n ${User.fragments.user}\n `,\n user2: gql`\n fragment RelationshipUser2User on User {\n ...User\n }\n ${User.fragments.user}\n `,\n};\n```\n\n```text\nRelationship.fragments = {\n user1: User.fragments.user,\n user2: User.fragments.user,\n};\n```\n\n```text\nUser.fragments\n```\n\n```text\nuser\n```\n\n```text\nUserUser\n```\n\n```text\nRelationship\n```\n\n```text\nme\n```\n\n```text\nfriend\n```\n\n```text\nme\n```\n\n```text\nRelationshipUserXUser\n```\n\n```text\nUser\n```\n\n```text\nRelationship\n```\n\n```text\nUser\n```\n\n```text\nRelationship\n```\n\n```text\nUserAlt\n```\n\n```text\nRelationship\n```\n\n```text\nconst userFragment = gql`\n fragment Relationship_user on User {\n ...User_user\n }\n ${User.fragments.user}\n`;\nRelationship.fragments = {\n user1: userFragment,\n user2: userFragment,\n};\n```\n\n```text\nUser.fragments.user\n```\n\n```text\nUser_user\n```\n\n```text\nRelationship.fragments.user\n```\n\n```text\nRelationship_user\n```\n\n========================================\n\nComments:\n- Thanks I'll try to these advices and report here if it improves the codebase\n- I'm starting using this convention as it seems to make sense. Btw this seems to also be the convention used in this article: medium.com/@wonderboymusic/…","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":299,"estimatedTokens":1662}}1027{"id":"stack-43690400","source":"stackoverflow","questionId":43690400,"title":"Passing arguments to graphQL query","tags":["graphql","graphql-js"],"text":"Title: Passing arguments to graphQL query\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am working on setting up a graphQL schema in node. The `/graphql` endpoint will typically be hit with argument(s) passed.\nFor example, one API call may be looking for \"checking\" accounts:\n\n```\nquery {\n accounts(type: \"checking\") {\n id\n type\n country\n currency\n }\n}\n```\n\nAnother may be looking for all accounts in the \"US\":\n\n```\nquery {\n accounts(country: \"US\") {\n id\n type\n country\n currency\n }\n}\n```\n\n...and yet another may be looking for \"savings\" accounts in the \"UK\" denominated in \"GBP\":\n\n```\nquery {\n accounts(type: \"savings\", country: \"UK\", currency: \"GBP\") {\n id\n type\n country\n currency\n }\n}\n```\n\nIs the proper approach defining this query as taking optional parameters for `type`, `country`, and `currency`?\n\n========================================\n\nCode:\n```text\nquery {\n accounts(type: \"checking\") {\n id\n type\n country\n currency\n }\n}\n```\n\n```text\nquery {\n accounts(country: \"US\") {\n id\n type\n country\n currency\n }\n}\n```\n\n```text\nquery {\n accounts(type: \"savings\", country: \"UK\", currency: \"GBP\") {\n id\n type\n country\n currency\n }\n}\n```\n\n```text\n/graphql\n```\n\n```text\ntype\n```\n\n```text\ncountry\n```\n\n```text\ncurrency\n```\n\n```text\ntype\n```\n\n```text\ncountry\n```\n\n```text\ncurrency\n```\n\n```text\nfilter\n```\n\n```text\ntype\n```\n\n```text\ncurrency\n```\n\n```text\ncountry\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":126,"estimatedTokens":355}}1028{"id":"stack-74037597","source":"stackoverflow","questionId":74037597,"title":"Can't use extensions with GraphQLError","tags":["exception","error-handling","graphql","apollo-server"],"text":"Title: Can't use extensions with GraphQLError\nTags: exception, error-handling, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nFrom the Apollo Graphql document, this way can define extension error:\n\nhttps://www.apollographql.com/docs/apollo-server/data/errors/\n\n```\nimport { GraphQLError } from 'graphql';\n\n throw new GraphQLError('the error message', \n extensions: {\n code: 'SOMETHING_BAD_HAPPENED',\n http: {\n status: 404,\n headers: new Map([\n ['some-header', 'it was bad'],\n ['another-header', 'seriously'],\n ]),\n },\n },\n );\n```\n\nBut in my case it got this error:\n\n```\nArgument of type '{ extensions: { code: string; http: { status: number; headers: Map; }; }; }' is not assignable to parameter of type 'Maybe'.\n Object literal may only specify known properties, and 'extensions' does not exist in type 'ASTNode | readonly ASTNode[]'.\n\n 23 extensions: {\n ~~~~~~~~~~~~~\n 24 code: 'SOMETHING_BAD_HAPPENED',\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n...\n 31 },\n ~~~~~~~~~~~~\n 32 },\n ~~~~~~~~~\n\nFound 1 error(s).\n```\n\nI'm using these packages:\n\n- \"apollo-server-core\": \"^3.7.0\",\n\n- \"apollo-server-express\": \"^3.4.0\",\n\n- \"apollo-server-plugin-base\": \"^0.13.0\",\n\nI also tried to install `apollo-server-testing` but still can't use extensions.\n\n========================================\n\nTop Answer:\nThis way works:\n\n```\nthrow new GraphQLError('the error message',\n null,\n null,\n null,\n null,\n null,\n {\n code: 'SOMETHING_BAD_HAPPENED',\n http: {\n status: 404,\n },\n },\n );\n```\n\n========================================\n\nCode:\n```js\nimport { GraphQLError } from 'graphql';\n\n throw new GraphQLError('the error message', \n extensions: {\n code: 'SOMETHING_BAD_HAPPENED',\n http: {\n status: 404,\n headers: new Map([\n ['some-header', 'it was bad'],\n ['another-header', 'seriously'],\n ]),\n },\n },\n );\n```\n\n```text\nArgument of type '{ extensions: { code: string; http: { status: number; headers: Map<string, string>; }; }; }' is not assignable to parameter of type 'Maybe<ASTNode | readonly ASTNode[]>'.\n Object literal may only specify known properties, and 'extensions' does not exist in type 'ASTNode | readonly ASTNode[]'.\n\n 23 extensions: {\n ~~~~~~~~~~~~~\n 24 code: 'SOMETHING_BAD_HAPPENED',\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n...\n 31 },\n ~~~~~~~~~~~~\n 32 },\n ~~~~~~~~~\n\nFound 1 error(s).\n```\n\n```text\napollo-server-testing\n```\n\n```js\nthrow new GraphQLError('the error message', \n{ // curly bracket here to open the object\n extensions: {\n code: 'SOMETHING_BAD_HAPPENED',\n http: {\n status: 404,\n headers: new Map([\n ['some-header', 'it was bad'],\n ['another-header', 'seriously'],\n ]),\n },\n },\n} // curly bracket here to close the object\n);\n```\n\n```text\n{ extensions }\n```\n\n```text\nthrow new GraphQLError('the error message',\n null,\n null,\n null,\n null,\n null,\n {\n code: 'SOMETHING_BAD_HAPPENED',\n http: {\n status: 404,\n },\n },\n );\n```\n\n```text\n// backend/errors/GraphQLError.ts\n\nimport { ASTNode, GraphQLError as OriginalGraphQLError, Source } from \"graphql\";\nimport { Maybe } from \"type-graphql\";\n\ntype ErrorOptions = {\n nodes?: Maybe<ReadonlyArray<ASTNode> | ASTNode>;\n source?: Maybe<Source>;\n positions?: Maybe<ReadonlyArray<number>>;\n path?: Maybe<ReadonlyArray<string | number>>;\n originalError?: Maybe<Error>;\n extensions?: Maybe<{ [key: string]: any }>;\n};\n\nexport class GraphQLError extends OriginalGraphQLError {\n constructor(message: string, options?: ErrorOptions) {\n const extensions = {\n ...(options?.originalError && {\n originalError: options?.originalError,\n }),\n ...(options?.extensions && {\n ...options?.extensions,\n }),\n };\n super(\n message,\n options?.nodes,\n options?.source,\n options?.positions,\n options?.path,\n options?.originalError,\n extensions\n );\n }\n}\n```\n\n```text\n// SomewhereResolver.ts\n\nasync destroyDbMutation(){\n try{\n const ok = await businessRequirement.destroyDB();\n return ok;\n }catch(error:any){\n throw new GraphQLError(error.message, { originalError: error });\n }\n}\n```\n\n```text\ngraphql@15\n```\n\n```text\ngraphql\n```\n\n```text\noriginalError\n```\n\n```text\nextensions\n```\n\n```text\ngraphql-yoga\n```\n\n```text\noriginalError\n```\n\n```text\nconst setHttpPlugin = {\n async requestDidStart() {\n return {\n async willSendResponse({ response }) {\n response.http.headers.set('Custom-Header', 'hello');\n if (response?.errors?.[0]?.message === 'teapot') {\n response.http.status = 418;\n }\n }\n };\n }\n};\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n csrfPrevention: true,\n cache: 'bounded',\n plugins: [\n setHttpPlugin,\n ApolloServerPluginLandingPageLocalDefault({ embed: true }),\n ],\n});\n```\n\n========================================\n\nComments:\n- Make sure you're using `graphql` >= 16. I forgot to run `yarn install`, so I had v15 installed, which is why I was seeing this error.\n- that is some unpleasing code but it actually works LOL\n- I tried the code above (which is the also the same as the code in apollo-server documentation) but I'm getting the same error mentioned in this post. Only the comment below worked with the null options and I don't think it's okay to use it. Any suggestions please?","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":261,"estimatedTokens":1359}}1029{"id":"stack-42625812","source":"stackoverflow","questionId":42625812,"title":"updateQueries after GraphQL mutation not working with the Apollo client","tags":["javascript","graphql","apollo","apollostack","react-apollo"],"text":"Title: updateQueries after GraphQL mutation not working with the Apollo client\nTags: javascript, graphql, apollo, apollostack, react-apollo\nSource: Stack Overflow\n\nQuestion:\nAfter I'm sending a `createMessage` mutation in my app, I want to update the local `ApolloStore` using `updateQueries`.\n\nMy setup looks as follows:\n\n```\nconst ChatWithAllMessages = graphql(allMessages, {name: 'allMessagesQuery'})(Chat)\nexport default graphql(createMessage, {\n props({ownProps, mutate}) {\n return {\n createMessageMutation(text, conversationId) {\n return mutate({\n variables: { text, conversationId },\n updateQueries: {\n allConversations: (previousState, {mutationResult}) => {\n console.log('Chat - did send mutation for allConversationsQuery: ', previousState, mutationResult)\n return ...\n }\n }\n })\n }\n }\n }\n})(ChatWithAllMessages)\n```\n\nI'm calling the `createMessageMutation` in my code like so:\n\n```\n_onSend = () => {\n this.props.createMessageMutation(this.state.message, this.props.conversationId)\n}\n```\n\nWith this setup I would expect the function that I specified in the value for `updateQueries` to be executed, however, that doesn't seem to happen (the logging statement is never printed).\n\nFor reference, this is what the `allConversation` query in the `ApolloStore` looks like:\n\nhttps://i.sstatic.net/utYAe.png\n\nAlso, this how it's defined in my JS code:\n\n```\nconst findConversations = gql`\n query allConversations($customerId: ID!) {\n allConversations(filter: {\n customer: {\n id: $customerId\n }\n }){\n id\n updatedAt\n slackChannelName\n agent {\n id\n slackUserName\n }\n messages(last: 1) {\n id\n text\n createdAt\n }\n }\n }\n`\n```\n\nDoes anyone spot what I'm doing wrong?\n\n========================================\n\nCode:\n```text\nconst ChatWithAllMessages = graphql(allMessages, {name: 'allMessagesQuery'})(Chat)\nexport default graphql(createMessage, {\n props({ownProps, mutate}) {\n return {\n createMessageMutation(text, conversationId) {\n return mutate({\n variables: { text, conversationId },\n updateQueries: {\n allConversations: (previousState, {mutationResult}) => {\n console.log('Chat - did send mutation for allConversationsQuery: ', previousState, mutationResult)\n return ...\n }\n }\n })\n }\n }\n }\n})(ChatWithAllMessages)\n```\n\n```text\n_onSend = () => {\n this.props.createMessageMutation(this.state.message, this.props.conversationId)\n}\n```\n\n```text\nconst findConversations = gql`\n query allConversations($customerId: ID!) {\n allConversations(filter: {\n customer: {\n id: $customerId\n }\n }){\n id\n updatedAt\n slackChannelName\n agent {\n id\n slackUserName\n }\n messages(last: 1) {\n id\n text\n createdAt\n }\n }\n }\n`\n```\n\n```text\ncreateMessage\n```\n\n```text\nApolloStore\n```\n\n```text\nupdateQueries\n```\n\n```text\ncreateMessageMutation\n```\n\n```text\nupdateQueries\n```\n\n```text\nallConversation\n```\n\n```text\nApolloStore\n```\n\n```js\nimport { compose } from 'react-apollo';\n\n...\n\nimport findConversationsQuery from './.../findConversationsQuery';\n\n...\n\nconst ChatWithAllMessages = compose(\n graphql(allMessages, {name: 'allMessagesQuery'}),\n findConversationsQuery,\n graphql(createMessage, {\n props({ ownProps, mutate }) {\n return {\n createMessageMutation(text, conversationId) {\n return mutate({\n variables: {\n text,\n conversationId\n },\n updateQueries: {\n allConversations: (previousState, {\n mutationResult\n }) => {\n console.log('Chat - did send mutation for allConversationsQuery: ', previousState, mutationResult)\n return ...\n }\n }\n })\n }\n }\n }\n })(Chat)\n```\n\n```js\nimport { graphql } from 'react-apollo';\nimport gql from 'graphql-tag';\n\nconst findConversations = gql`\n query allConversations($customerId: ID!) {\n allConversations(filter: {\n customer: {\n id: $customerId\n }\n }){\n id\n updatedAt\n slackChannelName\n agent {\n id\n slackUserName\n }\n messages(last: 1) {\n id\n text\n createdAt\n }\n }\n }\n`\n\nconst findConversationsQuery = graphql(findConversations, {\n name: \"findConversationsQuery\"\n});\n\nexport default findConversationsQuery\n```\n\n========================================\n\nComments:\n- > The updateQuery functionality is only called when the view for the mutation holds the reference to the query. Do you have a reference for that statement?\n- It is not written directly like this in the documentation of apollo. When you read through the updateQueries definition there are two statements \"We expose this mutation through a function prop that the CommentsPage component can call\" and \"The comments page itself is rendered with the following query\". So i thought the query has to be in the props of the component.\n- referring to this comment it sounds like that behaviour is a bug. Even though I'm not clear on the current agreement here.\n- Yes you're right, so maybe with version 0.11.1 it works without composing the query and the mutation\n- The mutation doesn't need to hold a reference to the query, it just needs to know the name of the query (not the JSvariable name, but the name given in the graphql query string, i.e. in \"query (var1: String, ...){ ... \"). UpdateQueries will only work if the named query was previously executed though, because otherwise Apollo Client isn't aware of the query. To circumvent that problem, you can provide a query + variables directly to updateQueries (instead of a query name). Could you update your answer accordingly?\n- > (not the JSvariable name, but the name given in the graphql query string, i.e. in \"query (var1: String, ...){ ... \") Arg, I'm tripping over that every single time :P\n- I had to update the node package to a higher version than it also worked with just the named query","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":236,"estimatedTokens":1573}}1030{"id":"stack-42855932","source":"stackoverflow","questionId":42855932,"title":"GraphQL and nested resources would make unnecessary calls?","tags":["graphql"],"text":"Title: GraphQL and nested resources would make unnecessary calls?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI read GraphQL specs and could not find a way to avoid 1 + N * number_of_nested calls, am I missing something?\n\ni.e. a query has a type client which has nested orders and addresses, if there are 10 clients it will do 1 call for the 10 clients + 10 calls for each client.orders + 10 calls for each client.addresses.\n\nIs there a way to avoid this? Not that it is not the same as caching an UUID of something, those are all different values and if you GraphQL points to a database which can make joins, it would be pretty bad on it because you could do 3 queries for any number of clients.\n\nI ask this because I wanted to integrate GraphQL with an API that can fetch nested resources in an efficient way and if there was a way to solve the whole graph before resolving it would be nice to try to put some nested stuff in just one call.\n\nOr I got it wrong and GraphQL is meant to be used only with microservices?\n\n========================================\n\nTop Answer:\nI consider, that you're talking about using GraphQL with SQL database backend. The standard itself is database agnostic, and it doesn't care, how are you going to work out the problems of possible N+1 SELECT issues in your code. That being said, the specific server-side implementations of GraphQL server introduce many different ways of mitigating that problem:\n\n- AFAIK, Ruby implementation is able to to make use of Active Record and gems such as bullet to apply horizontal batching of executed database calls.\n\n- JavaScript implementation may make use of DataLoader library, which have similar techinque of batching series of executed promises together. You can see it in action here.\n\n- Elixir and Python implementations have concept of runtime info about executed subqueries, that can be used to determine which data will be further needed in order to execute GraphQL query, and potentially prefetch it.\n\n- F# implementation works similar to Elixir, but plugin itself can perform live analysis of execution tree to better describe, which fields can be potentially used in code, allowing for easier split of GraphQL domain model from database model.\n\n- Many implementations (i.e. PostGraph) tie underlying database model directly into GraphQL schema. In this case GQL query is often translated directly into database query language.\n\n========================================\n\nComments:\n- That is useful not only for SQL backend, if you have an API that can fetch data in one request, it would be kinda bad doing multiple. As I saw both javascript and python implementation have a cache which only kinda solve for already seen objects, like the user -> friends where friends are also user instance and if you make that nested a lot, it would fix the problem for sure.\n- Thanks, Andy! Probably I won't use node, maybe python or rust but knowing that it is possible from GraphQL's architecture, I will start from there and try to build a solution.","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":35,"estimatedTokens":757}}1031{"id":"stack-42549684","source":"stackoverflow","questionId":42549684,"title":"Dynamically set GraphQL queries for React components with Apollo Client","tags":["reactjs","react-redux","graphql","react-apollo"],"text":"Title: Dynamically set GraphQL queries for React components with Apollo Client\nTags: reactjs, react-redux, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm building a React front end which allows users to select an \"active\" query from a list of static queries and flattens to the result to be displayed in a table. What is the best way to pass the GraphQL query from a higher-order component into a nested child component? \n\nMost of the documentation/solutions that I've seen focus on binding a static query with dynamical conditions from component states to a component, which would not work for my purpose as the different static queries have varying fields and query different node types. \n\nWhat is the best-practice/recommended approach here? I feel like this is not a very unique use case, but I can't seem to find any examples that would do something similar. \n\nI'm using Apollo-Client/Redux as my client-side store.\n\nBelow is the rough outline of the component:\n\n\r\n\r\n\n```\nclass GridViewPage extends React.Component{\r\n constructor(props, context) {\r\n super(props, context);\r\n this.state = {\r\n activeQuery = ... Stores the selected query ...\r\n };\r\n }\r\n\r\n render() {\r\n return (\r\n \r\n ...Component here allows users to select a query from the active list and saves it/it's ID/Index to the state...\r\n\r\n \r\n ...Some toolbar components...\r\n \r\n ...Component here displays the result of the query (Ideally by receiving the query or the result of as a prop?)...\r\n \r\n );\r\n }\r\n}\r\n\r\nGridViewPage.propTypes = {\r\n grids: PropTypes.array.isRequired,\r\n actions: PropTypes.object.isRequired\r\n};\r\n\r\nfunction mapStateToProps(state, ownProps) {\r\n return {\r\n // Receives list of available queries as a prop\r\n grids: state.grids\r\n };\r\n}\n```\n\n========================================\n\nCode:\n```js\nclass GridViewPage extends React.Component{\n constructor(props, context) {\n super(props, context);\n this.state = {\n activeQuery = ... Stores the selected query ...\n };\n }\n\n render() {\n return (\n <div className=\"gridContainer\">\n ...Component here allows users to select a query from the active list and saves it/it's ID/Index to the state...\n\n <Panel collapsible>\n ...Some toolbar components...\n </Panel>\n ...Component here displays the result of the query (Ideally by receiving the query or the result of as a prop?)...\n </div>\n );\n }\n}\n\nGridViewPage.propTypes = {\n grids: PropTypes.array.isRequired,\n actions: PropTypes.object.isRequired\n};\n\nfunction mapStateToProps(state, ownProps) {\n return {\n // Receives list of available queries as a prop\n grids: state.grids\n };\n}\n```\n\n```text\nimport React, { Component, PropTypes } from 'react';\nimport { graphql } from 'react-apollo';\nimport gql from 'graphql-tag';\n\nclass Profile extends Component { ... }\nProfile.propTypes = {\n data: PropTypes.shape({\n loading: PropTypes.bool.isRequired,\n currentUser: PropTypes.object,\n }).isRequired,\n};\n\n// We use the gql tag to parse our query string into a query document\nconst CurrentUserForLayout = gql`\n query CurrentUserForLayout {\n currentUser {\n login\n avatar_url\n }\n }\n`;\n\nconst ProfileWithData = graphql(CurrentUserForLayout)(Profile);\n```\n\n```text\nimport React, { Component, PropTypes } from 'react';\n\nexport class Profile extends Component { ... }\nProfile.propTypes = {\n data: PropTypes.shape({\n loading: PropTypes.bool.isRequired,\n currentUser: PropTypes.object,\n }).isRequired,\n};\n```\n\n```text\nimport React, { Component, PropTypes } from 'react';\nimport { graphql } from 'react-apollo';\nimport { Profile } from './Profile'\n\nexport default function createProfileWithData(query) => {\n return graphql(query)(Profile);\n}\n```\n\n```text\nimport React, { Component, PropTypes } from 'react';\nimport gql from 'graphql-tag';\nimport createProfileWithData from './createProfileWithData';\n\nclass Page extends Component { \n\n renderProfileWithData() {\n\n const { textQuery } = this.props;\n // Simplest way, though you can call gql as a function too\n const graphQLQuery = gql`${textQuery}`;\n\n const profileWithDataType = createProfileWithData(graphQLQuery);\n\n return (\n <profileWithDataType />\n );\n }\n\n render() {\n\n return (<div>\n ..\n {this.renderProfileWithData()}\n ..\n </div>)\n }\n\n}\n\nProfile.propTypes = {\n textQuery: PropTypes.string.isRequired,\n};\n```\n\n```text\nprops.data.currentUser\n```\n\n```text\nprops.data.*\n```\n\n========================================\n\nComments:\n- Thanks! Have started to apply this pattern in the project and I think I will get it to work eventually. One immediate error I am having is that `const profileWithDataType = createProfileWithData(graphQLQuery);` is returning a function type, and therefore not hitting the `render()`function when nested inside `{this.renderProfileWithData()}`? This might be a syntax issue on my code, but thought worth mentioning.\n- Yeah, it might be an issue with JSX. I always forget if that syntax is valid or not. You could also do: ``` return React.createElement(profileWithDataType, {}); ``` I am certain you already solved this by now, so an update would be nice :)\n- Hey! Actually I ended up skipping createProfileWithData.js and setting the query to the page directly in the Page.js with the equivalent of `graphql(query)(Profile)` and it works :)","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":191,"estimatedTokens":1350}}1032{"id":"stack-62728803","source":"stackoverflow","questionId":62728803,"title":"Overriding standard ID scalar","tags":["graphql","graphql-java"],"text":"Title: Overriding standard ID scalar\nTags: graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI want to use UUID as an identifier but standard scalar ID is coerced as string.\nSo have to parse uuid from string everywhere I use ID type.\n\nI wonder is it possible to override ID type with my own implementation?\nThis scalar type has some special meaning or I can just use my own scalar called UUID as identifier?\n\n========================================\n\nCode:\n```java\n@Override\npublic Object serialize(Object dataFetcherResult) {\n //\n}\n\n@Override\npublic Object parseValue(Object input) {\n //\n}\n\n@Override\npublic Object parseLiteral(Object input) {\n //\n}\n```\n\n========================================\n\nComments:\n- The link you have provided was really helpful. Thank you","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":35,"estimatedTokens":196}}1033{"id":"stack-71645881","source":"stackoverflow","questionId":71645881,"title":"Canceling previous pending request in React (Apollo client with useQuery)","tags":["reactjs","graphql","apollo-client","react-apollo"],"text":"Title: Canceling previous pending request in React (Apollo client with useQuery)\nTags: reactjs, graphql, apollo-client, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have on search page where we have search box so when typing continue then it is sending multiple requests for each type. I used debounce to handle this so my request is reduced but now I need to cancel the request which is pending and only the latest should be there\n\nI tried a few methods but it is not working for me.\n\nApollo client Version - `3.3.21`\nReact version - `17.0.2`\nReact-dom version - `17.0.2`\nNode - `16`\n\nThe method which I tried\n\n`Middleware`cancelRequest.ts.\n\n`Watchquery` with `queryDeduplication: false`\n\n========================================\n\nCode:\n```text\n3.3.21\n```\n\n```text\n17.0.2\n```\n\n```text\n17.0.2\n```\n\n```text\n16\n```\n\n```text\nMiddleware\n```\n\n```text\nWatchquery\n```\n\n```text\nqueryDeduplication: false\n```\n\n========================================\n\nComments:\n- I have the same issue , did you find a solution ?\n- Are you able to track when react is updating your components vs. when the query is being attempted? When working on a similar function I found that the react state was updating before a query that needed to be run after and resolved my issue.","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":56,"estimatedTokens":314}}1034{"id":"stack-72636356","source":"stackoverflow","questionId":72636356,"title":"GraphQL Resolvers for simple transformations","tags":["performance","graphql","query-optimization"],"text":"Title: GraphQL Resolvers for simple transformations\nTags: performance, graphql, query-optimization\nSource: Stack Overflow\n\nQuestion:\n**Situation**: We have some types of GQL that can provide *icon names*. Names are distinguished from different data properties (name, id, type, severity...). This is done by simple string transformations. At the end of the icons are some unified svg files somewhere in a CDN. The resources look like \"Php\", \"Apache Server\" etc. and the resolved icon names (keys) are \"php\", \"apache-server\" etc.\n\n**The question is what is better pattern**\n\nA. **To add one resolver** named \"icon\" for each type and provide all trnsformations on server-side. This means that GQL is more talkative, more data is transferred and FE code is more straightforward. The main arguments are that GQL should be client-oriented and the data are better to be consistent.\n\nB. **Or to provide the data as they are** and transform them into icon names on FE between query results and rendering in an object-specific manner. This means having less redundancy on the API and more complexity in the FE code. The main argument for such an approach is that the icons are resources on the clinet side and are irrelevant to the server.\n\n**Please how to decide between A and B?**\n\n*(the system is a business inteligence tool for low thousands simultaneous users)*\n\n========================================\n\nCode:\n```js\nconst resources = {\n php: {\n name: \"Php\",\n type: \"application\",\n severity: \"warn\",\n },\n \"apache-server\": {\n name: \"Apache Server\",\n //\n },\n};\n\nconst genericResource = {\n id: \"generic\",\n name: \"unknown resource\",\n type: \"application\",\n severity: \"warn\",\n};\n\nconst grapQLRequest = async () =>\n Promise.resolve().then(() => [\n { resource: \"php\", message: \"some string\", timestamp: \"\" },\n { resource: \"apache-server\", message: \"some string\", timestamp: \"\" },\n { resource: \"new-resource\", message: \"some string\", timestamp: \"\" },\n ]);\n\nconst handler = async () => {\n const result = await grapQLRequest().then((data) =>\n data.map((x) => ({\n ...x,\n resource: {\n id: x.resource,\n ...(resources[x.resource] || genericResource),\n },\n }))\n );\n\n console.log(result);\n};\n\nvoid handler();\n```\n\n```text\nnpm update\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.222Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":67,"estimatedTokens":572}}1035{"id":"stack-72981518","source":"stackoverflow","questionId":72981518,"title":"\"ERROR Error: Argument 2 `isExtractable` must be a function.\" when uploading files with Apollo Angular","tags":["angular","file-upload","graphql","apollo","apollo-client"],"text":"Title: \"ERROR Error: Argument 2 `isExtractable` must be a function.\" when uploading files with Apollo Angular\nTags: angular, file-upload, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nAccording to https://apollo-angular.com/docs/data/network#file-upload, in order to upload files with Apollo Angular you have to add `context: {useMultipart: true}` to the graphQL query, and the `extractFiles` function to the httpLink creation.\n\nHowever, I keep getting this error. It seems that the default `isExtractableFile` function is not used, and I have no idea why that is.\n\nHere's my `graphql.module.ts`:\n\n```\nconst uri = environment.graphQLUrl; // {\n return {\n link: httpLink.create({uri, useMultipart: true, extractFiles}),\n cache: new InMemoryCache(),\n };\n}\n\n@NgModule({\n exports: [ApolloModule],\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\n========================================\n\nCode:\n```text\nconst uri = environment.graphQLUrl; // <-- add the URL of the GraphQL server here\nexport function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {\n return {\n link: httpLink.create({uri, useMultipart: true, extractFiles}),\n cache: new InMemoryCache(),\n };\n}\n\n@NgModule({\n exports: [ApolloModule],\n providers: [\n {\n provide: APOLLO_OPTIONS,\n useFactory: createApollo,\n deps: [HttpLink],\n },\n ],\n})\nexport class GraphQLModule {}\n```\n\n```text\ncontext: {useMultipart: true}\n```\n\n```text\nextractFiles\n```\n\n```text\nisExtractableFile\n```\n\n```text\ngraphql.module.ts\n```\n\n```text\nimport extractFiles from 'extract-files/extractFiles.mjs';\nimport isExtractableFile from 'extract-files/isExtractableFile.mjs';\n\nhttpLink.create({\n ...\n extractFiles: (body) => extractFiles(body, isExtractableFile),\n});\n```\n\n========================================\n\nComments:\n- Have you tried using the `extractFiles` function example found in the linked Angular doc to see if there's any discrepancy between the two?\n- This solved the problem! I'm using `{ \"@apollo/client\": \"3.5.9\", \"apollo-angular\": \"3.0.1\", \"extract-files\": \"^13.0.0\", }`","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":88,"estimatedTokens":542}}1036{"id":"stack-58253618","source":"stackoverflow","questionId":58253618,"title":"AWS Amplify Appsync solving error when creating object with relationship","tags":["amazon-web-services","graphql","aws-amplify"],"text":"Title: AWS Amplify Appsync solving error when creating object with relationship\nTags: amazon-web-services, graphql, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI am trying to create an object with a relationship.\n\nI am using the auto generated amplify mutations\n\nWhen I create an object without the relationship the operation succeeds.\nWhen I create an object with the relationship the operation fails.\n\nThe error message I get is\n\n```\n\"The variables input contains a field name 'customer' that is not defined for input object type 'CreateCreditcardInput' \"\n```\n\nThe auto generated mutation is below.\n\n\r\n\r\n\n```\nexport const createCreditcard = `mutation CreateCreditcard($input: CreateCreditcardInput!) {\r\n createCreditcard(input: $input) {\r\n id\r\n number\r\n expiration\r\n customer {\r\n id\r\n firstName\r\n lastName\r\n phone\r\n address1\r\n address2\r\n city\r\n state\r\n postcode\r\n email\r\n creditcards {\r\n nextToken\r\n }\r\n }\r\n payment {\r\n id\r\n paymentType\r\n creditcard {\r\n id\r\n number\r\n expiration\r\n }\r\n orderAmount\r\n order {\r\n id\r\n date\r\n orderStatus\r\n }\r\n }\r\n }\r\n}\r\n`;\n```\n\n========================================\n\nCode:\n```text\n\"The variables input contains a field name 'customer' that is not defined for input object type 'CreateCreditcardInput' \"\n```\n\n```js\nexport const createCreditcard = `mutation CreateCreditcard($input: CreateCreditcardInput!) {\n createCreditcard(input: $input) {\n id\n number\n expiration\n customer {\n id\n firstName\n lastName\n phone\n address1\n address2\n city\n state\n postcode\n email\n creditcards {\n nextToken\n }\n }\n payment {\n id\n paymentType\n creditcard {\n id\n number\n expiration\n }\n orderAmount\n order {\n id\n date\n orderStatus\n }\n }\n }\n}\n`;\n```\n\n```text\n{id: \"\", number: 1212112, expiration: \"12/20\", customer: {id:\"81d86584-e031-41db-9c20-e6d3c5b005a6\"}}\n```\n\n```text\n{id: \"\", number: 1212112, expiration: \"12/20\", creditcardCustomerId: \"81d86584-e031-41db-9c20-e6d3c5b005a6\"}\n```\n\n========================================\n\nComments:\n- Such basic functionality for submitting an update. It seems `aws-amplify` should handle that for us, right? I gotta believe there is a way to transform the model as I'm using the same one that came from the query I'm now updating. π€\n- The best idea I can come up with is to write a function that takes a nested object then flattens it to comply with what aws-amplify wants. The nested object's property tree would accumulate into a string. So in this exmple creditcard.customer.id => creditcardCustomerId","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":125,"estimatedTokens":656}}1037{"id":"stack-70553210","source":"stackoverflow","questionId":70553210,"title":"SSR crashing in Next.js on unsuccessful GraphQL request (HTTP code 500) using Apollo Client","tags":["reactjs","graphql","next.js","apollo","apollo-client"],"text":"Title: SSR crashing in Next.js on unsuccessful GraphQL request (HTTP code 500) using Apollo Client\nTags: reactjs, graphql, next.js, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nWell, I'm a little dumpy. I will try to explain my problem as clearly as possible.\n\nI use Apollo client to do my GraphQL queries. I also use NextJS.\nI have a page that needs to be rendered on the server side for SEO reasons.\n\nSo I have a `getProductFromSlug` function that allows me to execute my request.\n\n```\nexport const getProductFromSlug = async (slug: string) => {\n try {\n const { data, error } = await apolloClient.query({\n query: GET_PRODUCT_BY_SLUG_QUERY,\n variables: {\n slug,\n },\n })\n\n if (error) {\n return { errors: [error.message] }\n }\n\n if (!('product' in data) || data.product === null) {\n return { errors: ['Product with specified url not found'] }\n }\n\n return {\n data,\n }\n } catch (error) {\n // @ts-ignore\n const formattedErrors: ApolloError = isApolloError(error)\n ? error.graphQLErrors.map((error) => error.message)\n : [`Unhandled error : ${error}`]\n\n return {\n errors: formattedErrors,\n }\n }\n}\n```\n\nHere's `getServerSideProps` to pass data to page\n\n```\nexport const getServerSideProps = async (\n context: GetServerSidePropsContext\n) => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const requestData = await getProductFromSlug(context.params.slug as string)\n return 'errors' in requestData\n ? { notFound: true, props: requestData }\n : { props: requestData }\n}\n```\n\nThe problem is that when I have a HTTP code 500 from the endpoint, the SSR is crashing and on Vercel, it's causing a serverless crash error.\n\nError: Response not successful: Received status code 500\nThis error happened while generating the page. Any console logs will be displayed in the terminal window\n\nIf needed, here's my entry point (_app.tsx):\n\n```\nfunction MyApp(props: AppProps) {\n return (\n \n \n \n \n \n \n \n \n \n )\n}\n```\n\nYou can see my Apollo Client here : https://gist.github.com/SirMishaa/d67e7229307b77b43a0b594d0c9e6943\n\nStack trace of `yarn run dev` (next dev -p 3005) :\n\n```\nServerError: Response not successful: Received status code 500\n at Object.throwServerError (C:\\Users\\misha\\Documents\\dev\\rekk-next\\node_modules\\@apollo\\client\\link\\utils\\utils.cjs:45:17)\n at C:\\Users\\misha\\Documents\\dev\\rekk-next\\node_modules\\@apollo\\client\\link\\http\\http.cjs:31:19\n at runMicrotasks ()\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\nerror - uncaughtException: ServerError: Response not successful: Received status code 500\nerror Command failed with exit code 1.\n```\n\n**NOTE** :\n**After some try with console.log in try and catch scope, it shows nothing in the Next SSR console, so the internal error of Apollo is not caught for some reason.**\n\nI appreciate your help, thank you!\n\nhttps://i.sstatic.net/iqsjP.png\n\n========================================\n\nCode:\n```text\nexport const getProductFromSlug = async (slug: string) => {\n try {\n const { data, error } = await apolloClient.query<{\n product: Product\n }>({\n query: GET_PRODUCT_BY_SLUG_QUERY,\n variables: {\n slug,\n },\n })\n\n if (error) {\n return { errors: [error.message] }\n }\n\n if (!('product' in data) || data.product === null) {\n return { errors: ['Product with specified url not found'] }\n }\n\n return {\n data,\n }\n } catch (error) {\n // @ts-ignore\n const formattedErrors: ApolloError = isApolloError(error)\n ? error.graphQLErrors.map((error) => error.message)\n : [`Unhandled error : ${error}`]\n\n return {\n errors: formattedErrors,\n }\n }\n}\n```\n\n```text\nexport const getServerSideProps = async (\n context: GetServerSidePropsContext\n) => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const requestData = await getProductFromSlug(context.params.slug as string)\n return 'errors' in requestData\n ? { notFound: true, props: requestData }\n : { props: requestData }\n}\n```\n\n```text\nfunction MyApp(props: AppProps) {\n return (\n <ApolloProvider client={apolloClient}>\n <RecoilRoot>\n <RecoilNexus />\n <AuthenticationFromStorage />\n <Layout>\n <props.Component {...props.pageProps} />\n </Layout>\n </RecoilRoot>\n </ApolloProvider>\n )\n}\n```\n\n```text\nServerError: Response not successful: Received status code 500\n at Object.throwServerError (C:\\Users\\misha\\Documents\\dev\\rekk-next\\node_modules\\@apollo\\client\\link\\utils\\utils.cjs:45:17)\n at C:\\Users\\misha\\Documents\\dev\\rekk-next\\node_modules\\@apollo\\client\\link\\http\\http.cjs:31:19\n at runMicrotasks (<anonymous>)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\nerror - uncaughtException: ServerError: Response not successful: Received status code 500\nerror Command failed with exit code 1.\n```\n\n```text\ngetProductFromSlug\n```\n\n```text\ngetServerSideProps\n```\n\n```text\nyarn run dev\n```\n\n```text\nforward(operation).subscribe({\n next: (data) => {\n ...\n this.subscribeToChannel(subscriptionChannel, observer)\n },\n // these two were missing\n error: (error) => observer.error(error),\n complete: () => observer.complete(),\n })\n```\n\n```text\nsubscribeObservable.subscribe = (observerOrNext, onError, onComplete) => {\n if (typeof(observerOrNext) == \"function\") {\n prevSubscribe(observerOrNext, onError, onComplete)\n } else {\n prevSubscribe(observerOrNext)\n }\n```\n\n```js\nimport { isApolloError } from '@apollo/client';\n...\n const formattedErrors = isApolloError(e)\n ? e.graphQLErrors.map(error => error.message)\n : [`Unhandled error : ${e}`];\n\n return {\n errors: formattedErrors,\n };\n```\n\n```text\nerror\n```\n\n```text\ncomplete\n```\n\n```text\nArray.isArray(apolloError)\n```\n\n```text\nArray.isArray(apolloError.graphQLErrors)\n```\n\n```text\nisApolloError\n```\n\n========================================\n\nComments:\n- How do you want to handle the 500 error on the frontend (as in what should be displayed to the user)? Isn't the error caught in the `catch` block enough?\n- Hi, no even with a try catch, ssr keep crashing\n- could you create an MRE, you can use this URL as the graphql endpoint to get always a 500 error\n- What are the server logs showing in Vercel?\n- I created this repo following the guide and put the same apollo client as yours except for the pusher link. It seems it works since I run `npx next dev -p 3005` with no errors. Maybe try running it without the pusher link and see what happens. However, to replicate it more accurately, please provide the versions of the packages you are using. It could be an issue for a specific version.\n- @diedu Thanks! I'm going to check your repo and if it still doesn't work, I'll make an minimal-reproducible-example\n- @diedu You are right! The issue is caused by the PusherLink, without it, the catch of the error is working good! Thank you very much! If you want to put an answer in order to get the reputation bounty, don't hesitate\n- Would that be a solution for you? Don't you need the PusherLink? if you add the code for that link, I could continue digging into it\n- Unfortunately, I need the pusher link, I need it for subscription with Laravel Lighthouse over Web socket. github.com/apollographql/apollo-client/issues/9427 I don't know why with PusherLink, error are not handled\n- @SirMishaa I think you could overcome the build problem if you exclude the link when the code is executed in the backend as I mention in my answer, but you could get that error in the front end as well. I'll take a look at the PusherLink code and give it a try\n- Hey @SirMishaa, through some intense debugging, I figured out what the problem was. Could you take a look at my updated answer and try again\n- I'm going to try it ! Thanks a lot, you helped me a lot <3\n- Hi, thanks for the response ! Indeed, isApolloError is cleaner but I still have the issue :/. My request is simple, I'm getting a Product entity from the endpoint using the slug of the page, when I enter an invalid slug, SSR is crashing because of the HTTP code 500 error (of the API). But it should absolutely not doing that, I'm using try / catch with your cleaner solution for the error handling... Any idea ?","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":264,"estimatedTokens":2075}}1038{"id":"stack-60740582","source":"stackoverflow","questionId":60740582,"title":"How to use middleware after resolver in graphene?","tags":["python","graphql","graphene-python"],"text":"Title: How to use middleware after resolver in graphene?\nTags: python, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nUsing Graphql in Node, you can use middlewares **BEFORE** or **AFTER** the resolver, using, for example, Prisma.\n\nIn Python, using Graphene, I could only find a way to use middleware **BEFORE** the resolver.\n\nIs there a way to use middlewares **AFTER** the resolver in Python?\n\n========================================\n\nTop Answer:\nYou can use Django middlewares to format output graphql query or mutation\n\n```\nclass FormatOutputMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n # Get the graphql response\n data = json.loads(response.content.decode(\"UTF-8\"))\n\n # do something with data\n\n response.content = json.dumps(data).encode(\"UTF-8\")\n return response\n```\n\n========================================\n\nCode:\n```py\nclass SomeMiddleware(object):\n def resolve(self, next, root, info, **args):\n next_node = next(root, info, **args)\n ...logic...\n return next_node\n```\n\n```py\nclass FormatOutputMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n # Get the graphql response\n data = json.loads(response.content.decode(\"UTF-8\"))\n\n # do something with data\n\n response.content = json.dumps(data).encode(\"UTF-8\")\n return response\n```\n\n========================================\n\nComments:\n- Thanks! And do you know if I can get the answer graphene returns? Or only the data fetched is available?\n- The answer, as in the value returned by the middleware's resolver?\n- No, the answer returned by the graphene. If I ask `{city {id}}` and the resolver returns `{city: {id: 1, name: 'ny'}}`, how can I get the response `{city: {id: 1}}` only? I'm trying to create a middleware to log requests/responses.\n- Oh! Does it? I was under the impression that graphene doesn't bother with resolving fields which have not been requested. The middleware fires after graphene is done with processing the request, so definitely this response gets forwarded to the client, but that's not how graphene works! Are you sure?\n- Yes. The resolver doesn't know what was asked. So it responds with the full data. Then, graphene maps the data and remove what was not asked. But I don't know how to get the final response, with the data already stripped out.\n- @frozenOne thanks for the answer, can you help a bit more, so i basically have a line of code i have to make sure , is executed only once during query lifetime, and that too at the end of query only. but as i put my code after the next_node line, it is being run multiple times , any solution for that??\n- @iron_man83 hey sorry, i saw it late. but did you can add a middleware that only runs post the query has been executed.","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":69,"estimatedTokens":740}}1039{"id":"stack-64932457","source":"stackoverflow","questionId":64932457,"title":"GraphQL Nexus Schema (nexusjs) doesn't compile with scalar types","tags":["graphql","scalar"],"text":"Title: GraphQL Nexus Schema (nexusjs) doesn't compile with scalar types\nTags: graphql, scalar\nSource: Stack Overflow\n\nQuestion:\nI am trying to the documentation on the Nexus-Schema (nexusjs) website for adding scalar types to my GraphQL application.\n\nI have tried adding many of the different implementations to my `src/types/Types.ts` file using the samples provided in the documentation and the interactive examples. My attempts include:\n\nWithout a 3rd party libraries:\n\n```\nconst DateScalar = scalarType({\n name: 'Date',\n asNexusMethod: 'date',\n description: 'Date custom scalar type',\n parseValue(value) {\n return new Date(value)\n },\n serialize(value) {\n return value.getTime()\n },\n parseLiteral(ast) {\n if (ast.kind === Kind.INT) {\n return new Date(ast.value)\n }\n return null\n },\n})\n```\n\nWith `graphql-iso-date` 3rd party library:\n\n```\nimport { GraphQLDate } from 'graphql-iso-date'\nexport const DateTime = GraphQLDate\n```\n\nWith `graphql-scalars` 3rd party library (as shown in the ghost example):\n\n```\nexport const GQLDate = decorateType(GraphQLDate, {\n rootTyping: 'Date',\n asNexusMethod: 'date',\n})\n```\n\nI am using this new scalar type in an object definition like the following:\n\n```\nconst SomeObject = objectType({\n name: 'SomeObject',\n definition(t) {\n t.date('createdAt') // t.date() is supposed to be available because of `asNexusMethod`\n },\n})\n```\n\nIn all cases, these types are exported from the types file and imported into the `makeSchema`'s `types` property.\n\n```\nimport * as types from './types/Types'\n\nconsole.log(\"Found types\", types)\n\nexport const apollo = new ApolloServer({\n schema: makeSchema({\n types,\n ...\n context:()=>(\n ...\n })\n})\n```\n\nThe `console.log` statement above does show that `const`s declared in the types file are in scope:\n\n```\nFound types { \n GQLDate: Date,\n ...\n}\n```\n\nIf I run the app in development mode, everything boots up and runs fine.\n\n```\nts-node-dev --transpile-only ./src/app.ts\n```\n\nHowever, I encounter errors whenever I try to compile the app to deploy to a server\n\n```\nts-node ./src/app.ts && tsc\n```\n\nNote: This error occurs occurs running just `ts-node ./src/app.ts` before it gets to `tsc`\n\nThe errors that shown during the build process are the following:\n\n```\n/Users/user/checkouts/project/node_modules/ts-node/src/index.ts:500\n return new TSError(diagnosticText, diagnosticCodes)\n ^\nTSError: β¨― Unable to compile TypeScript:\nsrc/types/SomeObject.ts:11:7 - error TS2339: Property 'date' does not exist on type 'ObjectDefinitionBlock'.\n\n11 t.date('createdAt')\n```\n\nDoes anyone have any ideas on either:\n\n- a) How can I work around this error? While long-term solutions are ideal, temporary solutions would also be appreciated.\n\n- b) Any steps I could to debug this error? Or ideas on how get additional information to assist with debugging?\n\nAny assistance would be very much welcomed. Thanks!\n\n========================================\n\nCode:\n```text\nconst DateScalar = scalarType({\n name: 'Date',\n asNexusMethod: 'date',\n description: 'Date custom scalar type',\n parseValue(value) {\n return new Date(value)\n },\n serialize(value) {\n return value.getTime()\n },\n parseLiteral(ast) {\n if (ast.kind === Kind.INT) {\n return new Date(ast.value)\n }\n return null\n },\n})\n```\n\n```text\nimport { GraphQLDate } from 'graphql-iso-date'\nexport const DateTime = GraphQLDate\n```\n\n```text\nexport const GQLDate = decorateType(GraphQLDate, {\n rootTyping: 'Date',\n asNexusMethod: 'date',\n})\n```\n\n```text\nconst SomeObject = objectType({\n name: 'SomeObject',\n definition(t) {\n t.date('createdAt') // t.date() is supposed to be available because of `asNexusMethod`\n },\n})\n```\n\n```text\nimport * as types from './types/Types'\n\nconsole.log(\"Found types\", types)\n\nexport const apollo = new ApolloServer({\n schema: makeSchema({\n types,\n ...\n context:()=>(\n ...\n })\n})\n```\n\n```text\nFound types { \n GQLDate: Date,\n ...\n}\n```\n\n```text\nts-node-dev --transpile-only ./src/app.ts\n```\n\n```text\nts-node ./src/app.ts && tsc\n```\n\n```text\n/Users/user/checkouts/project/node_modules/ts-node/src/index.ts:500\n return new TSError(diagnosticText, diagnosticCodes)\n ^\nTSError: β¨― Unable to compile TypeScript:\nsrc/types/SomeObject.ts:11:7 - error TS2339: Property 'date' does not exist on type 'ObjectDefinitionBlock<\"SomeObject\">'.\n\n11 t.date('createdAt')\n```\n\n```text\nsrc/types/Types.ts\n```\n\n```text\ngraphql-iso-date\n```\n\n```text\ngraphql-scalars\n```\n\n```text\nmakeSchema\n```\n\n```text\ntypes\n```\n\n```text\nconsole.log\n```\n\n```text\nconst\n```\n\n```text\nts-node ./src/app.ts\n```\n\n```text\ntsc\n```\n\n```text\nts-node --transpile-only ./src/app.ts\n```\n\n```text\nenv-cmd -f ./config/.env ts-node --transpile-only ./src/app.ts --nexusTypegen && tsc\n```\n\n```text\n--transpile-only\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":249,"estimatedTokens":1192}}1040{"id":"stack-50078774","source":"stackoverflow","questionId":50078774,"title":"Apollo: Extending type from remote schema","tags":["graphql","apollo","graphql-js","react-apollo","apollo-client"],"text":"Title: Apollo: Extending type from remote schema\nTags: graphql, apollo, graphql-js, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI currently have multiple GraphQL services running Apollo and have created a \"Gateway\" service that uses remote schema stitching in order to give me a single endpoint for access.\n\nWithin my Gateway service I am looking to extend the remote types to create references between the stitched schemas.\n\n```\nconst linkTypeDefs = `\n extend type User {\n profile: Profile\n }\n\n extend type Profile {\n user: User\n }`;\n\nconst schema = mergeSchemas({\n schemas: [userSchema, profileSchema, linkTypeDefs],\n resolvers: /* Resolvers */\n});\n```\n\nHowever I seem to be getting the following error:\n\n GraphQLError: Cannot extend type \"User\" because it does not exist in the existing schema.\n\nI have double checked and the type \"User\" and \"Profile\" exist and I can query them from the Gateway Graphiql.\n\nAre there any particular steps I need to take in order to extend types merged from a remote schema?\n\n========================================\n\nCode:\n```text\nconst linkTypeDefs = `\n extend type User {\n profile: Profile\n }\n\n extend type Profile {\n user: User\n }`;\n\nconst schema = mergeSchemas({\n schemas: [userSchema, profileSchema, linkTypeDefs],\n resolvers: /* Resolvers */\n});\n```\n\n```text\nuserSchema\n```\n\n```text\nprofileSchema\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":59,"estimatedTokens":348}}1041{"id":"stack-55902220","source":"stackoverflow","questionId":55902220,"title":"AssertionError: Found different types with the same name in the schema","tags":["python","graphql","graphene-python","graphene-sqlalchemy"],"text":"Title: AssertionError: Found different types with the same name in the schema\nTags: python, graphql, graphene-python, graphene-sqlalchemy\nSource: Stack Overflow\n\nQuestion:\nI have two classes: Products and SalableProducts in my models (SalableProducts inherits from Products so it has every field of it's database). Here is my schema down below\n\nI tried including the \"exclude_fields\" property but that didn't work\n\n**Product_schema.py:**\n\n```\nclass Product(SQLAlchemyObjectType):\n class Meta:\n model = ProductModel\n interfaces = (relay.Node, )\n\nclass ProductConnections(relay.Connection):\n class Meta:\n node = Product\n```\n\n**Salable_product_schema.py:**\n\n```\nclass SalableProduct(SQLAlchemyObjectType):\n class Meta:\n model = SalableProductModel\n interfaces = (relay.Node, )\n\nclass SalableProductConnections(relay.Connection):\n class Meta:\n node = SalableProduct\n```\n\n**Schema.py:**\n\n```\nclass Query(graphene.ObjectType):\n node = relay.Node.Field()\n all_products = SQLAlchemyConnectionField(ProductConnections)\n all_salable_products = \n SQLAlchemyConnectionField(SalableProductConnections)\n```\n\nThe result is this error : \n\n AssertionError: Found different types with the same name in the schema: product_status, product_status.\n\n(product_status is a propery shared by the two classes by inheritance)\n\n========================================\n\nCode:\n```py\nclass Product(SQLAlchemyObjectType):\n class Meta:\n model = ProductModel\n interfaces = (relay.Node, )\n\nclass ProductConnections(relay.Connection):\n class Meta:\n node = Product\n```\n\n```py\nclass SalableProduct(SQLAlchemyObjectType):\n class Meta:\n model = SalableProductModel\n interfaces = (relay.Node, )\n\nclass SalableProductConnections(relay.Connection):\n class Meta:\n node = SalableProduct\n```\n\n```py\nclass Query(graphene.ObjectType):\n node = relay.Node.Field()\n all_products = SQLAlchemyConnectionField(ProductConnections)\n all_salable_products = \n SQLAlchemyConnectionField(SalableProductConnections)\n```\n\n```text\ntechniques = SQLAlchemyConnectionField(TechniqueConnection)\nbelts = SQLAlchemyConnectionField(BeltConnection)\nbelt_techniques = SQLAlchemyConnectionField(BeltTechniqueConnections)\n```\n\n========================================\n\nComments:\n- I had the error too. I had a field in my models.py that I was named it `type`. It seemse to `type` is a reserved word\n- I too had the same error. Just renamed the class and it worked. Thanks. @chelista","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":95,"estimatedTokens":605}}1042{"id":"stack-55871899","source":"stackoverflow","questionId":55871899,"title":"GraphQL request error - Unknown argument 'slug'","tags":["reactjs","graphql","gatsby"],"text":"Title: GraphQL request error - Unknown argument 'slug'\nTags: reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI am trying to link my index.js page to an article template to display the data from a middleware Drupal site using a slug and `createPages`. I have the data displaying correctly on my index.js page and my `createPages` seems to not have any errors after changing the file path to `./src/templates/article.js`.\n\nI am running into this GraphQL error while compiling:\n\n error GraphQL Error There was an error while compiling your site's\n GraphQL queries. Error: RelayParser: Encountered 1 error(s):\n - Unknown argument 'slug'. Source: document `usersBrooksrelytHtdocsRepositoryGatsbyGraphqlGatsbySrcTemplatesArticleJs4119530598`\n file: `GraphQL request`\n\n```\nGraphQL request (3:12)\n 2: query($slug: String!) {\n 3: umdHub(slug: { eq: $slug }) {\n ^\n 4: articles {\n```\n\nMy article.js code:\n\n```\nimport React from 'react'\nimport { graphql } from 'gatsby'\nimport { ListGroup, ListGroupItem } from 'reactstrap';\n\n// eslint-disable-next-line\nimport Layout from \"../components/layout\"\nimport Header from \"../components/header\"\nimport Footer from \"../components/footer\"\n\nexport default ({ data }) => {\n return (\n \n \n \n \n \n \n \n \n- Highlighted\n \n- Innovation\n \n- Web Only\n \n- February 28, 2019\n \n \n \n\n### {data.title}\n\n {data.hero_image.map((hero, i) => (\n \n \n \n ))}\n \n \n \n\n### {data.subtitle}\n\n \n By Jane Doe | Photos by ISTOCK\n\n \n \n \n Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\n tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\n quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\n consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\n cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\n proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\n \n \n \n \n \n \n \n Recent Posts\n Dapibus ac facilisis in\n February 27, 2019\n Morbi leo risus\n February 27, 2019\n Porta ac consectetur ac\n February 27, 2019\n Vestibulum at eros\n February 27, 2019\n \n \n \n \n \n\n \n \n\n )\n}\n\nexport const query = graphql`\n query($slug: String!) {\n umdHub(slug: { eq: $slug }) {\n articles {\n data {\n id\n title\n subtitle\n body\n summary\n hero_image {\n url_1200_630\n }\n authorship_date {\n formatted_short\n unix\n unix_int\n formatted_long\n formatted_short\n time\n }\n slug\n }\n }\n }\n }\n`\n```\n\nMy gatsby-node.js:\n\n```\nconst path = require(`path`)\n\nexports.createPages = ({ graphql, actions }) => {\n const { createPage } = actions\n const articleTemplate = path.resolve(`./src/templates/article.js`)\n return graphql(`\n {\n umdHub {\n articles {\n data {\n id\n title\n subtitle\n body\n summary\n hero_image {\n url_1200_630\n }\n authorship_date {\n formatted_short\n unix\n unix_int\n formatted_long\n formatted_short\n time\n }\n slug\n }\n }\n }\n }\n `).then(result => {\n if (result.errors) {\n throw result.errors\n }\n\n result.data.umdHub.articles.data.forEach(data => {\n createPage({\n path: `${data.slug}`,\n component: articleTemplate,\n context: {\n\n },\n })\n })\n })\n}\n```\n\n========================================\n\nCode:\n```text\nGraphQL request (3:12)\n 2: query($slug: String!) {\n 3: umdHub(slug: { eq: $slug }) {\n ^\n 4: articles {\n```\n\n```text\nimport React from 'react'\nimport { graphql } from 'gatsby'\nimport { ListGroup, ListGroupItem } from 'reactstrap';\n\n// eslint-disable-next-line\nimport Layout from \"../components/layout\"\nimport Header from \"../components/header\"\nimport Footer from \"../components/footer\"\n\n\nexport default ({ data }) => {\n return (\n <div>\n <Header />\n <div className=\"container spaces article\">\n <div className=\"row\">\n <section className=\"col-md-9\">\n <div className=\"tag-list\">\n <ul class=\"list-inline\">\n <li class=\"list-inline-item\"><a href=\"/\">Highlighted</a></li>\n <li class=\"list-inline-item\"><a href=\"/\">Innovation</a></li>\n <li class=\"list-inline-item\"><a href=\"/\">Web Only</a></li>\n <li class=\"list-inline-item\">February 28, 2019</li>\n </ul>\n </div>\n <h1>{data.title}</h1>\n {data.hero_image.map((hero, i) => (\n <div key={i}>\n <img className=\"img-fluid no-pad-top med-spaces\" src={hero.url_1200_630} alt=\" \" />\n </div>\n ))}\n <div className=\"row article-content\">\n <div className=\"col-md-10 offset-md-1\">\n <h2 className=\"subheader\">{data.subtitle}</h2>\n <div className=\"author\"> \n <p>By <a href=\"/\">Jane Doe</a> | Photos by <a href=\"/\">ISTOCK</a></p>\n <hr />\n </div>\n <div>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\n tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\n quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\n consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\n cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\n proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n </div>\n </div>\n </div>\n </section>\n <aside className=\"col-md-3\">\n <div>\n <ListGroup flush>\n <ListGroupItem disabled tag=\"a\" href=\"#\">Recent Posts</ListGroupItem>\n <ListGroupItem tag=\"a\" href=\"#\">Dapibus ac facilisis in</ListGroupItem>\n <span>February 27, 2019</span>\n <ListGroupItem tag=\"a\" href=\"#\">Morbi leo risus</ListGroupItem>\n <span>February 27, 2019</span>\n <ListGroupItem tag=\"a\" href=\"#\">Porta ac consectetur ac</ListGroupItem>\n <span>February 27, 2019</span>\n <ListGroupItem tag=\"a\" href=\"#\">Vestibulum at eros</ListGroupItem>\n <span>February 27, 2019</span>\n </ListGroup>\n </div>\n </aside>\n </div>\n </div>\n\n\n <Footer />\n </div>\n\n )\n}\n\n\nexport const query = graphql`\n query($slug: String!) {\n umdHub(slug: { eq: $slug }) {\n articles {\n data {\n id\n title\n subtitle\n body\n summary\n hero_image {\n url_1200_630\n }\n authorship_date {\n formatted_short\n unix\n unix_int\n formatted_long\n formatted_short\n time\n }\n slug\n }\n }\n }\n }\n`\n```\n\n```text\nconst path = require(`path`)\n\nexports.createPages = ({ graphql, actions }) => {\n const { createPage } = actions\n const articleTemplate = path.resolve(`./src/templates/article.js`)\n return graphql(`\n {\n umdHub {\n articles {\n data {\n id\n title\n subtitle\n body\n summary\n hero_image {\n url_1200_630\n }\n authorship_date {\n formatted_short\n unix\n unix_int\n formatted_long\n formatted_short\n time\n }\n slug\n }\n }\n }\n }\n `).then(result => {\n if (result.errors) {\n throw result.errors\n }\n\n result.data.umdHub.articles.data.forEach(data => {\n createPage({\n path: `${data.slug}`,\n component: articleTemplate,\n context: {\n\n },\n })\n })\n })\n}\n```\n\n```text\ncreatePages\n```\n\n```text\ncreatePages\n```\n\n```text\n./src/templates/article.js\n```\n\n```text\nusersBrooksrelytHtdocsRepositoryGatsbyGraphqlGatsbySrcTemplatesArticleJs4119530598\n```\n\n```text\nGraphQL request\n```\n\n```text\nexport const query = graphql`\n query($slug: String!) {\n\n- umdHub(slug: { eq: $slug }) {\n+ umdHub(articles: { data: { slug: { eq: $slug } } }) {\n\n articles {\n data {\n slug\n }\n }\n }\n }\n```\n\n```text\nfilter\n```\n\n```text\numdHub\n```\n\n```text\narticles\n```\n\n```text\nslug\n```\n\n```text\numdHub\n```\n\n```text\numdHub.articles.data\n```\n\n========================================\n\nComments:\n- Hope useful: stackoverflow.com/a/55930667/8585114\n- Still getting the error on 'articles' in `umdHub(articles: { data: { slug: { eq: $slug } } }) {`\n- @brooksrelyt what error are you getting for articles?\n- `error GraphQL Error There was an error while compiling your site's GraphQL queries. Error: RelayParser: Encountered 1 error(s): - Unknown argument 'articles'. Source: document`usersBrooksrelytHtdocsRepositoryGatsbyGraphqlGatsbySrcTempla‌​tesArticleJs13609343‌​19` file: `GraphQL request` GraphQL request (3:12) 2: query($slug: String!) { 3: umdHub(articles: { data: { slug: { eq: $slug } } }) { ^ 4: articles {`\n- @brooksrelyt it looks like `umdHub` doesn't support filter & search. How did you create `umdHub`, or which cms / plugin created it for you?\n- @brooksrelyt it looks like my answer got awarded the bounty even though it didn't solve your problem. Ping me the next time you run into a difficult problem & I will add a bounty there for you!\n- You have answered more than one of my questions and have gotten me out of a few confusing situations. I owe you. I have learned a lot about querying even if it hasnβt helped this specific issue. I learned that it is not working because an outside development agency created their own GraphQL iteration, that they even said doesnβt work well with gatsby. I was emailed this on Tuesday\n- @brooksrelyt I'm glad my answers were helpful & you have figured out the problems. Good luck with your project!","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":427,"estimatedTokens":2460}}1043{"id":"stack-55423439","source":"stackoverflow","questionId":55423439,"title":"graphql-tools difference between mergeSchemas and makeExecutableSchema","tags":["graphql","apollo-server","graphql-tools"],"text":"Title: graphql-tools difference between mergeSchemas and makeExecutableSchema\nTags: graphql, apollo-server, graphql-tools\nSource: Stack Overflow\n\nQuestion:\nSo the reason I am asking this question is because I can get both of these to return a working result with just replacing one or the other. So which is the right one to use and why? \n\nWhat are their purposes in regards to schemas?\n\n```\nimport { mergeSchemas } from 'graphql-tools'\n\nimport bookSchema from './book/schema/book.gql'\nimport bookResolver from './book/resolvers/book'\n\nexport const schema = mergeSchemas({\n schemas: [bookSchema],\n resolvers: [bookResolver]\n})\n```\n\n```\nimport { makeExecutableSchema } from 'graphql-tools'\n\nimport bookSchema from './book/schema/book.gql'\nimport bookResolver from './book/resolvers/book'\n\nexport const schema = makeExecutableSchema({\n typeDefs: [bookSchema],\n resolvers: [bookResolver]\n})\n```\n\nBoth of these examples work and return the desired outcome. I believe the correct one to use here is the `makeExecutableSchema` but not sure why the first one would work?\n\n**EDIT**\nJust incase it would be nice to have the types/resolvers:\n\n**typeDefs**\n\n```\ntype Query {\n book(id: String!): Book\n bookList: [Book]\n}\n\ntype Book {\n id: String\n name: String\n genre: String\n}\n```\n\n**Resolvers**\n\n```\nexport default {\n Query: {\n book: () => {\n return {\n id: `1`,\n name: `name`,\n genre: `scary`\n }\n },\n bookList: () => {\n return [\n { id: `1`, name: `name`, genre: `scary` },\n { id: `2`, name: `name`, genre: `scary` }\n ]\n }\n }\n}\n```\n\n**Query Ran**\n\n```\nquery {\n bookList{\n id\n name\n genre\n }\n}\n```\n\n**Result**\n\n```\n{\n \"data\": {\n \"bookList\": [\n {\n \"id\": \"1\",\n \"name\": \"name\",\n \"genre\": \"scary\"\n },\n {\n \"id\": \"2\",\n \"name\": \"name\",\n \"genre\": \"scary\"\n }\n ]\n }\n}\n```\n\n========================================\n\nTop Answer:\nYes `makeExecutableSchema creates a GraphQL.js GraphQLSchema instance from GraphQL schema language` as per graphql-tools docs So if you are creating stand alone, contained GrpaphQL service is a way to go.\n\nBut if you are looking to consolidate multiple GraphQL services there are multiple different strategies you may consider such as schema-stitching, schema-merging from graphql-tools or federation from apollo (there are probably more).\n\nSince I landed here while searching what is the difference between `stitching` and `merging` I wanted to point out that they are not one and the same thing. Here is the answer I got for this question on graphql-tools github.\n\n========================================\n\nCode:\n```text\nimport { mergeSchemas } from 'graphql-tools'\n\nimport bookSchema from './book/schema/book.gql'\nimport bookResolver from './book/resolvers/book'\n\nexport const schema = mergeSchemas({\n schemas: [bookSchema],\n resolvers: [bookResolver]\n})\n```\n\n```text\nimport { makeExecutableSchema } from 'graphql-tools'\n\nimport bookSchema from './book/schema/book.gql'\nimport bookResolver from './book/resolvers/book'\n\nexport const schema = makeExecutableSchema({\n typeDefs: [bookSchema],\n resolvers: [bookResolver]\n})\n```\n\n```text\ntype Query {\n book(id: String!): Book\n bookList: [Book]\n}\n\ntype Book {\n id: String\n name: String\n genre: String\n}\n```\n\n```text\nexport default {\n Query: {\n book: () => {\n return {\n id: `1`,\n name: `name`,\n genre: `scary`\n }\n },\n bookList: () => {\n return [\n { id: `1`, name: `name`, genre: `scary` },\n { id: `2`, name: `name`, genre: `scary` }\n ]\n }\n }\n}\n```\n\n```text\nquery {\n bookList{\n id\n name\n genre\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"bookList\": [\n {\n \"id\": \"1\",\n \"name\": \"name\",\n \"genre\": \"scary\"\n },\n {\n \"id\": \"2\",\n \"name\": \"name\",\n \"genre\": \"scary\"\n }\n ]\n }\n}\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nmergeSchemas\n```\n\n```text\nmergeSchemas\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\nmergeSchemas\n```\n\n```text\nmergeSchemas\n```\n\n```text\nmakeExecutableSchema creates a GraphQL.js GraphQLSchema instance from GraphQL schema language\n```\n\n```text\nstitching\n```\n\n```text\nmerging\n```\n\n========================================\n\nComments:\n- Note that within the newer versions of GraphQL tools, the stitching function has been renamed `stitchSchemas` while `mergeSchemas` now does what you would expect, merging schemas directly without a proxy layer, (based on the functionality from GraphQL toolkit). The API for schema stitching has been much improved, but you should still avoid adding a proxy layer (if you don't need to).","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":250,"estimatedTokens":1167}}1044{"id":"stack-56832712","source":"stackoverflow","questionId":56832712,"title":"React Gatsbyjs add class to gatsby-image based on aspect ratio","tags":["javascript","reactjs","graphql","gatsby"],"text":"Title: React Gatsbyjs add class to gatsby-image based on aspect ratio\nTags: javascript, reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\ngatsby-image wraps each image with a gatsby-image-wrapper div which fills 100% of the available viewport width. This wrapper div can easily be styled with CSS but **there is no way to treat landscape, portrait or square images differently from each other.**\n\n What if, you wanted to have landscape images fill 80%-100% of the available width but have portrait and square images fill no more than 40-50% of the viewport width.\n\nSo ideally each gatsby-image-wrapper div gets a class added depending on its aspect ratio, which would be either; `landscape`, `portrait` or `square`.\n\nOne way to do this could be to write some conditional statement using the aspect ratio that comes with childImageSharp:\n\n```\nedges {\n node {\n name\n childImageSharp {\n fluid(maxWidth: 915, quality: 90) {\n aspectRatio\n ...GatsbyImageSharpFluid_withWebp\n }\n }\n }\n }\n```\n\nWhen I map over all my gallery images, I can grab the aspect ratio and add it to each gatsby-image-wrapper using className but it's not very useful in its raw format as the returned data for aspectRatio are numbers like `0.6666666666666666` for portrait images or `1.5003750937734435` for landscape. Having those classes mentioned above would be better to work with; `landscape`, `portrait` or `square`.\n\nThis is how I'm getting all my gallery images from the current post, along with their `aspectRatio`.\n\n```\nexport default ({ data }) => {\n return (\n \n \n {data.allFile.edges.map(({ node }, index) => (\n \n \n {node.childImageSharp.fluid.aspectRatio}\n \n ))}\n \n \n );\n};\n```\n\nThe full GraphQL query I am using is:\n\n```\nexport const query = graphql`\n query($slug: String!, $absolutePathRegex: String!) {\n markdownRemark(fields: { slug: { eq: $slug } }) {\n html\n frontmatter {\n title\n date\n modified\n caption\n description\n cover {\n publicURL\n childImageSharp {\n fluid(maxWidth: 915, quality: 90) {\n ...GatsbyImageSharpFluid_withWebp\n }\n }\n }\n }\n fields {\n slug\n }\n }\n allFile(\n filter: {\n extension: { regex: \"/(jpg)|(png)|(tif)|(tiff)|(webp)|(jpeg)/\" }\n absolutePath: { regex: $absolutePathRegex }\n }\n ) {\n edges {\n node {\n name\n childImageSharp {\n fluid(maxWidth: 915, quality: 90) {\n aspectRatio\n ...GatsbyImageSharpFluid_withWebp\n }\n }\n }\n }\n }\n }\n`;\n```\n\nThere must be a simple solution to this using a conditional statement in React where you map over all your images, take the aspect ratio\nand then convert the raw data to the desired classes.\n\nSo instead of:\n\n```\n\n```\n\nYou'd get:\n\n```\n\n```\n\nWhich could then be easily styled with css.\n\n========================================\n\nCode:\n```text\nedges {\n node {\n name\n childImageSharp {\n fluid(maxWidth: 915, quality: 90) {\n aspectRatio\n ...GatsbyImageSharpFluid_withWebp\n }\n }\n }\n }\n```\n\n```text\nexport default ({ data }) => {\n return (\n <Layout>\n <article>\n {data.allFile.edges.map(({ node }, index) => (\n <div>\n <Img\n key={index}\n className={node.childImageSharp.fluid.aspectRatio}\n alt={node.name}\n fluid={node.childImageSharp.fluid}\n />\n <span>{node.childImageSharp.fluid.aspectRatio}</span>\n </div>\n ))}\n </article>\n </Layout>\n );\n};\n```\n\n```text\nexport const query = graphql`\n query($slug: String!, $absolutePathRegex: String!) {\n markdownRemark(fields: { slug: { eq: $slug } }) {\n html\n frontmatter {\n title\n date\n modified\n caption\n description\n cover {\n publicURL\n childImageSharp {\n fluid(maxWidth: 915, quality: 90) {\n ...GatsbyImageSharpFluid_withWebp\n }\n }\n }\n }\n fields {\n slug\n }\n }\n allFile(\n filter: {\n extension: { regex: \"/(jpg)|(png)|(tif)|(tiff)|(webp)|(jpeg)/\" }\n absolutePath: { regex: $absolutePathRegex }\n }\n ) {\n edges {\n node {\n name\n childImageSharp {\n fluid(maxWidth: 915, quality: 90) {\n aspectRatio\n ...GatsbyImageSharpFluid_withWebp\n }\n }\n }\n }\n }\n }\n`;\n```\n\n```text\n<div class=\"1.5003750937734435 gatsby-image-wrapper\"></div>\n<div class=\"0.6666666666666666 gatsby-image-wrapper\"></div>\n<div class=\"0.6666666666666666 gatsby-image-wrapper\"></div>\n<div class=\"1.0000000000000000 gatsby-image-wrapper\"></div>\n<div class=\"1.5003750937734435 gatsby-image-wrapper\"></div>\n```\n\n```text\n<div class=\"landscape gatsby-image-wrapper\"></div>\n<div class=\"portrait gatsby-image-wrapper\"></div>\n<div class=\"portrait gatsby-image-wrapper\"></div>\n<div class=\"square gatsby-image-wrapper\"></div>\n<div class=\"landscape gatsby-image-wrapper\"></div>\n```\n\n```text\nlandscape\n```\n\n```text\nportrait\n```\n\n```text\nsquare\n```\n\n```text\n0.6666666666666666\n```\n\n```text\n1.5003750937734435\n```\n\n```text\nlandscape\n```\n\n```text\nportrait\n```\n\n```text\nsquare\n```\n\n```text\naspectRatio\n```\n\n```js\nimport React from 'react'\nimport Img from 'gatsby-image'\n\n// we only care about `aspectRatio`, the rest will be passed directly to `Img`\n// also take out `className` so it be merged with our generated `orientation` class name\nconst ImgWithOrient = ({ aspectRatio, className, ...props }) => {\n let orientation\n if (aspectRatio > 1) orientation = 'landscape'\n if (aspectRatio < 1) orientation = 'portrait'\n else orientation = 'square'\n\n return <Img className={`${className} ${orientation}`} {...props} />\n}\n\nexport default ({ data }) => {\n return (\n <Layout>\n <article>\n {data.allFile.edges.map(({ node }, index) => (\n <div key={index}>\n <ImgWithOrient\n key={index}\n aspectRatio={node.childImageSharp.fluid.aspectRatio}\n className=\"other class name\"\n alt={node.name}\n fluid={node.childImageSharp.fluid}\n />\n <span>{node.childImageSharp.fluid.aspectRatio}</span>\n </div>\n ))}\n </article>\n </Layout>\n )\n}\n```\n\n```text\nmap\n```\n\n```text\n<Img>\n```\n\n```text\nkey\n```\n\n```text\n<div>\n```\n\n```text\n<Img>\n```\n\n========================================\n\nComments:\n- Thanks Derek, your answer got this working. I had to play around with the less/greater than operators a bit to get the desired outcome. This is what I have based on your code: `const ImgWithOrient = ({ aspectRatio, className, ...props }) => { let orientation; if (aspectRatio >= 1.2) orientation = \"landscape\"; if (aspectRatio 0.8 && aspectRatio ; };`","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":311,"estimatedTokens":1676}}1045{"id":"stack-45844302","source":"stackoverflow","questionId":45844302,"title":"Relay based Pagination in Java for Java-GraphQL server","tags":["java","pagination","graphql","relay","graphql-java"],"text":"Title: Relay based Pagination in Java for Java-GraphQL server\nTags: java, pagination, graphql, relay, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI have implemented a java based GraphQL server using the GraphQL-Java-tools. Now I need to implement the Relay based pagination with the Java-GraphQL server that I have. \n\nI couldn't find anything helpful out there. Can anyone please help me in pointing out to the right place to find how to implement Relay based Pagination in Java_GraphQL server? \n\nThanks in anticipation.\n\n========================================\n\nCode:\n```text\ntype Query {\n users(first: Int, after: String): UserConnection @connection(for: \"User\")\n}\n\ntype User {\n id: ID!\n name: String\n}\n```\n\n```text\nclass QueryResolver implements GraphQLQueryResolver {\n\n public Connection<User> users(int first, String after, DataFetchingEnvironment env) {\n return new SimpleListConnection<>(Collections.singletonList(new User(1L, \"Luke\"))).get(env);\n }\n}\n```\n\n```text\n@connection\n```\n\n```text\nConnection<T>\n```\n\n```text\nSimpleListConnection\n```\n\n========================================\n\nComments:\n- ...and that's quite a pity because this `SimpleListConnection` expects you to provide the whole list of the enclosed entities... which is uppermost counterproductive in terms of requesting the database!!","metadata":{"transformedAt":"2026-08-18T18:32:36.223Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":50,"estimatedTokens":332}}1046{"id":"stack-48202002","source":"stackoverflow","questionId":48202002,"title":"GraphQL: best way to manage mutations with interfaces?","tags":["interface","graphql","apollo","mutation"],"text":"Title: GraphQL: best way to manage mutations with interfaces?\nTags: interface, graphql, apollo, mutation\nSource: Stack Overflow\n\nQuestion:\nI'am new to GraphQL but I really like it. Now that I'am playing with interfaces and unions, I'am facing a problem with mutations.\n\nSuppose that I have this schema :\n\n```\ninterface FoodType {\n id: String\n type: String\n}\n\ntype Pizza implements FoodType {\n id: String\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n}\n\ntype Salad implements FoodType {\n id: String\n type: String\n vegetarian: Boolean\n dressing: Boolean\n}\n\ntype BasicFood implements FoodType {\n id: String\n type: String\n}\n```\n\nNow, I'd like to create new food items, so I started doing something like this :\n\n```\ntype Mutation {\n addPizza(input:Pizza):FoodType\n addSalad(input:Salad):FoodType\n addBasic(input:BasicFood):FoodType\n}\n```\n\nThis did not work for 2 reasons :\n\n- If I want to pass an object as parameter, this one must be an \"input\" type. But \"Pizza\", \"Salad\" and \"BasicFood\" are just \"type\".\n\n- An input type cannot implement an interface.\n\nSo, my question is : How do you work with mutations in this context of interface without having to duplicate types too much? I'd like to avoid having a Pizza type for queries and an InputPizza type for mutations.\n\nThank you for your help.\n\n========================================\n\nCode:\n```text\ninterface FoodType {\n id: String\n type: String\n}\n\ntype Pizza implements FoodType {\n id: String\n type: String\n pizzaType: String\n toppings: [String]\n size: String\n}\n\ntype Salad implements FoodType {\n id: String\n type: String\n vegetarian: Boolean\n dressing: Boolean\n}\n\ntype BasicFood implements FoodType {\n id: String\n type: String\n}\n```\n\n```text\ntype Mutation {\n addPizza(input:Pizza):FoodType\n addSalad(input:Salad):FoodType\n addBasic(input:BasicFood):FoodType\n}\n```\n\n```text\nPizza\n```\n\n```text\nPizzaInput\n```\n\n```text\nPizza\n```\n\n```text\nPizzaInput\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":109,"estimatedTokens":486}}1047{"id":"stack-54351176","source":"stackoverflow","questionId":54351176,"title":"Gatsby.js - GraphQL Query pdf file in allMarkdownRemark","tags":["javascript","reactjs","graphql","gatsby"],"text":"Title: Gatsby.js - GraphQL Query pdf file in allMarkdownRemark\nTags: javascript, reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI am currently building a gatsby site for a school project and came across something I couldn't figure out myself.\n\nBasically I have some markdown files. They contain a frontmatter field called 'file' with the name of another file (for example: \"test.pdf\") as value.\nI need to know the public URL of these files.\n\nI tried to write my Query like this:\n\n```\nquery SiteQuery{\n publications: allMarkdownRemark(\n filter: { fileAbsolutePath: {regex : \"/publications/\"} },\n sort: { order: DESC, fields: [frontmatter___date] },\n ){\n edges {\n node {\n frontmatter {\n date(formatString: \"MMMM DD, YYYY\"),\n title,\n file{\n publicURL \n }\n }\n }\n }\n }\n }\n```\n\nBut it always interpreted the field 'file' as string, which I think is strange since I've already did the same procedure with images like this:\n\n```\n...\n node {\n frontmatter {\n date(formatString: \"MMMM DD, YYYY\"),\n title,\n picture {\n childImageSharp {\n fluid{\n ...GatsbyImageSharpFluid\n }\n }\n }\n } \n } \n...\n```\n\nI've already searched for an answer, but the most helpful result I could find was on this site: https://www.gatsbyjs.org/docs/adding-images-fonts-files/\n\nBut I couldn't make it work. \n\nCan somebody tell me what I am doing wrong here?\n\nOf course I could always write a second query with 'allFile' and then match the markdown file with the pdf file by absolute paths but I hope there's a better solution than that.\n\n========================================\n\nCode:\n```js\nquery SiteQuery{\n publications: allMarkdownRemark(\n filter: { fileAbsolutePath: {regex : \"/publications/\"} },\n sort: { order: DESC, fields: [frontmatter___date] },\n ){\n edges {\n node {\n frontmatter {\n date(formatString: \"MMMM DD, YYYY\"),\n title,\n file{\n publicURL \n }\n }\n }\n }\n }\n }\n```\n\n```js\n...\n node {\n frontmatter {\n date(formatString: \"MMMM DD, YYYY\"),\n title,\n picture {\n childImageSharp {\n fluid{\n ...GatsbyImageSharpFluid\n }\n }\n }\n } \n } \n...\n```\n\n```js\n// NOTE: the frontmatter `file` and property `base` must have unique values\n// That is, don't allow any files to have the same name if mapping `base`\nmapping: {\n 'MarkdownRemark.frontmatter.file' : 'File.base',\n}\n```\n\n```text\nquery SiteQuery{\n publications: allMarkdownRemark(\n filter: { fileAbsolutePath: {regex : \"/publications/\"} }\n sort: { order: DESC, fields: [frontmatter___date] }\n ){\n edges {\n node {\n frontmatter {\n date(formatString: \"MMMM DD, YYYY\")\n title\n file {\n publicURL \n }\n }\n }\n }\n }\n}\n```\n\n```text\nmapping\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":135,"estimatedTokens":776}}1048{"id":"stack-40897613","source":"stackoverflow","questionId":40897613,"title":"Returning error from GrapQL-Java","tags":["java","error-handling","graphql","graphql-java"],"text":"Title: Returning error from GrapQL-Java\nTags: java, error-handling, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI would like to validate input provided by user during mutation and then provide errors if there are some invalid fields provided.\n\nThere is a question which answers the question for GraphQL-JS here\n\nI want to ask this question about implementation using GraphQL-Java.\n\nLet's say you have a form which posts data to API server. The API server validates the input and returns JSON object. If the input is invalid an error objects like the one below is returned.\n\n`{errors: {field1: \"is required\"}}`\n\nHow do we handle and serve these kind of errors when using GraphQL? How and where should data validation be implemented (should that be part of GraphQL or should it be inside each resolve function)?\n\n========================================\n\nCode:\n```text\n{errors: {field1: \"is required\"}}\n```\n\n```text\nList<ValidationError> errors = validator.validateDocument(graphQLSchema, requestString);\nif (!errors.isEmpty()) { return executeError(errors); }\n```\n\n```text\ngraphql.validation.Validatior\n```\n\n```text\nList<ValidationError>\n```\n\n========================================\n\nComments:\n- Just a note. Any valid GraphQL implementation, graphql-java included, will validate each query by itself, and an invalid query will never trigger execution. The question is only how customizable is the error-handling behavior.","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":41,"estimatedTokens":359}}1049{"id":"stack-69330412","source":"stackoverflow","questionId":69330412,"title":"How do you handle lists that require joined data from multiple data sources in AppSync/GraphQL?","tags":["graphql","aws-appsync","aws-appsync-resolver"],"text":"Title: How do you handle lists that require joined data from multiple data sources in AppSync/GraphQL?\nTags: graphql, aws-appsync, aws-appsync-resolver\nSource: Stack Overflow\n\nQuestion:\n```\ntype Employee {\n id: String!\n name: String\n lastObservedStatus: String\n}\n\ntype Query {\n employees: [Employee]\n}\n```\n\nThis is a fictional schema to illustrate my question. I have two separate data sources that return lists that need to be joined in order to populate the response. The first data source 'employee list api' is an http API I can query to get an authoritative list of employees that I can use to populate the `id` and `name` columns. For example, I get a response like this:\n\n```\n[\n {\"id\": \"001\", \"name\": \"Harry\"},\n {\"id\": \"002\", \"name\": \"Jerry\"},\n {\"id\": \"003\", \"name\": \"Larry\"}\n]\n```\n\nI have a second http API 'employee observation log' I can query to get a list of statuses together with the associated ids. The id allows me to associate the number to an entry in the employee record, and I have a record date. There may be more than one status record, but in GraphQL I want to pick only the most recent one. Example response:\n\n```\n[\n {\"id\":\"002\", \"TimeStamp\":\"2021-07-01T12:30:00Z\", \"status\": \"eating\"},\n {\"id\":\"002\", \"TimeStamp\":\"2021-07-01T13:10:00Z\", \"status\": \"staring out the window\"},\n {\"id\":\"001\", \"TimeStamp\":\"2021-07-01T16:00:00Z\", \"status\": \"sleeping in lobby\"}\n]\n```\n\nNow, I want the graphQL response to return something like this:\n\n```\n{\n \"data\": {\n \"employees\": [\n {\n \"id\": \"001\",\n \"name\": \"Harry\",\n \"lastObservedStatus\": \"sleeping in lobby\"\n },\n {\n \"id\": \"002\",\n \"name\": \"Jerry\",\n \"lastObservedStatus\": \"staring out the window\"\n },\n {\n \"id\": \"003\",\n \"name\": \"Larry\",\n \"lastObservedStatus\": null\n }\n ]\n }\n}\n```\n\nSince 'employee list api' is the authoritative source about which employees exist, all queries to the 'employee' field should always trigger a query to that api, but the 'employee observation log' api should only be triggered if the 'lastObservedStatus' field is selected in the query.\n\nFor a schema like this, where should the resolvers be registered? I've read that the best practice is to always attach resolvers at the leaf nodes, but I'm not sure how that can be done in this situation. I'm not even sure what happens if you attach a resolver on subfields of a list.\n\nI feel like the correct way to handle this is to attach a lambda resolver to the `employees` field, and in the lambda resolver check the query's selectionSetList to check whether or not the 'lastObservedStatus' field has been selected. If not, then the lambda only queries 'employee list api', but otherwise the lambda also queries 'employee observation log' and does something similar to a SQL join before returning the result. But is that the correct way to handle this?\n\n========================================\n\nCode:\n```text\ntype Employee {\n id: String!\n name: String\n lastObservedStatus: String\n}\n\ntype Query {\n employees: [Employee]\n}\n```\n\n```text\n[\n {\"id\": \"001\", \"name\": \"Harry\"},\n {\"id\": \"002\", \"name\": \"Jerry\"},\n {\"id\": \"003\", \"name\": \"Larry\"}\n]\n```\n\n```text\n[\n {\"id\":\"002\", \"TimeStamp\":\"2021-07-01T12:30:00Z\", \"status\": \"eating\"},\n {\"id\":\"002\", \"TimeStamp\":\"2021-07-01T13:10:00Z\", \"status\": \"staring out the window\"},\n {\"id\":\"001\", \"TimeStamp\":\"2021-07-01T16:00:00Z\", \"status\": \"sleeping in lobby\"}\n]\n```\n\n```text\n{\n \"data\": {\n \"employees\": [\n {\n \"id\": \"001\",\n \"name\": \"Harry\",\n \"lastObservedStatus\": \"sleeping in lobby\"\n },\n {\n \"id\": \"002\",\n \"name\": \"Jerry\",\n \"lastObservedStatus\": \"staring out the window\"\n },\n {\n \"id\": \"003\",\n \"name\": \"Larry\",\n \"lastObservedStatus\": null\n }\n ]\n }\n}\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\nemployees\n```\n\n```text\nlastObservedStatus\n```\n\n```text\nemployees\n```\n\n```text\nid\n```\n\n```text\nname\n```\n\n```text\nEmployee\n```\n\n```text\n$ctx.source.id\n```\n\n```text\n$ctx.source.name\n```\n\n```text\nemployees\n```\n\n```text\nlastObservedStatus\n```\n\n```text\nlastObservedStatus\n```\n\n```text\n$ctx.prev.result\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":179,"estimatedTokens":1020}}1050{"id":"stack-46929327","source":"stackoverflow","questionId":46929327,"title":"How to nest two graphQL queries in a schema?","tags":["javascript","graphql"],"text":"Title: How to nest two graphQL queries in a schema?\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI've created a **GraphQLSchema** with two fields, both using a `resolve()` to get the data from a mongoDB.\n\nWith that, the query...\n\n```\n{\n article(id: \"Dn59y87PGhkJXpaiZ\") {\n title\n },\n articleContent(id: \"Dn59y87PGhkJXpaiZ\") {\n _id,\n content(language: \"en\"),\n type\n }\n}\n```\n\n...results in:\n\n```\n{\n \"data\": {\n \"article\": {\n \"title\": \"Sample Article\"\n },\n \"articleContent\": [\n {\n \"_id\": \"Kho2N8yip3uWj7Cib\",\n \"content\": \"group\",\n \"type\": \"group\"\n },\n {\n \"_id\": \"mFopAj4jQQuGAJoAH\",\n \"content\": \"paragraph\",\n \"type\": null\n }\n ]\n }\n}\n```\n\nBut I need a result structure like this (content should be inside of article object):\n\n**Expected result**\n\n```\n{\n \"data\": {\n \"article\": {\n \"title\": \"Sample Article\",\n \"content\": [\n {\n \"_id\": \"Kho2N8yip3uWj7Cib\",\n \"content\": \"group\",\n \"type\": \"group\"\n },\n {\n \"_id\": \"mFopAj4jQQuGAJoAH\",\n \"content\": \"paragraph\",\n \"type\": null\n }\n ]\n },\n }\n}\n```\n\nFor me the problem are both async mongoDB resolves in my schema:\n\n```\nexport default new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'RootQueryType',\n fields: {\n\n article: {\n type: new GraphQLObjectType({\n name: 'article',\n fields: {\n title: {\n type: GraphQLString,\n resolve (parent) {\n return parent.title\n }\n }\n }\n }),\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n async resolve ({ db }, { id }) {\n return db.collection('content').findOne({ _id: id })\n }\n },\n\n articleContent: {\n type: new GraphQLList(new GraphQLObjectType({\n name: 'articleContent',\n fields: {\n _id: { type: GraphQLID },\n type: { type: GraphQLString },\n content: {\n type: GraphQLString,\n args: {\n language: { type: new GraphQLNonNull(GraphQLString) }\n },\n resolve (parent, { language }, context) {\n return parent.content[language][0].content\n }\n }\n }\n })),\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n async resolve ({ db }, { id }) {\n return db.collection('content').find({ main: id }).toArray()\n }\n }\n }\n })\n})\n```\n\n**Update**\n\nIf I nest the content inside the article, I do get the error `Cannot read property 'collection' of undefined`\n\n```\nexport default new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'RootQueryType',\n fields: {\n\n article: {\n type: new GraphQLObjectType({\n name: 'article',\n fields: {\n title: {\n type: GraphQLString,\n resolve (parent) {\n return parent.title\n }\n },\n articleContent: {\n type: new GraphQLList(new GraphQLObjectType({\n name: 'articleContent',\n fields: {\n _id: { type: GraphQLID },\n type: { type: GraphQLString },\n content: {\n type: GraphQLString,\n args: {\n language: { type: new GraphQLNonNull(GraphQLString) }\n },\n resolve (parent, { language }, context) {\n return parent.content[language][0].content\n }\n }\n }\n })),\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n async resolve ({ db }, { id }) { // db is undefined here!!\n return db.collection('content').find({ main: id }).toArray()\n }\n }\n }\n }),\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n async resolve ({ db }, { id }) {\n return db.collection('content').findOne({ _id: id })\n }\n }\n }\n })\n})\n```\n\n========================================\n\nCode:\n```text\n{\n article(id: \"Dn59y87PGhkJXpaiZ\") {\n title\n },\n articleContent(id: \"Dn59y87PGhkJXpaiZ\") {\n _id,\n content(language: \"en\"),\n type\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"article\": {\n \"title\": \"Sample Article\"\n },\n \"articleContent\": [\n {\n \"_id\": \"Kho2N8yip3uWj7Cib\",\n \"content\": \"group\",\n \"type\": \"group\"\n },\n {\n \"_id\": \"mFopAj4jQQuGAJoAH\",\n \"content\": \"paragraph\",\n \"type\": null\n }\n ]\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"article\": {\n \"title\": \"Sample Article\",\n \"content\": [\n {\n \"_id\": \"Kho2N8yip3uWj7Cib\",\n \"content\": \"group\",\n \"type\": \"group\"\n },\n {\n \"_id\": \"mFopAj4jQQuGAJoAH\",\n \"content\": \"paragraph\",\n \"type\": null\n }\n ]\n },\n }\n}\n```\n\n```text\nexport default new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'RootQueryType',\n fields: {\n\n article: {\n type: new GraphQLObjectType({\n name: 'article',\n fields: {\n title: {\n type: GraphQLString,\n resolve (parent) {\n return parent.title\n }\n }\n }\n }),\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n async resolve ({ db }, { id }) {\n return db.collection('content').findOne({ _id: id })\n }\n },\n\n articleContent: {\n type: new GraphQLList(new GraphQLObjectType({\n name: 'articleContent',\n fields: {\n _id: { type: GraphQLID },\n type: { type: GraphQLString },\n content: {\n type: GraphQLString,\n args: {\n language: { type: new GraphQLNonNull(GraphQLString) }\n },\n resolve (parent, { language }, context) {\n return parent.content[language][0].content\n }\n }\n }\n })),\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n async resolve ({ db }, { id }) {\n return db.collection('content').find({ main: id }).toArray()\n }\n }\n }\n })\n})\n```\n\n```text\nexport default new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'RootQueryType',\n fields: {\n\n article: {\n type: new GraphQLObjectType({\n name: 'article',\n fields: {\n title: {\n type: GraphQLString,\n resolve (parent) {\n return parent.title\n }\n },\n articleContent: {\n type: new GraphQLList(new GraphQLObjectType({\n name: 'articleContent',\n fields: {\n _id: { type: GraphQLID },\n type: { type: GraphQLString },\n content: {\n type: GraphQLString,\n args: {\n language: { type: new GraphQLNonNull(GraphQLString) }\n },\n resolve (parent, { language }, context) {\n return parent.content[language][0].content\n }\n }\n }\n })),\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n async resolve ({ db }, { id }) { // db is undefined here!!\n return db.collection('content').find({ main: id }).toArray()\n }\n }\n }\n }),\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n async resolve ({ db }, { id }) {\n return db.collection('content').findOne({ _id: id })\n }\n }\n }\n })\n})\n```\n\n```text\nresolve()\n```\n\n```text\nCannot read property 'collection' of undefined\n```\n\n```text\nfunction resolve(root, args, context)\n```\n\n```text\napp.use('/graphql', graphqlHTTP({\n schema: schema,\n rootValue: root,\n context: {\n db: db\n },\n graphiql: true,\n}));\n```\n\n```text\nexport default new GraphQLSchema({\n query: new GraphQLObjectType({\n name: 'RootQueryType',\n fields: {\n article: {\n args: {\n id: { type: new GraphQLNonNull(GraphQLID) }\n },\n resolve (_, { id }) {\n return id; // will make it accessible to children resolvers\n }\n type: new GraphQLObjectType({\n name: 'article',\n fields: {\n title: {\n async resolve (id /* resolved by article */, _, { db } /* db from context */) {\n const article = await db.collection('content').findOne({ _id: id });\n return article.title;\n }\n type: GraphQLString,\n },\n content: {\n async resolve (id /* resolved by article */, _, { db } /* db from context */) {\n const contents = await db.collection('content').find({ main: id }).toArray();\n return contents;\n }\n type: new GraphQLList(new GraphQLObjectType({\n name: 'articleContent',\n fields: {\n _id: { type: GraphQLID },\n type: { type: GraphQLString },\n content: {\n args: {\n language: { type: new GraphQLNonNull(GraphQLString) }\n },\n aync resolve (parent /* resolved in content */, { language }) {\n return parent.content[language][0].content\n }\n type: GraphQLString,\n }\n }\n })),\n }\n }\n }),\n }\n }\n })\n})\n```\n\n```text\nroot\n```\n\n```text\nCannot read property 'collection' of undefined\n```\n\n```text\ndb\n```\n\n```text\nargs\n```\n\n```text\narticle(id:'someid')\n```\n\n```text\ncontext\n```\n\n```text\ndb\n```\n\n```text\ndb\n```\n\n```text\ndb\n```\n\n```text\ncontext\n```\n\n```text\nlanguage\n```\n\n========================================\n\nComments:\n- Your query and schema definition matches which is what you get as output.. Nest the content type in the article type to get the nested structure, You can have separate resolver to pull the article and content from its own collection based on the args\n- what do you mean by \"separate resolver\"? Could you post some code please?\n- I can but I'm not really clear why you have the query the way you have. Why not use query like `String query = { article(id: \"Dn59y87PGhkJXpaiZ\") { _id, content(language:\"en\") { content, timestamp } } }` and update your schema to embed the content in the articles as shown here. What am I missing here ? I have also added a complete working java example there. Please take a look and try to explain how is this different from that post.\n- Your linked code is nearly the same as I'm using. With that I do get the array which would be in this example `articleContent` and it's data comes from `find({ main: args.id })`. Additionally I need the title of the dataset. This data comes from `find({ _id: args.id})`, which is another document. And this is what makes the trouble for me.\n- I tried to nest the content into article, but get an undefined db. See updated post.\n- Are you looking for this kind of structure ? `{ \"data\": { \"article\": [ { \"_id\": \"9uPjYoYu58WM5Tbtf\", \"title\": \"parent\", \"content\": [ { \"content\": \"Third paragraph\", \"timestamp\": 1484939404 } ] }, { \"_id\": \"345869696665\", \"title\": \"parent\", \"content\": [ { \"content\": \"First paragraph\", \"timestamp\": 1484939404 } ] } ] } }`","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":484,"estimatedTokens":2685}}1051{"id":"stack-67726404","source":"stackoverflow","questionId":67726404,"title":"Is there anyway to add services to the service provider at runtime? Or rebuild it? On .NET 5.0 or .NET core 3+","tags":[".net",".net-core","graphql","hotchocolate"],"text":"Title: Is there anyway to add services to the service provider at runtime? Or rebuild it? On .NET 5.0 or .NET core 3+\nTags: .net, .net-core, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI have a multitenant application on a micro service architecture design.\n\nI want to inject X number of services, depending on the number of tenants running.\n\n```\npublic void ConfigureServices(IServiceCollection services)\n {\n // ... OTHER DI\n\n services.AddHttpClient(\"TenantsService\")\n .AddTypedClient(c => new TenantServiceClient(new TenantServiceClientSettings()\n {\n AccessKey = Configuration[\"TenantsService:ApiKey\"],\n BaseUrl = new Uri(Configuration[\"TenantsService:Url\"])\n }, c)); \n\n foreach (var tenant in TenantsToRegister)\n {\n services\n .AddGraphQLServer($\"{tenant.Name}\");\n }\n\n ...\n\n }\n```\n\nThe above code would work if I had the list of tenants when the application starts. But I need to request that list from another microservice. Having this constraint, I need to build the service provider in order to get that list. At the same time, I need the list before the service provider's build to inject the services I need.\n\nThe only option that I see is adding the services at runtime, but I'm not sure if it's possible.\n\n========================================\n\nTop Answer:\nYou have a problem... You are trying to scale vertically in multitenant environment. That you will do with 10 tenants? 100? It is tons of ram for single process on single node (it might be not a case if you 100% sure you will have some of them) without any chance to scale horizontally\n\nI think you can create service per tenant from same image, but different configuration and api gateway/loadbalancer depending on... Something... (Header, query param, user id, etc.). It might require some infrastructure investments, but will not be a pain in a future\n\nIf you really want to load tenants info from http client and then add HC gql servers per tenant i suggest you to write your own `IConfiguration` provider.\n\nThis is Consul integration, it has the same http roundtrip as you need https://github.com/wintoncode/Winton.Extensions.Configuration.Consul. It adds custom configuration source and loads it on startup\n\nAfter that you just map your tenants info from configuration in startup\n\n========================================\n\nCode:\n```text\npublic void ConfigureServices(IServiceCollection services)\n {\n // ... OTHER DI\n\n services.AddHttpClient(\"TenantsService\")\n .AddTypedClient<ITenantServiceClient>(c => new TenantServiceClient(new TenantServiceClientSettings()\n {\n AccessKey = Configuration[\"TenantsService:ApiKey\"],\n BaseUrl = new Uri(Configuration[\"TenantsService:Url\"])\n }, c)); \n\n foreach (var tenant in TenantsToRegister)\n {\n services\n .AddGraphQLServer($\"{tenant.Name}\");\n }\n\n ...\n\n }\n```\n\n```cs\nservices\n .AddHttpClient(\"TenantsService\")\n .AddTypedClient<ITenantServiceClient>(c => \n new TenantServiceClient(new TenantServiceClientSettings\n {\n AccessKey = \"THE KEY\", // Configuration[\"TenantsService:ApiKey\"], \n BaseUrl = new Uri(\"https://the-uri-you-need.com\") // new Uri(Configuration[\"TenantsService:Url\"])\n }, c));\n \n// build a temporary service provider before, with all services added until now.\nvar tempServiceProvider = services.BuildServiceProvider();\n\n// resolve the tenant service and query for tenants\nvar tenantsToRegister = tempServiceProvider.GetRequiredService<ITenantServiceClient>().GetTenants();\n\n// register needed tenants\nforeach (var tenant in tenantsToRegister)\n{\n services.AddGraphQLServer($\"{tenant}\");\n}\n```\n\n```text\nITenantServiceClient\n```\n\n```text\nIServiceProvider\n```\n\n```text\nIConfiguration\n```\n\n========================================\n\nComments:\n- Microsoft's DI is completely runtime. You can do whatever you need to do to acquire `TenantsToRegister` inside your `ConfigureServices` method.\n- @KevinKrumwiede When I said \"runtime\" what I really meant to say was \"after the service provider is built\". What I need to do it's an async HTTP call using `ITenantServiceClient` that I also inject in the service collection. I'm not finding any way to do this\n- Sounds like a job for GetRequiredService? andrewlock.net/…\n- thanks for your reply. The full example on the dotnet fiddle was very helpful and resolved my problem for now. For the ones that may be looking for the same solution, the only part on Martin's code that was missing was how to pass the collection built on the Main method back to the ConfigureServices on startup (to continue adding other DIs). I'm now posting the solution that I've used on another comment.\n- [link] dotnetfiddle.net/hi05JN Martin's solution with the mentioned detail (see previous comment)\n- @joao-figueira Thanks for the update :) . I will add this to the answer","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":119,"estimatedTokens":1267}}1052{"id":"stack-59919546","source":"stackoverflow","questionId":59919546,"title":"Problem with e2e testing with NestJS TestingModule, GraphQL code first and TypeOrm","tags":["graphql","e2e-testing","nestjs"],"text":"Title: Problem with e2e testing with NestJS TestingModule, GraphQL code first and TypeOrm\nTags: graphql, e2e-testing, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm in struggle since few days with **e2e testing** my **NestJS** application using **GraphQL** code first approach and **TypeOrm**.\n\nI'm trying to create a **TestingModule** by injecting nestjs **GraphQLModule** with *autoSchemaFile* and I'm always getting the error \"*Schema must contain uniquely named types but contains multiple types named ...*\".\n\nHere a reproduction of my bug with minimal code:\n\n`character.entity.ts`:\n\n```\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\nimport { ObjectType, Field, ID } from 'type-graphql';\n\n@Entity()\n@ObjectType()\nexport class Character {\n @PrimaryGeneratedColumn()\n @Field(() => ID)\n id: string;\n\n @Column({ unique: true })\n @Field()\n name: string;\n}\n```\n\n`character.resolver.ts`:\n\n```\nimport { Query, Resolver } from '@nestjs/graphql';\nimport { Character } from './models/character.entity';\nimport { CharacterService } from './character.service';\n\n@Resolver(() => Character)\nexport class CharacterResolver {\n constructor(private readonly characterService: CharacterService) {}\n\n @Query(() => [Character], { name: 'characters' })\n async getCharacters(): Promise {\n return this.characterService.findAll();\n }\n}\n```\n\n`character.module.ts`:\n\n```\nimport { Module } from '@nestjs/common';\nimport { CharacterResolver } from './character.resolver';\nimport { CharacterService } from './character.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Character } from './models/character.entity';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Character])],\n providers: [CharacterResolver, CharacterService],\n})\nexport class CharacterModule {}\n```\n\n`app.module.ts`:\n\n```\nimport { Module } from '@nestjs/common';\nimport { CharacterModule } from './character/character.module';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { GraphQLModule } from '@nestjs/graphql';\n\n@Module({\n imports: [TypeOrmModule.forRoot(), GraphQLModule.forRoot({ autoSchemaFile: 'schema.gql' }), CharacterModule],\n controllers: [],\n providers: [],\n})\nexport class AppModule {\n constructor(private readonly connection: Connection) {}\n}\n```\n\nand finally: `character.e2e-spec.ts`:\n\n```\nimport { INestApplication } from '@nestjs/common';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { CharacterModule } from '../src/character/character.module';\nimport { GraphQLModule } from '@nestjs/graphql';\n\ndescribe('CharacterResolver (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [\n TypeOrmModule.forRoot(),\n GraphQLModule.forRoot({ playground: false, autoSchemaFile: 'schema.gql' }),\n CharacterModule,\n ],\n }).compile();\n\n app = module.createNestApplication();\n await app.init();\n });\n\n it('should create testing module', () => {\n expect(1).toBe(1);\n });\n\n afterAll(async () => {\n await app.close();\n });\n});\n```\n\nAnd after running `npm run test:e2e`:\n\n```\nSchema must contain uniquely named types but contains multiple types named \"Character\".\n\n at typeMapReducer (../node_modules/graphql/type/schema.js:262:13)\n at Array.reduce ()\n at new GraphQLSchema (../node_modules/graphql/type/schema.js:145:28)\n at Function.generateFromMetadataSync (../node_modules/type-graphql/dist/schema/schema-generator.js:31:24)\n at Function. (../node_modules/type-graphql/dist/schema/schema-generator.js:16:33)\n at ../node_modules/tslib/tslib.js:110:75\n at Object.__awaiter (../node_modules/tslib/tslib.js:106:16)\n at Function.generateFromMetadata (../node_modules/type-graphql/dist/schema/schema-generator.js:15:24)\n```\n\nI don't find any other way to create a testing module with graphql code first approach on official doc or while googling... Am I missing something ?\n\n========================================\n\nCode:\n```js\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\nimport { ObjectType, Field, ID } from 'type-graphql';\n\n@Entity()\n@ObjectType()\nexport class Character {\n @PrimaryGeneratedColumn()\n @Field(() => ID)\n id: string;\n\n @Column({ unique: true })\n @Field()\n name: string;\n}\n```\n\n```js\nimport { Query, Resolver } from '@nestjs/graphql';\nimport { Character } from './models/character.entity';\nimport { CharacterService } from './character.service';\n\n@Resolver(() => Character)\nexport class CharacterResolver {\n constructor(private readonly characterService: CharacterService) {}\n\n @Query(() => [Character], { name: 'characters' })\n async getCharacters(): Promise<Character[]> {\n return this.characterService.findAll();\n }\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { CharacterResolver } from './character.resolver';\nimport { CharacterService } from './character.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Character } from './models/character.entity';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Character])],\n providers: [CharacterResolver, CharacterService],\n})\nexport class CharacterModule {}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { CharacterModule } from './character/character.module';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { GraphQLModule } from '@nestjs/graphql';\n\n@Module({\n imports: [TypeOrmModule.forRoot(), GraphQLModule.forRoot({ autoSchemaFile: 'schema.gql' }), CharacterModule],\n controllers: [],\n providers: [],\n})\nexport class AppModule {\n constructor(private readonly connection: Connection) {}\n}\n```\n\n```js\nimport { INestApplication } from '@nestjs/common';\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { CharacterModule } from '../src/character/character.module';\nimport { GraphQLModule } from '@nestjs/graphql';\n\ndescribe('CharacterResolver (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [\n TypeOrmModule.forRoot(),\n GraphQLModule.forRoot({ playground: false, autoSchemaFile: 'schema.gql' }),\n CharacterModule,\n ],\n }).compile();\n\n app = module.createNestApplication();\n await app.init();\n });\n\n it('should create testing module', () => {\n expect(1).toBe(1);\n });\n\n afterAll(async () => {\n await app.close();\n });\n});\n```\n\n```text\nSchema must contain uniquely named types but contains multiple types named \"Character\".\n\n at typeMapReducer (../node_modules/graphql/type/schema.js:262:13)\n at Array.reduce (<anonymous>)\n at new GraphQLSchema (../node_modules/graphql/type/schema.js:145:28)\n at Function.generateFromMetadataSync (../node_modules/type-graphql/dist/schema/schema-generator.js:31:24)\n at Function.<anonymous> (../node_modules/type-graphql/dist/schema/schema-generator.js:16:33)\n at ../node_modules/tslib/tslib.js:110:75\n at Object.__awaiter (../node_modules/tslib/tslib.js:106:16)\n at Function.generateFromMetadata (../node_modules/type-graphql/dist/schema/schema-generator.js:15:24)\n```\n\n```text\ncharacter.entity.ts\n```\n\n```text\ncharacter.resolver.ts\n```\n\n```text\ncharacter.module.ts\n```\n\n```text\napp.module.ts\n```\n\n```text\ncharacter.e2e-spec.ts\n```\n\n```text\nnpm run test:e2e\n```\n\n```text\n\"entities\": [\n \"src/**/*.entity.js\"\n ],\n \"migrations\": [\n \"src/migration/*.js\"\n ],\n \"cli\": {\n \"migrationsDir\": \"src/migration\"\n }\n```\n\n```text\normconfig.json\n```\n\n```text\nsrc\n```\n\n```text\ndist\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- Just set this up today and found the same issue. No clue what's leading to it. I can confirm the error occurs at the point: `app.init()`","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":304,"estimatedTokens":1995}}1053{"id":"stack-38165609","source":"stackoverflow","questionId":38165609,"title":"GraphQL schema won't import","tags":["express","graphql"],"text":"Title: GraphQL schema won't import\nTags: express, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm trying setup an express GraphQL server. Following a tutorial when I put the following in the server startup like this:\n\n```\n// ENTIRE SCHEMA IN MAIN FILE THIS WORKS!!!\n\n...\nvar graphql = require('graphql');\n\nconst RootQuery = new graphql.GraphQLObjectType({\n name: 'RootQuery',\n description: 'The root query',\n fields: {\n viewer: {\n type: graphql.GraphQLString,\n resolve() {\n return 'viewer!';\n }\n }\n }\n});\n\nconst Schema = new graphql.GraphQLSchema({\n query: RootQuery\n});\n\napp.use('/graphql', graphqlHTTP({ schema: Schema }));\n...\n```\n\nit works, returning the data 'viewer! But as I don't want everything in the main file, I tried to transfer this exact code to another file and import it like this:\n\n```\n//THIS DOES NOT WORK\n...\nvar Schema = require('./build/models/graphql/schema');\n app.use('/graphql', graphqlHTTP({ schema: Schema }));\n...\n```\n\nI get the following error:\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory.\"\n }\n ]\n}\n```\n\nI'm not sure what I'm doing wrong. In case this has anything to do with it, I am writing in es6 then transpiling back to 5 in a build script. Here's the build of the schema file: \n\n```\n// TRANSPILED SCHEMA\n\n'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar graphql = require('graphql');\n\nvar RootQuery = new graphql.GraphQLObjectType({\n name: 'RootQuery',\n description: 'The root query',\n fields: {\n viewer: {\n type: graphql.GraphQLString,\n resolve: function resolve() {\n return 'viewer!';\n }\n }\n }\n});\n\nvar Schema = new graphql.GraphQLSchema({\n query: RootQuery\n});\n\nexports.default = Schema;\n```\n\nAnd here is my package.json:\n\n```\n\"express\": \"^4.13.4\",\n \"express-graphql\": \"^0.5.3\",\n \"graphql\": \"^0.6.0\",\n```\n\nI've checked that only one graphql is in the node_modules folder. Does graphql expect the same INSTANCE across all modules, like a shared global instance? Does express-graphql use it's own version? How do I check? I'm new to node, is there a way to check the instances?\n\n========================================\n\nTop Answer:\nAlso ensure that there are not multiple versions of GraphQL installed in your node_modules directory.\n\nAs the error indicates, this most likely has to do with more than one copy of GraphQL in your node_modules directory. Have you checked that? If there is more than one copy, you might be able to solve it by running `npm dedupe` if you're using npm version 2. If you're using npm 3, then most likely you've installed two different versions of the `graphql` module.\n\nEither way, you have to make sure that after the compile step, express-graphql and your schema both point to the same copy of the `graphql` module.\n\n========================================\n\nCode:\n```text\n// ENTIRE SCHEMA IN MAIN FILE THIS WORKS!!!\n\n...\nvar graphql = require('graphql');\n\nconst RootQuery = new graphql.GraphQLObjectType({\n name: 'RootQuery',\n description: 'The root query',\n fields: {\n viewer: {\n type: graphql.GraphQLString,\n resolve() {\n return 'viewer!';\n }\n }\n }\n});\n\nconst Schema = new graphql.GraphQLSchema({\n query: RootQuery\n});\n\napp.use('/graphql', graphqlHTTP({ schema: Schema }));\n...\n```\n\n```text\n//THIS DOES NOT WORK\n...\nvar Schema = require('./build/models/graphql/schema');\n app.use('/graphql', graphqlHTTP({ schema: Schema }));\n...\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory.\"\n }\n ]\n}\n```\n\n```text\n// TRANSPILED SCHEMA\n\n'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar graphql = require('graphql');\n\nvar RootQuery = new graphql.GraphQLObjectType({\n name: 'RootQuery',\n description: 'The root query',\n fields: {\n viewer: {\n type: graphql.GraphQLString,\n resolve: function resolve() {\n return 'viewer!';\n }\n }\n }\n});\n\nvar Schema = new graphql.GraphQLSchema({\n query: RootQuery\n});\n\nexports.default = Schema;\n```\n\n```text\n\"express\": \"^4.13.4\",\n \"express-graphql\": \"^0.5.3\",\n \"graphql\": \"^0.6.0\",\n```\n\n```text\nmodule.exports = Schema\n```\n\n```text\nSchema = require(\"./...\").default\n```\n\n```text\nnpm dedupe\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql\n```\n\n```text\nimport graphly from \"graphqly\";\n\nconst gBuilder = graphly.createBuilder();\n\n// define types, inputs ... (in any order)\ngBuilder.type(\"Products\").implements(\"List\").def(`\n products: [Product]!\n`);\n\ngBuilder.type(\"Product\").def(`\n id: ID!\n name: String!\n link: String\n price: Int\n`);\n\n// we're too lazy to define a separate input, so we can `extend` other structure\ngBuilder.input(\"ProductInput\").ext(\"Product\");\n\ngBuilder.enum(\"ProductOrder\").def(`\n PRICE_DESCENDING\n PRICE_ASCENDING\n NEWEST\n`);\n```\n\n========================================\n\nComments:\n- Hi and thanks for replying - I have npm version 3.8.6 - I have only one copy of graphql in the node_modules folder. Does it install anywhere else? Perhaps as a dependency of express-graphql? Is there a way to tell where the instance is being pulled from?\n- You mentioned the second file was the result of transpiler output, looks like Babel. Is the first file also using Babel? I have a hunch that you're using ES6 import/export syntax in one file and using require() directly in another. I suggest using all of one syntax or all of the other to avoid this sort of mistake\n- Thanks Lee! You were right, I was transpiling with babel everything but the main file, which was boilerplate code that came from our production environment, so I left that alone. Once I went ahead and rewrote it in es6 and transpiled it down with all the rest, everything worked. This stuff is hard to for newbies. Appreciate the help!!!","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":246,"estimatedTokens":1490}}1054{"id":"stack-46755236","source":"stackoverflow","questionId":46755236,"title":"How to approach subscriptions in React app","tags":["javascript","reactjs","graphql","react-apollo","graphcool"],"text":"Title: How to approach subscriptions in React app\nTags: javascript, reactjs, graphql, react-apollo, graphcool\nSource: Stack Overflow\n\nQuestion:\nI need some help to figure out what is a general approach on subscriptions and real-time updating. I have a React Native app and using Apollo and Graphcool service as a backend. \n\nThere are a couple scenarios where user looking at the app receives a push notification that something has changed. Naturally, the screen data should get updated as well. Subscriptions are an obvious candidate for that job and I got it working essentially.\n\nI have a subscription like this which works just fine on its own (used to position player avatars on google map).\n\n```\nsubscription PlayerMap($gameId: ID) {\n Game(filter: { mutation_in: [CREATED, UPDATED], node: { id: $gameId } }) {\n node {\n players {\n id\n character {\n id\n name\n }\n user {\n id\n latitude\n longitude\n }\n }\n }\n }\n}\n```\n\nThen there is a different app screen executing a mutation `createPlayer` along with `refetchQueries` from Apollo (for simplicity) which runs this query to update stuff.\n\n```\nquery GameCharacters($gameId: ID!) {\n Game(id: $gameId) {\n players {\n id\n character {\n id\n name\n }\n }\n }\n}\n```\n\nNow when this completes, the subscription query (that is still active on another screen) also gets updated but for some reason whole `Game` node is missing in `data` object.\n\nFor handling subscriptions, I have a component like this.\n\n```\nclass Subscriber extends Component {\n componentDidMount() {\n this.subscribe()\n }\n componentWillReceiveProps({ data, shouldResubscribe }) {\n if (this.unsubscribe) {\n if (shouldResubscribe && shouldResubscribe(data, this.props.data) !== true) {\n return\n }\n this.unsubscribe()\n }\n this.subscribe()\n }\n subscribe() {\n const { data, query, variables } = this.props\n this.unsubscribe = data.subscribeToMore({\n document: query,\n variables,\n })\n }\n unsubscribe: ?Function = null\n render() {\n return this.props.children(this.props.data)\n }\n}\n```\n\nI can then use it simply like this with render prop pattern.\n\n```\nconst OrgMapScreen = ({ gameId, data: initialData }: Props) => (\n nextData.Game !== prevData.Game}\n >\n {({ Game }) => {\n const markers = Game.players.map(makePlayerMarker)\n return \n }}\n \n)\n```\n\nI am rather confused why is that happening. Is there some recommended way how to handle stuff like that? Perhaps instead of `refetchQueries` I should set up another subscription for `GameCharacters` too?\n\n========================================\n\nCode:\n```graphql\nsubscription PlayerMap($gameId: ID) {\n Game(filter: { mutation_in: [CREATED, UPDATED], node: { id: $gameId } }) {\n node {\n players {\n id\n character {\n id\n name\n }\n user {\n id\n latitude\n longitude\n }\n }\n }\n }\n}\n```\n\n```graphql\nquery GameCharacters($gameId: ID!) {\n Game(id: $gameId) {\n players {\n id\n character {\n id\n name\n }\n }\n }\n}\n```\n\n```js\nclass Subscriber extends Component<void, Props, void> {\n componentDidMount() {\n this.subscribe()\n }\n componentWillReceiveProps({ data, shouldResubscribe }) {\n if (this.unsubscribe) {\n if (shouldResubscribe && shouldResubscribe(data, this.props.data) !== true) {\n return\n }\n this.unsubscribe()\n }\n this.subscribe()\n }\n subscribe() {\n const { data, query, variables } = this.props\n this.unsubscribe = data.subscribeToMore({\n document: query,\n variables,\n })\n }\n unsubscribe: ?Function = null\n render() {\n return this.props.children(this.props.data)\n }\n}\n```\n\n```js\nconst OrgMapScreen = ({ gameId, data: initialData }: Props) => (\n <Subscriber\n data={initialData}\n query={OrgMapSubscription}\n variables={{ gameId }}\n shouldResubscribe={(nextData, prevData) => nextData.Game !== prevData.Game}\n >\n {({ Game }) => {\n const markers = Game.players.map(makePlayerMarker)\n return <MapScreen mapProps={{ markers }} />\n }}\n </Subscriber>\n)\n```\n\n```text\ncreatePlayer\n```\n\n```text\nrefetchQueries\n```\n\n```text\nGame\n```\n\n```text\ndata\n```\n\n```text\nrefetchQueries\n```\n\n```text\nGameCharacters\n```\n\n```text\ncomponentDidMount() {\n this.props.data.subscribeToMore({\n document: OrderSubscription,\n variables: {\n range: [0, 25]\n },\n updateQuery: (prev, { subscriptionData, }) => {\n // If no subscription data is passed, just return the previous\n // result from the initial `orders` query\n if (!subscriptionData.data) return prev\n\n // get the data for the updated order from the subscription \n const updatedOrder = subscriptionData.data.orderChanged\n\n // find the index of the updated order from within the existing \n // array of orders from the `orders` query\n const existingOrderIndex = prev.orders.findIndex(order => (order.id === updatedOrder.id))\n\n // guard for missing data\n if (existingOrderIndex) {\n // replace the old order with the updated order\n prev[existingOrderIndex] = updatedOrder\n // return orders with new, updated data\n return prev\n }\n\n return prev\n },\n })\n}\n```\n\n```text\ndocument\n```\n\n```text\nsubscribeToMore\n```\n\n```text\nupdateQuery\n```\n\n```text\nsubscribeToMore\n```\n\n```text\norderChanged\n```\n\n```text\nOrder\n```\n\n```text\norders\n```\n\n```text\nupdateQuery\n```\n\n```text\nsubscribeToMore\n```\n\n========================================\n\nComments:\n- Yeah turns out that `updateQuery` is kinda necessary. I don't know why I got an impression that Apollo would crawl the result on its own and update store based on types and `dataIdFromObject`. Oh well. Had to use `immutable-helper` for a deeply nested structure like mine, but it seems to be working now. Thanks","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":275,"estimatedTokens":1434}}1055{"id":"stack-55088628","source":"stackoverflow","questionId":55088628,"title":"Apollo GraphQL local and global error handling","tags":["reactjs","error-handling","graphql","apollo","react-apollo"],"text":"Title: Apollo GraphQL local and global error handling\nTags: reactjs, error-handling, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm using Apollo to interact with a GraphQL server in a Web application written in React. I'm trying to implement error handling in the application and relying on apollo-link-error for this.\n\nNow, there are 2 categories of errors that I need to handle:\n\n- errors that can be handled locally in the component which does the Apollo query or mutation, i.e. an invalid form field on which I need to show contextual error information\n\n- errors that can be handled globally, for example by showing a toast notification displaying error details somewhere in the page\n\nClearly, once the error is handled locally I need it to **not** be handled globally, because it doesn't make much sense to show an error message next to a form field *and* a generic error via a toast message.\n\nThe first stumbling block I encountered when trying to implement this is that the global error handling logic triggers **before** the local error handling logic, which prevents me from being able to intercept the error locally and then find a way to prevent the global logic from kicking in.\n\nI created codesandbox example which sets up an `ApolloClient` in the simplest possible way, uses the http and error links, and uses the `react-apollo` `Query` component to do a query for a resource that doesn't exist, generating an error.\n\nI'm handling the error both in the `onError` callback of the `Query` component (so local error handling), and in the `apollo-link-error` handler (so global error handling), and printing to the console the errors.\n\nhttps://i.sstatic.net/bV3D0.png\n\nIt shows that the global error handling logic kicks in before the local error handling. I would need it to be the other way around.\n\nhttps://codesandbox.io/s/x33wqxyyn4?fontsize=14\n\n========================================\n\nCode:\n```text\nApolloClient\n```\n\n```text\nreact-apollo\n```\n\n```text\nQuery\n```\n\n```text\nonError\n```\n\n```text\nQuery\n```\n\n```text\napollo-link-error\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":53,"estimatedTokens":518}}1056{"id":"stack-67240260","source":"stackoverflow","questionId":67240260,"title":"Property does not exist on type in GraphQL query result","tags":["typescript","graphql","graphql-codegen"],"text":"Title: Property does not exist on type in GraphQL query result\nTags: typescript, graphql, graphql-codegen\nSource: Stack Overflow\n\nQuestion:\nIn the React component I use a GraphQL query to fetch data:\n\n```\nconst { data, error, loading } = useGetEmployeeQuery({\n variables: { id: \"a34c0d11-f51d-4a9b-ac7fd-bfb7cbffa\" }\n});\n```\n\nOn the data destructure\n\n```\nconst { first_name } = data?.Employees_employees_by_pk;\n```\n\ntype checking returns an error\n\n```\nProperty 'first_name' does not exist on type 'Maybe> | undefined'\n```\n\nTried to assign a default `\"\"` to `first_name` which didn't help to eliminate the error.\n\nThe types are generated with graphql-codegen:\n\n```\nexport type GetEmployeeQuery = (\n { __typename?: 'query_root' }\n & { Employees_employees_by_pk?: Maybe\n )> }\n);\n```\n\nHow do I get the query result to destructure nicely?\n\n========================================\n\nTop Answer:\nYou can try\n\n```\nconst { data: { first_name } = {} } = useQuery(gql`...`);\n```\n\nSo typescript will assume `data` is an empty object instead of undefined\n\n========================================\n\nCode:\n```text\nconst { data, error, loading } = useGetEmployeeQuery({\n variables: { id: \"a34c0d11-f51d-4a9b-ac7fd-bfb7cbffa\" }\n});\n```\n\n```text\nconst { first_name } = data?.Employees_employees_by_pk;\n```\n\n```text\nProperty 'first_name' does not exist on type 'Maybe<{ __typename?: \"Employees_employees\" | undefined; } & Pick<Employees_Employees, \"id\" | \"first_name\" | \"last_name\" | \"email\" | \"avatar\" | \"started_at\" | \"created_at\" | \"updated_at\">> | undefined'\n```\n\n```text\nexport type GetEmployeeQuery = (\n { __typename?: 'query_root' }\n & { Employees_employees_by_pk?: Maybe<(\n { __typename?: 'Employees_employees' }\n & Pick<Employees_Employees, 'id' | 'first_name' | 'last_name' | 'email' | 'avatar' | 'started_at' | 'created_at' | 'updated_at'>\n )> }\n);\n```\n\n```text\n\"\"\n```\n\n```text\nfirst_name\n```\n\n```text\nif( data && data.Employees_employees_by_pk ) {\n // no undefined here\n // safe access to 'base type' fields\n const { first_name } = data.Employees_employees_by_pk;\n // use first_name\n}\n```\n\n```text\nconst { first_name } = data?.Employees_employees_by_pk;\n// possible access/destructure from undefined\n```\n\n```text\nconst { data: { first_name } = {} } = useQuery<Data>(gql`...`);\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- What happens when you inspect data in the debugger or with console logs? I think that the Maybe generic could extend Array\n- The received `data` contains the Object of `Employees_employees_by_pk` with all the expected props.\n- Just got the same problem. Any updates on this issue?\n- This worked for me but I really dislike the syntax, especially when dealing with nested values. Does anyone know of a cleaner solution?","metadata":{"transformedAt":"2026-08-18T18:32:36.224Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":114,"estimatedTokens":695}}1057{"id":"stack-62326596","source":"stackoverflow","questionId":62326596,"title":"Get results from different arrays in one Promise.All with Github GraphQL API","tags":["javascript","graphql","gatsby","github-api"],"text":"Title: Get results from different arrays in one Promise.All with Github GraphQL API\nTags: javascript, graphql, gatsby, github-api\nSource: Stack Overflow\n\nQuestion:\nI'm making a custom source plugin for Gatsby, that will get markdown files from a GitHub repository. The repository has individual files (blobs) and folders (trees), which in their turn also contain files. I need to get all files (including files inside folders) in one `Promise.all`, but I can't figure out how to do that. I've managed to get individual files from the repository and I have a function which returns an array of files from the trees. But I don't know how to combine them.\n\nHere is my code. GraphQL queries to get repository, trees and files information:\n\n```\nconst repositoryQuery = `\n{\n viewer {\n repository(name: \"repository-name\") {\n object(expression: \"master:\") {\n ... on Tree {\n entries {\n name\n oid\n type\n }\n }\n }\n }\n }\n}\n`\n\nconst treeQuery = `\n query getTree($id: GitObjectID!) {\n viewer {\n repository(name: \"repository-name\") {\n object(oid: $id) {\n ... on Tree {\n entries {\n name\n oid\n type\n }\n }\n }\n }\n }\n }\n`\n\nconst fileQuery = `\n query getFile($id: GitObjectID!) {\n viewer {\n repository(name: \"repository-name\") {\n object(oid: $id) {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n`\n```\n\nAnd the functions themselves:\n\n```\nconst data = await client.request(repositoryQuery)\n\nconst getTree = async entry => {\n const data = await client.request(treeQuery, { id: entry.oid })\n const array = await data.viewer.repository.object.entries\n return array\n}\n\nconst getFile = async entry => {\n const data = await client.request(fileQuery, { id: entry.oid })\n const result = await data.viewer.repository.object\n return result\n}\n\nconst files = await Promise.all(\n data.viewer.repository.object.entries\n .filter(entry => entry.type !== \"tree\")\n .map(entry => {\n return (\n getFile(entry)\n .then(file => {\n return {\n data: file.text\n }\n })\n )\n }\n )\n)\n\nfiles.forEach(file =>\n createNode({...})\n)\n```\n\nHow can I update `const files` so that it will:\n\n- Run `getFile()`, if `entry.type !== \"tree\"`\n\n- If `entry.type` is `tree`, get an array of files inside the tree with `getTree()` and then run `getFile()` for each file.\n\n- Combine all results in one array, so that I can apply to them `createNode`.\n\nI would really appreciate your help.\n\n========================================\n\nTop Answer:\nFirst you can run through each tree and then get an array of files for each tree, this will give you a 2 dimensional array:\n\n```\n.map(async entry => {\n const files = await getTree(entry);\n return Promise.all(\n files.map(file => getFile(file).then(fileRes => ({ data: fileRes.text })))\n );\n)\n```\n\nThen you need to flatten the result so that it is a single dimensional array:\n\n```\nconst files = allFiles.flat();\n```\n\nI hope I have understood your question correctly; The result from `getTree()` is a single dimensional array of files (i.e. `[file1, file2, file3]`) and not a multidimensional array (i.e. `[[file1, file2], [[file1, file2], [file1]], file1, file2]`).\n\n========================================\n\nCode:\n```text\nconst repositoryQuery = `\n{\n viewer {\n repository(name: \"repository-name\") {\n object(expression: \"master:\") {\n ... on Tree {\n entries {\n name\n oid\n type\n }\n }\n }\n }\n }\n}\n`\n\nconst treeQuery = `\n query getTree($id: GitObjectID!) {\n viewer {\n repository(name: \"repository-name\") {\n object(oid: $id) {\n ... on Tree {\n entries {\n name\n oid\n type\n }\n }\n }\n }\n }\n }\n`\n\nconst fileQuery = `\n query getFile($id: GitObjectID!) {\n viewer {\n repository(name: \"repository-name\") {\n object(oid: $id) {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n`\n```\n\n```text\nconst data = await client.request(repositoryQuery)\n\nconst getTree = async entry => {\n const data = await client.request(treeQuery, { id: entry.oid })\n const array = await data.viewer.repository.object.entries\n return array\n}\n\nconst getFile = async entry => {\n const data = await client.request(fileQuery, { id: entry.oid })\n const result = await data.viewer.repository.object\n return result\n}\n\nconst files = await Promise.all(\n data.viewer.repository.object.entries\n .filter(entry => entry.type !== \"tree\")\n .map(entry => {\n return (\n getFile(entry)\n .then(file => {\n return {\n data: file.text\n }\n })\n )\n }\n )\n)\n\nfiles.forEach(file =>\n createNode({...})\n)\n```\n\n```text\nPromise.all\n```\n\n```text\nconst files\n```\n\n```text\ngetFile()\n```\n\n```text\nentry.type !== \"tree\"\n```\n\n```text\nentry.type\n```\n\n```text\ntree\n```\n\n```text\ngetTree()\n```\n\n```text\ngetFile()\n```\n\n```text\ncreateNode\n```\n\n```text\nasync function walk(entry, isRoot) {\n if (isRoot){\n return await processEntry(entry);\n }\n let files = await getTreeEntryFromTree(repository, entry.oid);\n files = await Promise.all(files.data.viewer.repository.object.entries.map(async file => {\n return await processEntry(file);\n }));\n return files.reduce((all, folderContents) => all.concat(folderContents), []);\n}\n\nasync function processEntry(entry){\n if (entry.type === \"tree\") {\n return walk(entry, false); \n } else {\n let res = await getBlob(repository, entry.oid);\n return [{\n name: entry.name,\n oid: entry.oid,\n data:res.data.viewer.repository.object.text\n }];\n }\n}\n```\n\n```text\nconst { ApolloClient } = require(\"apollo-client\")\nconst { InMemoryCache } = require(\"apollo-cache-inmemory\")\nconst { HttpLink } = require(\"apollo-link-http\")\nconst fetch = require(\"node-fetch\")\nconst gql = require(\"graphql-tag\")\nconst { setContext } = require('apollo-link-context');\n\nconst token = \"YOUR_TOKEN\";\nconst repository = \"YOUR_REPO\";\n\nconst authLink = setContext((_, { headers }) => {\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : null,\n }\n }\n});\n\nconst defaultOptions = {\n watchQuery: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'ignore',\n },\n query: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'all',\n },\n}\n\nconst client = new ApolloClient({\n link: authLink.concat(new HttpLink({ uri: 'https://api.github.com/graphql', fetch: fetch })),\n cache: new InMemoryCache(),\n defaultOptions: defaultOptions,\n});\n\nexports.sourceNodes = async function sourceNodes(\n {\n actions,\n cache,\n createContentDigest,\n createNodeId,\n getNodesByType,\n getNode,\n },\n pluginOptions\n) {\n const { createNode, touchNode, deleteNode } = actions\n const { data } = await getTreeFromRepo(repository)\n\n let sourceData = data;\n\n fileArr = []\n sourceData.viewer.repository.object.entries.map(it => {\n fileArr.push(walk(it, true))\n });\n let res = await Promise.all(fileArr)\n let result = res.flat();\n console.log(result);\n console.log(`got ${result.length} results`);\n return\n}\n\nasync function walk(entry, isRoot) {\n if (isRoot){\n return await processEntry(entry);\n }\n let files = await getTreeEntryFromTree(repository, entry.oid);\n files = await Promise.all(files.data.viewer.repository.object.entries.map(async file => {\n return await processEntry(file);\n }));\n return files.reduce((all, folderContents) => all.concat(folderContents), []);\n}\n\nasync function processEntry(entry){\n if (entry.type === \"tree\") {\n return walk(entry, false); \n } else {\n let res = await getBlob(repository, entry.oid);\n return [{\n name: entry.name,\n oid: entry.oid,\n data:res.data.viewer.repository.object.text\n }];\n }\n}\n\nasync function getTreeFromRepo(repo) {\n return await client.query({\n query: gql`\n query {\n viewer {\n repository(name: \"${repo}\") {\n object(expression: \"master:\") {\n ... on Tree {\n entries {\n name\n oid\n type\n }\n }\n }\n }\n }\n }\n `,\n })\n}\n\nasync function getTreeEntryFromTree(repo, oid) {\n return await client.query({\n query: gql`\n query getTree($id: GitObjectID!) {\n viewer {\n repository(name: \"${repo}\") {\n object(oid: $id) {\n ... on Tree {\n entries {\n name\n oid\n type\n }\n }\n }\n }\n }\n }\n `,\n variables: {\n id: oid\n }\n })\n}\n\nasync function getBlob(repo, oid){\n return await client.query({\n query: gql`\n query getFile($id: GitObjectID!) {\n viewer {\n repository(name: \"${repo}\") {\n object(oid: $id) {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n `,\n variables: {\n id: oid\n }\n })\n}\n```\n\n```text\nasync function getAllEntries(repo, owner){\n return fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/master?recursive=1`,{\n headers: {\n 'Authorization': `Bearer ${token}`,\n }\n })\n .then(response => response.json());\n}\n```\n\n```text\nconst { ApolloClient } = require(\"apollo-client\")\nconst { InMemoryCache } = require(\"apollo-cache-inmemory\")\nconst { HttpLink } = require(\"apollo-link-http\")\nconst fetch = require(\"node-fetch\")\nconst gql = require(\"graphql-tag\")\nconst { setContext } = require('apollo-link-context');\n\nconst token = \"YOUR_TOKEN\";\nconst repository = \"YOUR_REPO\";\nconst owner = \"YOUR_LOGIN\";\n\nconst authLink = setContext((_, { headers }) => {\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : null,\n }\n }\n});\n\nconst defaultOptions = {\n watchQuery: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'ignore',\n },\n query: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'all',\n },\n}\n\nconst client = new ApolloClient({\n link: authLink.concat(new HttpLink({ uri: 'https://api.github.com/graphql', fetch: fetch })),\n cache: new InMemoryCache(),\n defaultOptions: defaultOptions,\n});\n\nexports.sourceNodes = async function sourceNodes(\n {\n actions,\n cache,\n createContentDigest,\n createNodeId,\n getNodesByType,\n getNode,\n },\n pluginOptions\n) {\n const { createNode, touchNode, deleteNode } = actions\n const { tree } = await getAllEntries(repository, owner)\n fileArr = []\n tree.map(it => {\n fileArr.push(walk(it, true))\n });\n let res = await Promise.all(fileArr)\n let result = res.filter(value => Object.keys(value).length !== 0);\n console.log(result);\n console.log(`got ${result.length} results`);\n return\n}\n\nasync function walk(entry){\n if (entry.type === \"blob\") {\n let res = await getBlob(repository, entry.sha);\n return {\n name: entry.path,\n oid: entry.sha,\n data: res.data.viewer.repository.object.text\n };\n }\n return {};\n}\n\nasync function getAllEntries(repo, owner){\n return fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/master?recursive=1`,{\n headers: {\n 'Authorization': `Bearer ${token}`,\n }\n })\n .then(response => response.json());\n}\n\nasync function getBlob(repo, oid){\n return await client.query({\n query: gql`\n query getFile($id: GitObjectID!) {\n viewer {\n repository(name: \"${repo}\") {\n object(oid: $id) {\n ... on Blob {\n text\n }\n }\n }\n }\n }\n `,\n variables: {\n id: oid\n }\n })\n}\n```\n\n```text\nconst fetch = require(\"node-fetch\")\n\nconst token = \"YOUR_TOKEN\";\nconst repository = \"YOUR_REPO\";\nconst owner = \"YOUR_LOGIN\";\n\nexports.sourceNodes = async function sourceNodes(\n {\n actions,\n cache,\n createContentDigest,\n createNodeId,\n getNodesByType,\n getNode,\n },\n pluginOptions\n) {\n const { createNode, touchNode, deleteNode } = actions\n const { tree } = await getAllEntries(repository, owner)\n fileArr = []\n tree.map(it => {\n fileArr.push(walk(it, true))\n });\n let res = await Promise.all(fileArr)\n console.log(res);\n console.log(`got ${res.length} results`);\n return\n}\n\nasync function walk(entry){\n if (entry.type === \"blob\") {\n let res = await getBlob(entry.url);\n return {\n name: entry.path,\n oid: entry.sha,\n data: res.content\n };\n }\n return {};\n}\n\nasync function getAllEntries(repo, owner){\n return fetch(`https://api.github.com/repos/${owner}/${repo}/git/trees/master?recursive=1`, {\n headers: {\n 'Authorization': `Bearer ${token}`,\n }\n })\n .then(response => response.json());\n}\n\nasync function getBlob(url){\n return fetch(url, {\n headers: {\n 'Authorization': `Bearer ${token}`,\n }\n })\n .then(response => response.json());\n}\n```\n\n```text\ngatsby-node.js\n```\n\n```text\ncreateSchemaCustomization\n```\n\n```text\n... on Blob { text }\n```\n\n```text\nnull\n```\n\n```text\ngatsby-node.js\n```\n\n```text\n.map(async entry => {\n const files = await getTree(entry);\n return Promise.all(\n files.map(file => getFile(file).then(fileRes => ({ data: fileRes.text })))\n );\n)\n```\n\n```text\nconst files = allFiles.flat();\n```\n\n```text\ngetTree()\n```\n\n```text\n[file1, file2, file3]\n```\n\n```text\n[[file1, file2], [[file1, file2], [file1]], file1, file2]\n```\n\n========================================\n\nComments:\n- If you want to iterate all the files recursively I think you would be better using the Github API v3 for this using api.github.com/repos/bertrandmartel/aws-admin/git/trees/… see this. This way, you wouldn't worry about iterating the tree yourself\n- I have been using this plugin gatsbyjs.org/packages/@mosch/gatsby-source-github, which uses GitHub API, and it was giving a lot of errors. If it's not possible to be done with GraphQL, I will look into Github API.\n- Thank you very much for such a full answer! I will try it and let you know the results. I'd like to ask, are there any reasons I would need a binary content? What is it used for?\n- @jupiteror I wasn't sure, maybe you wanted to get some image files from the repo ?\n- Yes, there might be some images to posts.\n- @jupiteror so most likely the last solution from this answer would be good, it's also the easier to implement. But you would need to base64 decode the files before storing them (if you plan to store them). Also the token may not be necessary if it's a public repository","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":672,"estimatedTokens":3597}}1058{"id":"stack-57577464","source":"stackoverflow","questionId":57577464,"title":"Subscriptions not working with Prisma 2 and Nexus?","tags":["javascript","graphql","prisma","prisma-graphql","nexus-prisma"],"text":"Title: Subscriptions not working with Prisma 2 and Nexus?\nTags: javascript, graphql, prisma, prisma-graphql, nexus-prisma\nSource: Stack Overflow\n\nQuestion:\nSubscriptions with Nexus are undocumented but I searched Github and tried every example in the book. It's just not working for me.\n\nI have cloned Prisma2 GraphQL boilerplate project & my files are as follows:\n\n### prisma/schema.prisma\n\n```\ndatasource db {\n provider = \"sqlite\"\n url = \"file:dev.db\"\n default = true\n}\n\ngenerator photon {\n provider = \"photonjs\"\n}\n\ngenerator nexus_prisma {\n provider = \"nexus-prisma\"\n}\n\nmodel Pokemon {\n id String @default(cuid()) @id @unique\n number Int @unique\n name String\n attacks PokemonAttack?\n}\n\nmodel PokemonAttack {\n id Int @id\n special Attack[]\n}\n\nmodel Attack {\n id Int @id\n name String\n damage String\n}\n```\n\n### src/index.js\n\n```\nconst { GraphQLServer } = require('graphql-yoga')\nconst { join } = require('path')\nconst { makeSchema, objectType, idArg, stringArg, subscriptionField } = require('@prisma/nexus')\nconst Photon = require('@generated/photon')\nconst { nexusPrismaPlugin } = require('@generated/nexus-prisma')\n\nconst photon = new Photon()\n\nconst nexusPrisma = nexusPrismaPlugin({\n photon: ctx => ctx.photon,\n})\n\nconst Attack = objectType({\n name: \"Attack\",\n definition(t) {\n t.model.id()\n t.model.name()\n t.model.damage()\n }\n})\n\nconst PokemonAttack = objectType({\n name: \"PokemonAttack\",\n definition(t) {\n t.model.id()\n t.model.special()\n }\n})\n\nconst Pokemon = objectType({\n name: \"Pokemon\",\n definition(t) {\n t.model.id()\n t.model.number()\n t.model.name()\n t.model.attacks()\n }\n})\n\nconst Query = objectType({\n name: 'Query',\n definition(t) {\n t.crud.findManyPokemon({\n alias: 'pokemons'\n })\n t.list.field('pokemon', {\n type: 'Pokemon',\n args: {\n name: stringArg(),\n },\n resolve: (parent, { name }, ctx) => {\n return ctx.photon.pokemon.findMany({\n where: {\n name\n }\n })\n },\n })\n },\n})\n\nconst Mutation = objectType({\n name: 'Mutation',\n definition(t) {\n t.crud.createOnePokemon({ alias: 'addPokemon' })\n },\n})\n\nconst Subscription = subscriptionField('newPokemon', {\n type: 'Pokemon',\n subscribe: (parent, args, ctx) => {\n return ctx.photon.$subscribe.pokemon()\n },\n resolve: payload => payload\n})\n\nconst schema = makeSchema({\n types: [Query, Mutation, Subscription, Pokemon, Attack, PokemonAttack, nexusPrisma],\n outputs: {\n schema: join(__dirname, '/schema.graphql')\n },\n typegenAutoConfig: {\n sources: [\n {\n source: '@generated/photon',\n alias: 'photon',\n },\n ],\n },\n})\n\nconst server = new GraphQLServer({\n schema,\n context: request => {\n return {\n ...request,\n photon,\n }\n },\n})\n\nserver.start(() => console.log(`π Server ready at http://localhost:4000`))\n```\n\nThe related part is the `Subscription` which I don't know why it's not working or how it's supposed to work.\n\nI searched Github for this query which results in all projects using `Subscriptions`.\n\nI also found out this commit in this project to be relevant to my answer. Posting the related code here for brevity:\n\n```\nimport { subscriptionField } from 'nexus';\nimport { idArg } from 'nexus/dist/core';\nimport { Context } from './types';\n\n export const PollResultSubscription = subscriptionField('pollResult', {\n type: 'AnswerSubscriptionPayload',\n args: {\n pollId: idArg(),\n },\n subscribe(_: any, { pollId }: { pollId: string }, context: Context) {\n // Subscribe to changes on answers in the given poll\n return context.prisma.$subscribe.answer({\n node: { poll: { id: pollId } },\n });\n },\n resolve(payload: any) {\n return payload;\n },\n});\n```\n\nWhich is similar to what I do. But they do have `AnswerSubscriptionPayload` & I don't get any generated type that contains `Subscription` in it.\n\nHow do I solve this? I think I am doing everything right but it's still not working. Every example on GitHub is similar to above & even I am doing the same thing.\n\nAny suggestions?\n\nEdit: Subscriptions aren't implemented yet :(\n\n========================================\n\nTop Answer:\nI seem to have got this working despite subscriptions not being implemented. I have a working pubsub proof of concept based off the prisma2 boilerplate and Ben Awad's video tutorial https://youtu.be/146AypcFvAU . Should be able to get this up and running with redis and websockets to handle subscriptions until the prisma2 version is ready.\n\nhttps://github.com/ryanking1809/prisma2_subscriptions\n\n========================================\n\nCode:\n```text\ndatasource db {\n provider = \"sqlite\"\n url = \"file:dev.db\"\n default = true\n}\n\ngenerator photon {\n provider = \"photonjs\"\n}\n\ngenerator nexus_prisma {\n provider = \"nexus-prisma\"\n}\n\nmodel Pokemon {\n id String @default(cuid()) @id @unique\n number Int @unique\n name String\n attacks PokemonAttack?\n}\n\nmodel PokemonAttack {\n id Int @id\n special Attack[]\n}\n\nmodel Attack {\n id Int @id\n name String\n damage String\n}\n```\n\n```text\nconst { GraphQLServer } = require('graphql-yoga')\nconst { join } = require('path')\nconst { makeSchema, objectType, idArg, stringArg, subscriptionField } = require('@prisma/nexus')\nconst Photon = require('@generated/photon')\nconst { nexusPrismaPlugin } = require('@generated/nexus-prisma')\n\nconst photon = new Photon()\n\nconst nexusPrisma = nexusPrismaPlugin({\n photon: ctx => ctx.photon,\n})\n\nconst Attack = objectType({\n name: \"Attack\",\n definition(t) {\n t.model.id()\n t.model.name()\n t.model.damage()\n }\n})\n\nconst PokemonAttack = objectType({\n name: \"PokemonAttack\",\n definition(t) {\n t.model.id()\n t.model.special()\n }\n})\n\nconst Pokemon = objectType({\n name: \"Pokemon\",\n definition(t) {\n t.model.id()\n t.model.number()\n t.model.name()\n t.model.attacks()\n }\n})\n\nconst Query = objectType({\n name: 'Query',\n definition(t) {\n t.crud.findManyPokemon({\n alias: 'pokemons'\n })\n t.list.field('pokemon', {\n type: 'Pokemon',\n args: {\n name: stringArg(),\n },\n resolve: (parent, { name }, ctx) => {\n return ctx.photon.pokemon.findMany({\n where: {\n name\n }\n })\n },\n })\n },\n})\n\nconst Mutation = objectType({\n name: 'Mutation',\n definition(t) {\n t.crud.createOnePokemon({ alias: 'addPokemon' })\n },\n})\n\nconst Subscription = subscriptionField('newPokemon', {\n type: 'Pokemon',\n subscribe: (parent, args, ctx) => {\n return ctx.photon.$subscribe.pokemon()\n },\n resolve: payload => payload\n})\n\nconst schema = makeSchema({\n types: [Query, Mutation, Subscription, Pokemon, Attack, PokemonAttack, nexusPrisma],\n outputs: {\n schema: join(__dirname, '/schema.graphql')\n },\n typegenAutoConfig: {\n sources: [\n {\n source: '@generated/photon',\n alias: 'photon',\n },\n ],\n },\n})\n\nconst server = new GraphQLServer({\n schema,\n context: request => {\n return {\n ...request,\n photon,\n }\n },\n})\n\nserver.start(() => console.log(`π Server ready at http://localhost:4000`))\n```\n\n```text\nimport { subscriptionField } from 'nexus';\nimport { idArg } from 'nexus/dist/core';\nimport { Context } from './types';\n\n export const PollResultSubscription = subscriptionField('pollResult', {\n type: 'AnswerSubscriptionPayload',\n args: {\n pollId: idArg(),\n },\n subscribe(_: any, { pollId }: { pollId: string }, context: Context) {\n // Subscribe to changes on answers in the given poll\n return context.prisma.$subscribe.answer({\n node: { poll: { id: pollId } },\n });\n },\n resolve(payload: any) {\n return payload;\n },\n});\n```\n\n```text\nSubscription\n```\n\n```text\nSubscriptions\n```\n\n```text\nAnswerSubscriptionPayload\n```\n\n```text\nSubscription\n```\n\n========================================\n\nComments:\n- I thought I'll add the answer when the subscriptions are added but I'll add the edit as the answer :)\n- Ohh yeah I saw your issue on GitHub. I'm already subscribed to that issue. I think subscriptions only work right now with Pub/Sub model which is kinda hackish. And I talked with the team in Slack & they said it's not even specced out yet so we gotta wait. Until then no real-time :)\n- Yeah, I'm happy to fill the space with PubSub until they have something else going.","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":381,"estimatedTokens":2033}}1059{"id":"stack-52711580","source":"stackoverflow","questionId":52711580,"title":"How to see graphene-django DEBUG logs","tags":["django","graphql","graphene-python"],"text":"Title: How to see graphene-django DEBUG logs\nTags: django, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI'm having trouble viewing `DEBUG` level logs with Graphene and Django. I've set the following in `settings.py`:\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['console'],\n 'level': 'DEBUG'\n },\n 'django.request': {\n 'handlers': ['console'],\n 'level': 'DEBUG'\n },\n },\n}\n\nHowever, when I try to look at the logs of my Django server all I see is:\n\n β―β―β― kubectl logs -f server-6b65f48895-bmp6w server\nOperations to perform:\n Apply all migrations: admin, auth, contenttypes, django_celery_beat, django_celery_results, server, sessions, social_django\nRunning migrations:\n No migrations to apply.\nPerforming system checks...\n\nSystem check identified no issues (0 silenced).\nOctober 08, 2018 - 23:59:00\nDjango version 2.0.6, using settings 'backend.settings'\nStarting development server at http://0.0.0.0:8000/\nQuit the server with CONTROL-C.\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\nHow can I view `DEBUG` level logs to figure out why my server is constantly serving 400s?\n\nI have the Django `DEBUG` environment variable unset. I'm trying to debug a production issue.\n\n========================================\n\nTop Answer:\nBased on @donnyy answer I came up with the following implementation\n\n```\nfrom promise import is_thenable\nfrom functools import partial\nimport logging\nimport sys\nimport json\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\nclass DebugMiddleware(object):\n def on_error(self, error ,info):\n log_request_body(info)\n\n def resolve(self, next, root, info, **args):\n\n result = next(root, info, **args)\n if is_thenable(result):\n result.catch(partial(self.on_error, info=info))\n return result\n\ndef log_request_body(info):\n body = info.context._body.decode('utf-8')\n try:\n json_body = json.loads(body)\n logging.error(' User: %s \\n Action: %s \\n Variables: %s \\n Body: %s',\n info.context.user,\n json_body['operationName'],\n json_body['variables'],\n json_body['query'])\n except:\n logging.error(body)\n```\n\n========================================\n\nCode:\n```text\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['console'],\n 'level': 'DEBUG'\n },\n 'django.request': {\n 'handlers': ['console'],\n 'level': 'DEBUG'\n },\n },\n}\n```\n\n```text\nβ―β―β― kubectl logs -f server-6b65f48895-bmp6w server\nOperations to perform:\n Apply all migrations: admin, auth, contenttypes, django_celery_beat, django_celery_results, server, sessions, social_django\nRunning migrations:\n No migrations to apply.\nPerforming system checks...\n\nSystem check identified no issues (0 silenced).\nOctober 08, 2018 - 23:59:00\nDjango version 2.0.6, using settings 'backend.settings'\nStarting development server at http://0.0.0.0:8000/\nQuit the server with CONTROL-C.\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n\"POST /graphql HTTP/1.1\" 400 113\n```\n\n```text\nDEBUG\n```\n\n```text\nsettings.py\n```\n\n```text\nDEBUG\n```\n\n```text\nDEBUG\n```\n\n```text\nfrom promise import is_thenable\n\n\nclass DebugMiddleware(object):\n def on_error(self, error):\n print(error)\n\n def resolve(self, next, root, info, **args):\n result = next(root, info, **args)\n if is_thenable(result):\n result.catch(self.on_error)\n\n return result\n```\n\n```text\nGRAPHENE = {\n ...\n 'MIDDLEWARE': [\n 'path.to.containing.module.DebugMiddleware',\n ...\n ]\n}\n```\n\n```text\ngraphene\n```\n\n```text\ngraphql\n```\n\n```text\nMIDDLEWARE = [\n \"path_to_file_below.GraphqlErrorLogMiddleware\",\n ...\n]\n\n# Some basic logging from the Django Documentation\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\"console\": {\"class\": \"logging.StreamHandler\"}},\n \"root\": {\"handlers\": [\"console\"], \"level\": \"DEBUG\"},\n}\n```\n\n```text\nclass GraphqlErrorLogMiddleware(object):\n \"\"\"\n Logs errors for invalid graphql queries\n \"\"\"\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n\n try:\n if (\n 400 >= response.status_code\n and response.status_code != 403\n and \"graphql\" in request.path.lower()\n ):\n response_json = json.loads(response.content)\n\n if \"errors\" in response_json:\n log_response(\n message=f\"Graphql Error: {response_json['errors']}\",\n response=response,\n level=\"error\",\n )\n except Exception as e:\n logging.debug(f\"Error logging Graphql Error: {e}\")\n\n return response\n```\n\n```text\nsettings.py\n```\n\n```text\nfrom promise import is_thenable\nfrom functools import partial\nimport logging\nimport sys\nimport json\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\nclass DebugMiddleware(object):\n def on_error(self, error ,info):\n log_request_body(info)\n\n def resolve(self, next, root, info, **args):\n\n result = next(root, info, **args)\n if is_thenable(result):\n result.catch(partial(self.on_error, info=info))\n return result\n\n\ndef log_request_body(info):\n body = info.context._body.decode('utf-8')\n try:\n json_body = json.loads(body)\n logging.error(' User: %s \\n Action: %s \\n Variables: %s \\n Body: %s',\n info.context.user,\n json_body['operationName'],\n json_body['variables'],\n json_body['query'])\n except:\n logging.error(body)\n```\n\n========================================\n\nComments:\n- Thanks for the help! Do you mind sharing how to wire this in properly too?\n- what's \"is_thenable\" ?\n- A utility function to determine if the specified object is a promise. Added missing import","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":283,"estimatedTokens":1684}}1060{"id":"stack-66393967","source":"stackoverflow","questionId":66393967,"title":"Apollo Gateway not working inside docker-compose","tags":["docker","docker-compose","graphql","microservices","apollo-server"],"text":"Title: Apollo Gateway not working inside docker-compose\nTags: docker, docker-compose, graphql, microservices, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup a simple Federated Apollo Gateway using Docker and docker-compose but can't seem to get the gateway to connect to the schemas services.\n\nHere is the `docker-compose.yml` file\n\n```\nversion: \"3.9\"\nservices:\n gateway:\n build: ./api-gateway\n ports:\n - 4000:8080\n depends_on:\n - robots\n - sitemaps\n environment:\n APOLLO_KEY: ${APOLLO_KEY}\n volumes:\n - ../secrets/credentials.json:/tmp/key/credentials.json\n - ./api-gateway/index.js:/usr/src/app/index.js\n \n robots:\n build: ./api-robots\n ports:\n - 4001:8080\n environment:\n GOOGLE_APPLICATION_CREDENTIALS: /tmp/key/credentials.json\n volumes:\n - ../secrets/credentials.json:/tmp/key/credentials.json\n - ./api-robots/src:/usr/src/app/src\n\n sitemaps:\n build: ./api-sitemaps\n ports:\n - 4002:8080\n environment:\n GOOGLE_APPLICATION_CREDENTIALS: /tmp/key/credentials.json\n volumes:\n - ../secrets/credentials.json:/tmp/key/credentials.json\n - ./api-sitemaps/src:/usr/src/app/src\n```\n\nIn the gateway code I am registering the `robots` and `sitemaps` services using the following:\n\n```\nconst { ApolloServer } = require(\"apollo-server\");\nconst { ApolloGateway } = require(\"@apollo/gateway\");\n\n// Initialize an ApolloGateway instance and pass it an array of\n// the implementing service names and URLs\nconst gateway = new ApolloGateway({\n serviceList: [\n { name: \"robots\", url: \"http://robots:4001\" },\n { name: \"sitemaps\", url: \"http://sitemaps:4002\" },\n ],\n});\n\nconst server = new ApolloServer({\n gateway,\n subscriptions: false,\n});\n\nserver\n .listen(8080)\n .then(({ url }) => {\n console.log(`π Gateway Server ready at ${url}`);\n })\n .catch((err) => {\n console.error(\"Failed to start Gateway\");\n });\n```\n\nYet, when it runs, I get the following error reported by the gateway service:\n\n```\ngateway_1 | Error checking for changes to service definitions: Couldn't load service definitions for \"robots\" at http://robots:4001: request to http://robots:4001/ failed, reason: connect ECONNREFUSED 172.19.0.3:4001\ngateway_1 | This data graph is missing a valid configuration. Couldn't load service definitions for \"robots\" at http://robots:4001: request to http://robots:4001/ failed, reason: connect ECONNREFUSED 172.19.0.3:4001\n```\n\nI know that the services are working correctly because I am able to connect to the `robots` and `sitemaps` services from the host at `http://localhost:4001` and `http://localhost:4002` respectively; and both work without any issues.\n\nI've read countless threads about this and the most common issue that I find is that others are incorrectly trying to connect on `localhost` instead of using the services name (e.g. `robots` and `sitemaps`) as the domain name. I am not making that mistake.\n\nHere are some other things I have tried, but also did not work ...\n\n- creating a custom `networks` definition and assigning it to each service\n\n- connecting to `http://robots:8080` and `http://sitemaps:8080`\n\n- connecting to `http://localhost:4001` and `http://localhost:4002`\n\nWhat am I doing wrong?\n\n========================================\n\nCode:\n```yaml\nversion: \"3.9\"\nservices:\n gateway:\n build: ./api-gateway\n ports:\n - 4000:8080\n depends_on:\n - robots\n - sitemaps\n environment:\n APOLLO_KEY: ${APOLLO_KEY}\n volumes:\n - ../secrets/credentials.json:/tmp/key/credentials.json\n - ./api-gateway/index.js:/usr/src/app/index.js\n \n robots:\n build: ./api-robots\n ports:\n - 4001:8080\n environment:\n GOOGLE_APPLICATION_CREDENTIALS: /tmp/key/credentials.json\n volumes:\n - ../secrets/credentials.json:/tmp/key/credentials.json\n - ./api-robots/src:/usr/src/app/src\n\n\n sitemaps:\n build: ./api-sitemaps\n ports:\n - 4002:8080\n environment:\n GOOGLE_APPLICATION_CREDENTIALS: /tmp/key/credentials.json\n volumes:\n - ../secrets/credentials.json:/tmp/key/credentials.json\n - ./api-sitemaps/src:/usr/src/app/src\n```\n\n```js\nconst { ApolloServer } = require(\"apollo-server\");\nconst { ApolloGateway } = require(\"@apollo/gateway\");\n\n// Initialize an ApolloGateway instance and pass it an array of\n// the implementing service names and URLs\nconst gateway = new ApolloGateway({\n serviceList: [\n { name: \"robots\", url: \"http://robots:4001\" },\n { name: \"sitemaps\", url: \"http://sitemaps:4002\" },\n ],\n});\n\nconst server = new ApolloServer({\n gateway,\n subscriptions: false,\n});\n\nserver\n .listen(8080)\n .then(({ url }) => {\n console.log(`π Gateway Server ready at ${url}`);\n })\n .catch((err) => {\n console.error(\"Failed to start Gateway\");\n });\n```\n\n```text\ngateway_1 | Error checking for changes to service definitions: Couldn't load service definitions for \"robots\" at http://robots:4001: request to http://robots:4001/ failed, reason: connect ECONNREFUSED 172.19.0.3:4001\ngateway_1 | This data graph is missing a valid configuration. Couldn't load service definitions for \"robots\" at http://robots:4001: request to http://robots:4001/ failed, reason: connect ECONNREFUSED 172.19.0.3:4001\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nrobots\n```\n\n```text\nsitemaps\n```\n\n```text\nrobots\n```\n\n```text\nsitemaps\n```\n\n```text\nhttp://localhost:4001\n```\n\n```text\nhttp://localhost:4002\n```\n\n```text\nlocalhost\n```\n\n```text\nrobots\n```\n\n```text\nsitemaps\n```\n\n```text\nnetworks\n```\n\n```text\nhttp://robots:8080\n```\n\n```text\nhttp://sitemaps:8080\n```\n\n```text\nhttp://localhost:4001\n```\n\n```text\nhttp://localhost:4002\n```\n\n```text\nhttp://robots:8080\n```\n\n```text\nhttp://sitemaps:8080\n```\n\n========================================\n\nComments:\n- hmm, probably networks will be the best option ... AFAIR related to some firewall settings ... log into gateway and check ping to services ... probably address resolved properly (you can try `extra_hosts` if not), then try curl some requests ... no `/graphql` endpoints (url) required on services ?\n- If the processes inside the containers are listening on port 8080, you need to use that port number in the URLs. `ports:` aren't considered (or required) when making connections between containers.\n- ra9r, are you on mac? If you can connect via `http://localhost:4001`, why are you trying to connect via `http://robots:4001`? Another thought - you lack container names in your docker-compose.yaml. So the real hostname (container name) wouldn't be `robots`, but some random name like `folder_robots_1` (checkable with `docker ps`)","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":245,"estimatedTokens":1629}}1061{"id":"stack-58617398","source":"stackoverflow","questionId":58617398,"title":"Next.JS: Resolver with promise doesn't work in api-routes-server-and-client-test on SSR","tags":["node.js","async-await","graphql","apollo","next.js"],"text":"Title: Next.JS: Resolver with promise doesn't work in api-routes-server-and-client-test on SSR\nTags: node.js, async-await, graphql, apollo, next.js\nSource: Stack Overflow\n\nQuestion:\nUsing next.js example api-routes-apollo-server-and-client. When I'm trying to implement delay in `apollo/resolvers.js` this way:\n\n```\nexport const resolvers = {\n Query: {\n viewer (_parent, _args, _context, _info) {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve({ id: 1, name: 'John Smith', status: 'cached' });\n }, 1000);\n })\n }\n }\n}\n```\n\nhttps://i.sstatic.net/Eziry.png\n\nThis doesn't work in SSR. The data is empty in the SSR apollo state but user data expected `{ id: 1, name: 'John Smith', status: 'cached' }`.\n\nI'm using that also with sequelize to fetch the data from database and it doesn't work too. I guess the reason is the same.\n\nMaybe I'm doing something wrong.\n\nClient-side part works fine (data are displayed after React hydratation).\n\nIf we're doing static object instead of Promise:\n\n```\nexport const resolvers = {\n Query: {\n viewer (_parent, _args, _context, _info) {\n return { id: 1, name: 'John Smith', status: 'cached' };\n }\n }\n}\n```\n\nEverything works fine and this puts object to initial state returned from SSR server with correct static markup...\n\nhttps://i.sstatic.net/AXfV3.png\n\n**What am I expecting?**\n\nI want just server render graphql requiest, finish promises, the put the data to apollo state for SSR and does the SSR for SEO purposes. Because for now if I connect to the database - it doesn't work at all (nothing's rendered. just empty page because rendering was interrupted by something).\n\n========================================\n\nTop Answer:\nIf you're trying to emulate the possible delay involved in resolving a remote request, or resolving promises in handlers in general, try this:\n\n```\nexport const resolvers = {\n Query: {\n async viewer(_parent, _args, _context, _info) {\n try {\n const resp = await new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve({ id: 1, name: 'John Smith', status: 'cached' })\n }, 1000)\n })\n return resp\n } catch (err) {\n throw new Error('failed')\n }\n // return { id: 1, name: 'John Smith', status: 'cached' }\n },\n },\n}\n```\n\n`return await new Promise()` doesn't work because the await keyword doesn't do anything in that case, and the object returned is *still* a promise, where your resolvers expect the return value to be an object.\n\nAssigning `await new Promise(...)` to a variable makes sure the promise resolves, and that the variable contains the expected object prior to being returned.\n\n========================================\n\nCode:\n```text\nexport const resolvers = {\n Query: {\n viewer (_parent, _args, _context, _info) {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve({ id: 1, name: 'John Smith', status: 'cached' });\n }, 1000);\n })\n }\n }\n}\n```\n\n```text\nexport const resolvers = {\n Query: {\n viewer (_parent, _args, _context, _info) {\n return { id: 1, name: 'John Smith', status: 'cached' };\n }\n }\n}\n```\n\n```text\napollo/resolvers.js\n```\n\n```text\n{ id: 1, name: 'John Smith', status: 'cached' }\n```\n\n```text\nnpm run build\n```\n\n```text\nnpm start\n```\n\n```js\nexport const resolvers = {\n Query: {\n async viewer(_parent, _args, _context, _info) {\n try {\n const resp = await new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve({ id: 1, name: 'John Smith', status: 'cached' })\n }, 1000)\n })\n return resp\n } catch (err) {\n throw new Error('failed')\n }\n // return { id: 1, name: 'John Smith', status: 'cached' }\n },\n },\n}\n```\n\n```text\nreturn await new Promise()\n```\n\n```text\nawait new Promise(...)\n```\n\n========================================\n\nComments:\n- Please show the calling code. ALL `async` functions return a promise so the caller has to use `await` or `.then()` to get the value from the returned promise. Also, `return await new Promise()` does nothing useful over `return new Promise()`. And, in fact, your function doesn't even need to be `async` as it finds no benefit from that either.\n- @jfriend00 I know. but I'm just emulating resolver with async and await. I'm not talking about optimizations. For calling code please refer to next.js example I linked to the question. So you can edit `apollo/resolvers.js` with contents I sent in the question and try to run. After you run it and disable javascript you'll see that there are no server-side rendered contents after gql query execution.\n- Well, if this is the example you're trying to emulate, you can't do that with an `async` function or a function that returns a promise. That example is a synchronous resolver. You cannot EVER get a synchronous result out of `async` function or out of a promise or any function that obtains its result asynchronously. Can't be done in Javascript. The caller must use `await` or `.then()` to get the value out of the promise.\n- I've done enough guessing here about what you're trying to do. If this isn't enough of a response for you, then please EDIT your question to add more detail that shows exactly what you're trying to do. Or, you can wait and see if someone else who can figure out what you're trying to do comes along. If that's the case, I'll bow out.\n- github.com/georgii-ivanov/next.js/tree/canary/examples/… I need this example working on server-side. This is it. Now it's working on SSR only in case Promise already resolved. (`Promise.resolve(...data)`)\n- For SSR rendering, either you trigger GraphQL queries server-side, and then you have to wait for them to be resolved server-side, or you just render the template and trigger queries client-side. You *cannot* trigger queries server-side, pass unresolved promises to the client and have them be resolved client-side, that just won't work... So it's normal that in your example, SSR works only when the Promise resolves.\n- @Jaxx they use `apollo-link-schema`. I need it to be resolved and pass the result to the apollo state. Apollo can work with promises but this `apollo-link-schema` for some reason only uses resolved promises. I tried to call graphql request from graphql playground and timer worked fine! I need to have server blocked by request it's intended for me because I need those data for SEO\n- This doesn't work as expected. Static markup doesn't have state data from for SSR...\n- removed stuff about async/await because as I can see it's confusing for people. But question about different thing. About SSR static markup\n- Thank you for the response. I'll check that all. I hope you right. I gave you my bounty cuz otherwise that'd be expired but you did your best with checking. Thank you. I'll keep you updated\n- Did that work for you? I've tried to do just that and found that its still populating the data into the state. I'm using the most recent version of the example. `{\"props\":{\"pageProps\":{\"apolloState\"‌​:{}}},\"page\":\"/\",\"qu‌​ery\":{},\"buildId\":\"j‌​uZ1Po43r3rpqmYm354AX‌​\"}`\n- What is your problem exactly?\n- Its not populating the html on that first load. With SSR I'd expect that the first page load fills the html with the data. I tried to do `build` then `start` but the result is still that the html isn't populated with the data. Right not it loads the HTML then makes the graphql call to get the data.","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":167,"estimatedTokens":1856}}1062{"id":"stack-43689284","source":"stackoverflow","questionId":43689284,"title":"How to query a range of values using graphql","tags":["graphql","graphql-js"],"text":"Title: How to query a range of values using graphql\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nMy data models are sequelized and I am looking for a straightforward way to query graphql using from: and to: params to specify range.\n\nAny syntax?\n\n========================================\n\nCode:\n```text\n{\n createdAt: {\n $lt: new Date(),\n $gt: new Date(new Date() - 24 * 60 * 60 * 1000)\n }\n}\n// createdAt < [timestamp] AND createdAt > [timestamp]\n```\n\n========================================\n\nComments:\n- Thanks for helping out ! Exactly what I was looking for.\n- Given that the reference and example is for a SQL ORM, and that the GraphQL spec makes no mention of `$gt` or `$lt`, how is this anything other than a fond fantasy? And how in the world did it get three upvotes???\n- @peteb4ker is mistaken, GraphQL has NO such built-in operators. The 'lt' and 'gt' range operators he refers to are specific to SequelizeJS. This answer should be edited and/or downvoted.\n- edstaub/petri thanks for the valuable feedback. Post updated to specifically call out Sequelize.","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":29,"estimatedTokens":272}}1063{"id":"stack-50284384","source":"stackoverflow","questionId":50284384,"title":"How do I set headers the react-dom/server renderToString passes to graphql server?","tags":["reactjs","graphql","server-side-rendering","react-server"],"text":"Title: How do I set headers the react-dom/server renderToString passes to graphql server?\nTags: reactjs, graphql, server-side-rendering, react-server\nSource: Stack Overflow\n\nQuestion:\nI have a webserver which receives the client's IP from the load balancer via the `X-Forwarded-For` header, but does not forward it to the GraphQL server, making debugging more difficult.\n\nIs it possible to turn this on, or would it require a patch to react-dom/server? How have others solved the problem of gathering contextual data in the graphql server request logs when they are triggered by a server-side-renderer?\n\n========================================\n\nCode:\n```text\nX-Forwarded-For\n```\n\n========================================\n\nComments:\n- You need tell more about which Load Balancer? Also does the LB interact directly with GraphQL server or how? This is a infrastructure dependent question and should include the infra details as well\n- @TarunLalwani the LB interacts with the GraphQL server through the webserverβs server side renderer, which uses the react/dom-server library\n- Which LB? AWS or something else. Also if you take LB out of picture the IP can be seen correctly?\n- I don't think the LB is in the picture, it just passes an X-Forwarded-For header which I know how to extract and would like to pass to `react-dom/server` to forward to the database.\n- I think now I get it, you use a graphql-client on server which makes the IP come as your server ip for every request and you want to actually see the client ip which triggered the server renderer. Right?\n- Yup! I see an internal webserver IP in my graphql logs and no user agent header where I would like to see some headers that would allow me to at least tie the two log statements together.\n- I am not sure if it is possible straight away, but if you provide a ready to use environment using docker-compose or something, I might be able to dig further and help you out. Else setting up the whole environment to reproduce the condition may take too much time for me\n- Itβs a k8s environment with svc local DNS touting. Whatever the library sends the GraphQL server is what it gets in headers β k8s does not any headers on application layer, I donβt think? Can test and verify tomorrow.\n- A repo with `deploy.sh` will also work even if it is a `k8s`, I have a local `k8s` minikube with me\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":29,"estimatedTokens":600}}1064{"id":"stack-43110757","source":"stackoverflow","questionId":43110757,"title":"What are some practical use cases of GraphQL? When should one choose GraphQL over REST?","tags":["graphql"],"text":"Title: What are some practical use cases of GraphQL? When should one choose GraphQL over REST?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nAs I am interested in the concept of graphql I want to understand the benefits of graphql and when to use it?\n\n========================================\n\nComments:\n- This might be helpful stackoverflow.com/questions/42477655/…\n- Thank you :) I hope this will help newcomers to understand graphQL concepts better.what it is and what it is not :) @rmuller\n- I'd say it is \"better\" than REST. I've added GraphQL API to our traditional REST API and I find myself cringing whenever I have to work with the old one. GQL FTW!\n- According to the official documentation, graphql.org/learn/best-practices it is not recommended to use it other endpoints at the same time\n- @Capaj rewriting an old API using new tech is going to feel good regardless of the paradigm used because you have learned from the mistakes of the last one. Most of what you like about GraphQL is probably completely available for REST too. blog.runscope.com/posts/you-might-not-need-graphql\n- Archived page web.archive.org/web/20190528142221/https://phil.tech/api/201‌​7/…","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":16,"estimatedTokens":301}}1065{"id":"stack-44670153","source":"stackoverflow","questionId":44670153,"title":"How to avoid client re fetching in react-apollo SSR with redux?","tags":["node.js","reactjs","redux","graphql","react-apollo"],"text":"Title: How to avoid client re fetching in react-apollo SSR with redux?\nTags: node.js, reactjs, redux, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI am new to graphql with react-appollo I would like to use react apollo with redux also server side rendering Every thing is fine my app is working but the problem is when my app render's it is actually recalling the api again it is not using my rendered state ..\n\nhttps://i.sstatic.net/semIK.gif\n\nserver .js\n\n```\nimport express from 'express';\nimport bodyParser from 'body-parser';\n\nimport path from 'path';\nimport expressGraphQL from 'express-graphql';\nimport schema from './GraphQL/Schema';\nimport React from 'react';\nimport ReactDOMServer from 'react-dom/server'\nimport { StaticRouter } from 'react-router';\nimport { ApolloClient, createNetworkInterface, ApolloProvider } from 'react-apollo';\nimport { getDataFromTree } from \"react-apollo\"\nimport store from '../client/Redux/Store/store';\n\nimport {serverClient} from './lib/apollo'\n\nrequire('es6-promise').polyfill();\nrequire('isomorphic-fetch');\n\nimport WApp from '../client/App';\n\n//Dev HMR\nimport HMR from './serverUtils/HMR';\n\nconst app = express();\napp.use(bodyParser.json());\n\napp.use('/api', expressGraphQL({\n schema,\n graphiql: true\n}));\napp.use('/static',express.static('build'));\nHMR(app);\n\nfunction Html({ content, state }) {\n return (\n \n \n \n \n \n \n \n );\n}\n\nfunction createReactHandler(req) {\n return async function reactHandler(ctx) {\n const routeContext = {};\n const client = serverClient();\n\n const components = (\n \n \n \n \n \n );\n\n await getDataFromTree(components);\n\n // const html = ReactDOMServer.renderToString(components);\n\n // // Handle redirects\n // if ([301, 302].includes(routeContext.status)) {\n // // 301 = permanent redirect, 302 = temporary\n // ctx.status = routeContext.status;\n //\n // // Issue the new `Location:` header\n // ctx.redirect(routeContext.url);\n //\n // // Return early -- no need to set a response body\n // return;\n // }\n //\n // // Handle 404 Not Found\n // if (routeContext.status === 404) {\n // // By default, just set the status code to 404. You can add your\n // // own custom logic here, if you want to redirect to a permanent\n // // 404 route or set a different response on `ctx.body`\n // ctx.status = routeContext.status;\n // }\n\n // return html;\n // console.log(html)\n\n }\n}\n\nconst HTML = ({ html,state}) => (\n\n \n \n \n \n \n \n\n \n \n \n \n\n \n\n \n \n);\n\napp.get('/*',(req,res) => {\n const routeContext = {};\n const client = serverClient();\n\n const components = (\n \n \n \n \n \n );\n\n getDataFromTree(components).then(() => {\n const html = ReactDOMServer.renderToString(components);\n const initialState = {apollo: client.getInitialState()}\n\n console.log(client);\n\n res.send(`\\n${ReactDOMServer.renderToStaticMarkup(\n ,\n )}`)\n })\n})\n\napp.listen(3000,() => {\n console.log('Man I on')\n})\n```\n\nstore.js\n\n```\nimport { createStore, compose, applyMiddleware } from 'redux';\nimport { syncHistoryWithStore } from 'react-router-redux';\nimport thunk from 'redux-thunk';\nimport {createLogger} from 'redux-logger';\n\nimport client from '../apolloClient';\nimport rootReducer from '../Reducers'\n\n//All Reducer\nimport {initialState as allPosts} from '../Reducers/AllPosts_Reucer';\nconst isProduction = process.env.NODE_ENV !== 'development';\nconst isClient = typeof document !== 'undefined';\nconst initialState = {\n allPosts\n};\n\nconst middlewares = [thunk, client.middleware()];\nconst enhancers = [];\n\nif (!isProduction && isClient) {\n const loggerMiddleware = createLogger();\n middlewares.push(loggerMiddleware);\n\n if (typeof devToolsExtension === 'function') {\n const devToolsExtension = window.devToolsExtension;\n enhancers.push(devToolsExtension());\n }\n}\n\nconst composedEnhancers = compose(\n applyMiddleware(...middlewares),\n ...enhancers\n);\nconst store = createStore(\n rootReducer,\n {},\n\n composedEnhancers,\n);\n\nexport default store;\n```\n\napolloClient.js\n\n```\nimport ApolloClient, {\n createNetworkInterface,\n\n} from 'apollo-client';\nconst isProduction = process.env.NODE_ENV !== 'development';\nconst testUrl = 'http://localhost:3000/api';\n\n// const url = isProduction ? productionUrl : testUrl;\nconst url = testUrl;\n\nconst client = new ApolloClient({\n\n networkInterface: createNetworkInterface({uri:testUrl}),\n dataIdFromObject:({id}) => id,\n initialState: (typeof window !=='undefined')? window.__STATE__:{},\n reduxRootSelector:state => state.custom\n\n});\n\nexport default client;\n```\n\nHome.js\n\n```\nimport React,{Component} from 'react';\nimport { connect } from 'react-redux';\nimport { bindActionCreators } from 'redux';\nimport { graphql } from 'react-apollo';\n\nimport gql from 'graphql-tag';\n\nimport * as postActions from '../../Redux/Actions/postActions';\n\nclass Home extends Component{\n componentWillMount(){\n // console.log('From Will Mount',this.props.posts)\n }\n renderAllPost(){\n const {loading,posts} = this.props;\n\n if(!loading){\n return posts.map(data => {\n return \n- {data.title}\n })\n }else{\n return loading\n }\n }\n render(){\n\n return(\n \n\n {this.renderAllPost()}\n\n \n )\n }\n}\n\n//start from here\nconst GetallPosts = gql`\nquery getAllPosts{\n posts{\n id\n title\n body\n }\n}\n`;\n\nconst mapDispatchToProps = (dispatch) => ({\n actions:bindActionCreators(\n postActions,\n dispatch\n )\n});\n\nconst ContainerWithData = graphql(GetallPosts,{\n props:({ data:{loading,posts} }) => ({\n posts,\n loading,\n })\n})(Home)\n\nexport default connect(\n // mapStateToPros,\n // mapDispatchToProps\n)(ContainerWithData)\n```\n\n========================================\n\nCode:\n```text\nimport express from 'express';\nimport bodyParser from 'body-parser';\n\nimport path from 'path';\nimport expressGraphQL from 'express-graphql';\nimport schema from './GraphQL/Schema';\nimport React from 'react';\nimport ReactDOMServer from 'react-dom/server'\nimport { StaticRouter } from 'react-router';\nimport { ApolloClient, createNetworkInterface, ApolloProvider } from 'react-apollo';\nimport { getDataFromTree } from \"react-apollo\"\nimport store from '../client/Redux/Store/store';\n\nimport {serverClient} from './lib/apollo'\n\nrequire('es6-promise').polyfill();\nrequire('isomorphic-fetch');\n\nimport WApp from '../client/App';\n\n//Dev HMR\nimport HMR from './serverUtils/HMR';\n\nconst app = express();\napp.use(bodyParser.json());\n\napp.use('/api', expressGraphQL({\n schema,\n graphiql: true\n}));\napp.use('/static',express.static('build'));\nHMR(app);\n\nfunction Html({ content, state }) {\n return (\n <html>\n <body>\n <div id=\"app\" dangerouslySetInnerHTML={{ __html: content }}/>\n <script src=\"/static/app.js\" />\n <script dangerouslySetInnerHTML={{\n __html: `window.__APOLLO_STATE__=${JSON.stringify(state).replace(/</g, '\\\\u003c')};`,\n }} />\n </body>\n </html>\n );\n}\n\nfunction createReactHandler(req) {\n return async function reactHandler(ctx) {\n const routeContext = {};\n const client = serverClient();\n\n const components = (\n <StaticRouter location={req.url} context={routeContext}>\n <ApolloProvider store={store} client={client}>\n <WApp />\n </ApolloProvider>\n </StaticRouter>\n );\n\n await getDataFromTree(components);\n\n // const html = ReactDOMServer.renderToString(components);\n\n // // Handle redirects\n // if ([301, 302].includes(routeContext.status)) {\n // // 301 = permanent redirect, 302 = temporary\n // ctx.status = routeContext.status;\n //\n // // Issue the new `Location:` header\n // ctx.redirect(routeContext.url);\n //\n // // Return early -- no need to set a response body\n // return;\n // }\n //\n // // Handle 404 Not Found\n // if (routeContext.status === 404) {\n // // By default, just set the status code to 404. You can add your\n // // own custom logic here, if you want to redirect to a permanent\n // // 404 route or set a different response on `ctx.body`\n // ctx.status = routeContext.status;\n // }\n\n // return html;\n // console.log(html)\n\n\n }\n}\n\n\n\nconst HTML = ({ html,state}) => (\n\n <html lang=\"en\" prefix=\"og: http://ogp.me/ns#\">\n <head>\n <meta charSet=\"utf-8\" />\n <meta httpEquiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta httpEquiv=\"Content-Language\" content=\"en\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n\n </head>\n <body>\n <div\n id=\"app\"\n dangerouslySetInnerHTML={{ __html: html }} />\n <script dangerouslySetInnerHTML={{\n __html: `window.__STATE__=${JSON.stringify(state)};`,\n }} />\n\n <script src=\"/static/app.js\" />\n\n </body>\n </html>\n);\n\napp.get('/*',(req,res) => {\n const routeContext = {};\n const client = serverClient();\n\n const components = (\n <StaticRouter location={req.url} context={routeContext}>\n <ApolloProvider store={store} client={client}>\n <WApp />\n </ApolloProvider>\n </StaticRouter>\n );\n\n getDataFromTree(components).then(() => {\n const html = ReactDOMServer.renderToString(components);\n const initialState = {apollo: client.getInitialState()}\n\n console.log(client);\n\n res.send(`<!DOCTYPE html>\\n${ReactDOMServer.renderToStaticMarkup(\n <HTML\n html={html}\n state={initialState}\n />,\n )}`)\n })\n})\n\n\n\n\napp.listen(3000,() => {\n console.log('Man I on')\n})\n```\n\n```text\nimport { createStore, compose, applyMiddleware } from 'redux';\nimport { syncHistoryWithStore } from 'react-router-redux';\nimport thunk from 'redux-thunk';\nimport {createLogger} from 'redux-logger';\n\n\nimport client from '../apolloClient';\nimport rootReducer from '../Reducers'\n\n//All Reducer\nimport {initialState as allPosts} from '../Reducers/AllPosts_Reucer';\nconst isProduction = process.env.NODE_ENV !== 'development';\nconst isClient = typeof document !== 'undefined';\nconst initialState = {\n allPosts\n};\n\nconst middlewares = [thunk, client.middleware()];\nconst enhancers = [];\n\nif (!isProduction && isClient) {\n const loggerMiddleware = createLogger();\n middlewares.push(loggerMiddleware);\n\n if (typeof devToolsExtension === 'function') {\n const devToolsExtension = window.devToolsExtension;\n enhancers.push(devToolsExtension());\n }\n}\n\n\nconst composedEnhancers = compose(\n applyMiddleware(...middlewares),\n ...enhancers\n);\nconst store = createStore(\n rootReducer,\n {},\n\n composedEnhancers,\n);\n\nexport default store;\n```\n\n```text\nimport ApolloClient, {\n createNetworkInterface,\n\n} from 'apollo-client';\nconst isProduction = process.env.NODE_ENV !== 'development';\nconst testUrl = 'http://localhost:3000/api';\n\n// const url = isProduction ? productionUrl : testUrl;\nconst url = testUrl;\n\n\nconst client = new ApolloClient({\n\n networkInterface: createNetworkInterface({uri:testUrl}),\n dataIdFromObject:({id}) => id,\n initialState: (typeof window !=='undefined')? window.__STATE__:{},\n reduxRootSelector:state => state.custom\n\n});\n\nexport default client;\n```\n\n```text\nimport React,{Component} from 'react';\nimport { connect } from 'react-redux';\nimport { bindActionCreators } from 'redux';\nimport { graphql } from 'react-apollo';\n\nimport gql from 'graphql-tag';\n\nimport * as postActions from '../../Redux/Actions/postActions';\n\n\nclass Home extends Component{\n componentWillMount(){\n // console.log('From Will Mount',this.props.posts)\n }\n renderAllPost(){\n const {loading,posts} = this.props;\n\n if(!loading){\n return posts.map(data => {\n return <li key={data.id}>{data.title}</li>\n })\n }else{\n return <div>loading</div>\n }\n }\n render(){\n\n return(\n <div>\n\n {this.renderAllPost()}\n\n </div>\n )\n }\n}\n\n\n//start from here\nconst GetallPosts = gql`\nquery getAllPosts{\n posts{\n id\n title\n body\n }\n}\n`;\n\nconst mapDispatchToProps = (dispatch) => ({\n actions:bindActionCreators(\n postActions,\n dispatch\n )\n});\n\n\nconst ContainerWithData = graphql(GetallPosts,{\n props:({ data:{loading,posts} }) => ({\n posts,\n loading,\n })\n})(Home)\n\n\nexport default connect(\n // mapStateToPros,\n // mapDispatchToProps\n)(ContainerWithData)\n```\n\n========================================\n\nComments:\n- Could you Pls Provide some Code example .ill give you what data you want.","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":593,"estimatedTokens":3136}}1066{"id":"stack-74066789","source":"stackoverflow","questionId":74066789,"title":"Apollo iOS client code generation: \"Error: Cannot query field\"","tags":["ios","graphql","apollo","apollo-client"],"text":"Title: Apollo iOS client code generation: \"Error: Cannot query field\"\nTags: ios, graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm trying to generate code following this steps using cocoa pods.\nOn step: 5. Setup and run code generation using `appolo-ios-cli generate` command I'm getting this error:\n\n```\nError: Cannot query field \"getAuthServiceHealth\" on type \"undefined\"\n ./../NetworkInterface/GraphQL/QueriesList.graphql:2:2\n1 | query Health {\n2 | getAuthServiceHealth{\n | ^\n3 | status\n```\n\nQueries.graphql:\n\n```\nquery Health {\n getAuthServiceHealth{\n status\n service\n }\n}\n```\n\nschema:\n\n```\n{\n \"__schema\": {\n \"queryType\": {\n \"name\": \"Query\"\n },\n \"mutationType\": null,\n \"subscriptionType\": null,\n \"types\": [\n {\n \"kind\": \"OBJECT\",\n \"name\": \"Query\",\n \"description\": null,\n \"fields\": [\n {\n \"name\": \"getAuthServiceHealth\",\n \"description\": null,\n \"args\": [],\n \"type\": {\n \"kind\": \"NON_NULL\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"OBJECT\",\n \"name\": \"HealthResponse\",\n \"ofType\": null\n }\n },\n \"isDeprecated\": false,\n \"deprecationReason\": null\n },\n```\n\nWhy I'm getting this error?\n\nThanks\n\n========================================\n\nCode:\n```text\nError: Cannot query field \"getAuthServiceHealth\" on type \"undefined\"\n ./../NetworkInterface/GraphQL/QueriesList.graphql:2:2\n1 | query Health {\n2 | getAuthServiceHealth{\n | ^\n3 | status\n```\n\n```text\nquery Health {\n getAuthServiceHealth{\n status\n service\n }\n}\n```\n\n```text\n{\n \"__schema\": {\n \"queryType\": {\n \"name\": \"Query\"\n },\n \"mutationType\": null,\n \"subscriptionType\": null,\n \"types\": [\n {\n \"kind\": \"OBJECT\",\n \"name\": \"Query\",\n \"description\": null,\n \"fields\": [\n {\n \"name\": \"getAuthServiceHealth\",\n \"description\": null,\n \"args\": [],\n \"type\": {\n \"kind\": \"NON_NULL\",\n \"name\": null,\n \"ofType\": {\n \"kind\": \"OBJECT\",\n \"name\": \"HealthResponse\",\n \"ofType\": null\n }\n },\n \"isDeprecated\": false,\n \"deprecationReason\": null\n },\n```\n\n```text\nappolo-ios-cli generate\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.225Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":122,"estimatedTokens":549}}1067{"id":"stack-70593242","source":"stackoverflow","questionId":70593242,"title":"How to setup Amplify Datastore schema for single table design","tags":["amazon-web-services","graphql","amazon-dynamodb","aws-amplify","aws-appsync"],"text":"Title: How to setup Amplify Datastore schema for single table design\nTags: amazon-web-services, graphql, amazon-dynamodb, aws-amplify, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nFor my project, I need to be able to query and change my data offline, syncing the changes whenever the connection is restored. Therefore, DynamoDB with Amplify Appsync and Datastore seems like the best option, but we are struggling with some conflicting recommendations.\n\nOur data is structured around Items, which have Locations that should be changed and synced in real-time. As a Location could contain multiple Items and an Item could have multiple Locations, we deal with many-to-many relations. We should be able to query all Items, all Locations, all Locations for a single Item, all Items for a Location. This is the base requirement of the data structure, but we should be able to add queries for things like last modified items etc. Next to this, we have a multi-tenant setup, so there should be a way to authorize users to parts of the data. We will probably use user groups to filter the data.\n\nMost resources online state that in order to take full advantage of DynamoDB, a single table design approach is the way to go. This would mean that we could use a structure as shown in this documentation, adding sortkeys to make additional queries.\n\nThe Datastore documentation says the @model directive should be used to be able to set up all mutations, queries and subscriptions. In order to make the relations between the Items and Locations, we should use the @manyToMany directive as stated here. All together this would result in the following schema:\n\n```\ntype Item \n @model\n @auth(rules: [{ allow: groups, groupsField: \"groups\" }])\n {\n ID: ID!\n groups: String!\n locations: [Location] @manyToMany(relationName: \"ItemLocation\")\n ...\n }\n\ntype Location \n @model\n @auth(rules: [{ allow: groups, groupsField: \"groups\" }])\n {\n ID: ID!\n groups: String!\n items: [Item] @manyToMany(relationName: \"ItemLocation\")\n ...\n }\n```\n\nWhen we deploy this schema using the Amplify CLI, all resources are generated without problems. However, if we look at the DynamoDB tables, we find that there are multiple tables generated: Item, Location and ItemLocation. The @model directive automatically deploys a table, as does the @manyToMany directive. Dynamodb documentation does not use these directives, so it should be possible to make a single table from the given requirements. I am not able to find how to do this from the Datastore/Amplify side, or how to connect Datastore to an existing DynamoDB as Datastore relies on the @model directive to store data locally (or that is what I suspect). This is not in line with the DynamoDB standard, and we would like to change this setup to a single table design.\n\nI have been looking in the Amplify, Datastore and DynamoDB documentation and in online rescources, but was not able to find any guidance or solutions. Hopefully someone can push me in the right direction, thanks!\n\n========================================\n\nTop Answer:\nThis may help someone else looking to use the single-table design feature of the DynamoDB with Amplify.\n\nAmplify Gen2 has added support to use existing resources that are not managed by Amplify.\n\nThis Amplify Documentation page shows how to configure it and also has examples of CRUD operations using AppSync.\n\nThis Medium article also has a good example of using AppSync/Amplify with single-table design. It avoids using @model directive from Amplify GraphQL\n\n========================================\n\nCode:\n```text\ntype Item \n @model\n @auth(rules: [{ allow: groups, groupsField: \"groups\" }])\n {\n ID: ID!\n groups: String!\n locations: [Location] @manyToMany(relationName: \"ItemLocation\")\n ...\n }\n\ntype Location \n @model\n @auth(rules: [{ allow: groups, groupsField: \"groups\" }])\n {\n ID: ID!\n groups: String!\n items: [Item] @manyToMany(relationName: \"ItemLocation\")\n ...\n }\n```\n\n```text\n@model\n```\n\n```text\n@manyToMany\n```\n\n========================================\n\nComments:\n- This is very helpful, thank you. We will start out using the default amplify setup, and work our way through until we have a stable product. In the future, we might want to change the structure to a single table design, should this be necessary. Do you know if this is feasible, including denormalizing the existing data? If so, is there documentation or a tutorial/guide demonstrating this process?\n- Glad to help. Sure, later table migration is possible. You will use the DynamoDB SDK to loop through the old table entries and make new entries in the new table.","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":88,"estimatedTokens":1168}}1068{"id":"stack-69988248","source":"stackoverflow","questionId":69988248,"title":"Apollo GraphQL dynamic authenticated subgraphs","tags":["graphql","apollo","apollo-server","graphql-js","apollo-federation"],"text":"Title: Apollo GraphQL dynamic authenticated subgraphs\nTags: graphql, apollo, apollo-server, graphql-js, apollo-federation\nSource: Stack Overflow\n\nQuestion:\nI'm building an Apollo Gateway w/ Federated schemas - and I have many subgraphs - each of them has their own authentication token (e.g many REST APIs, each user has his own token saved in the database for each REST API).\n\nI'm fetching the token for each REST API for each user in the Gateway to reduce the overload from each subgraph and to check the permissions on the gateway level, but I'm struggling with how to pass the credentials to each subgraph from the gateway.\n\nI came across this answer, however, here he's building the `serviceList` himself and I'm using Apollo Federation - and the gateway object doesn't have access to the `serviceMap` because it is a private under the Typescript definition, also - this is a very hackish way of accomplishing it:\n\n```\nclass RequestHander extends RemoteGraphQLDataSource {\n willSendRequest({ request }: { request: GraphQLRequest }) {\n // if request.http.url matches url of a service which you\n // use, add api-key to headers, e.g.\n if (request.http.url === 'http://localhost:3001') {\n request.http.headers.set('api-key', )\n }\n }\n}\n\nconst main = () => {\n const gateway = new ApolloGateway({\n buildService: ({ url }) => new RequestHander({ url }),\n serviceList: [\n { name: 'service1', url: 'http://localhost:3001' },\n { name: 'service2', url: 'http://localhost:3002' },\n ],\n })\n\n const server = new ApolloServer({ gateway })\n\n void server.listen({ port: 3000 }).then(({ url }) => {\n logger.info(`Apollo Gateway ready at ${url}`)\n })\n}\n```\n\nAny best practices or better methods to make dynamically authenticated subgraphs?\n\n========================================\n\nCode:\n```text\nclass RequestHander extends RemoteGraphQLDataSource {\n willSendRequest({ request }: { request: GraphQLRequest }) {\n // if request.http.url matches url of a service which you\n // use, add api-key to headers, e.g.\n if (request.http.url === 'http://localhost:3001') {\n request.http.headers.set('api-key', <API_KEY>)\n }\n }\n}\n\nconst main = () => {\n const gateway = new ApolloGateway({\n buildService: ({ url }) => new RequestHander({ url }),\n serviceList: [\n { name: 'service1', url: 'http://localhost:3001' },\n { name: 'service2', url: 'http://localhost:3002' },\n ],\n })\n\n const server = new ApolloServer({ gateway })\n\n void server.listen({ port: 3000 }).then(({ url }) => {\n logger.info(`Apollo Gateway ready at ${url}`)\n })\n}\n```\n\n```text\nserviceList\n```\n\n```text\nserviceMap\n```\n\n```js\nfor (const [serviceName, dataSource] of Object.entries((<any>gateway).serviceMap)) {\n if ((<any>dataSource).url == request.http?.url) { \n ... \n }\n}\n.\n```\n\n```text\nserviceMap\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":92,"estimatedTokens":716}}1069{"id":"stack-57084650","source":"stackoverflow","questionId":57084650,"title":"How do i add items to a list?","tags":["javascript","database","amazon-dynamodb","graphql","aws-appsync"],"text":"Title: How do i add items to a list?\nTags: javascript, database, amazon-dynamodb, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI'd like to add a string word to the `listOfVideosRated[]` list in my Users table.\n\n========================================\n\nCode:\n```text\nlistOfVideosRated[]\n```\n\n```text\nconst existingItem = {\n id: \"e5eb02ae-04d5-4331-91e6-11efaaf12ea5\",\n Pairs: [['a', 'b'],['c', 'd'],['e', 'f']]\n}\n\nconst newPairs = {\n number1: \"g\",\n number2: \"h\"\n}\n\nconst updateinfo = {\n id: existingItem.id,\n // Note that if existingItem.Pairs is always defined this can be simplified to\n // Pairs: [...existingItem.Pairs, [newPairs.number1, newPairs.number2]]\n Pairs: existingItem.Pairs ?\n [...existingItem.Pairs, [newPairs.number1, newPairs.number2]] : \n [[newPairs.number1, newPairs.number2]]\n}\n\ntry {\n await API.graphql(graphqlOperation (UpdateInfo, { input: updateinfo })) \n //mutation\n console.log('success')\n} \ncatch (err) {\n console.log(err)\n}\n```\n\n```text\n### SDL\ntype Item {\n id: ID!\n Pairs: [[String]]\n}\n\ninput AddPairInput {\n id: ID!\n number1: String!\n number2: String!\n}\n\ntype Mutation {\n addPairToItem(input: AddPairInput!): Item!\n}\n\n...rest of schema omitted for brevity \n\n### Resolver Request Mapping Template\n{\n \"version\": \"2017-02-28\",\n \"operation\": \"UpdateItem\",\n \"key\": {\n \"id\": { \"S\": \"$ctx.args.input.id\"}\n },\n \"update\": {\n ### Note: we also use if_not_exists here so this works if Pairs is not yet defined on the item.\n \"expression\":\"SET Pairs = list_append(if_not_exists(Pairs, :emptyList), :newPair)\",\n \"expressionValues\": \n { \n \":newPair\":{\"L\": [{\"L\":[{\"S\":\"$ctx.args.input.number1\"},\n {\"S\":\"$ctx.args.input.number2\"}]}]},\n \":emptyList\":{\"L\": []}\n }\n }\n}\n\n### Resolver Response Mapping Template\n$util.toJson($ctx.result)\n```\n\n```text\n### ./amplify/backend/api/<api_name>/schema.graphql\ntype Item @model {\n id: ID!\n Pairs: [[String]]\n}\n\ntype Mutation {\n addPairToItem(input: AddPairToItemInput!): Item!\n}\n\ninput AddPairToItemInput {\n id: ID!\n number1: String!\n number2: String!\n}\n```\n\n```text\n### ./amplify/backend/api/<api_name>/resolvers/Mutation.addPairToItem.req.vtl\n{\n \"version\": \"2017-02-28\",\n \"operation\": \"UpdateItem\",\n \"key\": {\n \"id\": { \"S\": \"$ctx.args.input.id\"}\n },\n \"update\": {\n \"expression\":\"SET Pairs = list_append(if_not_exists(Pairs, :emptyList), :newPair)\",\n \"expressionValues\":\n {\n \":newPair\":{\"L\": [{\"L\":[{\"S\":\"$ctx.args.input.number1\"},{\"S\":\"$ctx.args.input.number2\"}]}]},\n \":emptyList\":{\"L\": []}\n }\n }\n}\n```\n\n```text\n### ./amplify/backend/api/<api_name>/resolvers/Mutation.addPairToItem.res.vtl\n$util.toJson($ctx.result)\n```\n\n```text\n### ./amplify/backend/api/<api_name>/stacks/CustomResources.json\n \"Resources\": {\n // ...other resources may exist here\n \"AddPairToItemResolver\": {\n \"Type\": \"AWS::AppSync::Resolver\",\n \"Properties\": {\n \"ApiId\": {\n \"Ref\": \"AppSyncApiId\"\n },\n \"DataSourceName\": \"ItemTable\",\n \"TypeName\": \"Mutation\",\n \"FieldName\": \"addPairToItem\",\n \"RequestMappingTemplateS3Location\": {\n \"Fn::Sub\": [\n \"s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.addPairToItem.req.vtl\",\n {\n \"S3DeploymentBucket\": {\n \"Ref\": \"S3DeploymentBucket\"\n },\n \"S3DeploymentRootKey\": {\n \"Ref\": \"S3DeploymentRootKey\"\n }\n }\n ]\n },\n \"ResponseMappingTemplateS3Location\": {\n \"Fn::Sub\": [\n \"s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.addPairToItem.res.vtl\",\n {\n \"S3DeploymentBucket\": {\n \"Ref\": \"S3DeploymentBucket\"\n },\n \"S3DeploymentRootKey\": {\n \"Ref\": \"S3DeploymentRootKey\"\n }\n }\n ]\n }\n }\n }\n },\n```\n\n```text\nimport Amplify, { API, graphqlOperation } from \"aws-amplify\";\nimport * as mutations from './graphql/mutations';\n\n// Mutation\nconst addPairToItem = {\n id: '1',\n number1: 'a',\n number2: 'b'\n};\n\nconst newItem = await API.graphql(graphqlOperation(mutations.addPairToItem, {input: addPairToItem}));\n```\n\n```text\n### ./amplify/backend/api/<api_name>/schema.graphql\ntype Item @model {\n id: ID!\n words: [String]\n}\n\ninput AddWordInput {\n id: ID!\n word: String!\n}\n\ntype Mutation {\n addWordToItem(input: AddWordInput!): Item!\n}\n\n### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordToItem.req.vtl\n{\n \"version\": \"2017-02-28\",\n \"operation\": \"UpdateItem\",\n \"key\": {\n \"id\": { \"S\": \"$ctx.args.input.id\"}\n },\n \"update\": {\n \"expression\":\"SET words = list_append(if_not_exists(words, :emptyList), :newWord)\",\n \"expressionValues\":\n {\n \":newWord\":{\"L\": [{\"S\":\"$ctx.args.input.word\"}]},\n \":emptyList\":{\"L\": []}\n }\n }\n}\n\n### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordToItem.res.vtl\n$util.toJson($ctx.result)\n\n\n### Usage\nimport Amplify, { API, graphqlOperation } from \"aws-amplify\";\nimport * as mutations from './graphql/mutations';\n\n// Mutation\nconst newWord = {\n id: '1',\n word: 'foo'\n};\n\nconst newItem = await API.graphql(graphqlOperation(mutations.addWordToItem, {input: newWord}));\n```\n\n```text\n### ./amplify/backend/api/<api_name>/schema.graphql\ntype Item @model {\n id: ID!\n words: [String]\n}\n\ninput AddWordsInput {\n id: ID!\n words: [String!]!\n}\n\ntype Mutation {\n addWordsToItem(input: AddWordsInput!): Item!\n}\n\n### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordsToItem.req.vtl\n{\n \"version\": \"2017-02-28\",\n \"operation\": \"UpdateItem\",\n \"key\": {\n \"id\": { \"S\": \"$ctx.args.input.id\"}\n },\n \"update\": {\n \"expression\":\"SET words = list_append(if_not_exists(words, :emptyList), :newWords)\",\n \"expressionValues\":\n {\n \":newWords\": $util.dynamodb.toDynamoDBJson($ctx.args.input.words),\n \":emptyList\": $util.dynamodb.toDynamoDBJson([])\n }\n }\n}\n\n### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordsToItem.res.vtl\n$util.toJson($ctx.result)\n\n\n### Usage\nimport Amplify, { API, graphqlOperation } from \"aws-amplify\";\nimport * as mutations from './graphql/mutations';\n\n// Mutation\nconst newWords = {\n id: '1',\n words: [\"bar\",\"xyz\",\"bar\"]\n};\n\nconst newItem = await API.graphql(graphqlOperation(mutations.addWordsToItem, {input: newWords}));\n```\n\n```text\ntype Item @model {\n id: ID!\n words: [String]\n}\n\ninput RemoveWordInput {\n id: ID!\n wordIndex: Int!\n}\n\ntype Mutation {\n removeWordFromItem(input: RemoveWordInput!): Item!\n}\n\n### ./amplify/backend/api/<api_name>/resolvers/Mutation.removeWordFromItem.req.vtl\n{\n \"version\": \"2017-02-28\",\n \"operation\": \"UpdateItem\",\n \"key\": {\n \"id\": { \"S\": \"$ctx.args.input.id\"}\n },\n \"update\": {\n \"expression\":\"REMOVE words[$ctx.args.input.wordIndex]\"\n }\n}\n\n### ./amplify/backend/api/<api_name>/resolvers/Mutation.removeWordFromItem.res.vtl\n$util.toJson($ctx.result)\n\n\n### Usage\nimport Amplify, { API, graphqlOperation } from \"aws-amplify\";\nimport * as mutations from './graphql/mutations';\n\n// Mutation\nconst removeWord = {\n id: '1',\n // The index is 0 based so wordIndex: 0\n // would delete the first item,\n // wordIndex: 1 deletes the second, etc.\n wordIndex: 1 \n};\n\nconst newItem = await API.graphql(graphqlOperation(mutations.removeWordFromItem, {input: removeWord}));\n```\n\n```text\nPairs\n```\n\n```text\nlist_append\n```\n\n```text\nlist_append\n```\n\n```text\namplify api gql-compile\n```\n\n```text\namplify push\n```\n\n```text\namplify api console\n```\n\n```text\namplify codegen\n```\n\n```text\n$util.dynamodb.toDynamoDBJson\n```\n\n========================================\n\nComments:\n- I think you will need to get the record first, then update the record and push. The records in dynamo are stored as json objects, I don't think can modify an objects keys, just replace them. I could be wrong\n- @NathanQuinn How do we delete? And also how do we delete a single item from a list? list_append only concatenates two lists but there is no documetation on how to remove an item from a list.\n- @chai86 Do you mean just a list of scalar values? (e.g. [\"a\", \"b\", \"c])\n- @Babu When you say delete, do you mean remove an attribute entirely from an item? I understand what you mean when you ask about deleting an item from a list, but want to understand your first use case. I will post some additional examples of using other DynamoDB functions.\n- @chai86 I added an example of adding single scalar values and multiple scalar values to a list. This answer is getting pretty long now. I will make a GitHub repo containing more.\n- @NathanQuinn consider the dynamodb field type is \"List\" I need to remove an item from it.Right now list_append technically concatenates two lists? But I just need to implement the functionality to append and remove a single scalar type. Pls the github repo. Much appreciated and Thanks!!\n- @Babu I added an example of deleting an item here. I will update with the GitHub repo when I wrap up some more examples.\n- @NathanQuinn I'm soooo close to finishing the app i'm working on (and Amplify has been really useful). However i'm stuck on this last part to REMOVE a row, could you please urgently help!!!! I've updated the original post with all the information. Thanks :)\n- @NathanQuinn A github repo with examples is definitely MUCH appreciated, if you have time, adding \"an object\" to a list is also something I need right now, for example a type Message with ID, author and content, and a type Collection with [Message]\n- Absolutely fantastic answer, very helpful. Wish I could've upvoted more!\n- Great stuff, super useful answer, thanks for sharing.\n- how do one go about adding a custom object to a list ?","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":380,"estimatedTokens":2612}}1070{"id":"stack-59355574","source":"stackoverflow","questionId":59355574,"title":"Rejecting & error handling of GraphQL file upload","tags":["file-upload","error-handling","upload","graphql","express-graphql"],"text":"Title: Rejecting & error handling of GraphQL file upload\nTags: file-upload, error-handling, upload, graphql, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI have an express GraphQL endpoint with a resolver that accepts a single file. The resolver includes a simple validation of the file being received.\n\nThe problem is that when the validation fails, there is no way to immediately return the error to the front end, as throwing an error will not force the uploading request to be interrupted.\n\nAn over-simplified example:\n\n```\nfileUpload: async (parent, { file, otherdata }) => {\n const isValid = (some logic here)\n if(!isValid)\n throw new ApolloError('upload parameters not valid')\n\n //No need to get this far,\n //we could have rejected the request already by examining otherdata,\n //or the stream could be already created for max time utilization\n\n const { createReadStream, filename, mimetype, encoding } = await file;\n const readStream = await createReadStream()\n ...\n }\n```\n\n**Expected behavior:** The resolver returns the usual {errors:[], data:null} object - or the error itself - depending on the error-policy option.\n\n**Actual behavior:** The error is thrown in the backend but the request remains pending in the frontend.\n\nI have already unsuccessfully tried the following:\n\n- Initializing the readStream anyway and calling .destroy() on it. Result is that the read stream stops and the request remains pending for ever.\n\n- Including the request object (tried the response object as well) in the resolver context and calling .destroy() on it. This ends the request but results in a network error in the front end, leaving no opportunity for error specific handling.\n\nSome clarifications: \n\n- Apparently there is client side verifications as well, but that does not make server side verification unnecessary.\n\n- Waiting for the upload to be completed and then throwing the error obviously works, but that is not really an option, time and bandwidth wise.\n\nI understand that uploading files using GraphQL is borderline supported functionality, but in this case we are talking about a rather basic operation.\n\nI would appreciate any suggestions!\n\n========================================\n\nCode:\n```text\nfileUpload: async (parent, { file, otherdata }) => {\n const isValid = (some logic here)\n if(!isValid)\n throw new ApolloError('upload parameters not valid')\n\n //No need to get this far,\n //we could have rejected the request already by examining otherdata,\n //or the stream could be already created for max time utilization\n\n const { createReadStream, filename, mimetype, encoding } = await file;\n const readStream = await createReadStream()\n ...\n }\n```\n\n```text\nconst apollo = new ApolloServer({\n typeDefs,\n resolvers,\n context: ({ req, res }) => {\n return {\n req,\n res\n };\n }\n});\n```\n\n```text\nfileUpload: async (parent, { file, otherdata }, {req, res}) => {\n const isValid = (some logic here)\n if(!isValid){\n res.send(403).send(\"Some message\")\n // Throwing ApolloError could also work,\n // in which case response object would not be required, but not tested.\n // throw new ApolloError('upload parameters not valid')\n return req.destroy()\n }\n \n\n //No need to get this far,\n //we could have rejected the request already by examining otherdata,\n //or the stream could be already created for max time utilization\n\n const { createReadStream, filename, mimetype, encoding } = await file;\n const readStream = await createReadStream()\n ...\n }\n```\n\n========================================\n\nComments:\n- when i use `res.send(403)` nothing is happened, response is not send to client. Using `GraphQLError` is the same output\n- Is the response not sent even if it is the only action of the resolver?\n- in that case, resolver sends response","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":107,"estimatedTokens":973}}1071{"id":"stack-39644286","source":"stackoverflow","questionId":39644286,"title":"Composing GraphQL queries","tags":["graphql"],"text":"Title: Composing GraphQL queries\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nSuppose a GraphQL schema supports the following queries:\n\n```\n{\n person(id: String) {\n locationId\n }\n}\n```\n\nand\n\n```\n{\n location(id: String) {\n country\n }\n}\n```\n\nIs it possible to find a `person` by `id`, then use the resulting `locationid` to find their `location` by `id` (returning the `country` corresponding to that `location`) all the in a single query?\n\nOr would I have to make two separate queries?\n\n========================================\n\nTop Answer:\nThe query would look like this;\n\n```\n{\n person(id: string){\n location{\n country\n }\n }\n}\n```\n\nIn your person type, you can apply a resolver to the `location` field which gets the location based on the locationId of the person which the query is performed against.\n\n========================================\n\nCode:\n```text\n{\n person(id: String) {\n locationId\n }\n}\n```\n\n```text\n{\n location(id: String) {\n country\n }\n}\n```\n\n```text\nperson\n```\n\n```text\nid\n```\n\n```text\nlocationid\n```\n\n```text\nlocation\n```\n\n```text\nid\n```\n\n```text\ncountry\n```\n\n```text\nlocation\n```\n\n```text\nlocation\n```\n\n```text\nperson\n```\n\n```text\nlocation\n```\n\n```text\nperson\n```\n\n```text\nperson\n```\n\n```text\nlocation\n```\n\n```text\nlocations\n```\n\n```text\nlocation\n```\n\n```text\n{\n person(id: string){\n location{\n country\n }\n }\n}\n```\n\n```text\nlocation\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":138,"estimatedTokens":354}}1072{"id":"stack-60536395","source":"stackoverflow","questionId":60536395,"title":"I am getting the following errors saying 'Could not freeze ./node_modules/","tags":["reactjs","graphql","node-modules","prisma-graphql"],"text":"Title: I am getting the following errors saying 'Could not freeze ./node_modules/\nTags: reactjs, graphql, node-modules, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI'm building a web app using GraphQL and React. When compiling the front-end/client I see the following errors:\n\nhttps://i.sstatic.net/a9Tvp.png\n\nIs there something else I can provide to help debug this?\n\nThank you!\n\n========================================\n\nCode:\n```text\nrm -rf node_modules/.cache\n```\n\n========================================\n\nComments:\n- For those extra cautious with `rm -rf` :-). `cd node_modules/.cache; rm -rf hard-source` worked for me.\n- It's a temporary solution. It reoccurs after then second webpack.\n- I don't have a `.cache` in my `node_modules` folder.","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":26,"estimatedTokens":190}}1073{"id":"stack-64799192","source":"stackoverflow","questionId":64799192,"title":"TypeError: Cannot read property 'getPosts' of undefined - useQuery hook, react Functional Components","tags":["reactjs","graphql","react-hooks","apollo-client","react-functional-component"],"text":"Title: TypeError: Cannot read property 'getPosts' of undefined - useQuery hook, react Functional Components\nTags: reactjs, graphql, react-hooks, apollo-client, react-functional-component\nSource: Stack Overflow\n\nQuestion:\nI did try searching for the same question but all of those were of either angular or unrelated,\n\nI am trying to make a **Social app using MongoDB, Express, React, Node, Graphql with Apollo**, I am following a video from freecodecamp : Link to the video\nIn that video everything worked fine but in his deployed version he is having the same error as mine\n\nreact_devtools_backend.js:2450 TypeError:\n\nCannot read property 'getPosts' of undefined\n\nat ae (Home.js:14)\nat Jo (react-dom.production.min.js:3274)\n\nlink to the deployed app\n\n**My Code:** **I am dropping a link to my github repo** containing the whole project : Link to github\nrepo\n\n**Stack Overflow was throwing too many indentation issues so i have linked my github above** as there\nis too much of code\n\n- I'm using semantic-ui for styling\n\n- I'm using graphql the fetch posts from MongoDB\n\n- Apollo Client for rendering data\n\nThis is the error I am getting in the Home.js:\n**Screen Shot of the error:**\n\nhttps://i.sstatic.net/oVOIj.png\n\n========================================\n\nTop Answer:\nuse this code like this\n\nconst { loading, data: { posts } = {} } = useQuery(FETCH_POSTS_QUERY);\n\n========================================\n\nCode:\n```text\nconst { data, loading, error } = useQuery(FETCH_POSTS_QUERY);\nif(data) {\n console.log(data);\n const { getPosts: posts } = data;\n}\nif(error) {\n console.log(error);\n return \"error\"; // blocks rendering\n}\n```\n\n```text\n{loading && <h1>Loading posts..</h1>}\n {data && (\n <Transition.Group>\n {posts &&\n posts.map((post) => (\n <Grid.Column key={post.id} style={{ marginBottom: 20 }}>\n <PostCard post={post} />\n </Grid.Column>\n ))}\n </Transition.Group>\n )}\n```\n\n```text\ndata\n```\n\n```text\n!loading\n```\n\n```text\ndata != undefined\n```\n\n```text\nif(data)\n```\n\n```text\n(data &&\n```\n\n```text\nexport const FETCH_POSTS_QUERY = gql`\n query GetPosts {\n getPosts {\n // fields\n }\n }\n`\n```\n\n```text\nexport const FETCH_POSTS_QUERY = gql`\n query GetPosts {\n posts: getPosts {\n // fields\n }\n }\n`\n\nconst {\n loading,\n data: { posts } // uses alias directly. no need to rename\n} = useQuery(FETCH_POSTS_QUERY);\n```\n\n```text\nalias\n```\n\n```text\nconst { loading, data: { getPosts: posts } = {} } = useQuery(FETCH_POSTS_QUERY)\n```\n\n```text\n{loading ? (<h1>Loading posts...</h1>) \n : (data.getPosts &&\n data.getPosts.map((post) => (\n <Grid.Column key={post.id} style= {{ marginBottom: 20}}>\n <PostCard post={post} />\n </Grid.Column>\n```\n\n```text\nError! ${error.message}\n```\n\n========================================\n\nComments:\n- READ DOCS! 'data' CAN be undefined when in loading state ... `if(loading) { return \"loading\" };` before main return (and destructuring or any acces to deeper 'data' property) prevents this kind of errors\n- Can you please help me with the code, like can you post the code as answer?\n- apollographql.com/docs/react/api/react/hooks/#example-2 apollographql.com/docs/react/data/queries/#executing-a-query\n- I followed the docs now i am rendering the code conditionally but still facing the same error\n- ehhhh, look at network tab - response contains error - bad data, bad results ... `error` can be derived from hook, too and should block rendering like loading\n- nothing like that everything has a status code of 304 and no error\n- should be 200 for POST, always ... \"Cannot return null for non-nullable field Post.username.\" 54-th item is nulled ... render jsoned 'posts' (or insert 'debugger' before return) to check it ... disable minification, it's hard to check where points error displayed in console\n- code please, I am a beginner and hence it's for me to understand what you are trying to say\n- `if(data) console.log(posts);` before return\n- now it says data is undefined\n- in debugger? 'data' can be undefined at first (run - F5), later, after response (and 2nd rendering) it will be filled with data this should show array 'posts' (if no error)\n- no use same error I think I should just **drop this project**, anyways **I am really sorry** to waste such a huge time of yours @xadm and thanks for bearing me for such a long time.\n- Now i am getting this error : `TypeError: Cannot read property 'posts' of undefined`\n- @GayatriDipali, updated the answer to explicitly show a complete gql statement.\n- it worked for me just for one minute and now it's throwing the same error\n- It may be unrelated to `Home.js`. Maybe `SinglePost.js`?\n- **Thanks your debugging trick worked** now I am able to get know what actually the error is, I am getting network errors that is the issue by the line in which you wrote return error\n- usable ... for one depth level only\n- Some people might need a bit more explanation on object destructuring to better understand your answer.\n- it's needed to define data as an object. sets the default as an empty object which was the old behaviour.\n- old? HOCs? ... if you're refactoring to hooks then you can use new behaviour (undefined `data`) - you can use `if(!data)` as general not-ready condition, not relying on some, deeper (also undefined) prop","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":162,"estimatedTokens":1328}}1074{"id":"stack-64561818","source":"stackoverflow","questionId":64561818,"title":"How do insert multiple entities and return them in TypeORM","tags":["node.js","express","graphql","typeorm"],"text":"Title: How do insert multiple entities and return them in TypeORM\nTags: node.js, express, graphql, typeorm\nSource: Stack Overflow\n\nQuestion:\nLet's say i have a Vote entity. I want to insert an array with 5 votes simultaneously and return them. I have tried : await Vote.save(votes) but that doesnt work and it doesnt return them either. Any ideas?\n\n========================================\n\nCode:\n```text\nconst votesEntities = Vote.create(votes);\n```\n\n```text\nawait Vote.save(votesEntities);\n```\n\n```text\nasync insertVotes(votes) {\n const votesEntities = Vote.create(votes);\n await Vote.insert(votesEntities);\n return votesEntities;\n}\n```\n\n```text\ninsert\n```\n\n```text\nsave\n```\n\n```text\nsave\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":37,"estimatedTokens":175}}1075{"id":"stack-45238419","source":"stackoverflow","questionId":45238419,"title":"How to query Github GraphQL API from PHP script?","tags":["php","facebook","github","graphql","github-api"],"text":"Title: How to query Github GraphQL API from PHP script?\nTags: php, facebook, github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nI am querying Github API for some internal monitoring interface. I came across the new GraphQL implementation in the documentation and decided to use it for my interface.\n\nAccordingly, I prepared this small PHP script to test the Github GraphQL API which I have pasted below. I always get βProblems parsing JSONβ error whenever I run the script. Am I doing something wrong here? Can somebody help me highlight any mistake I am doing?\n\n```\n\n```\n\n========================================\n\nCode:\n```text\n<?php\n //GRAPHQL request\n $postData =<<<βJSONβ\n {\n βqueryβ: query{\n user(login:βtojochackoβ) {\n name\n }\n }\n }\n JSON;\n\n $json = json_encode($postData);\n\n $chObj = curl_init();\n curl_setopt($chObj, CURLOPT_URL, βhttps://api.github.com/graphqlβ);\n curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, βPOSTβ);\n curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);\n curl_setopt($chObj, CURLOPT_HEADER, true);\n curl_setopt($chObj, CURLOPT_VERBOSE, true);\n curl_setopt($chObj, CURLOPT_HTTPHEADER,\n array(\n βUser-Agent: PHP Scriptβ,\n βContent-Type: application/jsonβ,\n 'Authorization: bearer '.GITHUB_TOKEN\n )\n );\n\n $response = curl_exec($chObj);\n echo $response;\n?>\n```\n\n```text\n//GRAPHQL request\n$query = <<<'JSON'\nquery{\n user(login:\"tojochacko\") {\n name\n }\n}\nJSON;\n$variables = '';\n\n$json = json_encode(['query' => $query, 'variables' => $variables]);\n\n$chObj = curl_init();\ncurl_setopt($chObj, CURLOPT_URL, βhttps://api.github.com/graphqlβ);\ncurl_setopt($chObj, CURLOPT_RETURNTRANSFER, true); \ncurl_setopt($chObj, CURLOPT_CUSTOMREQUEST, 'POST');\ncurl_setopt($chObj, CURLOPT_HEADER, true);\ncurl_setopt($chObj, CURLOPT_VERBOSE, true);\ncurl_setopt($chObj, CURLOPT_POSTFIELDS, $json);\ncurl_setopt($chObj, CURLOPT_HTTPHEADER,\n array(\n 'User-Agent: PHP Script',\n 'Content-Type: application/json;charset=utf-8',\n 'Authorization: bearer '.GITHUB_TOKEN \n )\n ); \n\n$response = curl_exec($chObj);\necho $response;\n```\n\n========================================\n\nComments:\n- You can ommit the `curl_setopt($chObj, CURLOPT_HEADER, true);` line, because it includes the header information to the response, while someone might just want to `json_decode` it.","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":87,"estimatedTokens":614}}1076{"id":"stack-49421370","source":"stackoverflow","questionId":49421370,"title":"graphql-dotnet VS graphql-net - Which library is useful for fetching/writing data to/from DB","tags":["graphql","github-graphql"],"text":"Title: graphql-dotnet VS graphql-net - Which library is useful for fetching/writing data to/from DB\nTags: graphql, github-graphql\nSource: Stack Overflow\n\nQuestion:\nI want to integrate GraphQL to my existing ASP.NET Framework (with Entity Framework 4) application which has an MSSQL Server as the backend.\n\nWhile browsing through the GraphQL libraries for .NET I found 2 libraries - **graphql-dotnet** and **graphql-net**, being suggested on the GraphQL website (Link: http://graphql.org/code/#c-net)\n\nIt seems that (correct me if I'm wrong) :\n\n- **graphql-dotnet** (https://github.com/graphql-dotnet/graphql-dotnet) - This library only supports in-memory data\n\n- **graphql-net** (https://github.com/ckimes89/graphql-net) - This library works well if we want to work with data which has been stored in DB.\n\nAny suggestion or corrections? Is it possible to perform read/write to/from the DB using the former **(i.e. graphql-dotnet)** library? \nOr should I use the **graphql-net** library instead?\n\n========================================\n\nTop Answer:\nWell, in our project we decided to use graphql-dotnet lib to get data from API services and sharepoint lists - so, it's sort of proxy one WebAPI service. Now we are in production and it works fine with good performance (except getting data from sharepoint list, but it's issue of SharePoint - not graphql-dotnet lib).\n\nbtw, lib itself is more stable than graphql-net and has plenty of active contributes.\n\nOne more project or, I'd say component, where we decided to use graphql-dotnet lib has released as well. That component allows you to connect to db and configure GraphQL schemes easily (via json file). Already implemented main features like: sort, pagination and complex filter.\n\n========================================\n\nComments:\n- I have tried graphql-dotnet. That's not just In-memory you can integrate with DB as well. I tried with github.com/landmarkhw/Dapper.GraphQL to query from SQL\n- Here is the sample Application for grapql-dotnet and dapper : github.com/sandeepbs404/GraphQlWithDapper.Sample\n- Hey, I currently very new to GraphQL and was wondering if there any downsides using Hot Chocolate over GraphQL-dotnet? The main reason I am considering using Hot Chocolate is the code first approach where all properties of a model are loaded in the graph type and then you can specify further and ignore properties and so on. There are also some other minor things like the ErrorBuilder that look awesome. Did you benchmark both frameworks by any chance? Since both frameworks rely on the asp.net core there shouldn't be that much of a difference if any. I would really appreciate your view.\n- @ArturK. There is also schema stitching that we provide with hot chocolate. You can basically use Hot Chocolate to stitch together schemas from various GraphQL servers. hotchocolate.io/docs/stitching\n- I have been using hot chocolate library and it is awesome! You should definitely go through their documentation and try it out.","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":35,"estimatedTokens":747}}1077{"id":"stack-68810116","source":"stackoverflow","questionId":68810116,"title":"check if record exists using prisma graphql apollo","tags":["graphql","apollo-server","prisma"],"text":"Title: check if record exists using prisma graphql apollo\nTags: graphql, apollo-server, prisma\nSource: Stack Overflow\n\nQuestion:\ntrying to check if a record exists in a table in Postgres using Prisma, but seems like I can only query the id field, but not any other fields like `name` and `location`, which gives a compiler error\n\nmodel `schema.prisma`\n\n```\nmodel place {\n id Int @id @default(dbgenerated(\"nextval('place_id_seq'::regclass)\"))\n name String\n location String @unique\n}\n```\n\ngenerated type\n\n```\nexport type Place = {\n __typename?: 'Place';\n name?: Maybe;\n location?: Maybe;\n\n};\n```\n\nQuery resolver\n\n```\nlet findPlace = await prisma.place.findUnique(\n {\n where: {\n name: \"abc\"\n }\n }\n)\n```\n\nerror\n\n```\nType '{ name: string; }' is not assignable to type 'placeWhereUniqueInput'.\n Object literal may only specify known properties, and 'name' does not exist in type 'placeWhereUniqueInput'.ts(2322)\nindex.d.ts(1361, 5): The expected type comes from property 'where' which is declared here on type '{ select?: placeSelect | null | undefined; include?: placeInclude | null | undefined; rejectOnNotFound?: RejectOnNotFound | undefined; where: placeWhereUniqueInput; }'\n```\n\nwhat's missing here to make this work?\n\n========================================\n\nTop Answer:\n`findUnique` only works for unique fields. You shouldn't use `count` either as it unnecessarily goes through the whole table.\n\nThe better approach is to use `findFirst`, which is basically a `LIMIT 1` on the database, so the database can stop searching for more results after the first hit.\n\n```\nconst exists = !!await prisma.place.findFirst(\n {\n where: {\n name: \"abc\"\n }\n }\n);\n```\n\nI'm using the `!!` to cast the object to a boolean.\n\n========================================\n\nCode:\n```text\nmodel place {\n id Int @id @default(dbgenerated(\"nextval('place_id_seq'::regclass)\"))\n name String\n location String @unique\n}\n```\n\n```text\nexport type Place = {\n __typename?: 'Place';\n name?: Maybe<Scalars['String']>;\n location?: Maybe<Scalars['String']>;\n\n};\n```\n\n```text\nlet findPlace = await prisma.place.findUnique(\n {\n where: {\n name: \"abc\"\n }\n }\n)\n```\n\n```text\nType '{ name: string; }' is not assignable to type 'placeWhereUniqueInput'.\n Object literal may only specify known properties, and 'name' does not exist in type 'placeWhereUniqueInput'.ts(2322)\nindex.d.ts(1361, 5): The expected type comes from property 'where' which is declared here on type '{ select?: placeSelect | null | undefined; include?: placeInclude | null | undefined; rejectOnNotFound?: RejectOnNotFound | undefined; where: placeWhereUniqueInput; }'\n```\n\n```text\nname\n```\n\n```text\nlocation\n```\n\n```text\nschema.prisma\n```\n\n```js\nlet placeCount = await prisma.place.count(\n {\n where: {\n name: \"abc\"\n }\n }\n)\n// placeCount == 0 implies does not exist\n```\n\n```text\nfindUnique\n```\n\n```text\ncount\n```\n\n```js\nconst exists = !!await prisma.place.findFirst(\n {\n where: {\n name: \"abc\"\n }\n }\n);\n```\n\n```text\nfindUnique\n```\n\n```text\ncount\n```\n\n```text\nfindFirst\n```\n\n```text\nLIMIT 1\n```\n\n```text\n!!\n```\n\n========================================\n\nComments:\n- This is best because transmit less data.\n- I liked the `!!` cast","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":171,"estimatedTokens":825}}1078{"id":"stack-43233760","source":"stackoverflow","questionId":43233760,"title":"What are the differences between Apollo Client and Relay?","tags":["reactjs","graphql","relay","apollo","react-apollo"],"text":"Title: What are the differences between Apollo Client and Relay?\nTags: reactjs, graphql, relay, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI have just been introduced to GraphQL and am deciding between the two frameworks (Apollo and Relay) for implementing my front end React web app.\n\nI'm aware that Relay is built by Facebook, while Apollo is by Meteor. Has anyone tried both and how has your experience been? I'm wondering what are the differences between them and which kind of GraphQL apps would benefit more from using Relay as compared to Apollo.\n\n========================================\n\nCode:\n```text\nsubscriptions-transport-ws\n```\n\n========================================\n\nComments:\n- Thank you for your detailed answer (:","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":20,"estimatedTokens":187}}1079{"id":"stack-61978524","source":"stackoverflow","questionId":61978524,"title":"Error: Cannot find module 'graphql/validation/rules/PossibleTypeExtensions'","tags":["node.js","express","graphql"],"text":"Title: Error: Cannot find module 'graphql/validation/rules/PossibleTypeExtensions'\nTags: node.js, express, graphql\nSource: Stack Overflow\n\nQuestion:\nI am using the following book to build a MERN stack CRUD application. I'm having trouble installing and running graphql.\n\nhttps://www.amazon.com/Pro-MERN-Stack-Development-Express-dp-1484243900/dp/1484243900/ref=mt_paperback?_encoding=UTF8&me=&qid= (published in 2019).\n\nWhen I try to start the server contained in this repo https://github.com/vasansr/pro-mern-stack-2/tree/05.02-graphql-schema-file with the command npm start the app crashes and it returns an\n\nError: Cannot find module 'graphql/validation/rules/PossibleTypeExtensions'\n\nI then followed some advice from a previous instance of this question on here to npm install karma-sinon-chai for the dependancies. But then I get the following error:\n\nnpm WARN apollo-graphql@0.4.4 requires a peer of graphql@^14.2.1 but none is installed. You must install peer dependencies yourself.\n\n========================================\n\nTop Answer:\nFor me simply running `npm install -g graphql` fixed the problem (I had already installed Apollo globally with `npm install -g apollo`).\n\n========================================\n\nCode:\n```text\nnpm install -g graphql\n```\n\n```text\nnpm install -g apollo\n```\n\n========================================\n\nComments:\n- `yarn add graphql -D` is more than enough:)","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":37,"estimatedTokens":350}}1080{"id":"stack-62070769","source":"stackoverflow","questionId":62070769,"title":"Graphql-ruby how to define a hash as type","tags":["ruby-on-rails","ruby","graphql","graphql-ruby","graphql-schema"],"text":"Title: Graphql-ruby how to define a hash as type\nTags: ruby-on-rails, ruby, graphql, graphql-ruby, graphql-schema\nSource: Stack Overflow\n\nQuestion:\nIs there a possibility to define a Hash as Type field in graphql-ruby schema?\nIn my data structure there is a multi language String type, which consist out of the language code as key and a corresponding text. At the Moment there are 2 languages provided like:\n\n```\n{ \n \"en\" : \"hello\",\n \"de\" : \"hallo\"\n}\n```\n\nSo it is enough to build a type like that:\n\n```\nclass Types::LanguageStringType How does a type looks like which provides a Map of String to String? The corresponding typescript interface looks like this for example:\n\n```\ntitle: {\n [language: string]: string;\n}\n```\n\nTo make a step further, like a recursive node:\n\n```\nexport interface NodeDescription {\n name: string\n children?: {\n [childrenCategory: string]: NodeDescription[];\n }\n}\n```\n\nIs there a way to use this in a field as a Types::NodeDescriptionType in graphql-ruby schema?\n\n========================================\n\nCode:\n```text\n{ \n \"en\" : \"hello\",\n \"de\" : \"hallo\"\n}\n```\n\n```rb\nclass Types::LanguageStringType < GraphQL::Schema::Object\n field :de, String, null:true\n field :en, String, null:true\n end\n```\n\n```text\ntitle: {\n [language: string]: string;\n}\n```\n\n```text\nexport interface NodeDescription {\n name: string\n children?: {\n [childrenCategory: string]: NodeDescription[];\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks for your answer! I would like to dump my schema in a `schema.json` and use this file to generate typescript interfaces with `graphql-code-gen`. If there is a custom scalar type, is it possible to generate a Typescript Interface which looks like the `NodeDescription`? My feeling says it is impossible :/\n- I'm not familiar with graphql-code-gen, but it might be possible. I did a search for \"graphql-code-gen custom scalars\" and found some results that look more or less like what you want to do.","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":76,"estimatedTokens":495}}1081{"id":"stack-56955524","source":"stackoverflow","questionId":56955524,"title":"React-apollo update vs refetch","tags":["javascript","reactjs","graphql","react-apollo"],"text":"Title: React-apollo update vs refetch\nTags: javascript, reactjs, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI am using react-apollo and have been for quite some time. One thing that has already been a problem for me is the fact that refetch doesn't work when using a mutation This has been a know issue for as long as I have been using the app.\n\nI have got round this by using the `refetch` prop that is available on a query. \n\n```\n\n {({ loading, data, error, refetch }) => {\n ... pass down to mutation\n \n```\n\nHowever I am now reading in the documentation that you recieve \nan update method as part of a mutation and you should use this to update your application after a mutation.\n\nCan you use the `update` function to update your UI's data and have it update after finishing a mutation? If you can, is this the standard way to do updates now?\n\n*Using refetchQueries not working\n\nhttps://i.sstatic.net/AUVyY.png\n\nAs you can see in the image the `console.info()` displays that the `data.status = \"CREATED\";` but the request coming back from the mutation directly is `data.status = \"PICKED\";` `PICKED` is the correct and uptodate information in the DB.\n\n========================================\n\nCode:\n```text\n<Query query={query} fetchPolicy={fetchPolicy} {...props}>\n {({ loading, data, error, refetch }) => {\n ... pass down to mutation\n </Query>\n```\n\n```text\nrefetch\n```\n\n```text\nupdate\n```\n\n```text\nconsole.info()\n```\n\n```text\ndata.status = \"CREATED\";\n```\n\n```text\ndata.status = \"PICKED\";\n```\n\n```text\nPICKED\n```\n\n```text\n<Mutation\n mutation={ADD_TODO}\n update={(cache, { data: { addTodo } }) => {\n const { todos } = cache.readQuery({ query: GET_TODOS });\n cache.writeQuery({\n query: GET_TODOS,\n data: { todos: todos.concat([addTodo]) },\n });\n }}\n>\n {(addTodo) =>(...)}\n</Mutation>\n```\n\n```text\n<Mutation\n mutation={ADD_TODO}\n refetchQueries={() => [\n { query: TODOS_QUERY, variables: { foo: 'BAR' } },\n ]}\n>\n {(addTodo) =>(...)}\n</Mutation>\n```\n\n```text\nid\n```\n\n```text\n_id\n```\n\n```text\nid\n```\n\n```text\naddTypename\n```\n\n```text\nfalse\n```\n\n```text\nupdate\n```\n\n```text\nupdate\n```\n\n```text\nrefetchQueries\n```\n\n```text\nrefetchQueries\n```\n\n```text\nupdate\n```\n\n```text\nrefetch\n```\n\n```text\nrefetch\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nMutation\n```\n\n```text\nQuery\n```\n\n```text\nrefetchQueries\n```\n\n```text\nupdateQueries\n```\n\n```text\nupdate\n```\n\n```text\nupdate\n```\n\n========================================\n\nComments:\n- Oh wow... I did not realise that it would update if you supply a query to the mutation that it will auto update. If I do a `mutation something(){}` no data is returned, so for option 1. I need to supply a query along with the mutation I assume? Also thank you for the reply :)\n- You'd need to provide some kind of selection set regardless, unless your mutation just returns a scalar. But to answer your question, effectively, yes. Keep in mind, again, there's limitations to this mechanism as outlined in the answer. Check the normalization section in the docs for more details.\n- Ye I believe this will be my major problem then, `mutation returns the mutated result` . If I am correct I can manually map all of my data structures using `InMemoryCache({ dataIdFromObject` I have updated my question to include an image of why the `refetchQueries` does not work. Again I believe it is this mapping. Thank you a bloody ton for help too mate. Super helpful answer!!!\n- Ooo I think the issue could possible be because we are using `graph-lodash` I will play around with this\n- Wow... remove lodash.. problem solves!! You life saver Daniel. I will try to mention this in all of the github places I find people having similar problems. I've just recreated the `transform` that lodash was given us in our `apollo.js` component\n- `graphql-lodash` is an experimental project and probably shouldn't be used in production. I can't speak to how it would interact with Apollo's caching logic, but it sounds like there was some incongruity there. Glad you got it worked out.\n- If you need some more points Daniel :D stackoverflow.com/questions/57205665/…","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":177,"estimatedTokens":1034}}1082{"id":"stack-57790647","source":"stackoverflow","questionId":57790647,"title":"How to implement exception handler for GraphQL in Spring","tags":["java","spring-mvc","exception","graphql","graphql-java"],"text":"Title: How to implement exception handler for GraphQL in Spring\nTags: java, spring-mvc, exception, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI'm building web application that is using GraphQL with leangen graphql-spqr.\n\nI have problem with exception handling. For example inside service class I'm using spring bean validation that checks for some validity and if its not correct, its throwing ConstraintViolationException.\n\nIs there any way to add some exception handler that would send proper message to the client? Something like ExceptionHandler for controllers in rest api?\nOr maybe it should be done in other way?\n\n========================================\n\nCode:\n```text\npublic class ExceptionHandler implements DataFetcherExceptionHandler {\n\n @Override\n public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) {\n\n Throwable exception = handlerParameters.getException();\n\n // do something with exception\n\n GraphQLError error = GraphqlErrorBuilder\n .newError()\n .message(exception.getMessage())\n .build();\n\n return DataFetcherExceptionHandlerResult\n .newResult()\n .error(error)\n .build();\n }\n}\n```\n\n```text\nGraphQL.newGraphQL(someSchema)\n .queryExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))\n .mutationExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))\n .build();\n```\n\n========================================\n\nComments:\n- Please note, that default strategy for mutation is `AsyncSerialExecutionStrategy` if you want preserve defaults.\n- If you want to truely preserve defaults, you're better off setting the exception handler using the `defaultDataFetcherExceptionHandler` method.","metadata":{"transformedAt":"2026-08-18T18:32:36.226Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":50,"estimatedTokens":454}}1083{"id":"stack-58776809","source":"stackoverflow","questionId":58776809,"title":"Can custom headers be set for urql?","tags":["javascript","github","graphql","urql"],"text":"Title: Can custom headers be set for urql?\nTags: javascript, github, graphql, urql\nSource: Stack Overflow\n\nQuestion:\nThe Github GraphQL v4 API has so-called Schema Previews where you can use new schema features - but it requires a custom `Accept` header.\n\nI've used the Apollo client before but I'd like to try this new app with Formidables *urlq*. Is there a way to set customer headers with the urql client?\n\n**Update**\n\nI think this has gone into the codebase, it's just not documented - https://github.com/FormidableLabs/urql/pull/96/files\n\n========================================\n\nTop Answer:\nFor asynchronous token setting, you can use the auth exchange\n\n```\nimport { createClient, dedupExchange, cacheExchange, fetchExchange } from 'urql';\nimport { authExchange } from '@urql/exchange-auth';\n\nconst getAuth = async ({ authState, mutate }) => {\n if (!authState) {\n const token = await getToken();\n const refreshToken = await getRefreshToken();\n if (token && refreshToken) {\n return { token, refreshToken };\n }\n return null;\n }\n\n return null;\n};\n\nconst addAuthToOperation = ({ authState, operation }) => {\n if (!authState || !authState.token) {\n return operation;\n }\n\n const fetchOptions =\n typeof operation.context.fetchOptions === 'function'\n ? operation.context.fetchOptions()\n : operation.context.fetchOptions || {};\n\n return makeOperation(operation.kind, operation, {\n ...operation.context,\n fetchOptions: {\n ...fetchOptions,\n headers: {\n ...fetchOptions.headers,\n Authorization: authState.token,\n },\n },\n });\n};\n\nconst client = createClient({\n url: '/graphql',\n exchanges: [\n dedupExchange,\n cacheExchange,\n authExchange({\n getAuthToken,\n addAuthToOperation,\n }),\n fetchExchange,\n ],\n});\n```\n\n========================================\n\nCode:\n```text\nAccept\n```\n\n```text\nconst client = createClient({\n url: 'https://api.github.com/graphql',\n fetchOptions: {\n headers: {\n Authorization: `bearer ${GITHUB_TOKEN}`,\n Accept: 'application/vnd.github.packages-preview+json',\n },\n },\n})\n```\n\n```text\nconst client = createClient({\n url: 'http://localhost:8000/graphql/',\n // add token to header if present\n fetchOptions: () => {\n const token = getToken()\n return token ? { headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github.packages-preview+json' }} : {}\n },\n})\n```\n\n```text\nurql\n```\n\n```text\ncreateClient\n```\n\n```text\nfetchOptions\n```\n\n```text\nAuthorization\n```\n\n```text\nconst client = createClient({\n url: 'yoururl',\n fetchOptions: {\n headers: {\n 'content-type': 'application/json',\n 'x-hasura-admin-secret':'********'\n },\n },\n});\n```\n\n```text\nimport { createClient, dedupExchange, cacheExchange, fetchExchange } from 'urql';\nimport { authExchange } from '@urql/exchange-auth';\n\nconst getAuth = async ({ authState, mutate }) => {\n if (!authState) {\n const token = await getToken();\n const refreshToken = await getRefreshToken();\n if (token && refreshToken) {\n return { token, refreshToken };\n }\n return null;\n }\n\n return null;\n};\n\nconst addAuthToOperation = ({ authState, operation }) => {\n if (!authState || !authState.token) {\n return operation;\n }\n\n const fetchOptions =\n typeof operation.context.fetchOptions === 'function'\n ? operation.context.fetchOptions()\n : operation.context.fetchOptions || {};\n\n return makeOperation(operation.kind, operation, {\n ...operation.context,\n fetchOptions: {\n ...fetchOptions,\n headers: {\n ...fetchOptions.headers,\n Authorization: authState.token,\n },\n },\n });\n};\n\nconst client = createClient({\n url: '/graphql',\n exchanges: [\n dedupExchange,\n cacheExchange,\n authExchange({\n getAuthToken,\n addAuthToOperation,\n }),\n fetchExchange,\n ],\n});\n```\n\n========================================\n\nComments:\n- For async headers: formidable.com/open-source/urql/docs/common-questions\n- link is broken now\n- For browsers, you want to use a token that can be updated frequently. You can use a token provider such as firebase auth or oauth. Admin secret is designed for servers since they change infrequently and are not shared with many users. Also, admin role gives the request admin access so your access rules doesn't work\n- It's a lot of BS to get some headers.\n- If you already have the tokens cached, it's a much simpler implementation. If you want to load it asynchronously, then it's more complicated. I used this implementation because we wanted firebase to manage refetching the token if it expires, and that's promise-based","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":190,"estimatedTokens":1137}}1084{"id":"stack-58271819","source":"stackoverflow","questionId":58271819,"title":"How can I transform a query graphql to a json object?","tags":["javascript","json","npm","graphql"],"text":"Title: How can I transform a query graphql to a json object?\nTags: javascript, json, npm, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a problem and I need to transform a query graphql to a json object. That is, I get a query in the following way and I would like to have a json of that query. How could I do it? I've been searching and I haven't found a way.\n\nThank you.\n\n```\nquery {\n Patient(id:4){\n id\n birthDate {\n year,\n day\n }\n name {\n text\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nGraphQL does not define a JSON standard for queries. \n\nIf you want to express a graphQL in JSON, you can define your own structure and write your own serializers. but it will not be supported by any graphQL service\n\nEDIT: I found an NPM package that does that. It is not a standard whatsoever, but if you really need it, you can use this package: https://www.npmjs.com/package/json-to-graphql-query\n\n========================================\n\nCode:\n```text\nquery {\n Patient(id:4){\n id\n birthDate {\n year,\n day\n }\n name {\n text\n }\n }\n}\n```\n\n```text\nconst { parse } = require('graphql')\nconst object = parse(`\n query {\n # ...\n }\n`)\n```\n\n```text\nconst { print } = require('graphql')\nconst string = print(object)\n```\n\n```text\n{\n \"query\": \"[graphQL query here]\",\n \"variables\": {}\n}\n```\n\n```text\n{\n \"query\": \"query { Patient(id:4){ id birthDate { year, day } name { text } } }\",\n \"variables\": {}\n}\n```\n\n```text\n{\n pairs(where: {token0: \"0x1381f369d9d5df87a1a04ed856c9dbc90f5db2fa\", token1: \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\"}) {\n token0 {\n name\n symbol\n }\n token0Price\n token1 {\n name\n symbol\n }\n token1Price\n }\n}\n```\n\n```text\n{\n \"query\": \"{ pairs(where: {token0: \"0x1381f369d9d5df87a1a04ed856c9dbc90f5db2fa\", token1: \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\"}) { token0 { name symbol } token0Price token1 { name symbol } token1Price }}\"\n}\n```\n\n```text\n{\n \"query\": \"{ pairs(where: {token0: \\\"0x1381f369d9d5df87a1a04ed856c9dbc90f5db2fa\\\", token1: \\\"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\\\"}) { token0 { name symbol } token0Price token1 { name symbol } token1Price }}\"\n}\n```\n\n========================================\n\nComments:\n- Just to be sure, do you want a JSON representation of the query or the response ?\n- Could You please add an example of the object, returned by parse function?\n- I've found an example at github.com/egoist/parse-graphql\n- For me square brackets returned a 200 ok response with the message `Invalid Syntax`. I had to use it without square brackets: `{ \"query\": \"graphQL query here\", \"variables\": {} }` for it to work.\n- It just stores the query as a string value, that's ridiculous!","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":116,"estimatedTokens":682}}1085{"id":"stack-56695262","source":"stackoverflow","questionId":56695262,"title":"GraphQL error FieldsConflict: fields have different list shapes","tags":["graphql","aws-appsync"],"text":"Title: GraphQL error FieldsConflict: fields have different list shapes\nTags: graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nI'm using AWS AppSync's GraphQL server with the following (simplified) schema:\n\n```\ntype Query {\n getIssue(id: String!): Issue\n}\n\ntype Issue {\n id: String!\n data: IssueData!\n}\n\ntype Event {\n id: String!\n time: AWSDateTime!\n status: [String]\n}\n\ntype Payment {\n id: String!\n amount: Int!\n status: String\n}\n\nunion IssueData = Event | Payment\n```\n\nWhen I make a query that includes inline fragments to select the `status` as a child of either an `Event` or `Payment` type in the `Issue/data` field, I get a *FieldsConflict* error:\n\n```\nquery getIssue($id: String!) {\n getIssue(id: $id) {\n id\n data {\n ... on Event {\n time\n status\n }\n ... on Payment {\n amount\n status\n }\n }\n }\n}\n```\n\n Validation error of type FieldsConflict: status: fields have different list shapes @ 'getIssue/data'\n\nThis is presumably caused by the `Event/status` field returning an array of strings, while the `Payment/status` field returns a single string.\n\nWhy does GraphQL consider this to be a conflict? How should I construct my query to allow access to the status field on both data types?\n\nNote that I'm using a union rather than an extended interface because the `Issue` and `Payment` types have no common data structure.\n\n========================================\n\nCode:\n```text\ntype Query {\n getIssue(id: String!): Issue\n}\n\ntype Issue {\n id: String!\n data: IssueData!\n}\n\ntype Event {\n id: String!\n time: AWSDateTime!\n status: [String]\n}\n\ntype Payment {\n id: String!\n amount: Int!\n status: String\n}\n\nunion IssueData = Event | Payment\n```\n\n```text\nquery getIssue($id: String!) {\n getIssue(id: $id) {\n id\n data {\n ... on Event {\n time\n status\n }\n ... on Payment {\n amount\n status\n }\n }\n }\n}\n```\n\n```text\nstatus\n```\n\n```text\nEvent\n```\n\n```text\nPayment\n```\n\n```text\nIssue/data\n```\n\n```text\nEvent/status\n```\n\n```text\nPayment/status\n```\n\n```text\nIssue\n```\n\n```text\nPayment\n```\n\n```text\nquery getIssue($id: String!) {\n getIssue(id: $id) {\n id\n data {\n ... on Event {\n time\n eventStatus: status\n }\n ... on Payment {\n amount\n status\n }\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":155,"estimatedTokens":568}}1086{"id":"stack-61605203","source":"stackoverflow","questionId":61605203,"title":"How to use graphQL limit in aws amplify","tags":["javascript","graphql","amazon-dynamodb","aws-amplify"],"text":"Title: How to use graphQL limit in aws amplify\nTags: javascript, graphql, amazon-dynamodb, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI am new to using aws-amplify and have a function similar to this which hits a query called `listItems` and returns items where `isEnbled` is true (from a DynamoDB).\nI want this to filter the entire table which may be huge. I am therefore unable to simply set a limit like 1000 and leave it at that. Is there a way to specify limitless query and scan everything in the table? Or is there a different property I should be using instead?\n\n```\nimport { API } from 'aws-amplify'\n\n export async function getAllEnabledListItems() {\n const { data } = await API.graphql({\n query: queries.listItems,\n variables: { filter: { isEnabled: { eq: true } }, limit: 10000 },\n authMode: 'AMAZON_COGNITO_USER_POOLS' \n })\n return data\n }\n```\n\n========================================\n\nCode:\n```text\nimport { API } from 'aws-amplify'\n\n export async function getAllEnabledListItems() {\n const { data } = await API.graphql({\n query: queries.listItems,\n variables: { filter: { isEnabled: { eq: true } }, limit: 10000 },\n authMode: 'AMAZON_COGNITO_USER_POOLS' \n })\n return data\n }\n```\n\n```text\nlistItems\n```\n\n```text\nisEnbled\n```\n\n```text\nLastEvaluatedKey\n```\n\n```text\nLastEvaluatedKey\n```\n\n```text\nExclusiveStartKey\n```\n\n```text\nLastEvaluatedKey\n```\n\n```text\nLastEvaluatedKey\n```\n\n```text\npaginationToken\n```\n\n```text\nLastEvaluatedKey\n```\n\n```text\nExclusiveStartKey\n```\n\n========================================\n\nComments:\n- Thank you for the great explanation, this worked. We went with a global secondary index on a status field. It didn't seem to like having a GSI on a boolean field.\n- Is there a way to get the total number of records? To render page numbers on the client?\n- Rather than making your own `paginationToken` as this post suggests, I see that the mapping template now has `nextToken` which automatically handles this: docs.aws.amazon.com/appsync/latest/devguide/…","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":83,"estimatedTokens":506}}1087{"id":"stack-70131542","source":"stackoverflow","questionId":70131542,"title":"Hot Chocolate: Transforming results from [UseFiltering] Query","tags":["c#","entity-framework","graphql","hotchocolate"],"text":"Title: Hot Chocolate: Transforming results from [UseFiltering] Query\nTags: c#, entity-framework, graphql, hotchocolate\nSource: Stack Overflow\n\nQuestion:\nI'm looking to use Hot Chocolate's Filtering to query against one data type; and then transform that filtered output to another type before returning it as an IQueryable. But I can't seem to find anyway to capture the filter input to start my transform.\n\nHere's an example of what I'm trying to accomplish:\n\nGiven the data classes\n\n```\npublic class TypeA\n{\n public string Foo { get; set; }\n}\n\npublic class TypeB\n{\n public string Fizz { get; set; }\n public string Buzz { get; set; }\n}\n```\n\nI want to be able to create a query endpoint like\n\n```\npublic class Query\n{\n [UseDbContext(typeof(DbContext))]\n [UseFiltering(typeof(TypeA))]\n public IQueryable GetTypeB(\n [ScopedService] DbContext context,\n [SomeAttributeToCaptureTheFilter] Filter filter) // filteredTypeAs = context.TypeA.Filter(filter); // .Filter() doesn't exist, its just for example.\n IQueryable filteredTypeBs;\n \n /* Complex transformation logic that populates 'filteredTypeBs' \n * requiring the 'filteredTypeAs' and additional Data from \n * the database to complete. */\n\n return filteredTypeBs;\n }\n}\n```\n\nAgainst which, I can use a GraphQL Query like the following\n\n```\nquery {\n typeB(where: { foo: { eq: \"bar\" } }) {\n fizz\n buzz\n }\n}\n```\n\n`where: { foo: { eq: \"bar\" } }` Being the filter against `TypeA`, and the\n\n```\ntypeB {\n fizz\n buzz\n}\n```\n\npulling the content from the transformed `TypeB`.\n\nUsing `[UseFiltering(typeof(TypeA))]` does work, It sets up the schema to act as I want.\n\nWhat I'm looking for is something to the effect of the line `[SomeAttributeToCaptureTheFilter] Filter filter`. Just some way of capturing the filter and applying it to the data within the DbContext.\n\nI will also say I'm very new to GraphQL in general, so how I'm approaching this problem may be entirely wrong. Any advice would be helpful.\n\n========================================\n\nCode:\n```text\npublic class TypeA\n{\n public string Foo { get; set; }\n}\n\npublic class TypeB\n{\n public string Fizz { get; set; }\n public string Buzz { get; set; }\n}\n```\n\n```text\npublic class Query\n{\n [UseDbContext(typeof(DbContext))]\n [UseFiltering(typeof(TypeA))]\n public IQueryable<TypeB> GetTypeB(\n [ScopedService] DbContext context,\n [SomeAttributeToCaptureTheFilter] Filter filter) // <- this is the line I'm trying to figure out\n {\n IQueryable<TypeA> filteredTypeAs = context.TypeA.Filter(filter); // .Filter() doesn't exist, its just for example.\n IQueryable<TypeB> filteredTypeBs;\n \n /* Complex transformation logic that populates 'filteredTypeBs' \n * requiring the 'filteredTypeAs' and additional Data from \n * the database to complete. */\n\n return filteredTypeBs;\n }\n}\n```\n\n```text\nquery {\n typeB(where: { foo: { eq: \"bar\" } }) {\n fizz\n buzz\n }\n}\n```\n\n```text\ntypeB {\n fizz\n buzz\n}\n```\n\n```text\nwhere: { foo: { eq: \"bar\" } }\n```\n\n```text\nTypeA\n```\n\n```text\nTypeB\n```\n\n```text\n[UseFiltering(typeof(TypeA))]\n```\n\n```text\n[SomeAttributeToCaptureTheFilter] Filter filter\n```\n\n```text\nusing HotChocolate.Data;\nusing HotChocolate.Data.Filters.Expressions;\n\npublic class Query\n{\n [UseDbContext(typeof(DbContext))]\n [UseFiltering(typeof(TypeA))]\n public IQueryable<TypeB> GetTypeB(\n [ScopedService] DbContext context,\n IResolverContext resolverContext)\n {\n IQueryable<TypeA> filteredTypeAs = context.TypeA.Filter(resolverContext);\n IQueryable<TypeB> filteredTypeBs;\n \n /* Complex transformation logic that populates 'filteredTypeBs' \n * requiring the 'filteredTypeAs' and additional Data from \n * the database to complete. */\n\n return filteredTypeBs;\n }\n}\n```\n\n```text\nHotChocolate.Data\n```\n\n```text\nFilter\n```\n\n```text\nIQueryable<T>\n```\n\n```text\nIEnumerable<T>\n```\n\n```text\nIResolverContext\n```\n\n```text\nSort\n```\n\n```text\n[UseSorting]\n```\n\n========================================\n\nComments:\n- The need you are experiencing looks strange, to be honest. Could you provide the real example (not foo bar baz) where you need that?\n- Doesn't seem to work for me. var output = LorderRepository.Queryable().Sort(resolverContext).Filter(re‌​solverContext).Proje‌​ct(resolverContext).‌​ToList(); That still doesn't apply my where.\n- That's a great solution and agree it opens up a whole lot of possibilities !! Cheers!!","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":204,"estimatedTokens":1124}}1088{"id":"stack-70731524","source":"stackoverflow","questionId":70731524,"title":"Fetch error - Missing \\\"data\\\" payload in the request body","tags":["javascript","reactjs","graphql","strapi"],"text":"Title: Fetch error - Missing \\\"data\\\" payload in the request body\nTags: javascript, reactjs, graphql, strapi\nSource: Stack Overflow\n\nQuestion:\nThe GraphQL and Strapi API are changed and they added a parent level to the json object where the entire JSON object that has to be fetch must have a parent key called `data`, if you submit the request without this key, the API is rejected with a 400 error.\n\nMy JSON I submit is like this\n\n```\n{\"title\": \"aaa\", \"rating\": \"3\", \"body\": \"aa\", \"categories\": \"5\"}\n```\n\nThe api requires it to be like this\n\n```\n{\"data\" : {\"title\": \"aaa\", \"rating\": \"3\", \"body\": \"aa\", \"categories\": \"5\"}}\n```\n\nHow can I tweak my code in order to insert a parent key in this JSON object?\n\nWith Postman I am able to post the data in the Strapi, by submiting the data like this:\n\n```\n{ \"data\": {\n \"title\": \"the best car\",\n \"rating\": 7,\n \"body\": \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt. \",\n \"categories\": [3,7,4]\n\n }\n}\n```\n\nMy full code is bellow:\n\n```\nimport React, { useState } from \"react\";\nimport { useNavigate } from \"react-router-dom\";\nimport { useQuery, gql } from '@apollo/client'\nimport { useParams, Link } from 'react-router-dom'\n\nconst CATEGORIES = gql`\n query GetCategories {\n categories{\n data\n {\n id\n attributes{\n name\n }\n }\n }\n }\n`\n\nconst token =\"AlaBala\"\nconst Create = () => {\n const [title, setTitle] = useState('');\n const [body, setBody] = useState('');\n const [rating, setRating] = useState(3);\n const [categories, setCategories] = useState(5);\n const history = useNavigate();\n\n const { loading, error, data } = useQuery(CATEGORIES)\n\n if (loading) return Loading categories...\n\n if (error) return `Error! ${error}`\n\n const handleSubmit = (e) => {\n e.preventDefault();\n const review = { title, rating, body, categories };\n console.log(review)\n\n fetch('http://localhost:1337/api/reviews/', {\n method: 'POST',\n mode: 'cors',\n headers: { \"Content-Type\": \"application/json\",\n \"Authorization\" : \"Token \" + token },\n body: JSON.stringify(review)\n\n })\n }\nreturn (object etc...)\n```\n\n========================================\n\nTop Answer:\nRegarding making http POST requests to Strapi... Without having a \"content-type: application/json\" header set in Postman, I had the same issue.\n\nBut with that \"content-type: application/json\" header, it worked.\n\nI checked via the VS Code Extension \"HTTP Rest Client\" (which is similar to Postman), and it's the same result.\n\nSo, just make sure the header is set with \"content-type: application/json\" and you should be good to go.\n\n========================================\n\nCode:\n```text\n{\"title\": \"aaa\", \"rating\": \"3\", \"body\": \"aa\", \"categories\": \"5\"}\n```\n\n```text\n{\"data\" : {\"title\": \"aaa\", \"rating\": \"3\", \"body\": \"aa\", \"categories\": \"5\"}}\n```\n\n```text\n{ \"data\": {\n \"title\": \"the best car\",\n \"rating\": 7,\n \"body\": \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt. \",\n \"categories\": [3,7,4]\n\n }\n}\n```\n\n```text\nimport React, { useState } from \"react\";\nimport { useNavigate } from \"react-router-dom\";\nimport { useQuery, gql } from '@apollo/client'\nimport { useParams, Link } from 'react-router-dom'\n\nconst CATEGORIES = gql`\n query GetCategories {\n categories{\n data\n {\n id\n attributes{\n name\n }\n }\n }\n }\n`\n\nconst token =\"AlaBala\"\nconst Create = () => {\n const [title, setTitle] = useState('');\n const [body, setBody] = useState('');\n const [rating, setRating] = useState(3);\n const [categories, setCategories] = useState(5);\n const history = useNavigate();\n\n const { loading, error, data } = useQuery(CATEGORIES)\n\n if (loading) return <p>Loading categories...</p>\n if (error) return <p>`Error! ${error}`</p>\n\n const handleSubmit = (e) => {\n e.preventDefault();\n const review = { title, rating, body, categories };\n console.log(review)\n\n fetch('http://localhost:1337/api/reviews/', {\n method: 'POST',\n mode: 'cors',\n headers: { \"Content-Type\": \"application/json\",\n \"Authorization\" : \"Token \" + token },\n body: JSON.stringify(review)\n\n })\n }\nreturn (object etc...)\n```\n\n```text\ndata\n```\n\n```text\nfetch('http://localhost:1337/api/reviews/', {\n method: 'POST',\n mode: 'cors',\n headers: { \"Content-Type\": \"application/json\",\n \"Authorization\" : \"Token \" + token },\n body: JSON.stringify({data:review})\n\n })\n```\n\n========================================\n\nComments:\n- you're a great man! @OddRadAche\n- I've been trying to figure out ways to solve this since I convert my form to an Object using FormData and I needed the data before. Thank you so much! Such a simple solution...","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":190,"estimatedTokens":1196}}1089{"id":"stack-45000522","source":"stackoverflow","questionId":45000522,"title":"Mocking GraphQL, MockList genertes only two items in the array","tags":["javascript","mocking","graphql","graphql-js"],"text":"Title: Mocking GraphQL, MockList genertes only two items in the array\nTags: javascript, mocking, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI am trying to generate a list of 10 items in my GraphQL mock server like this: \n\n```\nimport { makeExecutableSchema, addMockFunctionsToSchema, MockList } from 'graphql-tools';\nimport casual from 'casual';\nimport typeDefs from './schema.graphql';\n\nexport const schema = makeExecutableSchema({ typeDefs });\n\nconst mocks = {\n File: () => ({\n path: casual.random_element([\n '/assets/images/cars/1.JPG',\n '/assets/images/cars/2.JPG',\n '/assets/images/cars/3.JPG',\n '/assets/images/cars/4.JPG',\n '/assets/images/cars/5.JPG',\n '/assets/images/cars/6.JPG',\n '/assets/images/cars/7.JPG',\n ]),\n }),\n UsedCar: () =>\n new MockList(10, () => ({\n price: casual.integer(10000, 99999999),\n year: casual.integer(1990, 2017),\n })),\n};\n\n// This function call adds the mocks to your schema!\naddMockFunctionsToSchema({ schema, mocks });\n```\n\nBut I always get two used cars I don't know why.\nCan anyone help?\n\nRegards,\nMostafa\n\n========================================\n\nCode:\n```text\nimport { makeExecutableSchema, addMockFunctionsToSchema, MockList } from 'graphql-tools';\nimport casual from 'casual';\nimport typeDefs from './schema.graphql';\n\nexport const schema = makeExecutableSchema({ typeDefs });\n\nconst mocks = {\n File: () => ({\n path: casual.random_element([\n '/assets/images/cars/1.JPG',\n '/assets/images/cars/2.JPG',\n '/assets/images/cars/3.JPG',\n '/assets/images/cars/4.JPG',\n '/assets/images/cars/5.JPG',\n '/assets/images/cars/6.JPG',\n '/assets/images/cars/7.JPG',\n ]),\n }),\n UsedCar: () =>\n new MockList(10, () => ({\n price: casual.integer(10000, 99999999),\n year: casual.integer(1990, 2017),\n })),\n};\n\n// This function call adds the mocks to your schema!\naddMockFunctionsToSchema({ schema, mocks });\n```\n\n```text\nmocks: {\n Query: () => ({\n getUsedCars: () => new MockList(10)\n }),\n UsedCar: () => ({\n price: casual.integer(10000, 99999999),\n year: casual.integer(1990, 2017),\n })\n}\n```\n\n```text\nUsedCar\n```\n\n```text\ngetUsedCars\n```\n\n========================================\n\nComments:\n- thanks got it working it was part of another graphql type UsedCarQuery: () => ({ find: () => new MockList(12), }),\n- Thank you so much for your answer, mocking the Query as well was the trick!\n- @Shalkam Did you have to add custom resolvers to be able to use 'getUsedCars' function during Mocking? I have a similar use case, where I am trying to return more than 2 objects but it doesn't seem to work. addMocksToSchema({ schema: apiSchema, mocks: mockedSchema, })\n- Does anybody know how to return custom objects with specific values? Say I need array of 2 object, one to have {price: 100, year: 2000}, another {price: 200, year: 2010} ?","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":103,"estimatedTokens":710}}1090{"id":"stack-42180756","source":"stackoverflow","questionId":42180756,"title":"How to setup a GraphQL Relay API in Rails","tags":["ruby-on-rails","graphql","relay"],"text":"Title: How to setup a GraphQL Relay API in Rails\nTags: ruby-on-rails, graphql, relay\nSource: Stack Overflow\n\nQuestion:\nI'm trying to wrap my head around GraphQL/Relay and I'm finding hard to get started on how to correctly setup a Relay compliant GraphQL API using Ruby on Rails.\n\nI've found multiple tutorials on how to do this:\n\nhttps://medium.com/react-weekly/relay-facebook-on-rails-8b4af2057152#.gd8p6tbwi\n\nhttps://medium.com/@gauravtiwari/graphql-and-relay-on-rails-getting-started-955a49d251de#.m05xjvi82\n\nBut they all refer to a `graphql-relay` gem that doesn't seem to be available at this moment: https://github.com/rmosolgo/graphql-relay-ruby\n\nThe `grahql-ruby` gem has a section in the documentation specific to relay, but I'm finding hard to understand what is needed to set this up to be consumed by a Relay client.\n\nWhat is necessary to implement a GraphQL API for a Relay client in Rails?\n\n========================================\n\nTop Answer:\nhave you tried installing it?\n\n```\nvagrant$ bundle install\nFetching gem metadata from https://rubygems.org/............\nFetching version metadata from https://rubygems.org/...\nFetching dependency metadata from https://rubygems.org/..\nResolving dependencies...\nInstalling graphql 0.19.4\nUsing bundler 1.11.2\nInstalling graphql-relay 0.12.0\nBundle complete! 1 Gemfile dependency, 3 gems now installed.\nUse `bundle show [gemname]` to see where a bundled gem is installed.\n```\n\nin Gemfile:\n\n```\ngem 'graphql-relay'\n```\n\n========================================\n\nCode:\n```text\ngraphql-relay\n```\n\n```text\ngrahql-ruby\n```\n\n```text\nApplicationSchema = GraphQL::Schema.define do\n /* Create IDs by joining the type name & ID, then base64-encoding it */\n id_from_object ->(object, type_definition, query_ctx) {\n GraphQL::Schema::UniqueWithinType.encode(type_definition.name, object.id)\n }\n\n object_from_id ->(id, query_ctx) {\n type_name, object_id = GraphQL::Schema::UniqueWithinType.decode(id)\n # Now, based on `type_name` and `id`\n # find an object in your application \n # This will give the user access to all records in your db\n # so you might want to restrict this properly\n Object.const_get(type_name).find(object_id)\n }\nend\n```\n\n```text\nPostType = GraphQL::ObjectType.define do\n name \"Post\"\n # Implements the \"Node\" interface for Relay\n interfaces [GraphQL::Relay::Node.interface]\n # exposes the global id\n global_id_field :id\n field :name, types.String\nend\n```\n\n```text\nquery {\n node(id: \"RmFjdGlvbjox\") {\n id\n ... on Post {\n name\n }\n }\n}\n```\n\n```text\nSchema.execute GraphQL::Introspection::INTROSPECTION_QUERY\n```\n\n```text\nPostType = GraphQL::ObjectType.define do\n # default connection\n # obj.comments by default\n connection :comments, CommentType.connection_type\n\n # custom connection\n connection :featured_comments, CommentType.connection_type do\n resolve ->(post, args, ctx) {\n comments = post.comments.featured\n\n if args[:since]\n comments = comments.where(\"created_at >= ?\", since)\n end\n\n comments\n }\n end\nend\n```\n\n```text\nquery {\n posts(first: 5) {\n edges {\n node {\n name\n }\n }\n }\n}\n```\n\n```text\ngraphql-ruby\n```\n\n```text\ngraphql-relay\n```\n\n```text\nid_from_object\n```\n\n```text\nobject_from_id\n```\n\n```text\nNodeInterface\n```\n\n```text\nglobal_id_field\n```\n\n```text\nbabel-relay-plugin\n```\n\n```text\nfirst\n```\n\n```text\nlast\n```\n\n```text\nbefore\n```\n\n```text\nafter\n```\n\n```text\nvagrant$ bundle install\nFetching gem metadata from https://rubygems.org/............\nFetching version metadata from https://rubygems.org/...\nFetching dependency metadata from https://rubygems.org/..\nResolving dependencies...\nInstalling graphql 0.19.4\nUsing bundler 1.11.2\nInstalling graphql-relay 0.12.0\nBundle complete! 1 Gemfile dependency, 3 gems now installed.\nUse `bundle show [gemname]` to see where a bundled gem is installed.\n```\n\n```text\ngem 'graphql-relay'\n```\n\n========================================\n\nComments:\n- yes it does work, but it uses an old version of `graphql`. I found out that `graphql-ruby` and `graphql-relay` were merged. I'm trying to get more comfortable building the api to give a better answer to this question, as it is definitely a pain to get started with it","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":196,"estimatedTokens":1060}}1091{"id":"stack-56797753","source":"stackoverflow","questionId":56797753,"title":"Should I use Ints for monetary values in GraphQL?","tags":["json","graphql","dataformat"],"text":"Title: Should I use Ints for monetary values in GraphQL?\nTags: json, graphql, dataformat\nSource: Stack Overflow\n\nQuestion:\nI know that I should use integers for \"money values\" when programming. I know it's because of the `0.1 + 0.2 != 0.3` problem. But I don't know the problem well enough to know if that's a problem in data formats (like JSON) as well.\n\nIn my concrete case: should I define\n\n```\ntype Money {\n amount: Float!\n # ...\n}\n```\n\nor\n\n```\ntype Money {\n amount: Int!\n # ...\n}\n```\n\nin GraphQL?\n\n========================================\n\nTop Answer:\nRepresenting Money in general is a hard problem. Handling currencies, formats, fractional vs non-fractional currencies, etc.\n\nModeling Money as a complex **object type** is often a good idea. This enables you to encode more data on the context of the monetary value. Another option is defining your own Scalar type that represents money.\n\nA good example to look at is Shopify's GraphQL API: https://help.shopify.com/en/api/graphql-admin-api/reference/object/moneyv2\n\nThey include both currency and amount, which is defined as a Decimal scalar. Having complex objects allows you to evolve that type better over time too. Using `Int` or `Float` will be hard to evolve if you add anything like server side formatting or currency information.\n\n========================================\n\nCode:\n```text\ntype Money {\n amount: Float!\n # ...\n}\n```\n\n```text\ntype Money {\n amount: Int!\n # ...\n}\n```\n\n```text\n0.1 + 0.2 != 0.3\n```\n\n```text\nFloat\n```\n\n```text\nInt\n```\n\n```text\nInt\n```\n\n```text\nFloat\n```\n\n========================================\n\nComments:\n- Thank you. Take another look at my examples. Obviously, the `Money` type would have a currency associated with it, and maybe some other fields. My question was just about the `amount` field and its type.\n- +1 to a custom scalar like decimal. GraphQL spec limits int support to 32 bit, which can be pretty restrictive spec.graphql.org/draft/#sel-HAHXRHFCBBB9FnnP","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":80,"estimatedTokens":494}}1092{"id":"stack-43245616","source":"stackoverflow","questionId":43245616,"title":"How to pass mocked executable schema to Apollo Client?","tags":["graphql","react-apollo"],"text":"Title: How to pass mocked executable schema to Apollo Client?\nTags: graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nThe Mocking example for Apollo GraphQL has the following code (see below). \n\nThe interesting thing is the last line - they create and execute the `graphql` query. But you usually need to create ApolloClient object. I can't figure out how to do that.\n\nThe ApolloClient expect the NetworkingInterface as an argument not the executable schema. \n\nSo, is there a way to create ApolloClient from the executable schema, without NetworkingInterface? \n\n```\nimport { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';\nimport { graphql } from 'graphql';\n\n// Fill this in with the schema string\nconst schemaString = `...`;\n\n// Make a GraphQL schema with no resolvers\nconst schema = makeExecutableSchema({ typeDefs: schemaString });\n\n// Add mocks, modifies schema in place\naddMockFunctionsToSchema({ schema });\n\nconst query = `\nquery tasksForUser {\n user(id: 6) { id, name }\n}\n`;\n\ngraphql(schema, query).then((result) => console.log('Got result', result));\n```\n\n========================================\n\nTop Answer:\nIn Apollo client v2, `networkInterface` has been replaced with `link` for the network layer (see the client docs here).\n\n`apollo-test-utils` hasn't been updated for Apollo client v2, and based on conversations from github, it seems the current recommendation is to use `apollo-link-schema`:\n\n```\nimport { ApolloClient } from 'apollo-client';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { SchemaLink } from 'apollo-link-schema';\nimport { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';\nimport { typeDefs } from './schema';\n\nconst schema = makeExecutableSchema({ typeDefs });\naddMockFunctionsToSchema({ schema });\n\nconst graphqlClient = new ApolloClient({\n cache: new InMemoryCache(),\n link: new SchemaLink({ schema })\n});\n```\n\nThen you just need to inject the client into whatever you're testing!\n\n========================================\n\nCode:\n```js\nimport { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';\nimport { graphql } from 'graphql';\n\n// Fill this in with the schema string\nconst schemaString = `...`;\n\n// Make a GraphQL schema with no resolvers\nconst schema = makeExecutableSchema({ typeDefs: schemaString });\n\n// Add mocks, modifies schema in place\naddMockFunctionsToSchema({ schema });\n\nconst query = `\nquery tasksForUser {\n user(id: 6) { id, name }\n}\n`;\n\ngraphql(schema, query).then((result) => console.log('Got result', result));\n```\n\n```text\ngraphql\n```\n\n```text\nimport { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';\nimport { mockNetworkInterfaceWithSchema } from 'apollo-test-utils';\nimport { typeDefs } from './schema';\n\n// Create GraphQL schema object\nconst schema = makeExecutableSchema({ typeDefs });\n\n// Add mocks\naddMockFunctionsToSchema({ schema });\n\n// Create network interface\nconst mockNetworkInterface = mockNetworkInterfaceWithSchema({ schema });\n\n// Initialize client\nconst client = new ApolloClient({\n networkInterface: mockNetworkInterface,\n});\n```\n\n```text\nmagbicaleman\n```\n\n```text\napollo-test-utils\n```\n\n```text\nimport { ApolloClient } from 'apollo-client';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\nimport { SchemaLink } from 'apollo-link-schema';\nimport { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';\nimport { typeDefs } from './schema';\n\nconst schema = makeExecutableSchema({ typeDefs });\naddMockFunctionsToSchema({ schema });\n\nconst graphqlClient = new ApolloClient({\n cache: new InMemoryCache(),\n link: new SchemaLink({ schema })\n});\n```\n\n```text\nnetworkInterface\n```\n\n```text\nlink\n```\n\n```text\napollo-test-utils\n```\n\n```text\napollo-link-schema\n```\n\n========================================\n\nComments:\n- There's an open PR to the docs that I still need to merge: github.com/apollographql/react-docs/pull/172\n- Ideally it should be something like `new ApolloClient({ schema: executableSchema })`\n- We aren't trying to optimize lines of code. In this case there is a specific method for each part of the process that does one thing well. You could easily write a helper function to make this one line if you wish!\n- It's not about lines of code but about the simplicity and ease of use.\n- This answer is only applicable for Apollo Client v1. In version 2, `networkInterface` has been replaced with `link`. More info here: github.com/apollographql/apollo-test-utils/issues/39","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":157,"estimatedTokens":1123}}1093{"id":"stack-39666940","source":"stackoverflow","questionId":39666940,"title":"How to batch GitHub GraphQL API queries?","tags":["github-api","graphql"],"text":"Title: How to batch GitHub GraphQL API queries?\nTags: github-api, graphql\nSource: Stack Overflow\n\nQuestion:\nHow can multiple queries be batched into a single request to GitHub's GraphQL API?\n\nFor example, how would you batch these 2 queries into a single request and receive a single response? And would this technique work with many more queries (say 200)?\n\n```\n{\n repositoryOwner(login:\"rails\") {\n repository(name:\"rails\") {\n description\n homepageURL\n }\n }\n}\n\n{\n repositoryOwner(login:\"github\") {\n repository(name:\"graphql-client\") {\n description\n homepageURL\n }\n }\n}\n```\n\n(The GitHub GraphQL API can be experimented with at https://developer.github.com/early-access/graphql/explorer/)\n\n========================================\n\nCode:\n```text\n{\n repositoryOwner(login:\"rails\") {\n repository(name:\"rails\") {\n description\n homepageURL\n }\n }\n}\n\n{\n repositoryOwner(login:\"github\") {\n repository(name:\"graphql-client\") {\n description\n homepageURL\n }\n }\n}\n```\n\n```text\n{\n repositoryOwner(login:\"rails\") {\n repository(name:\"rails\") {\n description\n homepageURL\n }\n } \n repositoryOwner(login:\"github\") {\n repository(name:\"graphql-client\") {\n description\n homepageURL\n }\n }\n}\n```\n\n```text\n{\n rails: repositoryOwner(login:\"rails\") {\n repository(name:\"rails\") {\n description\n homepageURL\n }\n } \n graphql_client: repositoryOwner(login:\"github\") {\n repository(name:\"graphql-client\") {\n description\n homepageURL\n }\n }\n }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":87,"estimatedTokens":383}}1094{"id":"stack-62077593","source":"stackoverflow","questionId":62077593,"title":"Nginx + GraphQL Connection Refused","tags":["nginx","graphql","next.js","nginx-config"],"text":"Title: Nginx + GraphQL Connection Refused\nTags: nginx, graphql, next.js, nginx-config\nSource: Stack Overflow\n\nQuestion:\nMy Client (next.js) app running at port `3000`\n\nMy Server (graphql) app running at port `4000`\n\nMy website is `https://example.com`, nginx will pass proxy port 3000.\n\nIf the user access the site, the page is loaded successfully. \n\nBut behind the scene, In my webpage some api requests are sended to graphql server. `(http://localhost:4000)`\n\n**This api requests are failed.**\n\nI don't know why, but when I access `http://example.com:4000/graphql` the graphql playground (graphiql?) loaded successfully and I can send some query and result showed well. But request from webpage is failed.\n\n**nginx/sites-enabled/example.com**\n\n```\nserver {\n listen 80;\n listen [::]:80;\n server_name www.example.com example.com;\n return 301 https://example.com$request_uri;\n}\n\nserver {\n listen 80;\n listen [::]:80;\n server_name example.com;\n\n location / {\n proxy_pass http://localhost:3000;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n }\n\n listen [::]:443 ssl ipv6only=on; # managed by Certbot\n listen 443 ssl; # managed by Certbot\n ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot\n ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot\n include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n\n}\n```\n\n**client app's graphql part**\n\n```\nexport default function createApolloClient(initialState, ctx) {\n return new ApolloClient({\n ssrMode: Boolean(ctx),\n link: authLink.concat(new HttpLink({\n uri: 'http://localhost:4000/graphql', // Server URL (must be absolute)\n credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`\n fetch,\n })),\n cache: new InMemoryCache({ fragmentMatcher }).restore(initialState),\n credentials: 'include',\n })\n}\n```\n\n** What I tried...**\n\nI added below snippets to nginx conf (above listen [::]443 part) and restart the nginx service, but nothing changed.\n\n```\nlocation /graphql {\n proxy_pass http://localhost:4000/graphql;\n }\n```\n\nI think I miss something in nginx conf. How do I fix it?\n\n========================================\n\nCode:\n```text\nserver {\n listen 80;\n listen [::]:80;\n server_name www.example.com example.com;\n return 301 https://example.com$request_uri;\n}\n\n\nserver {\n listen 80;\n listen [::]:80;\n server_name example.com;\n\n\n location / {\n proxy_pass http://localhost:3000;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection 'upgrade';\n proxy_set_header Host $host;\n proxy_cache_bypass $http_upgrade;\n }\n\n listen [::]:443 ssl ipv6only=on; # managed by Certbot\n listen 443 ssl; # managed by Certbot\n ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot\n ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot\n include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n\n}\n```\n\n```text\nexport default function createApolloClient(initialState, ctx) {\n return new ApolloClient({\n ssrMode: Boolean(ctx),\n link: authLink.concat(new HttpLink({\n uri: 'http://localhost:4000/graphql', // Server URL (must be absolute)\n credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`\n fetch,\n })),\n cache: new InMemoryCache({ fragmentMatcher }).restore(initialState),\n credentials: 'include',\n })\n}\n```\n\n```text\nlocation /graphql {\n proxy_pass http://localhost:4000/graphql;\n }\n```\n\n```text\n3000\n```\n\n```text\n4000\n```\n\n```text\nhttps://example.com\n```\n\n```text\n(http://localhost:4000)\n```\n\n```text\nhttp://example.com:4000/graphql\n```\n\n```text\n... createApolloClient(initialState, ctx) {\n return new ApolloClient({\n ...\n link: createHttpLink({ uri: '/graphql' })\n```\n\n```text\nlocation /graphql {\n proxy_pass http://localhost:4000/graphql;\n }\n```\n\n========================================\n\nComments:\n- What also should work is calling localhost:4000/index.php?graphql","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":177,"estimatedTokens":1096}}1095{"id":"stack-50211088","source":"stackoverflow","questionId":50211088,"title":"Can't set Authentication header for Apollo client","tags":["jwt","graphql","apollo"],"text":"Title: Can't set Authentication header for Apollo client\nTags: jwt, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI'm working on a Laravel application that uses React and Redux on the client side, with the React preset and Mix. I've decided to try out GraphQL for the API rather than the usual REST API approach and it's working OK so far. However, I've now got stuck.\n\nI'm using Apollo as my HTTP client since it's built for working with GraphQL. In the past I've used JWT Auth for securing APIs, so naturally I've gone for that approach here too, since implementation is just a case of adding an appropriate header. I've followed the instruction on setting headers with Apollo, but the headers aren't getting set. Here's the JS file in question:\n\n```\nimport LinkList from './components/LinkList';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport {Container} from './container';\nimport {createStore} from 'redux';\nimport reducer from './reducer';\nimport {Provider} from 'react-redux';\nimport {fromJS} from 'immutable';\nimport ApolloClient from 'apollo-boost';\nimport gql from 'graphql-tag';\nimport { createHttpLink } from 'apollo-link-http';\nimport { setContext } from 'apollo-link-context';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\n\nconst httpLink = createHttpLink({\n uri: window.initialData.graphql_route\n});\n\nconst authLink = setContext((_, { headers }) => {\n const token = window.initialData.jwt;\n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n});\n\nclient.query({\n query: gql`{\n links {\n id\n title\n link\n }}`\n}).then(result => console.log(result));\n\nconst store = createStore(\n reducer,\n fromJS(window.initialData),\n window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()\n);\n\nif (document.getElementById('list')) {\n ReactDOM.render(\n \n \n ,\n document.getElementById('list')\n );\n}\n```\n\nI populate `window.initialData` in the view, and that contains the necessary data, including the JWT token as `window.initialData.jwt`. Setting a breakpoint inside the definition of `authLink` does nothing, implying that it never gets called.\n\nAny idea what's gone wrong? I've followed the examples in the documentation pretty closely, so all I can think of is that they might be put of date.\n\n========================================\n\nCode:\n```text\nimport LinkList from './components/LinkList';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport {Container} from './container';\nimport {createStore} from 'redux';\nimport reducer from './reducer';\nimport {Provider} from 'react-redux';\nimport {fromJS} from 'immutable';\nimport ApolloClient from 'apollo-boost';\nimport gql from 'graphql-tag';\nimport { createHttpLink } from 'apollo-link-http';\nimport { setContext } from 'apollo-link-context';\nimport { InMemoryCache } from 'apollo-cache-inmemory';\n\nconst httpLink = createHttpLink({\n uri: window.initialData.graphql_route\n});\n\nconst authLink = setContext((_, { headers }) => {\n const token = window.initialData.jwt;\n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n authorization: token ? `Bearer ${token}` : \"\",\n }\n }\n});\n\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n});\n\nclient.query({\n query: gql`{\n links {\n id\n title\n link\n }}`\n}).then(result => console.log(result));\n\nconst store = createStore(\n reducer,\n fromJS(window.initialData),\n window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()\n);\n\nif (document.getElementById('list')) {\n ReactDOM.render(\n <Provider store={store}>\n <Container />\n </Provider>,\n document.getElementById('list')\n );\n}\n```\n\n```text\nwindow.initialData\n```\n\n```text\nwindow.initialData.jwt\n```\n\n```text\nauthLink\n```\n\n```text\nconst client = new ApolloClient({\n uri: ...,\n request: async operation => {\n const token = localStorage.getItem('token');\n operation.setContext({\n headers: {\n authorization: token ? `Bearer ${token}` : ''\n }\n });\n }\n});\n```\n\n```text\nInfo: Don't save your token in the localStorage\n```\n\n========================================\n\nComments:\n- `localStorage.getItem('token')` is synchronous thus should not be awaited","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":170,"estimatedTokens":1137}}1096{"id":"stack-63349984","source":"stackoverflow","questionId":63349984,"title":"Cannot return null for non-nullable field , Debugger dosen't show null","tags":["graphql","apollo","prisma"],"text":"Title: Cannot return null for non-nullable field , Debugger dosen't show null\nTags: graphql, apollo, prisma\nSource: Stack Overflow\n\nQuestion:\nI have this schema.graphql\n\n```\n### This file was generated by Nexus Schema\n### Do not make changes to this file directly\n\ntype AuthPayload {\n token: String!\n users: users!\n}\n\nscalar DateTime\n\ntype Mutation {\n login(email: String, password: String): AuthPayload!\n signup(CREATED_BY: String, EMAIL: String, FIRST_NAME: String, IS_ACTIVE: Boolean, PASSWORD: String, USERNAME: String): AuthPayload!\n}\n\ntype Query {\n me: users\n}\n\ntype users {\n CREATED_BY: String!\n CREATED_ON: DateTime\n EMAIL: String!\n FIRST_NAME: String!\n id: Int!\n IS_ACTIVE: Boolean!\n LAST_NAME: String\n MODIFIED_BY: String\n MODIFIED_ON: DateTime\n ORGANIZATION_ID: String\n PASSWORD: String!\n PHONE: String\n USERNAME: String!\n}\n```\n\nmutations :-\n\n```\nconst Mutation = mutationType({\n definition(t) {\n t.field('signup', {\n type: 'AuthPayload',\n args: {\n FIRST_NAME: stringArg({ nullable: true }),\n EMAIL: stringArg(),\n PASSWORD: stringArg(),\n IS_ACTIVE: booleanArg(),\n USERNAME: stringArg(),\n CREATED_BY: stringArg(),\n },\n resolve: async (parent, { FIRST_NAME, EMAIL, PASSWORD ,IS_ACTIVE ,USERNAME,CREATED_BY }, ctx) => {\n const hashedPassword = await hash(PASSWORD, 10)\n\n const user = await ctx.prisma.users.create({\n data: {\n FIRST_NAME,\n EMAIL,\n PASSWORD: hashedPassword,\n IS_ACTIVE,\n USERNAME,\n CREATED_BY\n },\n })\n return {\n token: sign({ userId: user.id }, APP_SECRET),\n user,\n }\n },\n })\n\n t.field('login', {\n type: 'AuthPayload',\n args: {\n email: stringArg(),\n password: stringArg(),\n },\n resolve: async (parent, { email, password }, context) => {\n const user = await context.prisma.users.findOne({\n where: {\n EMAIL : email,\n },\n })\n if (!user) {\n return new Error(`No user found for email: ${email}`)\n }\n const passwordValid = await compare(password, user.PASSWORD)\n if (!passwordValid) {\n return new Error('Invalid password')\n }\n const token = await sign({ userId: user.id }, APP_SECRET)\n return {\n token ,\n user,\n }\n },\n })\n },\n})\n```\n\nMy problem is when i try to mutate the login method with token return value , it works perfectly and here is my mutation\n\n```\nmutation{\nlogin(email :\"dondala422@hotmail.com\" password :\"aa\")\n{\n token\n}\n}\n```\n\nResponse\n\n```\n{\n \"data\": {\n \"login\": {\n \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjMyLCJpYXQiOjE1OTcxMDY0OTd9.d1Ra32ArCXumBfzg2vE1-xeea21cAkNwWBJPm3U3akM\"\n }\n }\n}\n```\n\nAs shown . this works perfectly . now as mentioned the AuthPayload return the token and the users type\nwhen i try to mutate with user :-\n\n```\nmutation{\nlogin(email :\"dondala422@hotmail.com\" password :\"aa\")\n{\n token\n users{\n USERNAME\n FIRST_NAME\n }\n}\n}\n```\n\nit gives me this error\n\n```\n{\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field AuthPayload.users.\",\n \"locations\": [\n {\n \"line\": 4,\n \"column\": 5\n }\n ],\n \"path\": [\n \"login\",\n \"users\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Cannot return null for non-nullable field AuthPayload.users.\",\n \" at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:595:13)\",\n \" at completeValueCatchingError (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:530:19)\",\n \" at resolveField (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:461:10)\",\n \" at executeFields (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:297:18)\",\n \" at collectAndExecuteSubfields (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:748:10)\",\n \" at completeObjectValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:738:10)\",\n \" at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:626:12)\",\n \" at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:592:21)\",\n \" at C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:527:16\"\n ]\n }\n }\n }\n ],\n \"data\": null\n}\n```\n\ni tried to attach the debugger to see where is the null occur\nand i didn't found any nullable values\n\nhere is a picture of vscode before return value , the token and user object are defined\nVSCode Debugger picture\n\n========================================\n\nCode:\n```text\n### This file was generated by Nexus Schema\n### Do not make changes to this file directly\n\n\ntype AuthPayload {\n token: String!\n users: users!\n}\n\nscalar DateTime\n\ntype Mutation {\n login(email: String, password: String): AuthPayload!\n signup(CREATED_BY: String, EMAIL: String, FIRST_NAME: String, IS_ACTIVE: Boolean, PASSWORD: String, USERNAME: String): AuthPayload!\n}\n\ntype Query {\n me: users\n}\n\ntype users {\n CREATED_BY: String!\n CREATED_ON: DateTime\n EMAIL: String!\n FIRST_NAME: String!\n id: Int!\n IS_ACTIVE: Boolean!\n LAST_NAME: String\n MODIFIED_BY: String\n MODIFIED_ON: DateTime\n ORGANIZATION_ID: String\n PASSWORD: String!\n PHONE: String\n USERNAME: String!\n}\n```\n\n```text\nconst Mutation = mutationType({\n definition(t) {\n t.field('signup', {\n type: 'AuthPayload',\n args: {\n FIRST_NAME: stringArg({ nullable: true }),\n EMAIL: stringArg(),\n PASSWORD: stringArg(),\n IS_ACTIVE: booleanArg(),\n USERNAME: stringArg(),\n CREATED_BY: stringArg(),\n },\n resolve: async (parent, { FIRST_NAME, EMAIL, PASSWORD ,IS_ACTIVE ,USERNAME,CREATED_BY }, ctx) => {\n const hashedPassword = await hash(PASSWORD, 10)\n\n const user = await ctx.prisma.users.create({\n data: {\n FIRST_NAME,\n EMAIL,\n PASSWORD: hashedPassword,\n IS_ACTIVE,\n USERNAME,\n CREATED_BY\n },\n })\n return {\n token: sign({ userId: user.id }, APP_SECRET),\n user,\n }\n },\n })\n\n t.field('login', {\n type: 'AuthPayload',\n args: {\n email: stringArg(),\n password: stringArg(),\n },\n resolve: async (parent, { email, password }, context) => {\n const user = await context.prisma.users.findOne({\n where: {\n EMAIL : email,\n },\n })\n if (!user) {\n return new Error(`No user found for email: ${email}`)\n }\n const passwordValid = await compare(password, user.PASSWORD)\n if (!passwordValid) {\n return new Error('Invalid password')\n }\n const token = await sign({ userId: user.id }, APP_SECRET)\n return {\n token ,\n user,\n }\n },\n })\n },\n})\n```\n\n```text\nmutation{\nlogin(email :\"dondala422@hotmail.com\" password :\"aa\")\n{\n token\n}\n}\n```\n\n```text\n{\n \"data\": {\n \"login\": {\n \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjMyLCJpYXQiOjE1OTcxMDY0OTd9.d1Ra32ArCXumBfzg2vE1-xeea21cAkNwWBJPm3U3akM\"\n }\n }\n}\n```\n\n```text\nmutation{\nlogin(email :\"dondala422@hotmail.com\" password :\"aa\")\n{\n token\n users{\n USERNAME\n FIRST_NAME\n }\n}\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Cannot return null for non-nullable field AuthPayload.users.\",\n \"locations\": [\n {\n \"line\": 4,\n \"column\": 5\n }\n ],\n \"path\": [\n \"login\",\n \"users\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Cannot return null for non-nullable field AuthPayload.users.\",\n \" at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:595:13)\",\n \" at completeValueCatchingError (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:530:19)\",\n \" at resolveField (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:461:10)\",\n \" at executeFields (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:297:18)\",\n \" at collectAndExecuteSubfields (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:748:10)\",\n \" at completeObjectValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:738:10)\",\n \" at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:626:12)\",\n \" at completeValue (C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:592:21)\",\n \" at C:\\\\Users\\\\donda\\\\Desktop\\\\New folder (3)\\\\prisma-examples\\\\javascript\\\\graphql-auth - Copy\\\\node_modules\\\\graphql\\\\execution\\\\execute.js:527:16\"\n ]\n }\n }\n }\n ],\n \"data\": null\n}\n```\n\n```text\nuser\n```\n\n```text\nusers\n```\n\n```text\nusers\n```\n\n```text\nnull\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":383,"estimatedTokens":2465}}1097{"id":"stack-58843960","source":"stackoverflow","questionId":58843960,"title":"Difference between `writeQuery` and `writeData` in Apollo client?","tags":["graphql","apollo","apollo-client"],"text":"Title: Difference between `writeQuery` and `writeData` in Apollo client?\nTags: graphql, apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nAccording to the docs on local state management, one can use both `writeData` and `writeQuery` for appending data to the cache.\n\nWhat are the best practices here? When to one over the other?\n\n========================================\n\nCode:\n```text\nwriteData\n```\n\n```text\nwriteQuery\n```\n\n```text\ncache.writeQuery\n```\n\n```text\ncache.writeData\n```\n\n```text\ncache.writeQuery\n```\n\n```text\ncache.writeData\n```\n\n```text\ndata\n```\n\n```text\ncache.writeQuery\n```\n\n```text\ncache.writeQuery\n```\n\n```text\ncache.writeData\n```\n\n```text\ncache.writeData\n```\n\n```text\ncache.writeQuery\n```\n\n```text\ncache.writeQuery\n```\n\n```text\ncache.writeData\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":67,"estimatedTokens":193}}1098{"id":"stack-67692244","source":"stackoverflow","questionId":67692244,"title":"Add headers to request using Ferry with Flutter","tags":["flutter","dart","graphql"],"text":"Title: Add headers to request using Ferry with Flutter\nTags: flutter, dart, graphql\nSource: Stack Overflow\n\nQuestion:\nit's my first time using Ferry to make GraphQL requests.\nMy GraphQL Server has some queries that need an HTTP header for authorization.\n\nI need to be able to add the header after initializing the client.\n\n**client.dart**:\n\n```\nFuture initClient() async {\n await Hive.initFlutter();\n\n final box = await Hive.openBox>(\"graphql\");\n\n await box.clear();\n\n final store = HiveStore(box);\n\n final cache = Cache(store: store);\n\n final link = HttpLink(\"example.com/\");\n\n final client = Client(\n link: link,\n cache: cache,\n );\n\n return client;\n}\n```\n\n**main.dart**:\n\n```\nvoid main() async{\n final client = await initClient();\n GetIt.I.registerLazySingleton(() => client);\n runApp(MyApp());\n}\n```\n\n**request file**:\n\n```\nclient.request(Req).listen((response) {\n print(response.graphqlErrors); // It will return an error because theres no header with the token\n print(response.data);\n });\n```\n\n========================================\n\nTop Answer:\n### Try this implementation work for me!\n\nsave auth_link.dar from graphql_flutter\n\n### Working example\n\n```\nimport 'dart:async';\n\nimport 'package:ferry/ferry.dart';\nimport 'package:ferry_hive_store/ferry_hive_store.dart';\nimport 'package:gql_http_link/gql_http_link.dart';\nimport 'package:hive_flutter/hive_flutter.dart';\nimport 'path_to/auth_link.dart';\nFuture initClient() async {\n final box = await Hive.openBox(\"graphql\");\n await box.clear();\n final store = HiveStore(box);\n final cache = Cache(store: store);\n var httpLink = HttpLink('http://localhost:4000/graphql');\n final AuthLink authLink = AuthLink(\n getToken: () async => await getBoxToken(),\n );\n\n final Link link = authLink.concat(httpLink);\n final client = Client(\n link: link,\n cache: cache,\n );\n return client;\n}\n\nFutureOr getBoxToken() async {\n final box = await Hive.openBox(\"fireToken\");\n return 'Bearer ${box.get('token')}';\n}\n```\n\n========================================\n\nCode:\n```text\nFuture<Client> initClient() async {\n await Hive.initFlutter();\n\n final box = await Hive.openBox<Map<String, dynamic>>(\"graphql\");\n\n await box.clear();\n\n final store = HiveStore(box);\n\n final cache = Cache(store: store);\n\n final link = HttpLink(\"example.com/\");\n\n final client = Client(\n link: link,\n cache: cache,\n );\n\n return client;\n}\n```\n\n```text\nvoid main() async{\n final client = await initClient();\n GetIt.I.registerLazySingleton<Client>(() => client);\n runApp(MyApp());\n}\n```\n\n```text\nclient.request(Req).listen((response) {\n print(response.graphqlErrors); // It will return an error because theres no header with the token\n print(response.data);\n });\n```\n\n```dart\nimport 'package:ferry/ferry.dart';\nimport 'package:gql_http_link/gql_http_link.dart';\n\nClient initGqlClient(String url) {\n final link = HttpLink(\n url,\n defaultHeaders: {\n 'Authorization':\n 'Bearer eyJ0eXAiOi...',\n },\n );\n\n final client = Client(link: link);\n\n return client;\n}\n```\n\n```text\ndefaultHeaders\n```\n\n```text\nHttpLink\n```\n\n```dart\nimport 'dart:async';\n\nimport 'package:ferry/ferry.dart';\nimport 'package:ferry_hive_store/ferry_hive_store.dart';\nimport 'package:gql_http_link/gql_http_link.dart';\nimport 'package:hive_flutter/hive_flutter.dart';\nimport 'path_to/auth_link.dart';\nFuture<Client> initClient() async {\n final box = await Hive.openBox(\"graphql\");\n await box.clear();\n final store = HiveStore(box);\n final cache = Cache(store: store);\n var httpLink = HttpLink('http://localhost:4000/graphql');\n final AuthLink authLink = AuthLink(\n getToken: () async => await getBoxToken(),\n );\n\n final Link link = authLink.concat(httpLink);\n final client = Client(\n link: link,\n cache: cache,\n );\n return client;\n}\n\nFutureOr<String> getBoxToken() async {\n final box = await Hive.openBox(\"fireToken\");\n return 'Bearer ${box.get('token')}';\n}\n```\n\n```text\nFuture<Client> initClient(Config config) async {\n await Hive.initFlutter();\n final box = await Hive.openBox<dynamic>('graphql');\n final store = HiveStore(box);\n final cache = Cache(store: store);\n final link = HttpLink(config.graphqlServerUrl);\n return Client(link: link, cache: cache);\n}\n```\n\n```text\nimport 'package:gql_exec/gql_exec.dart'; // requires this package\n\nContext buildContextWithHttpHeaders(Map<String, String> headers) {\n return const Context().withEntry(HttpLinkHeaders(headers: headers));\n}\n```\n\n```text\nfinal token = await getAuthToken();\nfinal headers = { 'Authorization': 'Bearer $token' };\nfinal request = GSomeReq(\n (builder) => builder\n ..fetchPolicy = FetchPolicy.NetworkOnly\n ..context = buildContextWithHttpHeaders(headers),\n);\n```\n\n```yaml\nferry: ^0.16.0+1\ngql_exec: ^1.0.0+1\ngql_http_link: ^1.1.0\n```\n\n```text\n// gql_http_link: ^1.1.0\nMap<String, String> _getHttpLinkHeaders(Request request) {\n ...\n final HttpLinkHeaders? linkHeaders = request.context.entry();\n ...\n}\n\nhttp.BaseRequest _prepareRequest(Request request) {\n ...\n final contextHeaders = _getHttpLinkHeaders(request);\n final headers = {\n \"Content-type\": \"application/json\",\n \"Accept\": \"*/*\",\n ...defaultHeaders,\n ...contextHeaders,\n };\n ...\n}\n```\n\n```text\nHttpLinkHeaders\n```\n\n```text\nContext\n```\n\n```text\nHttpLink\n```\n\n```text\nContext\n```\n\n```text\nHttpLink\n```\n\n========================================\n\nComments:\n- Check this post on their Github which explains how to add a header. github.com/gql-dart/ferry/issues/95 Also an example github.com/gql-dart/gql/blob/…\n- @ChiragBargoojar thanks, I don't know if I understood the code correctly but that example won't force to have a token?\n- I don't think it will force you to pass token just try it that's the only way to find out.\n- Thanks I will try.\n- Hi, what if my bearer-token need to change (after refresh) in your case it will need to reconstruct the whole HttpLink and thus the entire Client as well\n- I was looking to `concat` the HttpLink with `AuthLink` but I can't find where I can import the `AuthLink`\n- Just an update, I've switched to Artemis which I like better because it decouples the frontend from the backend better, and overall is more flexible, customizable to use cases.","metadata":{"transformedAt":"2026-08-18T18:32:36.227Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":281,"estimatedTokens":1552}}1099{"id":"stack-60451843","source":"stackoverflow","questionId":60451843,"title":"How can one get a complete GraphQL schema from an Apollo Server endpoint?","tags":["graphql","apollo-server","keystonejs","graphql-schema"],"text":"Title: How can one get a complete GraphQL schema from an Apollo Server endpoint?\nTags: graphql, apollo-server, keystonejs, graphql-schema\nSource: Stack Overflow\n\nQuestion:\nI'm writing a GraphQL interface between GraphQL and REST services using Apollo Server. This interface will provide a single GraphQL endpoint for an Apollo Client front. \n\nThe single service at the moment is a KeystoneJS app which provides a GraphQL endpoint, through (as far as I know) Apollo Server. To keep things simple for the moment, I'm downloading the GraphQL schema from the KeystoneJS server GraphQL Playground and using it as my interface's GraphQL schema (after removing definitions that Keystone generates and Apollo Server doesn't understand).\n\nI'd like to automate this process -- that is, somehow 'grab' the GraphQL schema that KeystoneJS/Apollo Server generates, just as if I were to download it from the GraphQL Playground. Is there a way to do this from the endpoint? (I don't want to touch the KeystoneJS internals, just access the schema through the endpoint)\n\n========================================\n\nCode:\n```text\nconst { buildClientSchema, getIntrospectionQuery, printSchema } = require('graphql')\nconst axios = require('axios')\n\nconst ENDPOINT_URL = \"\";\n\n(async () => {\n const res = await axios.post(ENDPOINT_URL, { query: getIntrospectionQuery() })\n const schema = buildClientSchema(res.data.data)\n const sdl = printSchema(schema)\n console.log(sdl)\n})()\n```\n\n```text\nbuildClientSchema\n```\n\n```text\nprintSchema\n```\n\n```text\nbuildClientSchema\n```\n\n========================================\n\nComments:\n- If you're currently using GraphQL Playground to run an introspection query, is there any reason you can't just make a request to the KeystoneJS endpoint with the same query using an HTTP library of your choice?\n- @DanielRearden -- I had thought about that. I'm new to GraphQL so haven't used introspections before. As I see it from graphql.org/learn/introspection, one can get JSON that gives you information about specific aspects of the schema. I suppose I could use that to reconstruct the SDL of the complete schema, but I am working with a large schema -- at present 820 lines, and it will grow -- with lots of nested types. Is there a way to simply request the entire schema through introspections and quickly/easily convert it to SDL? Is it easy enough to do using introspections?\n- My bad -- I forgot Playground had a \"download\" button for the schema so I misunderstood you when you said you were downloading the schema via Playground. I assumed you were already using introspection to do so.\n- FWIW, I imagine instead of doing the request with axios, you can also use executeQuery if you have access to the Keystone instance.\n- This would be in a separate application, so unless I exposed it through the Keystone API, I wouldn't....","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":713}}1100{"id":"stack-70155710","source":"stackoverflow","questionId":70155710,"title":"How to get updated / lastmod value for static files for sitemap Gatsby","tags":["reactjs","graphql","gatsby"],"text":"Title: How to get updated / lastmod value for static files for sitemap Gatsby\nTags: reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI've been using Gatsby and have been trying to create a `sitemap` with `lastmod` values for static pages (`src/pages`). I saw a random code snippet in which someone ran the query below within his `gatsby-config.js` and was able to get the date he last modified them.\n\n```\nallSitePage {\n nodes {\n path\n context {\n updated\n }\n }\n}\n```\n\nI've not been able to achieve the same feat.\n\nThis is what I've tried so far. I've assumed he was using a context manager and set context within his `js` files and updating the value of the context manually every time he edited the files.\n\n```\nconst Updated = React.createContext('2021-11-29')\n\nclass IndexPage extends React.Component {\n render() {\n return (\n \n {/* Example */}\n \n )\n }\n}\n\n/* Also tried IndexPage.contextType = Updated */\nIndexPage.useContext = Updated\n\nexport default IndexPage\n```\n\nI've ran the query again, but have not been able to pass the value to be seen within the `graphql` query. This is the query I ran in the Graphql playground.\n\n```\nquery MyQuery {\n allSitePage {\n nodes {\n id\n context {\n updated\n }\n }\n }\n}\n```\n\nThis is what my whole data structure looks like within the Graphql playground.\nhttps://i.sstatic.net/riDN3.png\n\nHow would I be able to get / set a `updated` value to be used in `gatsby-config.js` when creating a sitemap?\n\n========================================\n\nTop Answer:\n```\n\"allSitePage\": {\n \"nodes\": [\n {\n \"path\": \"/signup/united-states/new-york/\"\n },\n {\n \"path\": \"/signup/united-kingdom/london/\"\n }\n ]\n}\n```\n\nIf your project have **nested page structure** than use this below code.\n\n\r\n\r\n\n```\n{\n resolve: \"gatsby-source-filesystem\",\n options: {\n name: \"pages\",\n path: \"./src/pages/\",\n },\n},\n`gatsby-transformer-gitinfo`, {\n resolve: \"gatsby-plugin-sitemap\",\n options: {\n query: `{\n site {\n siteMetadata {\n siteUrl\n }\n }\n allSitePage {\n nodes {\n path\n }\n }\n allFile(filter: {sourceInstanceName: {eq: \"pages\"}}) {\n edges {\n node {\n fields {\n gitLogLatestDate\n }\n relativePath\n }\n }\n }\n }`,\n resolvePages: ({\n allSitePage: {\n nodes: sitePages\n },\n allFile: {\n edges: pageFiles\n }\n }) => {\n return sitePages.map(page => {\n const pageFile = pageFiles.find(({\n node\n }) => {\n let fileName = node.relativePath.split('.').slice(0, -1).join('.')\n fileName = fileName === 'index' ? '/' : `/${fileName.replace('/index','')}/`\n return page.path === fileName;\n });\n\n return { ...page, ...pageFile?.node?.fields }\n })\n },\n serialize: ({\n path,\n gitLogLatestDate\n }) => {\n return {\n url: path,\n lastmod: gitLogLatestDate\n }\n },\n createLinkInHead: true,\n },\n}\n```\n\n========================================\n\nCode:\n```text\nallSitePage {\n nodes {\n path\n context {\n updated\n }\n }\n}\n```\n\n```js\nconst Updated = React.createContext('2021-11-29')\n\nclass IndexPage extends React.Component {\n render() {\n return (\n <div>\n {/* Example */}\n </div>\n )\n }\n}\n\n/* Also tried IndexPage.contextType = Updated */\nIndexPage.useContext = Updated\n\nexport default IndexPage\n```\n\n```text\nquery MyQuery {\n allSitePage {\n nodes {\n id\n context {\n updated\n }\n }\n }\n}\n```\n\n```text\nsitemap\n```\n\n```text\nlastmod\n```\n\n```text\nsrc/pages\n```\n\n```text\ngatsby-config.js\n```\n\n```text\njs\n```\n\n```text\ngraphql\n```\n\n```text\nupdated\n```\n\n```text\ngatsby-config.js\n```\n\n```text\n{\n resolve: \"gatsby-source-filesystem\",\n options: {\n name: \"pages\",\n path: \"./src/pages/\",\n },\n},\n```\n\n```text\n{\n resolve: \"gatsby-source-filesystem\",\n options: {\n name: \"pages\",\n path: \"./src/pages/\",\n },\n},\n`gatsby-transformer-gitinfo`,\n```\n\n```text\nquery MyQuery {\n site {\n siteMetadata {\n siteUrl\n }\n }\n allSitePage {\n nodes {\n path\n }\n }\n allFile(filter: {sourceInstanceName: {eq: \"pages\"}}) {\n edges {\n node {\n fields {\n gitLogLatestDate\n }\n name\n }\n }\n }\n}\n```\n\n```text\n{\n \"data\": {\n \"site\": {\n \"siteMetadata\": {\n \"siteUrl\": \"https://www.example.com\"\n }\n },\n \"allSitePage\": {\n \"nodes\": [\n {\n \"path\": \"/dev-404-page/\"\n },\n {\n \"path\": \"/404/\"\n },\n {\n \"path\": \"/404.html\"\n },\n {\n \"path\": \"/contact/\"\n },\n {\n \"path\": \"/features/\"\n },\n {\n \"path\": \"/\"\n },\n {\n \"path\": \"/privacy/\"\n },\n {\n \"path\": \"/terms/\"\n }\n ]\n },\n \"allFile\": {\n \"edges\": [\n {\n \"node\": {\n \"fields\": {\n \"gitLogLatestDate\": \"2021-12-09 23:18:29 -0600\"\n },\n \"name\": \"404\"\n }\n },\n {\n \"node\": {\n \"fields\": {\n \"gitLogLatestDate\": \"2021-12-09 23:18:29 -0600\"\n },\n \"name\": \"contact\"\n }\n },\n {\n \"node\": {\n \"fields\": {\n \"gitLogLatestDate\": \"2021-12-09 23:18:29 -0600\"\n },\n \"name\": \"privacy\"\n }\n },\n {\n \"node\": {\n \"fields\": {\n \"gitLogLatestDate\": \"2021-12-07 19:11:12 -0600\"\n },\n \"name\": \"index\"\n }\n },\n {\n \"node\": {\n \"fields\": {\n \"gitLogLatestDate\": \"2021-12-09 23:18:29 -0600\"\n },\n \"name\": \"terms\"\n }\n },\n {\n \"node\": {\n \"fields\": {\n \"gitLogLatestDate\": \"2021-12-09 23:18:29 -0600\"\n },\n \"name\": \"features\"\n }\n }\n ]\n }\n },\n \"extensions\": {}\n}\n```\n\n```text\n{\n resolve: \"gatsby-source-filesystem\",\n options: {\n name: \"pages\",\n path: \"./src/pages/\",\n },\n},\n`gatsby-transformer-gitinfo`,\n{\n resolve: \"gatsby-plugin-sitemap\",\n options: {\n query: `{\n site {\n siteMetadata {\n siteUrl\n }\n }\n allSitePage {\n nodes {\n path\n }\n }\n allFile(filter: {sourceInstanceName: {eq: \"pages\"}}) {\n edges {\n node {\n fields {\n gitLogLatestDate\n }\n name\n }\n }\n }\n }`,\n resolvePages: ({\n allSitePage: { nodes: sitePages },\n allFile: { edges: pageFiles }\n }) => {\n return sitePages.map(page => {\n const pageFile = pageFiles.find(({ node }) => {\n const fileName = node.name === 'index' ? '/' : `/${node.name}/`;\n return page.path === fileName;\n });\n\n return { ...page, ...pageFile?.node?.fields }\n })\n },\n serialize: ({ path, gitLogLatestDate }) => {\n return {\n url: path,\n lastmod: gitLogLatestDate\n }\n },\n createLinkInHead: true,\n },\n}\n```\n\n```text\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:news=\"http://www.google.com/schemas/sitemap-news/0.9\"\n xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\"\n xmlns:video=\"http://www.google.com/schemas/sitemap-video/1.1\">\n <url>\n <loc>https://www.example.com/contact/</loc>\n <lastmod>2021-12-10T05:18:29.000Z</lastmod>\n </url>\n <url>\n <loc>https://www.example.com/features/</loc>\n <lastmod>2021-12-10T05:18:29.000Z</lastmod>\n </url>\n <url>\n <loc>https://www.example.com/</loc>\n <lastmod>2021-12-08T01:11:12.000Z</lastmod>\n </url>\n <url>\n <loc>https://www.example.com/privacy/</loc>\n <lastmod>2021-12-10T05:18:29.000Z</lastmod>\n </url>\n <url>\n <loc>https://www.example.com/terms/</loc>\n <lastmod>2021-12-10T05:18:29.000Z</lastmod>\n </url>\n</urlset>\n```\n\n```text\n\"gatsby\": \"^4.0.0\",\n\"gatsby-plugin-sitemap\": \"^5.3.0\",\n\"gatsby-source-filesystem\": \"^4.3.0\",\n\"gatsby-transformer-gitinfo\": \"^1.1.0\",\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\ngatsby-config.js\n```\n\n```text\nname\n```\n\n```text\ngatsby-transformer-gitinfo\n```\n\n```text\nFile\n```\n\n```text\nmodifiedTime\n```\n\n```text\nmtime\n```\n\n```text\nchangeTime\n```\n\n```text\nctime\n```\n\n```text\nFile\n```\n\n```text\nsourceInstanceName\n```\n\n```text\noptions.name\n```\n\n```text\ngatsby-config.js\n```\n\n```text\ngatsby-plugin-sitemap\n```\n\n```text\nquery\n```\n\n```text\nresolvePages\n```\n\n```text\nquery\n```\n\n```text\nallSitePage\n```\n\n```text\nallFile\n```\n\n```text\nsitePages\n```\n\n```text\nallSitePage.nodes\n```\n\n```text\npage.path\n```\n\n```text\nname\n```\n\n```text\nname\n```\n\n```text\nindex\n```\n\n```text\n/\n```\n\n```text\n/index/\n```\n\n```text\nname\n```\n\n```text\nresolvePages\n```\n\n```text\nallPages\n```\n\n```text\nserialize\n```\n\n```text\nallPages\n```\n\n```text\nresolvePages\n```\n\n```text\npath\n```\n\n```text\ngitLogLatestDate\n```\n\n```text\nurl\n```\n\n```text\nsiteMetaData.siteUrl\n```\n\n```text\nlastmod\n```\n\n```text\nlastmod\n```\n\n```text\ngatsby-plugin-sitemap\n```\n\n```text\ngatsby-plugin-sitemap\n```\n\n```text\nlastmodDateOnly\n```\n\n```text\ngatsby-plugin-sitemap\n```\n\n```text\ncreateLinkInHead\n```\n\n```text\ngatsby build\n```\n\n```text\npublic/sitemap/sitemap-0.xml\n```\n\n```text\ngatsby-plugin-sitemap\n```\n\n```text\n\"allSitePage\": {\n \"nodes\": [\n {\n \"path\": \"/signup/united-states/new-york/\"\n },\n {\n \"path\": \"/signup/united-kingdom/london/\"\n }\n ]\n}\n```\n\n```js\n{\n resolve: \"gatsby-source-filesystem\",\n options: {\n name: \"pages\",\n path: \"./src/pages/\",\n },\n},\n`gatsby-transformer-gitinfo`, {\n resolve: \"gatsby-plugin-sitemap\",\n options: {\n query: `{\n site {\n siteMetadata {\n siteUrl\n }\n }\n allSitePage {\n nodes {\n path\n }\n }\n allFile(filter: {sourceInstanceName: {eq: \"pages\"}}) {\n edges {\n node {\n fields {\n gitLogLatestDate\n }\n relativePath\n }\n }\n }\n }`,\n resolvePages: ({\n allSitePage: {\n nodes: sitePages\n },\n allFile: {\n edges: pageFiles\n }\n }) => {\n return sitePages.map(page => {\n const pageFile = pageFiles.find(({\n node\n }) => {\n let fileName = node.relativePath.split('.').slice(0, -1).join('.')\n fileName = fileName === 'index' ? '/' : `/${fileName.replace('/index','')}/`\n return page.path === fileName;\n });\n\n return { ...page, ...pageFile?.node?.fields }\n })\n },\n serialize: ({\n path,\n gitLogLatestDate\n }) => {\n return {\n url: path,\n lastmod: gitLogLatestDate\n }\n },\n createLinkInHead: true,\n },\n}\n```\n\n========================================\n\nComments:\n- Field SitePage.context is no longer available in GraphQL queries since Gatsby 4 (link) (docs)\n- This worked out pretty awesome in 2025 - the `gatsby-transformer-gitinfo` package seems to be abandoned (last update 6 years ago) - but there's a fork that is working for me: github.com/skylerwlewis/gatsby-transformer-gitinfo","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":67,"totalLines":732,"estimatedTokens":2766}}1101{"id":"stack-50497417","source":"stackoverflow","questionId":50497417,"title":"Cascade delete related nodes using GraphQL and Prisma","tags":["graphql","cascading-deletes","prisma"],"text":"Title: Cascade delete related nodes using GraphQL and Prisma\nTags: graphql, cascading-deletes, prisma\nSource: Stack Overflow\n\nQuestion:\nI'm trying to figure out cascade deletion in GraphQL.\n\nI'm attempting to delete a node of type `Question`, but type `QuestionVote` has a required relation to `Question`. I'm looking for a way to delete a `Question` and all its votes at once.\n\nMutation for deleting a `Question`:\n\n```\ntype Mutation {\n deleteQuestion(where: QuestionWhereUniqueInput!): Question!\n}\n```\n\nAnd its resolver (I'm using Prisma): \n\n```\nfunction deleteQuestion(parent, args, context, info) {\n const userId = getUserId(context) \n return context.db.mutation.deleteQuestion(\n {\n where: {id: args.id}\n },\n info,\n )\n}\n```\n\nHow can I modify that mutation to also delete related `QuestionVote` nodes? Or should I add a separate mutation that deletes one or multiple instances of `QuestionVote`?\n\nIn case it's important, here are the mutations that create `Question` and `QuestionVote`:\n\n```\nfunction createQuestion(parent, args, context, info) {\n const userId = getUserId(context)\n return context.db.mutation.createQuestion(\n {\n data: {\n content: args.content,\n postedBy: { connect: { id: userId } },\n },\n },\n info,\n )\n}\n\nasync function voteOnQuestion(parent, args, context, info) {\n const userId = getUserId(context)\n\n const questionExists = await context.db.exists.QuestionVote({\n user: { id: userId },\n question: { id: args.questionId },\n })\n if (questionExists) {\n throw new Error(`Already voted for question: ${args.questionId}`)\n }\n\n return context.db.mutation.createQuestionVote(\n {\n data: {\n user: { connect: { id: userId } },\n question: { connect: { id: args.questionId } },\n },\n },\n info,\n )\n}\n```\n\nThanks!\n\n========================================\n\nCode:\n```text\ntype Mutation {\n deleteQuestion(where: QuestionWhereUniqueInput!): Question!\n}\n```\n\n```text\nfunction deleteQuestion(parent, args, context, info) {\n const userId = getUserId(context) \n return context.db.mutation.deleteQuestion(\n {\n where: {id: args.id}\n },\n info,\n )\n}\n```\n\n```text\nfunction createQuestion(parent, args, context, info) {\n const userId = getUserId(context)\n return context.db.mutation.createQuestion(\n {\n data: {\n content: args.content,\n postedBy: { connect: { id: userId } },\n },\n },\n info,\n )\n}\n\nasync function voteOnQuestion(parent, args, context, info) {\n const userId = getUserId(context)\n\n const questionExists = await context.db.exists.QuestionVote({\n user: { id: userId },\n question: { id: args.questionId },\n })\n if (questionExists) {\n throw new Error(`Already voted for question: ${args.questionId}`)\n }\n\n return context.db.mutation.createQuestionVote(\n {\n data: {\n user: { connect: { id: userId } },\n question: { connect: { id: args.questionId } },\n },\n },\n info,\n )\n}\n```\n\n```text\nQuestion\n```\n\n```text\nQuestionVote\n```\n\n```text\nQuestion\n```\n\n```text\nQuestion\n```\n\n```text\nQuestion\n```\n\n```text\nQuestionVote\n```\n\n```text\nQuestionVote\n```\n\n```text\nQuestion\n```\n\n```text\nQuestionVote\n```\n\n```text\ntype Question {\n id: ID! @unique\n votes: [QuestionVote!]! @relation(name: \"QuestionVotes\")\n text: String!\n}\n\ntype QuestionVote {\n id: ID! @unique\n question: Question @relation(name: \"QuestionVotes\")\n isUpvote: Boolean!\n}\n```\n\n```text\ntype Question {\n id: ID! @unique\n votes: [QuestionVote!]! @relation(name: \"QuestionVotes\" onDelete: CASCADE)\n text: String!\n}\n\ntype QuestionVote {\n id: ID! @unique\n question: Question @relation(name: \"QuestionVotes\")\n isUpvote: Boolean!\n}\n```\n\n```text\nonCascade: DELETE\n```\n\n```text\n@relation\n```\n\n```text\nQuestion\n```\n\n```text\nQuestionVote\n```\n\n```text\nonDelete\n```\n\n```text\nonDelete: SET_NULL\n```\n\n```text\nnull\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":223,"estimatedTokens":954}}1102{"id":"stack-43292529","source":"stackoverflow","questionId":43292529,"title":"How can I use from GraphQl in android?","tags":["android","graphql","graphql-java"],"text":"Title: How can I use from GraphQl in android?\nTags: android, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI need to a simple example for use `GraphQl` in android .\n\nHow can I use from `GraphQl` in android (tutorial).\n\n========================================\n\nTop Answer:\nHere is an example of querying GraphQl from Client. In this example I am using Retrofit 2:\n\n```\n// QueryHelper.java\n// This line below is the simple format of Gql query\nquery = \"query{me{name, location, majorOfInterest,profilePhoto{url(size: 400) }}}\";\n\n//Post the query using Retrofit2\nGqlRetrofitClient.getInstance(getContext()).fetchUserDetails(new GqlQueryRequest(queryUserDetails)).enqueue(new Callback() {\n @Override\n public void onResponse(Call call, Response response) {\n //OnResponse do something(); \n }\n\n @Override\n public void onFailure(Call call, Throwable t) {\n Log.d(TAG, \"Failed to fetch User details\");\n }\n });\n\n//GqlClient.java\npublic class GqlRetrofitClient {\npublic static final String BASE_URL = BuildConfig.DOMAIN;\nprivate static GqlRetrofitClient sInstance;\nprivate GqlRetrofitService mGqlRetrofitService;\n\nGson gson = new GsonBuilder().create();\n\n private GqlRetrofitClient(final Context context) {\n // Network Interceptor for logging\n HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();\n httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);\n\n OkHttpClient okHttpClient = new OkHttpClient.Builder()\n .addNetworkInterceptor(new Interceptor() {\n @Override\n public Response intercept(Chain chain) throws IOException {\n Request request = chain.request().newBuilder()\n .addHeader(\"X-User-Token\", \"AUTH_TOKEN\")\n .addHeader(\"X-User_Email\", \"Email\")\n .addHeader(\"content-type\", \"application/json\")\n .build();\n return chain.proceed(request);\n }\n })\n .addInterceptor(httpLoggingInterceptor)\n .build();\n\n // Retrofit initialization\n final Retrofit retrofit = new Retrofit.Builder()\n .baseUrl(BASE_URL)\n .addConverterFactory(GsonConverterFactory.create(gson))\n .client(okHttpClient)\n .build();\n\n mGqlRetrofitService = retrofit.create(GqlRetrofitService.class);\n }\n\n // Create an instance of GqlRetrofitClient to create retrofit service\n public static GqlRetrofitClient getInstance(Context context){\n if(sInstance == null){\n sInstance = new GqlRetrofitClient(context.getApplicationContext());\n }\n return sInstance;\n }\n\n // Method call to get User details\n public Call fetchUserDetails(GqlQueryRequest queryUserDetails){\n return mGqlRetrofitService.getUserDetails(queryUserDetails);\n }\n}\n\n//GqlRetrofitService.java\npublic interface GqlRetrofitService{\n @POST(\"/api/graph.json\")\n Call getUserDetails(@Body GqlQueryRequest body);\n}\n```\n\n========================================\n\nCode:\n```text\nGraphQl\n```\n\n```text\nGraphQl\n```\n\n```text\n// QueryHelper.java\n// This line below is the simple format of Gql query\nquery = \"query{me{name, location, majorOfInterest,profilePhoto{url(size: 400) }}}\";\n\n//Post the query using Retrofit2\nGqlRetrofitClient.getInstance(getContext()).fetchUserDetails(new GqlQueryRequest(queryUserDetails)).enqueue(new Callback<UserDetails>() {\n @Override\n public void onResponse(Call<UserDetails> call, Response<UserDetails> response) {\n //OnResponse do something(); \n }\n\n @Override\n public void onFailure(Call<UserDetails> call, Throwable t) {\n Log.d(TAG, \"Failed to fetch User details\");\n }\n });\n\n\n//GqlClient.java\npublic class GqlRetrofitClient {\npublic static final String BASE_URL = BuildConfig.DOMAIN;\nprivate static GqlRetrofitClient sInstance;\nprivate GqlRetrofitService mGqlRetrofitService;\n\nGson gson = new GsonBuilder().create();\n\n private GqlRetrofitClient(final Context context) {\n // Network Interceptor for logging\n HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();\n httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);\n\n OkHttpClient okHttpClient = new OkHttpClient.Builder()\n .addNetworkInterceptor(new Interceptor() {\n @Override\n public Response intercept(Chain chain) throws IOException {\n Request request = chain.request().newBuilder()\n .addHeader(\"X-User-Token\", \"AUTH_TOKEN\")\n .addHeader(\"X-User_Email\", \"Email\")\n .addHeader(\"content-type\", \"application/json\")\n .build();\n return chain.proceed(request);\n }\n })\n .addInterceptor(httpLoggingInterceptor)\n .build();\n\n // Retrofit initialization\n final Retrofit retrofit = new Retrofit.Builder()\n .baseUrl(BASE_URL)\n .addConverterFactory(GsonConverterFactory.create(gson))\n .client(okHttpClient)\n .build();\n\n mGqlRetrofitService = retrofit.create(GqlRetrofitService.class);\n }\n\n // Create an instance of GqlRetrofitClient to create retrofit service\n public static GqlRetrofitClient getInstance(Context context){\n if(sInstance == null){\n sInstance = new GqlRetrofitClient(context.getApplicationContext());\n }\n return sInstance;\n }\n\n // Method call to get User details\n public Call<UserDetails> fetchUserDetails(GqlQueryRequest queryUserDetails){\n return mGqlRetrofitService.getUserDetails(queryUserDetails);\n }\n}\n\n//GqlRetrofitService.java\npublic interface GqlRetrofitService{\n @POST(\"/api/graph.json\")\n Call<UserDetails> getUserDetails(@Body GqlQueryRequest body);\n}\n```\n\n```text\npublic class GraphQLConverter extends Converter.Factory {\n\n private static final MediaType MEDIA_TYPE = MediaType.parse(\"application/json; charset=UTF-8\");\n\n private GraphQueryProcessor graphProcessor;\n private final Gson mGson;\n\n private GraphQLConverter(Context context) {\n graphProcessor = new GraphQueryProcessor(context);\n mGson = new GsonBuilder()\n .enableComplexMapKeySerialization()\n .setLenient()\n .create();\n }\n\n public static GraphQLConverter create(Context context) {\n return new GraphQLConverter(context);\n }\n\n /** Override Converter.Factory Methods **/\n @Override\n public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {\n return null;\n }\n\n @Override\n public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {\n if(type == QueryContainerBuilder.class){\n return new GraphRequestConverter(methodAnnotations);\n } else {\n return null;\n }\n }\n\n /** RequestConverter Class **/\n private class GraphRequestConverter implements Converter<QueryContainerBuilder, RequestBody> {\n\n private Annotation[] mAnnotations;\n\n private GraphRequestConverter(Annotation[] annotations) {\n mAnnotations = annotations;\n }\n\n @Override\n public RequestBody convert(@NonNull QueryContainerBuilder containerBuilder) {\n QueryContainerBuilder.QueryContainer queryContainer = containerBuilder\n .setQuery(graphProcessor.getQuery(mAnnotations))\n .build();\n return RequestBody.create(MEDIA_TYPE, mGson.toJson(queryContainer).getBytes());\n }\n\n }\n}\n```\n\n```text\n@Target(ElementType.METHOD)\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface GraphQuery {\n\n String value() default \"\";\n\n}\n```\n\n```text\nclass GraphQueryProcessor {\n\n private static final String TAG = GraphQueryProcessor.class.getSimpleName();\n // GraphQl Constants\n private static final String EXT_GRAPHQL = \".graphql\";\n private static final String ROOT_FOLDER_GRAPHQL = \"graphql\";\n\n private final Map<String, String> mGraphQueries;\n private Context mContext;\n\n GraphQueryProcessor(Context context) {\n mGraphQueries = new WeakHashMap<>();\n mContext = context;\n populateGraphQueries(ROOT_FOLDER_GRAPHQL);\n }\n\n /** Package-Private Methods **/\n String getQuery(Annotation[] annotations) {\n if(mGraphQueries == null || mGraphQueries.isEmpty()){\n populateGraphQueries(ROOT_FOLDER_GRAPHQL);\n }\n\n GraphQuery graphQuery = null;\n for (Annotation annotation : annotations) {\n if (annotation instanceof GraphQuery) {\n graphQuery = (GraphQuery) annotation;\n break;\n }\n }\n\n if (graphQuery != null) {\n String fileName = String.format(\"%s%s\", graphQuery.value(), EXT_GRAPHQL);\n if (mGraphQueries != null && mGraphQueries.containsKey(fileName)) {\n return mGraphQueries.get(fileName);\n }\n }\n return null;\n }\n\n /** Private Methods **/\n private void populateGraphQueries(@NonNull String path) {\n try {\n String[] paths = mContext.getAssets().list(path);\n if (paths != null && paths.length > 0x0) {\n for (String item : paths) {\n String absolute = path + \"/\" + item;\n if (!item.endsWith(EXT_GRAPHQL)) {\n populateGraphQueries(absolute);\n } else {\n mGraphQueries.put(item, getFileContents(mContext.getAssets().open(absolute)));\n }\n }\n }\n } catch (IOException ioE) {\n BaseEnvironment.onExceptionLevelLow(TAG, ioE);\n }\n }\n\n private String getFileContents(InputStream inputStream) {\n StringBuilder queryBuffer = new StringBuilder();\n try {\n InputStreamReader inputStreamReader = new InputStreamReader(inputStream);\n BufferedReader bufferedReader = new BufferedReader(inputStreamReader);\n for (String line; (line = bufferedReader.readLine()) != null; )\n queryBuffer.append(line);\n inputStreamReader.close();\n bufferedReader.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return queryBuffer.toString();\n }\n\n}\n```\n\n```text\npublic class QueryContainerBuilder {\n\n // Mask Types\n private static final byte MASK_REPLACE_QUERY_ARGUMENTS = 0b1; // Invece di inviare il json con le variabili va a inserirle nella query i valori sostituendo i tipi degli argomenti.\n private static final byte MASK_REPLACE_EXPLICIT_QUOTES = MASK_REPLACE_QUERY_ARGUMENTS << 0b1; // Alle stringhe non vengono automaticamente messe le virgolette ma devono essere aggiunte nei valori passati per le variabili.\n private static final byte MASK_REPLACE_WITH_PLACEHOLDERS = MASK_REPLACE_EXPLICIT_QUOTES << 0b1; // Va a sostituire i placeholders \"<key_var_name>\" presenti nella query con i valori delle variabili.\n\n private QueryContainer mQueryContainer;\n private byte mMask;\n\n public QueryContainerBuilder() {\n mQueryContainer = new QueryContainer();\n }\n\n /** Setter Methods **/\n public QueryContainerBuilder setQuery(String query) {\n mQueryContainer.setQuery(query);\n return this;\n }\n\n public QueryContainerBuilder setReplaceQueryArguments(){\n mMask = MASK_REPLACE_QUERY_ARGUMENTS;\n return this;\n }\n\n public QueryContainerBuilder setReplaceExplicitQuotes(){\n mMask = MASK_REPLACE_QUERY_ARGUMENTS | MASK_REPLACE_EXPLICIT_QUOTES;\n return this;\n }\n\n public QueryContainerBuilder setReplaceWithPlaceholders(){\n mMask = MASK_REPLACE_QUERY_ARGUMENTS | MASK_REPLACE_WITH_PLACEHOLDERS;\n return this;\n }\n\n /** Public Methods **/\n public QueryContainerBuilder putVariable(String key, Object value) {\n mQueryContainer.putVariable(key, value);\n return this;\n }\n\n public boolean containsVariable(String key) {\n return mQueryContainer.containsVariable(key);\n }\n\n /** Builder Methods **/\n public QueryContainer build() {\n if((mMask & MASK_REPLACE_QUERY_ARGUMENTS) != 0x0){\n if((mMask & MASK_REPLACE_WITH_PLACEHOLDERS) != 0x0){\n mQueryContainer.replaceVariablesPlaceholdersInQuery();\n } else {\n mQueryContainer.replaceVariablesInQuery(mQueryContainer.mVariables, 0x0);\n }\n mQueryContainer.mVariables = null;\n }\n return mQueryContainer;\n }\n\n /** Public Static Classes **/\n public class QueryContainer {\n\n @SerializedName(\"variables\")\n private LinkedHashMap<String, Object> mVariables;\n @SerializedName(\"query\")\n private String mQuery;\n\n QueryContainer() {\n mVariables = new LinkedHashMap<>();\n }\n\n /** Private Methods **/\n private void setQuery(String query) {\n mQuery = query;\n }\n\n private void putVariable(String key, Object value) {\n mVariables.put(key, value);\n }\n\n private boolean containsVariable(String key) {\n return mVariables != null && mVariables.containsKey(key);\n }\n\n private void replaceVariablesInQuery(LinkedHashMap<String, Object> map, int index){\n if(!TextUtils.isEmpty(mQuery) && map.size() > 0x0){\n List<String> keys = new ArrayList<>(map.keySet());\n for(String key : keys){\n Object value = map.get(key);\n if(value instanceof LinkedHashMap){\n replaceVariablesInQuery((LinkedHashMap<String, Object>) value, index);\n } else {\n int i = mQuery.indexOf(key + \":\", index) + key.length() + 0x1;\n int z;\n if(keys.indexOf(key) < keys.size() - 0x1){\n z = mQuery.indexOf(\",\", i);\n } else {\n z = mQuery.indexOf(\")\", i);\n int x = mQuery.substring(i, z).indexOf('}');\n if(x != -0x1){\n if(mQuery.substring(i, i + 0x4).contains(\"{\")){\n x++;\n }\n z -= ((z - i) - x);\n }\n }\n\n String replace;\n if((mMask & MASK_REPLACE_EXPLICIT_QUOTES) != 0x0){\n replace = String.valueOf(value);\n } else {\n replace = value instanceof String ?\n \"\\\"\" + value.toString() + \"\\\"\" : String.valueOf(value);\n }\n String sub = mQuery.substring(i, z)\n .replaceAll(\"[\\\\\\\\]?\\\\[\", \"\\\\\\\\\\\\[\").replaceAll(\"[\\\\\\\\]?\\\\]\", \"\\\\\\\\\\\\]\")\n .replaceAll(\"[\\\\\\\\]?\\\\{\", \"\\\\\\\\\\\\{\").replaceAll(\"[\\\\\\\\]?\\\\}\", \"\\\\\\\\\\\\}\");\n mQuery = mQuery.replaceFirst(sub.contains(\"{}\") ? sub.replace(\"{}\", \"\").trim() : sub.trim(), replace);\n index = z + 0x1;\n }\n }\n }\n }\n\n private void replaceVariablesPlaceholdersInQuery(){\n if(!TextUtils.isEmpty(mQuery) && mVariables.size() > 0x0){\n for(String key : mVariables.keySet()){\n mQuery = mQuery.replaceFirst(\"\\\\<\" + key + \"\\\\>\", mVariables.get(key) != null ? mVariables.get(key).toString() : \"null\");\n }\n mVariables = null;\n }\n }\n\n }\n\n}\n```\n\n```text\nquery {\n myQuery(param1: <myParam1>) {\n ....\n }\n}\n```\n\n```text\nquery ($p1: String!) {\n muQuery(p1: $id) {\n ...\n }\n}\n```\n\n```text\nnew Retrofit.Builder()\n .baseUrl(mBaseUrl)\n .addConverterFactory(GraphQLConverter.create(context))\n .addConverterFactory(GsonConverterFactory.create(gson))\n .client(getBaseHttpClient(interceptor))\n .build();\n```\n\n```text\n@POST(AppConstants.SERVICE_GQL)\n@GraphQuery(AppConstants.MY_GRAPHQL_QUERY_FILENAME)\nfun callMyGraphQlQuery(@Body query: QueryContainerBuilder): Call<MyGraphQlResponse>\n```\n\n```text\nval query = QueryContainerBuilder()\n .putVariable(\"myParam1\", myValue)\n .setReplaceWithPlaceholders()\n createService(API::class.java).callMyGraphQlQuery(query)\n\nval query = QueryContainerBuilder()\n .putVariable(\"p1\", myValue)\n .setReplaceQueryArguments()\n createService(API::class.java).callMyGraphQlQuery(query)\n\n\nval query = QueryContainerBuilder()\n .putVariable(\"p1\", myValue)\n createService(API::class.java).callMyGraphQlQuery(query)\n```\n\n```text\n<uses-permission android:name=\"android.permission.INTERNET\"/>\n```\n\n```text\n// Kotlin Coroutines\nimplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4'\n\n//OkHttp\nimplementation (\"com.squareup.okhttp3:okhttp:3.12.12\"){\n force = true //API 19 support\n}\nimplementation 'com.squareup.okhttp3:logging-interceptor:3.12.12'\n\n//retrofit\nimplementation \"com.squareup.retrofit2:retrofit:2.7.1\"\nimplementation \"com.squareup.retrofit2:converter-scalars:$2.7.1\"\n```\n\n```text\nandroid {\n\n ...\n compileOptions {\n sourceCompatibility JavaVersion.VERSION_1_8\n targetCompatibility JavaVersion.VERSION_1_8\n }\n\n kotlinOptions {\n jvmTarget = \"1.8\"\n }\n}\n```\n\n```text\nimport retrofit2.Response\nimport retrofit2.http.Body\nimport retrofit2.http.Headers\nimport retrofit2.http.POST\n\ninterface GraphQLService {\n\n @Headers(\"Content-Type: application/json\")\n @POST(\"/\")\n suspend fun postDynamicQuery(@Body body: String): Response<String>\n}\n```\n\n```text\nimport retrofit2.Retrofit\nimport retrofit2.converter.scalars.ScalarsConverterFactory\n\nobject GraphQLInstance {\n\n private const val BASE_URL: String = \"http://192.155.1.55:2000/\"\n\n val graphQLService: GraphQLService by lazy {\n Retrofit\n .Builder()\n .baseUrl(BASE_URL)\n .addConverterFactory(ScalarsConverterFactory.create())\n .build().create(GraphQLService::class.java)\n }\n}\n```\n\n```text\nprivate fun post(userId: String){\n val retrofit = GraphQLInstance.graphQLService\n val paramObject = JSONObject()\n paramObject.put(\"query\", \"query {users(userid:$userId){username}}\")\n GlobalScope.launch {\n try {\n val response = retrofit.postDynamicQuery(paramObject.toString())\n Log.e(\"response\", response.body().toString())\n }catch (e: java.lang.Exception){\n e.printStackTrace()\n }\n }\n}\n```\n\n```text\nparamObject.put(\"query\", \"query {users(userid:$userId){username}}\")\n```\n\n```text\nparamObject.put(\"query\", \"mutation {users(userid:$userId){username}}\")\n```\n\n========================================\n\nComments:\n- @ nburk ,Thanks a lot .\n- Here's a simple instagram example (see the data model for `graphql-up` in the GitHub readme): github.com/graphcool-examples/android-http-instagram-example\n- A sample app using graphql in Android: github.com/graphcool-examples/android-graphql","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":605,"estimatedTokens":4786}}1103{"id":"stack-57490569","source":"stackoverflow","questionId":57490569,"title":"Import graphql query .gql file into plain Javascript and run an axios call","tags":["javascript","graphql","axios","graphql-tag"],"text":"Title: Import graphql query .gql file into plain Javascript and run an axios call\nTags: javascript, graphql, axios, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nI have a simple axios call that I want to make to fetch some graphql data.\nI also have a `.gql` file that I want to import to use as a query:\n\n**pages.gql**\n\n```\n{\n entries(section: [pages]) {\n uri\n slug\n }\n}\n```\n\nNow in my other file I want to import that:\n\n`import query from './queries/pages.gql'`\n\nTo later make that axios call:\n\n```\nconst routes = await axios.post(\n endpoint,\n { query },\n { headers: { Authorization: `Bearer ${token}` } }\n )\n .then(result => {\n console.log('result: ', result)\n })\n .catch(error => {\n console.log('error: ', error)\n })\n```\n\nBut whenever I do that I will get this error:\n\n missing ) after argument list 09:55:25\n\n \n entries(section: [pages]) {\n\n \n ^^^^^^^\n\n \n SyntaxError: missing ) after argument list\n\nSo I can't just import the gql file.\nI have `graphql-tag` imported\n(`import gql from 'graphql-tag'`), so I could do something like this:\n\n```\nconst QUERY = gql`\n ${query}\n`\n```\n\nbut first I have to import the gql file, right?\n\nAny help would be much appreciated...\ncheers\n\n---- Edit 2019-08-28: ----\n\nOK, another case:\n\nI have an axios call that works like a charm:\n\n```\nawait axios\n .post(\n endpoint,\n { query: `query Page($slug: String!) {\n entries(section: [pages], slug: $slug) {\n slug\n title\n }\n }`,\n variables: { slug: params.slug }\n },\n { headers: { Authorization: `Bearer ${env.GRAPHQL_TOKEN}` } }\n ).then(result => {\n console.log('result: ', result)\n })\n .catch(error => {\n console.log('error: ', error)\n })\n```\n\nI also have a page.gql file with the exact same content:\n\n```\nquery Page($slug: String!) {\n entries(section: [pages], slug: $slug) {\n slug\n title\n }\n}\n```\n\nI found out that importing the page.gql file like this\n`import page from '~/apollo/queries/page'`\nWould import something of this structure:\n\n```\npage: { 15:16:40\n kind: 'Document',\n definitions: [...],\n loc: {\n start: 0,\n end: 181,\n source: {\n body: 'query Page($slug: String!) {\\n ' +\n 'entries(section: [pages], slug: $slug) {\\n ' +\n 'slug\\n title\\n }\\n }\\n}\\n',\n name: 'GraphQL request',\n locationOffset: [Object]\n }\n },\n Page: {...}\n }\n```\n\nSo to use the page.gql in my query I have to use this `page.loc.source.body`:\n\n```\nawait axios\n .post(\n endpoint,\n { query: page.loc.source.body,\n variables: { slug: params.slug }\n },\n { headers: { Authorization: `Bearer ${env.GRAPHQL_TOKEN}` } }\n ).then(result => {\n console.log('result: ', result)\n })\n .catch(error => {\n console.log('error: ', error)\n })\n```\n\nIs there a better way than this?\n\n========================================\n\nCode:\n```text\n{\n entries(section: [pages]) {\n uri\n slug\n }\n}\n```\n\n```text\nconst routes = await axios.post(\n endpoint,\n { query },\n { headers: { Authorization: `Bearer ${token}` } }\n )\n .then(result => {\n console.log('result: ', result)\n })\n .catch(error => {\n console.log('error: ', error)\n })\n```\n\n```text\nconst QUERY = gql`\n ${query}\n`\n```\n\n```text\nawait axios\n .post(\n endpoint,\n { query: `query Page($slug: String!) {\n entries(section: [pages], slug: $slug) {\n slug\n title\n }\n }`,\n variables: { slug: params.slug }\n },\n { headers: { Authorization: `Bearer ${env.GRAPHQL_TOKEN}` } }\n ).then(result => {\n console.log('result: ', result)\n })\n .catch(error => {\n console.log('error: ', error)\n })\n```\n\n```text\nquery Page($slug: String!) {\n entries(section: [pages], slug: $slug) {\n slug\n title\n }\n}\n```\n\n```text\npage: { 15:16:40\n kind: 'Document',\n definitions: [...],\n loc: {\n start: 0,\n end: 181,\n source: {\n body: 'query Page($slug: String!) {\\n ' +\n 'entries(section: [pages], slug: $slug) {\\n ' +\n 'slug\\n title\\n }\\n }\\n}\\n',\n name: 'GraphQL request',\n locationOffset: [Object]\n }\n },\n Page: {...}\n }\n```\n\n```text\nawait axios\n .post(\n endpoint,\n { query: page.loc.source.body,\n variables: { slug: params.slug }\n },\n { headers: { Authorization: `Bearer ${env.GRAPHQL_TOKEN}` } }\n ).then(result => {\n console.log('result: ', result)\n })\n .catch(error => {\n console.log('error: ', error)\n })\n```\n\n```text\n.gql\n```\n\n```text\nimport query from './queries/pages.gql'\n```\n\n```text\ngraphql-tag\n```\n\n```text\nimport gql from 'graphql-tag'\n```\n\n```text\nimport page from '~/apollo/queries/page'\n```\n\n```text\npage.loc.source.body\n```\n\n```text\nimport gql from 'graphql-tag';\nimport { print } from 'graphql/language/printer';\n\nconst AST = gql`\n {\n user(id: 5) {\n firstName\n lastName\n }\n }\n`\nconst query = print(AST);\n```\n\n```text\ngql`..`\n```\n\n========================================\n\nComments:\n- Thanks. This will be the first thing, I try tomorrow!\n- It was of course not the first thing, because other fires have to been put out first. Anyway: This was absolutely correct and worked. Thank you very much! I would never have found out by myself.","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":293,"estimatedTokens":1326}}1104{"id":"stack-44246290","source":"stackoverflow","questionId":44246290,"title":"How to use unions with GraphQL buildSchema","tags":["graphql","graphql-js"],"text":"Title: How to use unions with GraphQL buildSchema\nTags: graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nHere is how I am using a GraphQL schema string to create a schema and attach it to my Express server:\n\n```\nvar graphql = require('graphql');\nvar graphqlHTTP = require('express-graphql');\n[...]\n return graphqlHTTP({\n schema: graphql.buildSchema(schemaText),\n rootValue: resolvers,\n graphiql: true,\n });\n```\n\nThis is all very basic use of the modules. It works well and is quite convenient until I want to define a union:\n\n```\nunion MediaContents = Photo|Youtube\n\ntype Media {\n Id: String\n Type: String\n Contents: MediaContents\n}\n```\n\nI have found no way to make this work, querying Contents does what it has to do, returns the correct object but fails with the message `Generated Schema cannot use Interface or Union types for execution`. \n\nIs it at all possible to use unions when using buildSchema ?\n\n========================================\n\nTop Answer:\nIn case you are returning an object with all the information, you can add a __typename field in your object. Like this:\n\n```\nreturn {\n token: res.token,\n user: {\n __typename: 'YOUR_TYPE_HERE',\n ...res.user\n }\n};\n```\n\n========================================\n\nCode:\n```text\nvar graphql = require('graphql');\nvar graphqlHTTP = require('express-graphql');\n[...]\n return graphqlHTTP({\n schema: graphql.buildSchema(schemaText),\n rootValue: resolvers,\n graphiql: true,\n });\n```\n\n```text\nunion MediaContents = Photo|Youtube\n\ntype Media {\n Id: String\n Type: String\n Contents: MediaContents\n}\n```\n\n```text\nGenerated Schema cannot use Interface or Union types for execution\n```\n\n```text\n# Schema\nunion Vehicle = Airplane | Car\n\ntype Airplane {\n wingspan: Int\n}\n\ntype Car {\n licensePlate: String\n}\n\n// Resolvers\nconst resolverMap = {\n Vehicle: {\n __resolveType(obj, context, info){\n if(obj.wingspan){\n return 'Airplane';\n }\n if(obj.licensePlate){\n return 'Car';\n }\n return null;\n },\n },\n};\n```\n\n```text\nconst graphqlTools = require('graphql-tools');\nreturn graphqlHTTP({\n schema: graphqlTools.makeExecutableSchema({\n typeDefs: schemaText,\n resolvers: resolvers\n }),\n graphiql: true,\n});\n```\n\n```text\ngraphql-tools\n```\n\n```text\nbuildSchema\n```\n\n```text\n__resolveType\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\n(root, args, context)\n```\n\n```text\n(args, context)\n```\n\n```text\nrootValue\n```\n\n```text\nreturn {\n token: res.token,\n user: {\n __typename: 'YOUR_TYPE_HERE',\n ...res.user\n }\n};\n```\n\n========================================\n\nComments:\n- ok, that's what I thought, there is no way to do it with buildSchema. I wanted to make sure before adding one more dependency to the project :) one more question: I don't quite understand the syntax of resolverMap, is Vehicle a class defined inline here (I've never seen that before, I'm more of a C++ person, and get confused all the time in JS :D )\n- This is a great answer. Just what I was looking for.\n- Thank you so much. Easy fix!","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":160,"estimatedTokens":757}}1105{"id":"stack-49143973","source":"stackoverflow","questionId":49143973,"title":"GraphQL field of type graphql object within an array","tags":["node.js","graphql","graphql-js"],"text":"Title: GraphQL field of type graphql object within an array\nTags: node.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI have a graphQL object defined here: \n\n```\nconst graphql = require('graphql');\nconst { GraphQLObjectType } = require('graphql');\n\nconst ProductType = new GraphQLObjectType({\n name: 'Product',\n description: 'Product GraphQL Object Schemal Model',\n fields: {\n productId: { type: graphql.GraphQLString },\n SKU: { type: graphql.GraphQLString },\n quantity: { type: graphql.GraphQLFloat },\n unitaryPrice: { type: graphql.GraphQLFloat },\n subTotal: { type: graphql.GraphQLFloat },\n discount: { type: graphql.GraphQLFloat },\n totalBeforeTax: { type: graphql.GraphQLFloat },\n isTaxAplicable: { type: graphql.GraphQLBoolean },\n unitaryTax: { type: graphql.GraphQLFloat },\n totalTax: { type: graphql.GraphQLFloat }\n }\n});\n\nmodule.exports.ProductType = { ProductType };\n```\n\nAnd then, I want to use this ProductType inside another GraphQL object, but I need that object to be an array structure, something like this:\n\n```\nconst graphql = require('graphql');\nconst { GraphQLObjectType } = require('graphql');\n\nconst { ProductType } = require('./product');\n\nconst ShoppingCartType = new GraphQLObjectType({\n name: 'ShoppingCart',\n description: 'Shopping Cart GraphQL Object Schema Model',\n fields: {\n cartId: { type: graphql.GraphQLString },\n userId: { type: graphql.GraphQLString },\n products: [{ type: ProductType }]\n }\n});\n\nmodule.exports.ShoppingCartType = { ShoppingCartType };\n```\n\nIs this possible?\n\n========================================\n\nCode:\n```text\nconst graphql = require('graphql');\nconst { GraphQLObjectType } = require('graphql');\n\nconst ProductType = new GraphQLObjectType({\n name: 'Product',\n description: 'Product GraphQL Object Schemal Model',\n fields: {\n productId: { type: graphql.GraphQLString },\n SKU: { type: graphql.GraphQLString },\n quantity: { type: graphql.GraphQLFloat },\n unitaryPrice: { type: graphql.GraphQLFloat },\n subTotal: { type: graphql.GraphQLFloat },\n discount: { type: graphql.GraphQLFloat },\n totalBeforeTax: { type: graphql.GraphQLFloat },\n isTaxAplicable: { type: graphql.GraphQLBoolean },\n unitaryTax: { type: graphql.GraphQLFloat },\n totalTax: { type: graphql.GraphQLFloat }\n }\n});\n\nmodule.exports.ProductType = { ProductType };\n```\n\n```text\nconst graphql = require('graphql');\nconst { GraphQLObjectType } = require('graphql');\n\nconst { ProductType } = require('./product');\n\nconst ShoppingCartType = new GraphQLObjectType({\n name: 'ShoppingCart',\n description: 'Shopping Cart GraphQL Object Schema Model',\n fields: {\n cartId: { type: graphql.GraphQLString },\n userId: { type: graphql.GraphQLString },\n products: [{ type: ProductType }]\n }\n});\n\nmodule.exports.ShoppingCartType = { ShoppingCartType };\n```\n\n```text\nproducts: { type: new GraphQLList(ProductType) }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":103,"estimatedTokens":737}}1106{"id":"stack-52141588","source":"stackoverflow","questionId":52141588,"title":"AWS Appsync + DynamoDB with business logic","tags":["amazon-web-services","graphql","aws-appsync"],"text":"Title: AWS Appsync + DynamoDB with business logic\nTags: amazon-web-services, graphql, aws-appsync\nSource: Stack Overflow\n\nQuestion:\nIs it possible to have business logic on my AppSync's mutation when the datasource is dynamoDB? \n\nI'm fairly new to GraphQL and Appsync. My understanding is when you're using plain GraphQL you can have business logic inside your resolver to validate before updating. How would you achieve the same thing with AWS AppSync when you pass it the GraphQL schema with DynamoDB as the datasource?\n\n========================================\n\nTop Answer:\nAccording to AWS AppSync's Website: **With AppSync, your app can access data in Amazon DynamoDB, trigger AWS Lambda functions, or run Amazon Elasticsearch queries**.\n\nYou can think of it as a gateway for clients to access different backends (data sources), defined by mapping templates attached to GraphQL fields (resolvers). \n\nAppSync supports DynamoDB and ElasitcSearch queries natively, but if you want to perform business logic you will have to add a AWS Lambda data source and then use AWS SDKs to R/W DynamoDB or anything else such as another API or maybe even an excel file!\n\nAdditionally, you can use Apache VTL along with AppSync's available helpers such as $context to help you perform authorization or field data access based on permissions. Keep in mind that your DynamoDB or ES resolver can only perform 1 operation at the end, Apache VTL only helps you build the resolver that will be run by AppSync.\n\nHere are two diagrams that compare a traditional approach vs appsync\n\nhttps://i.sstatic.net/OM9cY.jpg\n\nhttps://i.sstatic.net/ApYMu.jpg\n\n========================================\n\nComments:\n- Thanks. I saw VTLs but was secretly hoping this wasn't the way to do it. I can see why people seem to prefer having their own GraphQL inside a Lambda over using AppSync.\n- We realize that working with VTLs is the most painful part with using AWS AppSync today, and we are working on multiple things to make this process as simple as possible, so that there is very little to none VTL code written for most scenarios. For instance, check out GraphQL Transformer in amplify-cli: github.com/aws-amplify/amplify-cli/blob/master/….","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":31,"estimatedTokens":554}}1107{"id":"stack-56743804","source":"stackoverflow","questionId":56743804,"title":"Gatsby graphql with regex as variable","tags":["graphql","gatsby"],"text":"Title: Gatsby graphql with regex as variable\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI would like to use regex with graphql query variable. \n\nThis does't return results:\n\n```\nexport const query = graphql`\n query(\n $episodes: String!\n ) {\n episodes: allMarkdownRemark(\n filter: { fields: { slug: { regex: $episodes } } }\n ) {\n edges {\n node {\n id\n }\n }\n }\n }\n`;\n```\n\nHowever, this would work:\n\n```\nexport const query = graphql`\n query() {\n episodes: allMarkdownRemark(\n filter: { fields: { slug: { regex: \"/episodes/travel/\" } } }\n ) {\n edges {\n node {\n id\n }\n }\n }\n }\n`;\n```\n\nwhat's wrong?\n\n========================================\n\nCode:\n```text\nexport const query = graphql`\n query(\n $episodes: String!\n ) {\n episodes: allMarkdownRemark(\n filter: { fields: { slug: { regex: $episodes } } }\n ) {\n edges {\n node {\n id\n }\n }\n }\n }\n`;\n```\n\n```text\nexport const query = graphql`\n query() {\n episodes: allMarkdownRemark(\n filter: { fields: { slug: { regex: \"/episodes/travel/\" } } }\n ) {\n edges {\n node {\n id\n }\n }\n }\n }\n`;\n```\n\n```text\ncontext: {\n- episodes: /episodes\\/traveller/ <-- doesn't work\n+ episodes: /episodes\\/traveller/.toString() <-- works\nor episodes: \"/episodes\\\\/traveller/\" <-- also works\n }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":91,"estimatedTokens":342}}1108{"id":"stack-41121532","source":"stackoverflow","questionId":41121532,"title":"How bad would it be to have nested mutations?","tags":["graphql"],"text":"Title: How bad would it be to have nested mutations?\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI am aware that it would be considered as an anti-pattern, but why exactly?\n\n```\nmutation {\n createUser(name: \"john doe\") {\n addToTeam(teamID: \"123\") {\n name,\n id\n },\n\n id\n }\n}\n```\n\nWouldn't it be more convenient than two HTTP calls?\n\n```\nmutation {\n createUser(name: \"john doe\") {\n id, # we store the ID\n }\n}\n\nmutation {\n addToTeam(userID: id, teamID: \"123\") {\n name,\n id,\n }\n}\n```\n\n========================================\n\nTop Answer:\nThere are two reasons why this is an anti-pattern:\n\n**First**, there are two atomic operations here, each may involve some extra logic related to authentication, validation, and yield different errors. So mixing them together could lead to some extra complexity.\n\nFor example, say a team can only have 10 people, and it has reached its max. Should the compose operation fail altogether? Shall we just add the user but not add it to the team? What the response will look like?\n\n**Second**, lumping two operations in such way may potentially expose application logic. One can be tempted to use such mutations to perform 'When X happens Y should also happen as well'. For instance, when adding a new line to an invoice, the total should update. This should really happen with one mutation, *addLineToInvoice*, and have the logic reside on the server.\n\nIn a way, the command part of APIs is better being process (or action) centric, rather than data centric. If your API calls are focused on data manipulation, you are risking loading the client with business logic that should live in the server. You may also be losing on quite a few goodies like middleware (which is great for cross-cutting concerns, like permissions and logging).\n\n========================================\n\nCode:\n```text\nmutation {\n createUser(name: \"john doe\") {\n addToTeam(teamID: \"123\") {\n name,\n id\n },\n\n id\n }\n}\n```\n\n```text\nmutation {\n createUser(name: \"john doe\") {\n id, # we store the ID\n }\n}\n\nmutation {\n addToTeam(userID: id, teamID: \"123\") {\n name,\n id,\n }\n}\n```\n\n```text\nmutation {\n createUser(name: \"john doe\", teamId: \"team-id\") {\n id\n team {\n id\n }\n }\n}\n```\n\n```text\nmutation {\n createUser(name: \"john doe\", team: {name: \"New team\"}) { \n id\n team {\n id\n }\n }\n}\n```\n\n```text\nTeam\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- Why not add an optional `teamID` to `createUser()`, to do it all in one HTTP request with a more traditional mutation?\n- Yes it would actually work if you wanted to add the user to the team every time, but if that's not the case, would you necesserally create an extra mutation on the server: `createUserAndAddToTeam` ?\n- \"it would actually work if you wanted to add the user to the team every time\" -- no. An optional `teamID` is optional. Using `String!` for the type means that you can pass in `null` to indicate that you do not want to add the user to a team.\n- Oh yeah true, I havnt considered that option.\n- How does a parameter from this mutation get passed to the nested type? How is the return field `team { id }` resolved? I'm trying to do a similar mutation, but GraphQL says it expected a root argument: stackoverflow.com/questions/50211978/…","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":119,"estimatedTokens":827}}1109{"id":"stack-53983896","source":"stackoverflow","questionId":53983896,"title":"Missing allposts attribute on result","tags":["vue.js","vuejs2","graphql","apollo"],"text":"Title: Missing allposts attribute on result\nTags: vue.js, vuejs2, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI am Django developer so for the first time I got my hands on vue and graphql, I don't know how exactly to deal with this error.\n\nhttps://i.sstatic.net/TXfMJ.png\n\nHere is my code, probably something is wrong in my query,\n\n```\n\n \n \n \n\n### hiii\n\n \n \n \n \n\n### hey\n\n **{{id}}**:\n {{title}}\n \n \n \n \n \n \n\n \n import gql from \"graphql-tag\";\n\n const PostQuery = gql`\n query allposts {\n allPosts {\n id\n title\n }\n }\n `;\n\n export default {\n props: [],\n data() {\n return {\n allposts: []\n };\n },\n\n apollo: {\n allposts: PostQuery\n }\n };\n \n```\n\nI can see the data is fetched successfully\n\nhttps://i.sstatic.net/8sKRj.png\n\nCan anyone please guide me what I am doing wrong here?\n\nThanks in advance.\n\n========================================\n\nTop Answer:\nCame here via Google. Checked out the docs, which explain the problem, and how to solve it:\nhttps://apollo.vuejs.org/guide/apollo/queries.html#name-matching\n\n Please note that a common beginner's mistake is to use a data name different from the field name in the query.\n\nThe example they give:\n\n```\napollo: {\n world: gql`query {\n hello\n }`\n}\n```\n\n`world` and `hello` don't match, so you'd get an error.\n\nThe name has to either match, or as the docs suggest, you can provide an `update` function:\n\n```\napollo: {\n world: {\n query: gql`query {\n hello\n }`,\n update: data => data.hello\n }\n}\n```\n\nOr, rename the field in the GraphQL document:\n\n```\napollo: {\n world: gql`query {\n world: hello\n }`\n}\n```\n\n========================================\n\nCode:\n```html\n<template>\n <section>\n <div class=\"home\">\n <h2>hiii</h2>\n <div v-for=\"i in allposts\" :key=\"i.id\">\n <ul>\n <li>\n <h3>hey</h3>\n <strong>{{id}}</strong>:\n <span>{{title}}</span>\n </li>\n </ul>\n </div>\n </div>\n </section>\n </template>\n\n <script>\n import gql from \"graphql-tag\";\n\n const PostQuery = gql`\n query allposts {\n allPosts {\n id\n title\n }\n }\n `;\n\n export default {\n props: [],\n data() {\n return {\n allposts: []\n };\n },\n\n apollo: {\n allposts: PostQuery\n }\n };\n </script>\n```\n\n```text\napollo: {\n world: gql`query {\n hello\n }`\n}\n```\n\n```text\napollo: {\n world: {\n query: gql`query {\n hello\n }`,\n update: data => data.hello\n }\n}\n```\n\n```text\napollo: {\n world: gql`query {\n world: hello\n }`\n}\n```\n\n```text\nworld\n```\n\n```text\nhello\n```\n\n```text\nupdate\n```\n\n========================================\n\nComments:\n- Thanks! Strange that the naming has to match the query name.","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":204,"estimatedTokens":691}}1110{"id":"stack-67298396","source":"stackoverflow","questionId":67298396,"title":"Nest.js GraphQL Schema generation during build","tags":["graphql","nestjs"],"text":"Title: Nest.js GraphQL Schema generation during build\nTags: graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using the code-first approach to GraphQL with NestJS and have a monorepo setup using Nx.\n\nThe `schema.gql` is only produced when I run the server, which I can't do during CI. It's impractical for me to copy the whole repository into the docker image and start the server. The `schema.gql` isn't generated when you build the nest application.\n\nI've also looked at Generating the SDL manually doc on the NestJS website, but not really sure how to integrate that script.\n\nJust wondering if someone has managed to generate the schema without starting the server?\n\n========================================\n\nTop Answer:\nThe following worked out well for me. I spotted this in the docs here:\n\nhttps://docs.nestjs.com/graphql/quick-start#accessing-generated-schema\n\nI added a check to see if the ENV was production, as the location I wanted the file generating does already exist when in development mode.\n\n```\nimport { NestFactory } from '@nestjs/core';\nimport { GraphQLSchemaHost } from '@nestjs/graphql';\nimport { writeFileSync } from 'fs';\nimport { printSchema } from 'graphql';\nimport { join } from 'path';\nimport { ServerModule } from './server.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(ServerModule);\n await app.listen(process.env.PORT || 3001);\n\n if (process.env.NODE_ENV === 'production') {\n const { schema } = app.get(GraphQLSchemaHost);\n writeFileSync(join(process.cwd(), `/src/schema.gql`), printSchema(schema));\n }\n}\nbootstrap();\n```\n\n========================================\n\nCode:\n```text\nschema.gql\n```\n\n```text\nschema.gql\n```\n\n```js\nconst resolvers = [MyResolver]\n\n/**\n * Generate GraphQL schema manually. NestJS does not generate the GraphQL schema\n * automatically during the build process and it doesn't generate the GraphQL\n * schema when starting the built app. This schema needs to be generated or\n * the GraphQL api would have nothing to use.\n *\n * @param {MyServices} serviceName - Name of the gavel service to generate a unique\n * schema.\n * @param {Function[]} resolvers - List of GraphQL resolvers being used in that app.\n * @returns {Promise<void>} Nothing gets returned. It will just write the schema and\n * throw an error if it fails.\n */\nexport async function generateGraphQLSchema(\n serviceName: MyServices,\n resolvers: Function[],\n): Promise<void> {\n const app = await NestFactory.create(GraphQLSchemaBuilderModule)\n await app.init()\n\n const gqlSchemaFactory = app.get(GraphQLSchemaFactory)\n const schema = await gqlSchemaFactory.create(resolvers)\n\n writeFileSync(join(process.cwd(), `/${serviceName}-schema.gql`), printSchema(schema))\n}\n\n/**\n * Setup nest application.\n *\n * @param {string} port - Port the application should listen to.\n * @param {unknown} appModule - Main app module from a nest application.\n * @param {MyServices} serviceName - Name of the gavel service to generate a unique\n * schema.\n * @returns {Promise<void>}\n */\nasync function bootstrap(port: string, appModule: any, serviceName: MyServices): Promise<void> {\n const app = await NestFactory.create(appModule)\n\n // Endpoint prefix\n const globalPrefix = `${config.get(`env`)}/v1/${serviceName}`\n app.setGlobalPrefix(globalPrefix)\n\n // Start Server\n await app.listen(port, () => {\n Logger.log(`Listening at http://localhost:${port}/${globalPrefix}/graphql`)\n })\n}\n\n/**\n * Helper to crate standard Nest JS Server.\n *\n * @param {MyServices} serviceName - Name of service.\n * @param {unknown} appModule - Main app module from a nest application.\n */\nexport function initializeServer(serviceName: GavelService, appModule: any): void {\n const environment = config.get(`env`)\n const port = config.get(`port`)\n initializeElasticApm(`service-${serviceName}`, {\n framework: `nest`,\n environment,\n version: `${packageJson.version}`,\n })\n bootstrap(port, appModule, serviceName).catch((error) => {\n const logger = getElasticSearchLogger(serviceName)\n logger.error(\n { error, environment: config.get(`env`), applicationName: serviceName },\n error.message,\n )\n })\n}\n\ngenerateGraphQLSchema(MyServices.SERVICE_A, resolvers)\n .then(() => initializeServer(MyServices.SERVICE_A, AppModule))\n .catch((e) => console.error(e))\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { GraphQLSchemaHost } from '@nestjs/graphql';\nimport { writeFileSync } from 'fs';\nimport { printSchema } from 'graphql';\nimport { join } from 'path';\nimport { ServerModule } from './server.module';\n\nasync function bootstrap() {\n const app = await NestFactory.create(ServerModule);\n await app.listen(process.env.PORT || 3001);\n\n if (process.env.NODE_ENV === 'production') {\n const { schema } = app.get(GraphQLSchemaHost);\n writeFileSync(join(process.cwd(), `/src/schema.gql`), printSchema(schema));\n }\n}\nbootstrap();\n```\n\n```js\nimport { NestFactory } from '@nestjs/core';\nimport { GraphQLSchemaBuilderModule, GraphQLSchemaFactory } from '@nestjs/graphql';\nimport { writeFileSync } from 'fs';\nimport { printSchema } from 'graphql';\nimport { join } from 'path';\n\nconst resolvers = [\n // Your resolvers here\n];\n\nconst scalars = [\n // Your scalars here\n];\n\nconst main = async () => {\n const app = await NestFactory.create(GraphQLSchemaBuilderModule);\n await app.init();\n\n const gqlSchemaFactory = app.get(GraphQLSchemaFactory);\n const schema = await gqlSchemaFactory.create(resolvers, scalars);\n\n writeFileSync(join(process.cwd(), '/schema.graphql'), printSchema(schema));\n};\nmain();\n```\n\n```text\nnest start --entryFile generate-schema\n```\n\n```text\nsrc/generate-schema.ts\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":185,"estimatedTokens":1414}}1111{"id":"stack-47773538","source":"stackoverflow","questionId":47773538,"title":"TypeError: obj.hasOwnProperty is not a function when calling Graphql mutation","tags":["node.js","graphql","graphql-js","node-soap"],"text":"Title: TypeError: obj.hasOwnProperty is not a function when calling Graphql mutation\nTags: node.js, graphql, graphql-js, node-soap\nSource: Stack Overflow\n\nQuestion:\nI get a strange error and can't figure out what I am doing wrong. I wrote a graphql mutation to call an api:\n\n```\ndomainStuff: async (parent, { command, params }, { models }) => {\n console.log(\"Params:\", params);\n const result = await dd24Api(command, params);\n return result;\n}\n```\n\nThis it the function I call:\n\n```\nexport default async (command, parameter) => {\n const args = _.merge({ params: parameter }, auth);\n // Eleminate copying mistakes\n console.log(typeof args);\n const properCommand = command + \"Async\";\n const result = await soap\n .createClientAsync(apiWSDL)\n .then(client => {\n return client[properCommand](args)\n .then(res => {\n console.log(res[command + \"Result\"]);\n return res[command + \"Result\"];\n })\n .catch(err => {\n console.log(err);\n return err;\n });\n })\n .catch(err => console.log(err));\n\nreturn result;\n```\n\nwith this query variables:\n\n```\n{\n\"command\": \"CheckDomain\",\n\"params\": {\"domain\": \"test.it\"}\n}\n```\n\nThe console.log shows me that args is an object, but I get this error (from the first catch block):\n\n```\nTypeError: obj.hasOwnProperty is not a function\n```\n\nHow can that be? After all I checked whether it is an object and it is. More strange, if I give a hardcoded object into the query, this for example:\n\n```\ndomainStuff: async (parent, { command, params }, { models }) => {\n console.log(\"Params:\", params);\n const result = await dd24Api(command, {domain: \"test.com\"});\n return result;\n}\n```\n\nthen it works perfectly fine. What am I doing wrong? Thx for any help in advance.\n\nEDIT: I am using \"graphql-server-express\": \"^0.8.0\" and \"graphql-tools\": \"^1.0.0\"\n\n========================================\n\nTop Answer:\nIf you are using `graphql-js` there are a lot of places where new objects are created using `Object.create(null)` which is different from `{}` you can read an explanation about that here Creating Js object with Object.create(null)?\n\nBut essentially an object created with `Object.create(null)` has no `hasOwnProperty` method\n\nYou can try it in node with\n\n```\nconst obj1 = Object.create(null)\nconsole.log(typeof obj1.hasOwnProperty)\n// 'undefined'\nconst obj2 = {}\nconsole.log(typeof obj2.hasOwnProperty)\n// 'function'\n```\n\nAnother method you can use for determining if an object has a key that will work on an object created with `Object.create(null)` is\n\n```\nfunction hasKey(obj, key) {\n return Object.keys(obj).indexOf(key) !== -1\n}\n```\n\n========================================\n\nCode:\n```text\ndomainStuff: async (parent, { command, params }, { models }) => {\n console.log(\"Params:\", params);\n const result = await dd24Api(command, params);\n return result;\n}\n```\n\n```text\nexport default async (command, parameter) => {\n const args = _.merge({ params: parameter }, auth);\n // Eleminate copying mistakes\n console.log(typeof args);\n const properCommand = command + \"Async\";\n const result = await soap\n .createClientAsync(apiWSDL)\n .then(client => {\n return client[properCommand](args)\n .then(res => {\n console.log(res[command + \"Result\"]);\n return res[command + \"Result\"];\n })\n .catch(err => {\n console.log(err);\n return err;\n });\n })\n .catch(err => console.log(err));\n\nreturn result;\n```\n\n```text\n{\n\"command\": \"CheckDomain\",\n\"params\": {\"domain\": \"test.it\"}\n}\n```\n\n```text\nTypeError: obj.hasOwnProperty is not a function\n```\n\n```text\ndomainStuff: async (parent, { command, params }, { models }) => {\n console.log(\"Params:\", params);\n const result = await dd24Api(command, {domain: \"test.com\"});\n return result;\n}\n```\n\n```text\nconst args = _.merge(auth, { params: parameter });\n```\n\n```text\nconst obj1 = Object.create(null)\nconsole.log(typeof obj1.hasOwnProperty)\n// 'undefined'\nconst obj2 = {}\nconsole.log(typeof obj2.hasOwnProperty)\n// 'function'\n```\n\n```text\nfunction hasKey(obj, key) {\n return Object.keys(obj).indexOf(key) !== -1\n}\n```\n\n```text\ngraphql-js\n```\n\n```text\nObject.create(null)\n```\n\n```text\n{}\n```\n\n```text\nObject.create(null)\n```\n\n```text\nhasOwnProperty\n```\n\n```text\nObject.create(null)\n```\n\n```text\ndata = JSON.parse(JSON.stringify(data));\n```\n\n========================================\n\nComments:\n- I am using \"graphql-server-express\": \"^0.8.0\" and \"graphql-tools\": \"^1.0.0\". I just did a console.log with args.hasOwnProperty and I got back function. So it has this function. Nonetheless, thx for the explanation, definitively learned something here.\n- your error output says `obj.hasOwnProperty is not a function` not `args.hasOwnProperty` so i would look for a variable named `obj` and try the console.log on that\n- Fixed the error. Both were objects, but only one of them had the needed hasOwnProperty function. Seems like the data from the graphql variable overwrote the prototype. Had only to switch the sequence of the variables in the merge function. Thx for your input.\n- Thanks. Writing to firestore from a graphql server and this was driving me crazy. A shorter alternative that seems to work is `const newData = {...incomingData}`\n- @tehfailsafe does not work for nested objects (creates shallow copy)","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":205,"estimatedTokens":1305}}1112{"id":"stack-58126454","source":"stackoverflow","questionId":58126454,"title":"using spread syntax with Mongoose Document after calling the .save method results in undefined keys","tags":["node.js","mongodb","express","mongoose","graphql"],"text":"Title: using spread syntax with Mongoose Document after calling the .save method results in undefined keys\nTags: node.js, mongodb, express, mongoose, graphql\nSource: Stack Overflow\n\nQuestion:\nI'm using a Mongoose/MongoDB and I'm getting some odd behaviour when I try to use the spread syntax to return values from a document after I call .save() on it.\n\n```\n// Npc is a Mongoose schema\nconst npc = new Npc({\n ...input,\n creator: userId\n });\n\nconst createdNpc = await npc.save();\n```\n\nI have tried using the spead operator, but the name and description keys do not exist.\n\n```\nreturn {\n ...createdNpc\n creator: userFromId(npc.creator)\n}\n```\n\nhowever when I access those values directly they ARE defined\n\n```\nreturn {\n description: createdNpc.description,\n name: createdNpc.name,\n creator: userFromId(npc.creator)\n };\n```\n\nI've made sure that the spelling of description and name are correct. I've tried logging both `{...createdNpc}` and `{...createdNpc, description: createdNpc.description, name: createdNpc.name}`. In the logs I've confirmed that name and description are both not defined (the keys don't exist) inside of {...createdNpc}\n\nI have also tried logging `createdNpc` and `{...createdNpc}` and have confirmed that they return different values.\n\nhere's createdNpc:\n\n```\n{\n _id: 5d8d5c7a04fc40483be74b3b,\n name: 'NPC Name',\n description: 'My Postman NPC',\n creator: 5d8d50e0b5c8a6317541d067,\n __v: 0\n}\n```\n\nit doesn't actually look like a Mongoose Document at all. I would post the result of `{...createdNPC}` to show the difference but it's a huge code snippet and I don't want to clutter the question. I'm happy to provide it if it will help!\n\nI'm still very new to MongoDB & Mongoose. Why would using the spread syntax on a Mongoose Document change its value?\n\nI don't think this should be relevant to the question but just in case I'll also mention this is for a graphql resolver.\n\n========================================\n\nCode:\n```text\n// Npc is a Mongoose schema\nconst npc = new Npc({\n ...input,\n creator: userId\n });\n\nconst createdNpc = await npc.save();\n```\n\n```text\nreturn {\n ...createdNpc\n creator: userFromId(npc.creator)\n}\n```\n\n```text\nreturn {\n description: createdNpc.description,\n name: createdNpc.name,\n creator: userFromId(npc.creator)\n };\n```\n\n```text\n{\n _id: 5d8d5c7a04fc40483be74b3b,\n name: 'NPC Name',\n description: 'My Postman NPC',\n creator: 5d8d50e0b5c8a6317541d067,\n __v: 0\n}\n```\n\n```text\n{...createdNpc}\n```\n\n```text\n{...createdNpc, description: createdNpc.description, name: createdNpc.name}\n```\n\n```text\ncreatedNpc\n```\n\n```text\n{...createdNpc}\n```\n\n```text\n{...createdNPC}\n```\n\n```text\ncreatedNpc.toObject()\n```\n\n========================================\n\nComments:\n- I bet the properties are on an internal prototype, rather than on the object itself, in which case spread won't copy them - examine via `console.dir` to tell for certain","metadata":{"transformedAt":"2026-08-18T18:32:36.228Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":124,"estimatedTokens":738}}1113{"id":"stack-52926896","source":"stackoverflow","questionId":52926896,"title":"Querying graphiql leads Apollo error forward is not a function","tags":["graphql","apollo","react-apollo","graphiql"],"text":"Title: Querying graphiql leads Apollo error forward is not a function\nTags: graphql, apollo, react-apollo, graphiql\nSource: Stack Overflow\n\nQuestion:\nI have an express back-end with GraphQL that works when I go to `/graphiql`and manually perform some searches. My React front-end is trying to perform a search on the back-end. The following code should perform the query asynchronously:\n\n```\nconst data = await this.props.client.query({\n query: MY_QUERY,\n variables: { initials: e.target.value }\n});\nconsole.log(data);\n```\n\nWhere `MY_QUERY` is defined before and represents a query that I know works and has been tested on `/graphiql`. To do this in my React component I export it as `export default withApollo(MyComponent)` so that it has the `client` variable in the `props`.\n\nIn the `index.js` file I defined through Apollo the connection to `/graphiql` in order to perform the queries:\n\n```\n//link defined to deal with errors, this was found online\nconst link = onError(({ graphQLErrors, networkError }) => {\n if (graphQLErrors)\n graphQLErrors.map(({ message, locations, path }) =>\n console.log(\n `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,\n ),\n );\n\n if (networkError) console.log(`[Network error]: ${networkError}`);\n});\n\n//the httpLink to my GraphQL instance, BASE_URL is defined elsewhere\nconst httpLink = new HttpLink({\n uri: BASE_URL,\n headers: {\n },\n});\n\n//here I define the client linking the GraphQL instance, the cache, and error handling\nconst client = new ApolloClient({\n link: httpLink,\n cache,\n link\n});\n```\n\nWhen executing the above mentioned query without the `link`variable that handles the error, I receive a `400 Bad Request` from the server (`ApolloError.js:37 Uncaught (in promise) Error: Network error: Response not successful: Received status code 400`). Since this doesn't tell me more, here on StackOverflow and on the Apollo Web page I've found the above error declaration that outputs `[Network error]: TypeError: forward is not a function`. What does this error mean and how do I solve it?\n\nThanks!\n\n========================================\n\nCode:\n```text\nconst data = await this.props.client.query({\n query: MY_QUERY,\n variables: { initials: e.target.value }\n});\nconsole.log(data);\n```\n\n```text\n//link defined to deal with errors, this was found online\nconst link = onError(({ graphQLErrors, networkError }) => {\n if (graphQLErrors)\n graphQLErrors.map(({ message, locations, path }) =>\n console.log(\n `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,\n ),\n );\n\n if (networkError) console.log(`[Network error]: ${networkError}`);\n});\n\n//the httpLink to my GraphQL instance, BASE_URL is defined elsewhere\nconst httpLink = new HttpLink({\n uri: BASE_URL,\n headers: {\n },\n});\n\n//here I define the client linking the GraphQL instance, the cache, and error handling\nconst client = new ApolloClient({\n link: httpLink,\n cache,\n link\n});\n```\n\n```text\n/graphiql\n```\n\n```text\nMY_QUERY\n```\n\n```text\n/graphiql\n```\n\n```text\nexport default withApollo(MyComponent)\n```\n\n```text\nclient\n```\n\n```text\nprops\n```\n\n```text\nindex.js\n```\n\n```text\n/graphiql\n```\n\n```text\nlink\n```\n\n```text\n400 Bad Request\n```\n\n```text\nApolloError.js:37 Uncaught (in promise) Error: Network error: Response not successful: Received status code 400\n```\n\n```text\n[Network error]: TypeError: forward is not a function\n```\n\n```text\nconst errorLink = onError(...)\nconst httpLink = new HttpLink(...)\nconst link = ApolloLink.from([\n errorLink,\n httpLink,\n])\nconst client = new ApolloClient({\n link,\n cache,\n})\n```\n\n```text\nlink\n```\n\n```text\nHttpLink\n```\n\n```text\nErrorLink\n```\n\n```text\nHttpLink\n```\n\n```text\nErrorLink\n```\n\n```text\nErrorLink\n```\n\n```text\nonError\n```\n\n```text\nHttpLink\n```\n\n```text\nlink\n```\n\n```text\nconcat\n```\n\n```text\nApolloLink.from\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":194,"estimatedTokens":968}}1114{"id":"stack-65470444","source":"stackoverflow","questionId":65470444,"title":"type-graphql Cannot find module 'class-validator' exception","tags":["express","graphql","typeorm","typegraphql"],"text":"Title: type-graphql Cannot find module 'class-validator' exception\nTags: express, graphql, typeorm, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a GQL mutation by TypeORM and using SQL Server as database. If I am trying to run the mutation it is throwing exception. Sharing the code below;\n\n**index.ts**\n\n```\n(async () => {\n const app = express();\n \n await createConnection();\n \n const apolloServer = new ApolloServer({\n schema: await buildSchema({\n resolvers: [UserRegistrationResolver, HealthResolver],\n }),\n tracing: true,\n context: ({ req, res }) => ({ req, res })\n });\n \n apolloServer.applyMiddleware({ app, cors: false });\n \n app.listen(4000, () => {\n console.log(\"App is started\");\n })\n })();\n```\n\n**GQL Types:**\n\n```\n@InputType()\nexport class UserRegistrationType {\n\n /*......*/\n @Field()\n Reg_Security_Qus_Ans: string;\n /*......*/\n\n}\n```\n\n**Entity:**\n\n```\n@ObjectType()\n@Entity()\nexport class User_Registration extends BaseEntity {\n\n /*......*/\n\n @Field(() => Int)\n @OneToOne(()=> Security_Questions)\n @JoinColumn()\n Reg_Security_Qus_ID: Security_Questions;\n\n /*......*/\n}\n```\n\n**Mutation:**\n\n```\n@Resolver()\nexport class UserRegistrationResolver {\n@Mutation(() => User_Registration)\n async createRegistrations(\n @Arg(\"RegistrationMutation\") registrationMutation: UserRegistrationType\n ) {\n console.log(\"Boom1\");\n let oneUser = await User_Registration.insert(registrationMutation);\n return oneUser; \n }\n \n @Query(() => User_Registration)\n getUsers() {\n console.log(\"Boom\");\n return User_Registration.find();\n } \n}\n```\n\nWhen, I am trying to execute the mutation some weird error is appearing like below, asking me for **'class-validator'**, the error looks something like this,\n\n```\n\"message\": \"Cannot find module 'class-validator'\\nRequire stack:\\n-\n```\n\nCan anyone help me to solve this. I am stuck with this. Thanks in advance.\n\n========================================\n\nTop Answer:\nEither install `class-validator` or use `validate: false` option of `buildSchema`.\n\n========================================\n\nCode:\n```text\n(async () => {\n const app = express();\n \n await createConnection();\n \n const apolloServer = new ApolloServer({\n schema: await buildSchema({\n resolvers: [UserRegistrationResolver, HealthResolver],\n }),\n tracing: true,\n context: ({ req, res }) => ({ req, res })\n });\n \n apolloServer.applyMiddleware({ app, cors: false });\n \n app.listen(4000, () => {\n console.log(\"App is started\");\n })\n })();\n```\n\n```text\n@InputType()\nexport class UserRegistrationType {\n\n /*......*/\n @Field()\n Reg_Security_Qus_Ans: string;\n /*......*/\n\n}\n```\n\n```text\n@ObjectType()\n@Entity()\nexport class User_Registration extends BaseEntity {\n\n /*......*/\n\n @Field(() => Int)\n @OneToOne(()=> Security_Questions)\n @JoinColumn()\n Reg_Security_Qus_ID: Security_Questions;\n\n /*......*/\n}\n```\n\n```text\n@Resolver()\nexport class UserRegistrationResolver {\n@Mutation(() => User_Registration)\n async createRegistrations(\n @Arg(\"RegistrationMutation\") registrationMutation: UserRegistrationType\n ) {\n console.log(\"Boom1\");\n let oneUser = await User_Registration.insert(registrationMutation);\n return oneUser; \n }\n \n @Query(() => User_Registration)\n getUsers() {\n console.log(\"Boom\");\n return User_Registration.find();\n } \n}\n```\n\n```text\n\"message\": \"Cannot find module 'class-validator'\\nRequire stack:\\n-\n```\n\n```text\nnpm i class-validator\n```\n\n```text\nclass-validator\n```\n\n```text\nvalidate: false\n```\n\n```text\nbuildSchema\n```\n\n========================================\n\nComments:\n- Same bruh, was about to curse my internet out lol\n- Not stupid. npm 7+ installs absent peer dependencies automatically. npm 6- does not. We discovered this when trying to build on the server recently. But thank you for verifying. We ran into the same error again because the server's npm version got reverted.\n- I had to install `class-validator`, even though `validate` was set to `false` in my `buildSchema`","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":197,"estimatedTokens":1057}}1115{"id":"stack-66287582","source":"stackoverflow","questionId":66287582,"title":"WARNING Configuring `gql_build:serializer_builder` in target `WelcomeApp: WelcomeApp` but this is not a known Builder","tags":["flutter","graphql"],"text":"Title: WARNING Configuring `gql_build:serializer_builder` in target `WelcomeApp: WelcomeApp` but this is not a known Builder\nTags: flutter, graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to use Ferry with Flutter using the official documentation . I have placed my schema.graphql into my project and it has auto generated the necessary files, which has enabled me to extract my first query Login no problem.\n\nI have created a build.yaml file to which I have posted the following code....\n\n```\ntargets:\n $default:\n builders:\n gql_build|schema_builder:\n enabled: true\n gql_build|ast_builder:\n enabled: true\n gql_build|data_builder:\n enabled: true\n options:\n schema: WelcomeApp|lib/schema.graphql\n gql_build|var_builder:\n enabled: true\n options:\n schema: WelcomeApp|lib/schema.graphql\n gql_build|serializer_builder: And added my query into a file called login.graphql.\n\nHowever when calling flutter\n\n```\npub run build_runner watch --delete-conflicting-outputs\n```\n\nit builds some of the autogenerated files associated with the login.schema but the login.req.gql.dart is full of errors. I believe I am missing all the files with the .g.dart extension. I receive the following error associated with line 15 in the build.yaml file....\n\n```\n[WARNING] Configuring `gql_build:serializer_builder` in target `WelcomeApp: WelcomeApp` but this is not a known Builder\n```\n\nI believe the missing files that are not being auto generated are....\n\nlogin.data.gql.g.dart\n\nlogin.req.gql.g.dart\n\nlogin.var.gql.g.dart\n\nThanks for any help you can provide.\n\n========================================\n\nTop Answer:\na few of the builders have been removed, see https://github.com/gql-dart/ferry/blob/master/examples/pokemon_explorer/build.yaml for latest one:\n\n```\ntargets:\n $default:\n builders:\n ferry_generator|graphql_builder:\n enabled: true\n options:\n schema: pokemon_explorer|lib/schema.graphql\n\n ferry_generator|serializer_builder:\n enabled: true\n options:\n schema: pokemon_explorer|lib/schema.graphql\n```\n\n========================================\n\nCode:\n```text\ntargets:\n $default:\n builders:\n gql_build|schema_builder:\n enabled: true\n gql_build|ast_builder:\n enabled: true\n gql_build|data_builder:\n enabled: true\n options:\n schema: WelcomeApp|lib/schema.graphql\n gql_build|var_builder:\n enabled: true\n options:\n schema: WelcomeApp|lib/schema.graphql\n gql_build|serializer_builder: <-------------------ERROR ON THIS LINE\n enabled: true\n options:\n schema: WelcomeApp|lib/schema.graphql\n\n ferry_generator|req_builder:\n enabled: true\n options:\n schema: WelcomeApp|lib/schema.graphql\n```\n\n```text\npub run build_runner watch --delete-conflicting-outputs\n```\n\n```text\n[WARNING] Configuring `gql_build:serializer_builder` in target `WelcomeApp: WelcomeApp` but this is not a known Builder\n```\n\n```text\ndependencies:\n ferry:\n gql_http_link:\n get: ^4.1.1\n get_storage: ^2.0.1\n get_it:\n gql_build: ^0.1.4+2\n\ndependency_overrides:\n analyzer: ^0.41.2`\n```\n\n```text\ntargets:\n $default:\n builders:\n ferry_generator|graphql_builder:\n enabled: true\n options:\n schema: pokemon_explorer|lib/schema.graphql\n\n ferry_generator|serializer_builder:\n enabled: true\n options:\n schema: pokemon_explorer|lib/schema.graphql\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":134,"estimatedTokens":850}}1116{"id":"stack-53773837","source":"stackoverflow","questionId":53773837,"title":"Why is graphql-dotnet returning \"Expected non-null value\" error for this schema?","tags":["c#","graphql","graphql-dotnet"],"text":"Title: Why is graphql-dotnet returning \"Expected non-null value\" error for this schema?\nTags: c#, graphql, graphql-dotnet\nSource: Stack Overflow\n\nQuestion:\nI have a simple schema that I'm trying to query as follows:\n\n```\n{\n subQuery {\n subObjectGraph {\n Name\n }\n }\n}\n```\n\nBut \"graphiql\" throws the following error, without even seeming to run my query. \n\n```\n{\n \"errors\": [\n {\n \"message\": \"Expected non-null value, resolve delegate return null for \\\"$Api.Schema.Queries.MySubObjectGraphType\\\"\",\n \"extensions\": {\n \"code\": \"INVALID_OPERATION\"\n }\n }\n ]\n}\n```\n\nWhat is wrong with my schema (below)? I am new-ing up a SubObject, so I don't understand why the error message implies the value is null.\n\n```\npublic class Schema: GraphQL.Types.Schema\n {\n public Schema(IDependencyResolver resolver): base(resolver)\n {\n Query = resolver.Resolve(); \n Mutation = null;\n }\n }\n\n public class RootQuery: ObjectGraphType\n {\n public RootQuery(IDependencyResolver resolver)\n {\n Name = \"Query\";\n\n Field(\n name: \"subQuery\",\n resolve: ctx => resolver.Resolve());\n }\n }\n\n public class MySubQuery: ObjectGraphType\n {\n public MySubQuery()\n {\n Name = \"TempSubQuery\";\n\n Field(\"SubQueryName\", resolve: ctx => \"Some string value\");\n\n Field(\n name: \"subObjectGraph\",\n resolve: ctx => FetchFromRepo());\n }\n\n //Repo access would go here, but just new-ing the object for now.\n private SubObject FetchFromRepo()\n {\n return new SubObject() { Name = \"some sub object\" };\n }\n }\n\n public class SubObject\n {\n public string Name { get; set; }\n }\n\n public class MySubObjectGraphType: ObjectGraphType\n {\n public MySubObjectGraphType()\n {\n Name = \"MySubObject\";\n Description = \"An object with leaf nodes\";\n\n Field(l => l.Name);\n }\n }\n```\n\nThe code works fine if I substitute MySubObjectGraphType with StringGraphType, so the problem must be with configuration of MySubObjectGraphType.\n\nPlease help? I'm using v2.4.\n\n========================================\n\nTop Answer:\nYou are returning a GraphType in subQuery in your RootQuery. Resolvers should only return DTOs and never GraphTypes.\n\nIf you are trying to organize your queries, then just return an empty object.\n\n```\nField(\n name: \"subQuery\",\n resolve: ctx => new {});\n```\n\nhttps://graphql-dotnet.github.io/docs/getting-started/query-organization\n\n========================================\n\nCode:\n```text\n{\n subQuery {\n subObjectGraph {\n Name\n }\n }\n}\n```\n\n```text\n{\n \"errors\": [\n {\n \"message\": \"Expected non-null value, resolve delegate return null for \\\"$Api.Schema.Queries.MySubObjectGraphType\\\"\",\n \"extensions\": {\n \"code\": \"INVALID_OPERATION\"\n }\n }\n ]\n}\n```\n\n```text\npublic class Schema: GraphQL.Types.Schema\n {\n public Schema(IDependencyResolver resolver): base(resolver)\n {\n Query = resolver.Resolve<RootQuery>(); \n Mutation = null;\n }\n }\n\n public class RootQuery: ObjectGraphType\n {\n public RootQuery(IDependencyResolver resolver)\n {\n Name = \"Query\";\n\n Field<MySubQuery>(\n name: \"subQuery\",\n resolve: ctx => resolver.Resolve<MySubQuery>());\n }\n }\n\n\n public class MySubQuery: ObjectGraphType\n {\n public MySubQuery()\n {\n Name = \"TempSubQuery\";\n\n Field<StringGraphType>(\"SubQueryName\", resolve: ctx => \"Some string value\");\n\n Field<MySubObjectGraphType>(\n name: \"subObjectGraph\",\n resolve: ctx => FetchFromRepo());\n }\n\n\n //Repo access would go here, but just new-ing the object for now.\n private SubObject FetchFromRepo()\n {\n return new SubObject() { Name = \"some sub object\" };\n }\n }\n\n\n public class SubObject\n {\n public string Name { get; set; }\n }\n\n public class MySubObjectGraphType: ObjectGraphType<SubObject>\n {\n public MySubObjectGraphType()\n {\n Name = \"MySubObject\";\n Description = \"An object with leaf nodes\";\n\n Field(l => l.Name);\n }\n }\n```\n\n```text\nMySubObjectGraphType\n```\n\n```text\nStartup.cs\n```\n\n```text\nObjectGraphType\n```\n\n```text\nStartup.cs\n```\n\n```text\nservices.AddSingleton<MySubObjectGraphType>();\n```\n\n```text\nField<MySubQuery>(\n name: \"subQuery\",\n resolve: ctx => new {});\n```\n\n========================================\n\nComments:\n- Thanks Joe, and thanks for a great library! I tried changing as you suggested, but I still get the exact same issue. Looks like something is wrong with MySubObjectGraphType, but I can't figure out what. The \"FetchFromRepo\" method returns a Dto, so I imagine it should map to the graphType without issues? Slightly updated gist over here: gist.github.com/willemodendaal/77ff0feded77a33238e43142c7a00‌​f3f\n- I'm using v2.4 by the way.","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":231,"estimatedTokens":1200}}1117{"id":"stack-47458143","source":"stackoverflow","questionId":47458143,"title":"How to download Github repositories via GraphQL API search?","tags":["git","github","graphql","github-api"],"text":"Title: How to download Github repositories via GraphQL API search?\nTags: git, github, graphql, github-api\nSource: Stack Overflow\n\nQuestion:\nI want to make some data researches and want to download repositories content from the search results with Github GraphQL API. \n\nWhat I already found is how to make simple search query, but the question is:\n**How to download repositories content from the search results?**\n\nHere is my current code that returns repositories name and description (try to run here):\n\n```\n{\n search(query: \"example\", type: REPOSITORY, first: 20) {\n repositoryCount\n edges {\n node {\n ... on Repository {\n name\n descriptionHTML\n }\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\n@tharinduwijewardane\n\nJFYI, you can download a zip of a specific branch by this query\n\n```\nrepository(owner: \"owner\", name: \"repo name\") {\n object(expression: \"branch\") {\n ... on Commit {\n zipballUrl\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n search(query: \"example\", type: REPOSITORY, first: 20) {\n repositoryCount\n edges {\n node {\n ... on Repository {\n name\n descriptionHTML\n }\n }\n }\n }\n}\n```\n\n```graphql\n{\n repository(owner: \"google\", name: \"gson\") {\n\n defaultBranchRef {\n target {\n ... on Commit {\n tarballUrl\n zipballUrl\n }\n }\n }\n }\n}\n```\n\n```graphql\n{\n search(query: \"example\", type: REPOSITORY, first: 20) {\n repositoryCount\n edges {\n node {\n ... on Repository {\n defaultBranchRef {\n target {\n ... on Commit {\n zipballUrl\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```bash\ncurl -s -H \"Authorization: bearer YOUR_TOKEN\" -d '\n{\n \"query\": \"query { search(query: \\\"example\\\", type: REPOSITORY, first: 20) { repositoryCount edges { node { ... on Repository { defaultBranchRef { target { ... on Commit { zipballUrl } }}}}}}}\"\n}\n' https://api.github.com/graphql | jq -r '.data.search.edges[].node.defaultBranchRef.target.zipballUrl' | xargs -I{} curl -O {}\n```\n\n```text\nrepository(owner: \"owner\", name: \"repo name\") {\n object(expression: \"branch\") {\n ... on Commit {\n zipballUrl\n }\n }\n}\n```\n\n========================================\n\nComments:\n- how to get a zip of a specific branch i name?","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":123,"estimatedTokens":590}}1118{"id":"stack-67707389","source":"stackoverflow","questionId":67707389,"title":"How to use redux with graphql","tags":["redux","graphql","apollo"],"text":"Title: How to use redux with graphql\nTags: redux, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI like graphql. Because it has a single endpoint and I can only pull out the data I need.\n\nSo I use apollo-server for the server and apollo-client for the client.\n\nStarting with apollo-client 3.0, state-management is supported.\n\nThe reactive variable function of the apollo-client is very convenient, but I prefer redux.\n\nRedux toolkit also shortened the length of code that needs to be written.\n\nThe question is this.\n\nCan't I use apollo-client 3.0 and redux together?\n\nCan't I just use graphql without an apollo-client on redux? then How?\n\ncheck please!\n\n========================================\n\nComments:\n- use Apollo client [with **normalizing cache**] for all fetched data (copying/duplicating data to redux doesn't make sense, managing fetching/waiting/error handling, too) ... redux for other, global app state (drawer open, active filter, [default] sorting order, etc.) common/consumed in many places/components\n- The second link points to an empty sandbox. Do you know of a RTK/GraphQL example I could check?\n- Yeah, I wrote that before we had released RTKQ, so those pointed to preview branches. Just updated the links to point to our current docs and examples.","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":29,"estimatedTokens":318}}1119{"id":"stack-65602563","source":"stackoverflow","questionId":65602563,"title":"Possible to use only one package version using pnpm?","tags":["npm","graphql","dependencies","apollo-server","pnpm"],"text":"Title: Possible to use only one package version using pnpm?\nTags: npm, graphql, dependencies, apollo-server, pnpm\nSource: Stack Overflow\n\nQuestion:\nI need to use `apollo-server` and `graphql-upload` to handle file uploads. This is working as expected with the old graphql-upload v9. Updating to the latest v11 results in failing uploads. To make it short, the problem is, that `apollo-server` (and `@nestjs/graphql`) are depending on the old `graphql-upload` v8. (For those, who are interested in more) To get everything working, there should only be one version (v11) in my project.\n\nI'm using **pnpm**. Listing which packages are using `graphql-upload` I get following:\n\n```\n@nestjs/graphql 7.9.1\nβββ¬ @apollo/gateway 0.17.0\nβ βββ¬ apollo-server-core 2.19.0\nβ βββ graphql-upload 8.1.0 // <--\nβββ¬ apollo-server-core 2.16.1\nβ βββ graphql-upload 8.1.0 // <--\nβββ¬ apollo-server-testing 2.19.0\n βββ¬ apollo-server-core 2.19.0\n βββ graphql-upload 8.1.0 // <--\napollo-server 2.19.0\nβββ¬ apollo-server-core 2.19.0\nβ βββ graphql-upload 8.1.0 // <--\nβββ¬ apollo-server-express 2.19.0\n βββ¬ apollo-server-core 2.19.0\n βββ graphql-upload 8.1.0 // <--\ngraphql-upload 9.0.0 // <-- only working if <v10\n```\n\n========================================\n\nCode:\n```text\n@nestjs/graphql 7.9.1\nβββ¬ @apollo/gateway 0.17.0\nβ βββ¬ apollo-server-core 2.19.0\nβ βββ graphql-upload 8.1.0 // <--\nβββ¬ apollo-server-core 2.16.1\nβ βββ graphql-upload 8.1.0 // <--\nβββ¬ apollo-server-testing 2.19.0\n βββ¬ apollo-server-core 2.19.0\n βββ graphql-upload 8.1.0 // <--\napollo-server 2.19.0\nβββ¬ apollo-server-core 2.19.0\nβ βββ graphql-upload 8.1.0 // <--\nβββ¬ apollo-server-express 2.19.0\n βββ¬ apollo-server-core 2.19.0\n βββ graphql-upload 8.1.0 // <--\ngraphql-upload 9.0.0 // <-- only working if <v10\n```\n\n```text\napollo-server\n```\n\n```text\ngraphql-upload\n```\n\n```text\napollo-server\n```\n\n```text\n@nestjs/graphql\n```\n\n```text\ngraphql-upload\n```\n\n```text\ngraphql-upload\n```\n\n```json\n{\n \"pnpm\": {\n \"overrides\": {\n \"graphql-upload\": \"11\"\n }\n }\n}\n```\n\n```text\npackage.json\n```\n\n```text\npnpm install\n```\n\n========================================\n\nComments:\n- That link is broken.\n- fixed. The domain changed to pnpm.io from pnpm.js.org","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":97,"estimatedTokens":562}}1120{"id":"stack-66225288","source":"stackoverflow","questionId":66225288,"title":"NestJs: Make sure your class is decorated with an appropriate decorator","tags":["javascript","node.js","typescript","graphql","nestjs"],"text":"Title: NestJs: Make sure your class is decorated with an appropriate decorator\nTags: javascript, node.js, typescript, graphql, nestjs\nSource: Stack Overflow\n\nQuestion:\nI am using `graphql-request` as a GraphQL client to query a headless CMS to fetch stuff, modify and return to the original request/query. headless cms is hosted separately fyi.\n\nI have the following code :\n\n```\n@Query(returns => BlogPost)\n async test() {\n const endpoint = 'https://contentxx.com/api/content/project-dev/graphql'\n const graphQLClient = new GraphQLClient(endpoint, {\n headers: {\n authorization: 'Bearer xxxxxxx',\n },\n })\n const query = gql`\n {\n findContentContent(id: \"9f5dde89-7f9b-4b9c-8669-1f0425b2b55d\") {\n id\n flatData {\n body\n slug\n subtitle\n title\n }\n }\n }`\n\n return await graphQLClient.request(query);\n }\n```\n\n`BlogPost` is a model having the types :\n\n```\nimport { Field, ObjectType } from '@nestjs/graphql';\nimport { BaseModel } from './base.model';\nimport FlatDateType from '../resolvers/blogPost/types/flatDatatype.type';\n\n@ObjectType()\nexport class BlogPost extends BaseModel {\n @Field({ nullable: true })\n id!: string;\n\n @Field((type) => FlatDateType)\n flatData: FlatDateType;\n}\n```\n\nand `FlatDateType` has the following code\n\n```\nexport default class FlatDateType {\n body: string;\n slug: string;\n subtitle: string;\n title: string;\n}\n```\n\nit throws the following exception :\n\nError: Cannot determine a GraphQL output type for the \"flatData\". Make\nsure your class is decorated with an appropriate decorator.\n\nWhat is missing in here?\n\n========================================\n\nTop Answer:\n`FlatDataType` is not defined as `@ObjectType()`, therefore type-graphql (or @nestjs/graphql) can't take it as an output in GraphQL.\n\n========================================\n\nCode:\n```text\n@Query(returns => BlogPost)\n async test() {\n const endpoint = 'https://contentxx.com/api/content/project-dev/graphql'\n const graphQLClient = new GraphQLClient(endpoint, {\n headers: {\n authorization: 'Bearer xxxxxxx',\n },\n })\n const query = gql`\n {\n findContentContent(id: \"9f5dde89-7f9b-4b9c-8669-1f0425b2b55d\") {\n id\n flatData {\n body\n slug\n subtitle\n title\n }\n }\n }`\n\n return await graphQLClient.request(query);\n }\n```\n\n```text\nimport { Field, ObjectType } from '@nestjs/graphql';\nimport { BaseModel } from './base.model';\nimport FlatDateType from '../resolvers/blogPost/types/flatDatatype.type';\n\n@ObjectType()\nexport class BlogPost extends BaseModel {\n @Field({ nullable: true })\n id!: string;\n\n @Field((type) => FlatDateType)\n flatData: FlatDateType;\n}\n```\n\n```text\nexport default class FlatDateType {\n body: string;\n slug: string;\n subtitle: string;\n title: string;\n}\n```\n\n```text\ngraphql-request\n```\n\n```text\nBlogPost\n```\n\n```text\nFlatDateType\n```\n\n```text\nFlatDataType\n```\n\n```text\n@ObjectType()\n```\n\n```text\n@Field()\n```\n\n```text\nFlatDataType\n```\n\n```text\n@ObjectType()\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":159,"estimatedTokens":749}}1121{"id":"stack-53683009","source":"stackoverflow","questionId":53683009,"title":"Row level security using prisma and postgres","tags":["postgresql","graphql","prisma","row-level-security","prisma-graphql"],"text":"Title: Row level security using prisma and postgres\nTags: postgresql, graphql, prisma, row-level-security, prisma-graphql\nSource: Stack Overflow\n\nQuestion:\nI am using prisma and yoga graphql servers with a postgres DB.\n\nI want to implement authorization for my graphql queries. I saw solutions like graphql-shield that solve `column level security` nicely - meaning I can define a permission and according to it block or allow a specific table or column of data (on in graphql terms, block a whole entity or a specific field).\n\nThe part I am stuck on is `row level security` - filtering rows by the data they contain - say I want to allow a logged in user to view only the data that is related to him, so depending on the value in a user_id column I would allow or block access to that row (the logged in user is one example, but there are other usecases in this genre).\n\nThis type of security requires running a query to check which rows the current user has access to and I can't find a way (that is not horrible) to implement this with prisma.\n\nIf I was working without prisma, I would implement this in the level of each resolver but since I am forwarding my queries to prisma I do not control the internal resolvers on a nested query.\n\nBut I do want to work with prisma, so one idea we had was handling this in the DB level using postgres policy. This could work as follows:\n\n- Every query we run will be surrounded with βbegin transactionβ and βcommit transactionβ\n\n- Before the query I want to run βset local context.user_id to 5\"\n\n- Then I want to run the query (and the policy will filter results according to the current_setting(βcontext.user_idβ))\n\nFor this to work I would need prisma to allow me to either add pre/post queries to each query that runs or let me set a context for the db.\n\nBut these options are not available in prisma.\n\nAny ideas?\n\n========================================\n\nTop Answer:\nWith the approach you're looking to take, I'd definitely recommend a look at Graphile. It approaches row-level security essentially the same way that you're thinking of. Unfortunately, it seems like Prisma doesn't help you move away from writing traditional REST-style controller methods in this regard.\n\n========================================\n\nCode:\n```text\ncolumn level security\n```\n\n```text\nrow level security\n```\n\n```text\nprisma-client\n```\n\n```text\nprisma-binding\n```\n\n```text\nprisma-binding\n```\n\n```text\nprisma-client\n```\n\n```text\nprisma-client\n```\n\n========================================\n\nComments:\n- Without the schema, I can't give a definitive answer but have you tried to create a policy using ((id)::name = SESSION_USER) or something in those lines. SESSION_USER is the role used to connect to the DB.\n- I assume you are using `prisma-binding` for the forwarding. Maybe using `prisma-client` would be a better choice so you would implement this logic inside resolvers ? (That would also work with nested queries)\n- Regarding session user my connection to the db through prisma is always with the same user and role. The users are managed in the applicatuon level, not the db. I dont think it is even possible to have a specific role per query to prisma. If that was possible it could solve the problem. Is it possible and i am missing something?","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":71,"estimatedTokens":819}}1122{"id":"stack-62527982","source":"stackoverflow","questionId":62527982,"title":"GraphQL queries in Separate File (gql, graphql)","tags":["reactjs","graphql","gql","postgraphile"],"text":"Title: GraphQL queries in Separate File (gql, graphql)\nTags: reactjs, graphql, gql, postgraphile\nSource: Stack Overflow\n\nQuestion:\nI am working on project with teachnology combination of React + Postgraphile (GraphQL) + axios(http request to postgraphile server).\n\nIt has lots of GraphQL queries. Initially started with queries in same file with the other JavaScript and rendering code but it became messy as soon as specific queries has been added.\n\nWhile searching I came to know that we can detach queries into separate files - .graphql or .gql\nFor this to allow I have to integrate with Webpack module -\n\n**I wanted to know if there is simpler(kind of out of the box) way to achieve similar thing without using Webpack as it needs lots of configuration in place.**\n\nAny pointers or examples will be really helpful.\n\nThank you.\n\n========================================\n\nTop Answer:\nSince it's non-standard functionality to import/require a file that's not `.js` or `.json`, you need some kind of plugin to tell the runtime how to interpret it and not crash. The two ways I know of are:\n\n- using the graphql-tag/loader in webpack, with only a single loader rule:\n\n```\nmodule.exports = {\n // ...\n module: {\n rules: [\n // babel loader, css imports,\n {\n test: /\\.(graphql|gql)$/,\n exclude: /node_modules/,\n loader: 'graphql-tag/loader'\n },\n ],\n },\n // ...\n}\n```\n\n- or, with babel-plugin-import-graphql in babel, though this plugin just mimcs the functionality of the above webpack loader, and in fact suggests using it along side graphql-tag to reduce the size of the compiled query. It is useful if you need to run your code with `babel-node`, but I would suggest the above webpack loader in most cases.\n\n========================================\n\nCode:\n```text\nexport const GET_TEAM_QUERY = `\n query {\n // your query here\n }\n`\n```\n\n```text\npages\n```\n\n```text\ngraphql\n```\n\n```text\njs\n```\n\n```text\nts\n```\n\n```js\nmodule.exports = {\n // ...\n module: {\n rules: [\n // babel loader, css imports,\n {\n test: /\\.(graphql|gql)$/,\n exclude: /node_modules/,\n loader: 'graphql-tag/loader'\n },\n ],\n },\n // ...\n}\n```\n\n```text\n.js\n```\n\n```text\n.json\n```\n\n```text\nbabel-node\n```\n\n========================================\n\nComments:\n- I appreciate you tried to answer it. Let me try it. Thank you.\n- What If we have params that we wanna use to construct the query?","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":105,"estimatedTokens":600}}1123{"id":"stack-59365316","source":"stackoverflow","questionId":59365316,"title":"Why do you need graphql-tag with Apollo","tags":["vue.js","graphql","apollo-client","graphql-tag"],"text":"Title: Why do you need graphql-tag with Apollo\nTags: vue.js, graphql, apollo-client, graphql-tag\nSource: Stack Overflow\n\nQuestion:\nFollowing some tutorials and examples, I integrated a GraphQL API into a simple Vue application. I'm using Apollo to interact with the API and graphql-tag's provided template literal to write the queries, like so:\n\n```\ngql`\n query getUser($userId: ID) {\n user(id: $userId) {\n name,\n email\n }\n }\n`\n```\n\nHowever, I don't quite understand the necessity of the graphql-tag package. From what I understand, this package translates the query into AST, but what is the purpose of this in the frontend and why do you need graphql-tag package to do this? Can't GraphQL queries be sent to server as they are?\n\n========================================\n\nTop Answer:\nThey can be just plain strings, you can get IDE extensions to give you syntax highlighting where it sees the `gql` tag. Strings are inconvenient to manipulate, if you are trying to do things like add extra fields, merge multiple queries together, or other interesting stuff. It also semanticity separates the difference & importance of the following string.\n\n========================================\n\nCode:\n```text\ngql`\n query getUser($userId: ID) {\n user(id: $userId) {\n name,\n email\n }\n }\n`\n```\n\n```text\n{\n foo\n bar\n}\n\nquery SomeOperationName {\n foo\n bar\n}\n\nquery { foo bar }\n\n{\n bar\n qux: foo\n}\n```\n\n```text\nDocumentNode\n```\n\n```text\ngql\n```\n\n========================================\n\nComments:\n- I don't get from your answer why graphql-tag is required, though, which seems to be what the OP is asking.\n- @Mitya my understanding is that you don't need graphql-tag, but if you did have it, graphql-tag would help Apollo to recognise those objects as the same thing and cache them / reduce the amount of caching. i.e. it helps Apollo.","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":71,"estimatedTokens":468}}1124{"id":"stack-46547326","source":"stackoverflow","questionId":46547326,"title":"Compress GraphQL Query?","tags":["python","graphql"],"text":"Title: Compress GraphQL Query?\nTags: python, graphql\nSource: Stack Overflow\n\nQuestion:\nI am looking for a *standard* way of compressing a GraphQL query/response to send it through MQTT. \n\nI am thinking of something that can: \n\n- Remove extra spaces\n\n- Remove extra new lines (`\\n`, `\\r`);\n\n- Compress the message (zlib?)\n\nI took a look to Graphene and other GraphQL modules for Python, but I have not found what I am looking for yet. \n\nIs there a terminology that I am missing or is this something that I should not do?\n\n========================================\n\nCode:\n```text\n\\n\n```\n\n```text\n\\r\n```\n\n```py\nimport shlex\n\nquery_with_strings = \"\"\"\n query someQuery {\n Field(\n search: \"string with spaces\"\n ) {\n foo\n }\n }\n\"\"\"\n\n\ndef compress_graphql(q):\n \"\"\"Compress a GraphQL query by removing unnecessary whitespace.\n\n >>> compress_graphql(query_with_strings)\n u'query someQuery { Field( search: \"string with spaces\" ) { foo } }'\n \"\"\"\n return u' '.join(shlex.split(q, posix=False))\n```\n\n```text\nunicode\n```\n\n```text\nstr\n```\n\n========================================\n\nComments:\n- Thankfully this is probably no different than compressing any JSON over AJAX.","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":65,"estimatedTokens":319}}1125{"id":"stack-50328851","source":"stackoverflow","questionId":50328851,"title":"GraphQL Java custom scalar type for map is not accepted by schema","tags":["java","graphql","graphql-java"],"text":"Title: GraphQL Java custom scalar type for map is not accepted by schema\nTags: java, graphql, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI try to add a custom scalar type for GraphQL Java. I need it to resolve a Map without creating a type for it because it is a common return type in my logic.\n\nI followed the instruction (*here*: http://graphql-java.readthedocs.io/en/latest/scalars.html) to create a scalar type.\n\nThis is my `MapScalar.java`\n\n```\npublic class MapScalar {\n private static final Logger LOG = LoggerFactory.getLogger(MapScalar.class);\n\n public static final GraphQLScalarType MAP = new GraphQLScalarType(\"Map\", \"A custom map scalar type\", new Coercing() {\n @Override\n public Object serialize(Object dataFetcherResult) throws CoercingSerializeException {\n Map map = null;\n try {\n map = Map.class.cast(dataFetcherResult);\n } catch (ClassCastException exception) {\n throw new CoercingSerializeException(\"Could not convert \" + dataFetcherResult + \" into a Map\", exception);\n }\n return map;\n }\n\n @Override\n public Object parseValue(Object input) throws CoercingParseValueException {\n LOG.warn(\"parseValue called\");\n return null;\n }\n\n @Override\n public Object parseLiteral(Object input) throws CoercingParseLiteralException {\n LOG.warn(\"parseLiteral called\");\n return null;\n }\n });\n}\n```\n\nI added this scalar instance to `RunTimeWiring`\n\n```\nfinal RuntimeWiring runtimeWiring = newRuntimeWiring()\n .type(queryTypeFactory.getQueryBaseQueryType()) // just convenience methods I made\n .type(queryTypeFactory.getPageQueryType(viewName)) // ...\n .type(queryTypeFactory.getContentQueryType(viewName)) // ...\n .type(queryTypeFactory.getPictureQueryType()) // ...\n .type(queryTypeFactory.getSettingQueryType()) // just convenience methods I made\n .scalar(MapScalar.MAP) // added new scalar here\n .build();\n```\n\nI defined this `MapDataFetcher`\n\n```\n@Component\npublic class MapDataFetcher implements DataFetcher {\n\n @Override\n public Object get(DataFetchingEnvironment environment) {\n String fieldName = environment.getField().getName();\n Content source = Content.class.cast(environment.getSource());\n return source.getStruct(fieldName).toNestedMaps(); // returns a Map\n }\n\n}\n```\n\nAnd the schema for this field/scalar is defined as followed:\n\n```\ntype Content {\n //... other fields\n settings: Map\n}\n```\n\nWhen debugging the `RunTimeWiring` everthing seems fine. The scalar has been added to the default scalars:\n\nhttps://i.sstatic.net/cn4rG.png\n\nStill this **error** occurs:\n\n```\nSCHWERWIEGEND: Servlet.service() for servlet [cae] in context with path [/blueprint] threw exception [Request processing failed; nested exception is SchemaProblem{errors=[The field type 'Map' is not present when resolving type 'Content' [@10:1], The field type 'Map' is not present when resolving type 'Setting' [@28:1]]}] with root cause\nSchemaProblem{errors=[The field type 'Map' is not present when resolving type 'Content' [@10:1], The field type 'Map' is not present when resolving type 'Setting' [@28:1]]}\n```\n\nI can not find any hind in the tutorials to find out what I am missing out to make it work. I understand that there is a missing type here. But creating a new Type with `newRunTimeWiring().type()` is a for creating Non-Scalar types isn't it? Or do I still need to create a `Map` type in there?\n\n========================================\n\nCode:\n```text\npublic class MapScalar {\n private static final Logger LOG = LoggerFactory.getLogger(MapScalar.class);\n\n public static final GraphQLScalarType MAP = new GraphQLScalarType(\"Map\", \"A custom map scalar type\", new Coercing() {\n @Override\n public Object serialize(Object dataFetcherResult) throws CoercingSerializeException {\n Map map = null;\n try {\n map = Map.class.cast(dataFetcherResult);\n } catch (ClassCastException exception) {\n throw new CoercingSerializeException(\"Could not convert \" + dataFetcherResult + \" into a Map\", exception);\n }\n return map;\n }\n\n @Override\n public Object parseValue(Object input) throws CoercingParseValueException {\n LOG.warn(\"parseValue called\");\n return null;\n }\n\n @Override\n public Object parseLiteral(Object input) throws CoercingParseLiteralException {\n LOG.warn(\"parseLiteral called\");\n return null;\n }\n });\n}\n```\n\n```text\nfinal RuntimeWiring runtimeWiring = newRuntimeWiring()\n .type(queryTypeFactory.getQueryBaseQueryType()) // just convenience methods I made\n .type(queryTypeFactory.getPageQueryType(viewName)) // ...\n .type(queryTypeFactory.getContentQueryType(viewName)) // ...\n .type(queryTypeFactory.getPictureQueryType()) // ...\n .type(queryTypeFactory.getSettingQueryType()) // just convenience methods I made\n .scalar(MapScalar.MAP) // added new scalar here\n .build();\n```\n\n```text\n@Component\npublic class MapDataFetcher implements DataFetcher {\n\n @Override\n public Object get(DataFetchingEnvironment environment) {\n String fieldName = environment.getField().getName();\n Content source = Content.class.cast(environment.getSource());\n return source.getStruct(fieldName).toNestedMaps(); // returns a Map<String,Object>\n }\n\n}\n```\n\n```text\ntype Content {\n //... other fields\n settings: Map\n}\n```\n\n```text\nSCHWERWIEGEND: Servlet.service() for servlet [cae] in context with path [/blueprint] threw exception [Request processing failed; nested exception is SchemaProblem{errors=[The field type 'Map' is not present when resolving type 'Content' [@10:1], The field type 'Map' is not present when resolving type 'Setting' [@28:1]]}] with root cause\nSchemaProblem{errors=[The field type 'Map' is not present when resolving type 'Content' [@10:1], The field type 'Map' is not present when resolving type 'Setting' [@28:1]]}\n```\n\n```text\nMapScalar.java\n```\n\n```text\nRunTimeWiring\n```\n\n```text\nMapDataFetcher\n```\n\n```text\nRunTimeWiring\n```\n\n```text\nnewRunTimeWiring().type()\n```\n\n```text\nMap\n```\n\n```text\nscalar Map\n```\n\n```text\nMap\n```\n\n========================================\n\nComments:\n- Your implementation is quite broken in that this scalar will be silently ignored if used as input directly or as a variable. See a more complete implementation here. Also, why the funky `Map.class.cast(dataFetcherResult)`? What's wrong with simple `(Map) dataFetcherResult`?\n- I can read it better and am reminded to use it when having Java Streams API and method references `stream().map(Map.class::cast)`\n- thanks. that's exactly what I was looking for. you should select your answer .\n- It is actually documented in github.com/graphql-java/graphql-java-extended-scalars, it says pretty straight forward, after you register the scalar with graphql-java, you need to use it in your schema.","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":203,"estimatedTokens":1680}}1126{"id":"stack-63117446","source":"stackoverflow","questionId":63117446,"title":"Can't get Graphql-tools to read my schema.graphql file","tags":["javascript","graphql","apollo-server","graphql-tools"],"text":"Title: Can't get Graphql-tools to read my schema.graphql file\nTags: javascript, graphql, apollo-server, graphql-tools\nSource: Stack Overflow\n\nQuestion:\nI am using Apollo-server-express and Graphql-tools. I have been all over the Graphql-tools documentation and I can't get this to work. I'm trying to get my schema.graphql file to import as my typeDefs. It seems like Graphql-tools should be making this easy, but something isn't falling into place.\n\nindex.js\n\n```\nconst { ApolloServer } = require(\"apollo-server-express\");\nconst { makeExecutableSchema } = require('@graphql-tools/schema');\nconst express = require(\"express\");\nconst { join } = require(\"path\");\nconst { loadSchema } = require(\"@graphql-tools/load\");\nconst { GraphQLFileLoader } = require(\"@graphql-tools/graphql-file-loader\");\nconst { addResolversToSchema } = require(\"@graphql-tools/schema\");\nconst app = express();\n\nconst resolvers = {\n Query: {\n items: (parent, args, ctx, info) => {\n return ctx.prisma.item.findMany();\n },\n },\n Mutation: {\n makeItem: (parent, args, context, info) => {\n const newItem = context.prisma.item.create({\n data: {\n ...args,\n price: parseInt(Math.ceil(args.price * 100)),\n },\n });\n return newItem;\n },\n deleteItem: (parent, args, context, info) => {\n return context.prisma.item.delete({\n where: {\n id: args.id,\n },\n });\n },\n },\n};\n\nconst schemaSource = loadSchemaSync(join(__dirname, \"schema.graphql\"), {\n loaders: [new GraphQLFileLoader()],\n});\n\nconst schema = makeExecutableSchema({\n typeDefs: schemaSource,\n resolvers,\n});\n\nconst server = new ApolloServer({\n schema,\n resolvers,\n});\n\nserver.applyMiddleware({ app });\n\napp.listen(\n { port: 4000 },\n () =>\n console.log(\n `π => Backend server is now running on port http://localhost:4000`\n )\n);\n```\n\nschema.graphql\n\n```\ntype Query {\n items: [Item!]!\n}\n\ntype Mutation {\n makeItem(\n piece: String!\n image: String!\n identifier: String!\n price: Float!\n itemNumber: Int!\n ): Item!\n deleteItem(id: ID!): Item!\n}\n\ntype Item {\n id: ID!\n piece: String!\n image: String!\n identifier: String!\n price: Int!\n itemNumber: Int!\n}\n```\n\nIn its current state I am getting an error that says: \"Error: typeDefs must be a string, array or schema AST, got object\"\n\nAs I understand it makeExecutableSchema should be doing all the necessary steps, like changing the schema into a string. I can't seem to figure out what is going on here and any help would be greatly appreciated.\n\n========================================\n\nCode:\n```text\nconst { ApolloServer } = require(\"apollo-server-express\");\nconst { makeExecutableSchema } = require('@graphql-tools/schema');\nconst express = require(\"express\");\nconst { join } = require(\"path\");\nconst { loadSchema } = require(\"@graphql-tools/load\");\nconst { GraphQLFileLoader } = require(\"@graphql-tools/graphql-file-loader\");\nconst { addResolversToSchema } = require(\"@graphql-tools/schema\");\nconst app = express();\n\nconst resolvers = {\n Query: {\n items: (parent, args, ctx, info) => {\n return ctx.prisma.item.findMany();\n },\n },\n Mutation: {\n makeItem: (parent, args, context, info) => {\n const newItem = context.prisma.item.create({\n data: {\n ...args,\n price: parseInt(Math.ceil(args.price * 100)),\n },\n });\n return newItem;\n },\n deleteItem: (parent, args, context, info) => {\n return context.prisma.item.delete({\n where: {\n id: args.id,\n },\n });\n },\n },\n};\n\nconst schemaSource = loadSchemaSync(join(__dirname, \"schema.graphql\"), {\n loaders: [new GraphQLFileLoader()],\n});\n\nconst schema = makeExecutableSchema({\n typeDefs: schemaSource,\n resolvers,\n});\n\nconst server = new ApolloServer({\n schema,\n resolvers,\n});\n\nserver.applyMiddleware({ app });\n\napp.listen(\n { port: 4000 },\n () =>\n console.log(\n `π => Backend server is now running on port http://localhost:4000`\n )\n);\n```\n\n```text\ntype Query {\n items: [Item!]!\n}\n\ntype Mutation {\n makeItem(\n piece: String!\n image: String!\n identifier: String!\n price: Float!\n itemNumber: Int!\n ): Item!\n deleteItem(id: ID!): Item!\n}\n\ntype Item {\n id: ID!\n piece: String!\n image: String!\n identifier: String!\n price: Int!\n itemNumber: Int!\n}\n```\n\n```text\nconst sources = loadTypedefsSync(join(__dirname, \"schema.graphql\"), {\n loaders: [new GraphQLFileLoader()],\n});\nconst typeDefs = sources.map(source => source.document)\nconst server = new ApolloServer({ typeDefs, resolvers })\n```\n\n```text\nconst schema = loadSchemaSync(join(__dirname, \"schema.graphql\"), {\n loaders: [new GraphQLFileLoader()],\n});\n\nconst resolvers = {...};\nconst schemaWithResolvers = addResolversToSchema({\n schema,\n resolvers,\n});\nconst server = new ApolloServer({ schema: schemaWithResolvers })\n```\n\n```text\nloadSchemaSync\n```\n\n```text\nGraphQLSchema\n```\n\n```text\nloadTypedefsSync\n```\n\n```text\nloadSchema\n```\n\n```text\nmakeExecutableSchema\n```\n\n========================================\n\nComments:\n- If you are using babel to transpile your code, I think you can import directly your schema file like: `import yourSchema from \"./path/to/yourSchema.graphql\";` by the support of the plugin `babel-plugin-import-graphql`\n- Just to be clear: are you saying use loadTypedefsSync and then pass schemaSource to the new ApolloServer? I have tried that as well without success. I tried loadSchema and loadSchemaSync. I tried addResolversToSchema and passing that to the server. No luck. I keep getting the typeDefs must be a string error.\n- If you use loadSchema and addResolversToSchema, you should pass the schema like this: `new ApolloServer({ schema: schemaWithResolvers })`. Please see the edit for additional details.\n- I must have a typo or something that I'm not seeing. I commented out all of my code and copied and pasted yours in and it works. But for the life of me I can't see the difference in the code... ha must be something though. Thank you very much for the help!\n- It is worth noting here that addResolversToSchema() requires you to pass \"schema\". I was passing \"sources\". It was my understanding that variable names were irrelevant, but that seems to not be the case. That is where part of my problem was coming from.\n- Variable names are irrelevant, but in this case you are passing in an object literal, not a variable, and using shorthand notation.\n- Ahhh right, of course. Thanks for pointing that out.","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":243,"estimatedTokens":1590}}1127{"id":"stack-63054130","source":"stackoverflow","questionId":63054130,"title":"The best way to pass authorization header in nextJs using Apollo client? ReferenceError: localStorage is not defined","tags":["javascript","reactjs","graphql","next.js","apollo-client"],"text":"Title: The best way to pass authorization header in nextJs using Apollo client? ReferenceError: localStorage is not defined\nTags: javascript, reactjs, graphql, next.js, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI am trying to fetch protected resource from my graphql server using nextJs and apollo client. I stored the authorization token in the client browser (localstorage) and try to read the token from apolloClient.Js file; but it throws a ReferenceError (***ReferenceError: localStorage is not defined***). This makes me to understand quickly that the server side was trying to reference localStorage from the backend; but fails because it is only available in the client. My question is, what is the best way to solve this issue? I am just using apollo client for the first time in my project. I have spent more than 10 hours trying to figure out the solution to this problem. I have tried so many things on web; not lucky to get the solution. Here is the code am using in apolloClient file:\n\n```\nimport { useMemo } from 'react'\nimport { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'\nimport { concatPagination } from '@apollo/client/utilities'\nimport { GQL_URL } from '../utils/api'\n\nlet apolloClient\n\nconst authToken = localStorage.getItem('authToken') || '';\n\nfunction createApolloClient() {\n return new ApolloClient({\n ssrMode: typeof window === 'undefined',\n link: new HttpLink({\n uri: GQL_URL, // Server URL (must be absolute)\n credentials: 'include', // Additional fetch() options like `credentials` or `headers`\n headers: {\n Authorization: `JWT ${authToken}`\n }\n\n }),\n\n \n cache: new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n allPosts: concatPagination(),\n },\n },\n },\n }),\n })\n}\n\nexport function initializeApollo(initialState = null) {\n const _apolloClient = apolloClient ?? createApolloClient()\n\n // If your page has Next.js data fetching methods that use Apollo Client, the initial state\n // gets hydrated here\n if (initialState) {\n _apolloClient.cache.restore(initialState)\n }\n // For SSG and SSR always create a new Apollo Client\n if (typeof window === 'undefined') return _apolloClient\n // Create the Apollo Client once in the client\n if (!apolloClient) apolloClient = _apolloClient\n\n return _apolloClient\n}\n\nexport function useApollo(initialState) {\n const store = useMemo(() => initializeApollo(initialState), [initialState])\n return store\n}\n```\n\n========================================\n\nTop Answer:\nI can see this issue has been solved. But only partially. Right now this is fine for making authorized client-side queries but if someone is trying to make an **authorized** query on the server-side, then this would be an issue as it doesn't have access to local storage.\n\nSo modifying this :\n\n```\n//AUTH_TOKEN is the name you've set for your cookie\n\nlet apolloClient;\n\nconst httpLink = createHttpLink({\n uri: //Your URL,\n});\n\nconst getAuthLink = (ctx) => {\n return setContext((_, { headers }) => {\n return {\n headers: {\n ...headers,\n authorization: isSSR()\n ? ctx?.req?.cookies[AUTH_TOKEN] // server-side auth token\n : getPersistedAuthToken(), /* This is your auth token from \n localstorage */\n },\n };\n });\n};\n\nfunction createApolloClient(ctx) {\n return new ApolloClient({\n ssrMode: typeof window === undefined,\n link: from([getAuthLink(ctx), httpLink]),\n cache: new InMemoryCache(),\n });\n}\n\nexport function initializeApollo({ initialState = null, ctx = null }) {\n const _apolloClient = apolloClient ?? createApolloClient(ctx);\n if (initialState) {\n const existingCache = _apolloClient.extract();\n _apolloClient.cache.restore({ ...existingCache, ...initialState });\n }\n if (isSSR()) return _apolloClient;\n if (!apolloClient) apolloClient = _apolloClient;\n return _apolloClient;\n}\n```\n\nThe getServerSide function would look like this:\n\n```\nexport async function getServerSideProps(ctx) {\n const { req } = ctx;\n if (req?.cookies[AUTH_TOKEN]) {\n const apolloClient = initializeApollo({ initialState: null, ctx });\n try {\n const { data } = await apolloClient.query({\n query: GET_USER_DETAILS,\n });\n // Handle what you want to do with this data / Just cache it\n } catch (error) {\n const gqlError = error.graphQLErrors[0];\n if (gqlError) {\n //Handle your error cases\n }\n }\n }\n return {\n props: {},\n };\n}\n```\n\nThis way the apollo client can be used to make **authorized** calls on the server-side as well.\n\n========================================\n\nCode:\n```text\nimport { useMemo } from 'react'\nimport { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'\nimport { concatPagination } from '@apollo/client/utilities'\nimport { GQL_URL } from '../utils/api'\n\nlet apolloClient\n\nconst authToken = localStorage.getItem('authToken') || '';\n\nfunction createApolloClient() {\n return new ApolloClient({\n ssrMode: typeof window === 'undefined',\n link: new HttpLink({\n uri: GQL_URL, // Server URL (must be absolute)\n credentials: 'include', // Additional fetch() options like `credentials` or `headers`\n headers: {\n Authorization: `JWT ${authToken}`\n }\n\n }),\n\n \n cache: new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n allPosts: concatPagination(),\n },\n },\n },\n }),\n })\n}\n\nexport function initializeApollo(initialState = null) {\n const _apolloClient = apolloClient ?? createApolloClient()\n\n // If your page has Next.js data fetching methods that use Apollo Client, the initial state\n // gets hydrated here\n if (initialState) {\n _apolloClient.cache.restore(initialState)\n }\n // For SSG and SSR always create a new Apollo Client\n if (typeof window === 'undefined') return _apolloClient\n // Create the Apollo Client once in the client\n if (!apolloClient) apolloClient = _apolloClient\n\n return _apolloClient\n}\n\nexport function useApollo(initialState) {\n const store = useMemo(() => initializeApollo(initialState), [initialState])\n return store\n}\n```\n\n```text\nimport { useMemo } from 'react'\nimport { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';\nimport { setContext } from '@apollo/client/link/context';\nimport { GQL_URL } from '../utils/api'\n\nlet apolloClient\n\nfunction createApolloClient() {\n // Declare variable to store authToken\n let token;\n \n const httpLink = createHttpLink({\n uri: GQL_URL,\n credentials: 'include',\n });\n\n const authLink = setContext((_, { headers }) => {\n // get the authentication token from local storage if it exists\n if (typeof window !== 'undefined') {\n token = localStorage.getItem('authToken');\n }\n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n Authorization: token ? `JWT ${token}` : \"\",\n }\n }\n });\n\n const client = new ApolloClient({\n ssrMode: typeof window === 'undefined',\n link: authLink.concat(httpLink),\n cache: new InMemoryCache()\n });\n\n return client;\n}\n```\n\n```text\n//AUTH_TOKEN is the name you've set for your cookie\n\nlet apolloClient;\n\nconst httpLink = createHttpLink({\n uri: //Your URL,\n});\n\nconst getAuthLink = (ctx) => {\n return setContext((_, { headers }) => {\n return {\n headers: {\n ...headers,\n authorization: isSSR()\n ? ctx?.req?.cookies[AUTH_TOKEN] // server-side auth token\n : getPersistedAuthToken(), /* This is your auth token from \n localstorage */\n },\n };\n });\n};\n\nfunction createApolloClient(ctx) {\n return new ApolloClient({\n ssrMode: typeof window === undefined,\n link: from([getAuthLink(ctx), httpLink]),\n cache: new InMemoryCache(),\n });\n}\n\nexport function initializeApollo({ initialState = null, ctx = null }) {\n const _apolloClient = apolloClient ?? createApolloClient(ctx);\n if (initialState) {\n const existingCache = _apolloClient.extract();\n _apolloClient.cache.restore({ ...existingCache, ...initialState });\n }\n if (isSSR()) return _apolloClient;\n if (!apolloClient) apolloClient = _apolloClient;\n return _apolloClient;\n}\n```\n\n```text\nexport async function getServerSideProps(ctx) {\n const { req } = ctx;\n if (req?.cookies[AUTH_TOKEN]) {\n const apolloClient = initializeApollo({ initialState: null, ctx });\n try {\n const { data } = await apolloClient.query({\n query: GET_USER_DETAILS,\n });\n // Handle what you want to do with this data / Just cache it\n } catch (error) {\n const gqlError = error.graphQLErrors[0];\n if (gqlError) {\n //Handle your error cases\n }\n }\n }\n return {\n props: {},\n };\n}\n```\n\n========================================\n\nComments:\n- Are you getting the error on the server or on the client?\n- The error is from the server!\n- please post your server code as well\n- I mean the server side of next js; no error from my graphql server\n- Did you find a solution to this? I haven't been able to add authorization header because the Apollo Client instance created in the server is passed to the client, and you can't access any of the cookies or localstorage in the server.\n- Yes, I solved it; I just forgot to post it here.... Let me post my solution here for the sake of others that might run into similar issue.","metadata":{"transformedAt":"2026-08-18T18:32:36.229Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":317,"estimatedTokens":2291}}1128{"id":"stack-64405463","source":"stackoverflow","questionId":64405463,"title":"How to restrict api call by useQuery to be called only once?","tags":["reactjs","graphql","react-apollo","apollo-client"],"text":"Title: How to restrict api call by useQuery to be called only once?\nTags: reactjs, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI've following component, which has a `date` variable. On each re render, `date` variable is getting updated. Now the the problem is as I've assigned date to a query variable, graphql fetches again and again infinitely. I have debugged the code and found apollo is Observing on `date` variable, when it is receiving a new value, it is to re.\n\n```\nimport React from 'react';\nimport { getISODate } from '../../dateUtils';\nimport { useQuery } from '@apollo/react-hooks';\nimport { GET_EXPENSE_STATUS } from '../../queries';\nimport get from 'lodash/get';\n\nconst ExpenseStatus = (props) => {\n const date = getISODate(); // returns current date as ISO String Format\n const { loading, error, data } = useQuery(GET_EXPENSE_STATUS, {\n variables: {\n date\n }\n });\n if (error) return Error :(\n\n;\n return(\n \n {get(data, 'expenseStatus.value')}\n \n );\n};\n```\n\nI also tried with `useLazyQuery`. But no luck.\n\n```\nconst date = getISODate(); // returns current date in ISO String\n\n const [loadExpenseStatus, { loading, error, data }] = useLazyQuery(GET_EXPENSE_STATUS, {\n variables: {\n date\n }\n });\n\n useEffect(() => {\n if(!called) {\n loadExpenseStatus();\n }\n }, []);\n```\n\nSo, Is there any way, I can skip this Observer? I just want to receive the fetch call once.\n\n========================================\n\nCode:\n```text\nimport React from 'react';\nimport { getISODate } from '../../dateUtils';\nimport { useQuery } from '@apollo/react-hooks';\nimport { GET_EXPENSE_STATUS } from '../../queries';\nimport get from 'lodash/get';\n\nconst ExpenseStatus = (props) => {\n const date = getISODate(); // returns current date as ISO String Format\n const { loading, error, data } = useQuery(GET_EXPENSE_STATUS, {\n variables: {\n date\n }\n });\n if (error) return <p>Error :(</p>;\n return(\n <div>\n {get(data, 'expenseStatus.value')}\n </div>\n );\n};\n```\n\n```text\nconst date = getISODate(); // returns current date in ISO String\n\n const [loadExpenseStatus, { loading, error, data }] = useLazyQuery(GET_EXPENSE_STATUS, {\n variables: {\n date\n }\n });\n\n useEffect(() => {\n if(!called) {\n loadExpenseStatus();\n }\n }, []);\n```\n\n```text\ndate\n```\n\n```text\ndate\n```\n\n```text\ndate\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nconst [staticDate] = useState( getISODate() );\nconst { loading, error, data } = useQuery(GET_EXPENSE_STATUS, {\n variables: {\n date: staticDate\n }\n});\n```\n\n```text\nconst [loadExpenseStatus, { loading, error, data }] = useLazyQuery(GET_EXPENSE_STATUS);\n\nuseEffect(() => {\n loadExpenseStatus( {\n variables: {\n date: getISODate()\n }\n } );\n}, []); // called once\n```\n\n```text\nconst [date] = useState( getISODate() );\n```\n\n```text\nvariables: { date }\n```\n\n```text\ndate\n```\n\n========================================\n\nComments:\n- possible duplicate of this question stackoverflow.com/questions/56964838/…\n- you can also use `const [staticDate] = useState( getISODate() )` - fired once - as variables params (`date: staticDate`)\n- you don't need lodash to prevent undefined data .. just use `if(loading) return \"loading\";` before main return\n- Its not duplicate :)\n- Is there any alternative other than introducing a state variable? @xdam. I am aware of loading part. But I don't want that\n- state was 2nd alternative ... did you tested earlier one? ... return null (instead of any loading content)? ... or simple `{data && data.expenseStatus.value}`?\n- Yes, I tried variables: { date: getISODate() } but did not help\n- ... then no ... use state or useLazyQuery but define variables inside effect (loadExpenseStatus arg), no `!called` condition required\n- @GregBrodzik I'm affraid in this case (date=null) it wouldn't work at all ... no value preserved from earlier render (useState required for that in FC) ... or would be stopped until updated on external rerendering reason (no 'state update' to force rerendering)\n- @xadm you are absolutely correct. Still believe your initial recomendation to freeze with useState is the best solution.\n- I was looking for the 2nd option. Thanks","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":157,"estimatedTokens":1044}}1129{"id":"stack-62752716","source":"stackoverflow","questionId":62752716,"title":"Add many to many connection in amplify graphql","tags":["graphql","many-to-many","aws-amplify"],"text":"Title: Add many to many connection in amplify graphql\nTags: graphql, many-to-many, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI have a time consuming problem and no idea what I can test more.\nThis is working, but I need the in Recruiter for positions an array. But then I have a many to many connection and nothing is working anymore. Is there a nice way to solve it?\nHere is my code:\n\n```\ntype Position @model @auth(rules: []) {\n id: ID!\n title: String!\n candidates: [Candidate]! @connection(name: \"PositionCandidates\")\n interestedRecruiters: [Recruiter]! @connection(name: \"PositionRecruiter\")\n}\ntype Candidate @model @auth(rules: []) {\n id: ID!\n firstname: String!\n lastname: String!\n email: AWSEmail!\n birthday: AWSDate!\n position: Position! @connection(name: \"PositionCandidates\")\n}\ntype Recruiter @model @auth(rules: []) {\n id: ID!\n firstname: String!\n lastname: String!\n email: AWSEmail!\n birthday: AWSDate!\n positions: Position! @connection(name: \"PositionRecruiter\")\n}\n```\n\nthanks !\n\n========================================\n\nCode:\n```text\ntype Position @model @auth(rules: []) {\n id: ID!\n title: String!\n candidates: [Candidate]! @connection(name: \"PositionCandidates\")\n interestedRecruiters: [Recruiter]! @connection(name: \"PositionRecruiter\")\n}\ntype Candidate @model @auth(rules: []) {\n id: ID!\n firstname: String!\n lastname: String!\n email: AWSEmail!\n birthday: AWSDate!\n position: Position! @connection(name: \"PositionCandidates\")\n}\ntype Recruiter @model @auth(rules: []) {\n id: ID!\n firstname: String!\n lastname: String!\n email: AWSEmail!\n birthday: AWSDate!\n positions: Position! @connection(name: \"PositionRecruiter\")\n}\n```\n\n```text\ntype User @model {\n id: ID!\n name: String\n documents: [UserDocument] @connection(name: \"UserDocumentConnection\")\n}\n\ntype Document @model {\n id: ID!\n title: String\n content: String\n users: [UserDocument] @connection(name: \"DocumentUserConnection\")\n}\n\ntype UserDocument @model {\n id: ID!\n user: User @connection(name: \"UserDocumentConnection\")\n document: Document @connection(name: \"DocumentUserConnection\")\n}\n```\n\n========================================\n\nComments:\n- Do you have a solution to add amplify auth protections to the above schema? I've been working at that for awhile and can't seem to figure it out and instead i'm rolling with a custom role's object but its dirty and I don't care for it much.\n- Hey Engam, I have a similar issue to this, but this solution no longer works due to the updates in AWS Amplify. Could you please take a look? I'd really appreciate it! stackoverflow.com/q/73421399/8304719","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":90,"estimatedTokens":650}}1130{"id":"stack-59590186","source":"stackoverflow","questionId":59590186,"title":"GraphQL fragment of fragments","tags":["javascript","graphql"],"text":"Title: GraphQL fragment of fragments\nTags: javascript, graphql\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQL query like this:\n\n```\nimport { gql } from 'apollo-boost';\n\nexport default gql`\n {\n pageHomeCollection(limit: 1) {\n items {\n navigationLinkLeft {\n ... on PageBasic {\n slug\n title\n }\n ... on PageShop {\n title\n }\n ... on PostCollection {\n slug\n title\n }\n }\n navigationLinkRight {\n ... on PageBasic {\n slug\n title\n }\n ... on PageShop {\n title\n }\n ... on PostCollection {\n slug\n title\n }\n }\n title\n }\n }\n }\n`;\n```\n\nThe requested data for both `navigationLinkLeft` and `navigationLinkRight` are the same, so I'd like to avoid the duplication. I know about fragments, but not sure if it's possible to extract the 3 `... on` because I'm not sure what type the fragment would be. Is this possible?\n\n========================================\n\nCode:\n```text\nimport { gql } from 'apollo-boost';\n\nexport default gql`\n {\n pageHomeCollection(limit: 1) {\n items {\n navigationLinkLeft {\n ... on PageBasic {\n slug\n title\n }\n ... on PageShop {\n title\n }\n ... on PostCollection {\n slug\n title\n }\n }\n navigationLinkRight {\n ... on PageBasic {\n slug\n title\n }\n ... on PageShop {\n title\n }\n ... on PostCollection {\n slug\n title\n }\n }\n title\n }\n }\n }\n`;\n```\n\n```text\nnavigationLinkLeft\n```\n\n```text\nnavigationLinkRight\n```\n\n```text\n... on\n```\n\n```text\n{\n pageHomeCollection(limit: 1) {\n items {\n navigationLinkLeft {\n ...YourFragment\n }\n navigationLinkRight {\n ...YourFragment\n }\n title\n }\n}\n\nfragment YourFragment on SomeInterfaceOrUnionType {\n ... on PageBasic {\n slug\n title\n }\n ... on PageShop {\n title\n }\n ... on PostCollection {\n slug\n title\n }\n}\n```\n\n```text\n{\n pageHomeCollection(limit: 1) {\n items {\n navigationLinkLeft {\n ...NavigationLinkLeftFragment\n }\n navigationLinkRight {\n ...NavigationLinkRightFragment\n }\n title\n }\n}\n\nfragment NavigationLinkLeftFragment on PageHomeNavigationLinkLeft {\n ...PageBasicFragment\n ...PageShopFragment\n ...PostCollectionFragment\n}\n\nfragment NavigationLinkRightFragment on NavigationLinkRight {\n ...PageBasicFragment\n ...PageShopFragment\n ...PostCollectionFragment\n}\n\nfragment PageBasicFragment on PageBasic {\n slug\n title\n}\n\nfragment PageShopFragment on PageShop {\n title\n}\n\nfragment PostCollectionFragment on PostCollection {\n slug\n title\n}\n```\n\n```text\nnavigationLinkLeft {\n ...PageBasicFragment\n ...PageShopFragment\n ...PostCollectionFragment\n}\nnavigationLinkRight {\n ...PageBasicFragment\n ...PageShopFragment\n ...PostCollectionFragment\n}\n```\n\n```text\nnavigationLinkLeft\n```\n\n```text\nnavigationLinkRight\n```\n\n```text\nnavigationLinkLeft\n```\n\n```text\nnavigationLinkRight\n```\n\n========================================\n\nComments:\n- Does this answer your question? Using GraphQL Fragment on multiple types\n- Sorry for the late reply. So I figured you could do this but wasn't sure what `SomeInterfaceOrUnionType` would need to be in this case. Each of the 3 things in the fragment are their own types.\n- @Coop you need to check the schema you're querying to determine what the type is for the `navigationLinkLeft` field. If you didn't write the schema yourself, you can check the docs in GraphiQL or GraphQL Playground, or use introspection.\n- Righty. So GraphiQL is telling me the 3 potential datasets on navigationLeftLink are of type `PageHomeNavigationLinkLeft` and the 3 on navigationLinkRight are of type `NavigationLinkRight`. So is it still possible to achieve what I want when the types are different?\n- @Coop Sorry, I misunderstood your comment. If the types are different, then, no you won't be able to do DRY things up as much. Please see my edit.","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":211,"estimatedTokens":990}}1131{"id":"stack-60794161","source":"stackoverflow","questionId":60794161,"title":"Apollo Server: How can I add a custom endpoint for Stripe webhook?","tags":["node.js","graphql","apollo-server"],"text":"Title: Apollo Server: How can I add a custom endpoint for Stripe webhook?\nTags: node.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI have a graphql server that I want to add a custom endpoint for so that Stripe can communicate with it when a customer's Subscription status changes.\n\nCurrently, my index.js file looks like a typical Apollo Server set up:\n\n```\nimport { ApolloServer } from \"apollo-server\";\nimport { connectDb } from \"./models\";\n\nimport schema from \"./schema\";\nimport resolvers from \"./resolvers\";\nimport contexts from \"./contexts\";\n\nconst server = new ApolloServer({\n typeDefs: schema,\n resolvers,\n context: async ({ req }) => {\n const { getCurrentUser } = contexts;\n\n const currentUser = await getCurrentUser(req);\n return { models, currentUser };\n },\n});\n\nconnectDb().then(async () => {\n server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {\n console.log(`π Server ready at ${url}`);\n });\n});\n```\n\nSo only `/graphql` is exposed.\n\nHow would I add a custom `POST /foobar` endpoint that does something similar to this? (source: https://stripe.com/docs/webhooks/build#example-code)\n\n```\n// This example uses Express to receive webhooks\nconst app = require('express')();\n\n// Use body-parser to retrieve the raw body as a buffer\nconst bodyParser = require('body-parser');\n\n// Match the raw body to content type application/json\napp.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {\n let event;\n\n try {\n event = JSON.parse(request.body);\n } catch (err) {\n response.status(400).send(`Webhook Error: ${err.message}`);\n }\n\n // Handle the event\n switch (event.type) {\n case 'payment_intent.succeeded':\n const paymentIntent = event.data.object;\n // Then define and call a method to handle the successful payment intent.\n // handlePaymentIntentSucceeded(paymentIntent);\n break;\n case 'payment_method.attached':\n const paymentMethod = event.data.object;\n // Then define and call a method to handle the successful attachment of a PaymentMethod.\n // handlePaymentMethodAttached(paymentMethod);\n break;\n // ... handle other event types\n default:\n // Unexpected event type\n return response.status(400).end();\n }\n\n // Return a response to acknowledge receipt of the event\n response.json({received: true});\n});\n\napp.listen(8000, () => console.log('Running on port 8000'));\n```\n\n========================================\n\nTop Answer:\nhere's how I set this up for anyone who stumbles on this. I'm using `apollo-server-express`:\n\n```\nimport express from 'express';\nimport { createServer } from 'http';\nimport { pinoLogger } from './lib/logger.js';\nimport { graphql } from './api/graphql/server.js';\n\nconst PORT = process.env.PORT || 5001;\n\nconst app = express();\nconst httpServer = createServer(app);\n\n// this is where I set up the ApolloServer with it's resolvers and schema\ngraphql({ app, httpServer });\n\napp.post('/webhooks/stripe', async (req, res) => {\n const event = req.body;\n const logger = pinoLogger.child({ stripeEventId: event.id });\n logger.info('Received stripe event', { event });\n res.sendStatus(200);\n})\n\nhttpServer.listen(PORT, () => {\n pinoLogger.info(`Server running at http://localhost:${PORT}/graphql`);\n});\n```\n\n========================================\n\nCode:\n```text\nimport { ApolloServer } from \"apollo-server\";\nimport { connectDb } from \"./models\";\n\nimport schema from \"./schema\";\nimport resolvers from \"./resolvers\";\nimport contexts from \"./contexts\";\n\nconst server = new ApolloServer({\n typeDefs: schema,\n resolvers,\n context: async ({ req }) => {\n const { getCurrentUser } = contexts;\n\n const currentUser = await getCurrentUser(req);\n return { models, currentUser };\n },\n});\n\nconnectDb().then(async () => {\n server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {\n console.log(`π Server ready at ${url}`);\n });\n});\n```\n\n```text\n// This example uses Express to receive webhooks\nconst app = require('express')();\n\n// Use body-parser to retrieve the raw body as a buffer\nconst bodyParser = require('body-parser');\n\n// Match the raw body to content type application/json\napp.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {\n let event;\n\n try {\n event = JSON.parse(request.body);\n } catch (err) {\n response.status(400).send(`Webhook Error: ${err.message}`);\n }\n\n // Handle the event\n switch (event.type) {\n case 'payment_intent.succeeded':\n const paymentIntent = event.data.object;\n // Then define and call a method to handle the successful payment intent.\n // handlePaymentIntentSucceeded(paymentIntent);\n break;\n case 'payment_method.attached':\n const paymentMethod = event.data.object;\n // Then define and call a method to handle the successful attachment of a PaymentMethod.\n // handlePaymentMethodAttached(paymentMethod);\n break;\n // ... handle other event types\n default:\n // Unexpected event type\n return response.status(400).end();\n }\n\n // Return a response to acknowledge receipt of the event\n response.json({received: true});\n});\n\napp.listen(8000, () => console.log('Running on port 8000'));\n```\n\n```text\n/graphql\n```\n\n```text\nPOST /foobar\n```\n\n```text\napollo-server\n```\n\n```text\napollo-server-express\n```\n\n```js\nimport express from 'express';\nimport { createServer } from 'http';\nimport { pinoLogger } from './lib/logger.js';\nimport { graphql } from './api/graphql/server.js';\n\nconst PORT = process.env.PORT || 5001;\n\nconst app = express();\nconst httpServer = createServer(app);\n\n// this is where I set up the ApolloServer with it's resolvers and schema\ngraphql({ app, httpServer });\n\napp.post('/webhooks/stripe', async (req, res) => {\n const event = req.body;\n const logger = pinoLogger.child({ stripeEventId: event.id });\n logger.info('Received stripe event', { event });\n res.sendStatus(200);\n})\n\nhttpServer.listen(PORT, () => {\n pinoLogger.info(`Server running at http://localhost:${PORT}/graphql`);\n});\n```\n\n```text\napollo-server-express\n```\n\n```text\nimport { ApolloServer } from '@apollo/server';\nimport { expressMiddleware } from '@apollo/server/express4';\nimport cors from 'cors';\nimport express from 'express';\n\nconst app = express();\n\nconst server = new ApolloServer<MyContext>({\n typeDefs,\n resolvers,\n});\n// Note you must call `start()` on the `ApolloServer`\n// instance before passing the instance to `expressMiddleware`\nawait server.start();\n\n// Specify the path where we'd like to mount our server\napp.use('/graphql', cors<cors.CorsRequest>(), express.json(), expressMiddleware(server));\n```\n\n```text\napollo-server-express\n```\n\n```text\nexpressMiddleware\n```\n\n========================================\n\nComments:\n- Awesome Iβll look into that. Thanks!\n- @bigpatato hi can you help me abput this question ? i want to the same :/ and i cant add spesific endpoint my apollo server","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":262,"estimatedTokens":1711}}1132{"id":"stack-52750446","source":"stackoverflow","questionId":52750446,"title":"Apollo Server 2 + Express: req.body missing on post handler","tags":["graphql","apollo-server"],"text":"Title: Apollo Server 2 + Express: req.body missing on post handler\nTags: graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nHad this working in version 1, but the whole server config has changed. This is what I have, after adding bodyparser() to the express app as was suggested by Daniel in the comments:\n\n```\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n playground: {\n settings: {\n 'editor.theme': 'light',\n }\n },\n})\n\n// Initialize the app\nconst app = express();\napp.use(cors())\napp.use(bodyParser.json())\n\nserver.applyMiddleware({\n app\n})\n\napp.post('/calc', function(req, res){\n const {body} = req;\n\n console.log(\"HOWDYHOWDYHOWDY\", body) // res.send(result))\n .catch(e => res.status(400).send({error: e.toString()})) \n})\n```\n\nThe request body is never making it to the app.post handler, though the handler is called. I see it going out from the browser, though. Any ideas?\n\n**Update:** Daniel had the correct answer, but I had another problem in the request headers I was using. Once I fixed that, then the post handler received the body.\n\n========================================\n\nTop Answer:\nI just ran into this as well. Fixed it by passing the following into the headers:\n\n```\nContent-Type: application/json\n```\n\n========================================\n\nCode:\n```text\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n playground: {\n settings: {\n 'editor.theme': 'light',\n }\n },\n})\n\n// Initialize the app\nconst app = express();\napp.use(cors())\napp.use(bodyParser.json())\n\nserver.applyMiddleware({\n app\n})\n\napp.post('/calc', function(req, res){\n const {body} = req;\n\n console.log(\"HOWDYHOWDYHOWDY\", body) // <== body is {}\n\n res.setHeader('content-type', 'application/json')\n\n calculate(body)\n .then(result => res.send(result))\n .catch(e => res.status(400).send({error: e.toString()})) \n})\n```\n\n```text\napp.use(bodyParser.json())\napp.post('/calc', routeHandler)\n\n// or...\napp.post('/calc', bodyParser.json(), routeHandler)\n```\n\n```text\nreq.body\n```\n\n```text\nContent-Type: application/json\n```\n\n```text\nexpressMiddleware\n```\n\n```text\nconst { expressMiddleware } = require(\"@as-integrations/express5\");\n```\n\n```text\nimport {expressMiddleware } from \" @as-integrations/express5 \"\n```\n\n========================================\n\nComments:\n- I appreciate your response, Daniel. I did what you suggested, and will update my original post. Now I get an empty JSON object, instead of undefined. Better? So I am a little surprised that the req.body would be empty without bodyparser middleware attached to the app--I would expect a text body. Without bodyparser.json() = undefined; with = {}\n- req.body is undefined by default (see express docs: expressjs.com/en/4x/api.html#req.body) You may need to select the appropriate parser to see the body populated correctly, depending on what you're sending. See this answer (stackoverflow.com/a/47486182/6024220) and the body-parser docs for more details. Also be aware that if you're using a multipart bodies, you'll need a different library like multer instead.\n- Okay, learned something. I am calling the correct bodyparser, so that's not the problem. Other people are having similar issues it seems. Can't find a direct corollary with what I'm trying to do here, but when I find an answer I will post it.\n- You could also just try moving your `/calc` route above your `applyMiddleware` call, so it's called and terminated before apollo does anything to your request.\n- yes, I did try that, to no effect. BUT... turns out I had an fault with the request headers in my client code (a line I forgot to delete), so that was the second issue. Now, no matter where the post handler is placed, I see a body (finally!). Marking your response as the answer. Thanks again.","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":120,"estimatedTokens":952}}1133{"id":"stack-56154360","source":"stackoverflow","questionId":56154360,"title":"Undefined args on a mutation, using apollo-server","tags":["express","graphql","apollo-server"],"text":"Title: Undefined args on a mutation, using apollo-server\nTags: express, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nIm working with apollo-server, everything works as expetected but the mutation arguments are undefined when the mutation is called from the frontend.\n\n```\nconst express = require('express');\nconst morgan = require('morgan');\nconst { ApolloServer, gql } = require('apollo-server-express');\nconst mongoose = require('mongoose');\nrequire('dotenv').config();\n\nconst app = express();\n\nconst typeDefs = gql`\n type msgFields {\n email: String!\n textarea: String!\n createdAt: String!\n }\n\n input MsgFieldsInput {\n email: String!\n textarea: String!\n createdAt: String!\n }\n\n type Query {\n formContact: msgFields!\n }\n\n type Mutation {\n createMsg(email: String!, textarea: String!, createdAt: String!): String!\n }\n\n`;\n\nconst resolvers = {\n Query: {\n formContact: () => {\n return {\n email: 'test@mail.com',\n textarea: 'checking Checking checking Checking checking Checking'\n } \n }\n },\n Mutation: {\n createMsg: (args) => {\n console.log(args); // => undefined here\n return 'Worked';\n }\n }\n}\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers\n});\n\napp.use(morgan('dev'));\n\nserver.applyMiddleware({app})\n\nmongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true })\n .then(() => {\n app.listen({port: 4000}, () => {\n console.log(`Server and DB ready at http://localhost:4000${server.graphqlPath}`)\n });\n })\n .catch(err => {\n throw err;\n })\n```\n\nThis is what i send from /graphql\nmutation {\n createMsg(email: \"test@mail.com\" textarea: \"testing textarea\" createdAt: \"19-05-2018\")\n}\n\n========================================\n\nCode:\n```text\nconst express = require('express');\nconst morgan = require('morgan');\nconst { ApolloServer, gql } = require('apollo-server-express');\nconst mongoose = require('mongoose');\nrequire('dotenv').config();\n\nconst app = express();\n\nconst typeDefs = gql`\n type msgFields {\n email: String!\n textarea: String!\n createdAt: String!\n }\n\n input MsgFieldsInput {\n email: String!\n textarea: String!\n createdAt: String!\n }\n\n type Query {\n formContact: msgFields!\n }\n\n type Mutation {\n createMsg(email: String!, textarea: String!, createdAt: String!): String!\n }\n\n`;\n\nconst resolvers = {\n Query: {\n formContact: () => {\n return {\n email: 'test@mail.com',\n textarea: 'checking Checking checking Checking checking Checking'\n } \n }\n },\n Mutation: {\n createMsg: (args) => {\n console.log(args); // => undefined here\n return 'Worked';\n }\n }\n}\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers\n});\n\n\napp.use(morgan('dev'));\n\nserver.applyMiddleware({app})\n\nmongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true })\n .then(() => {\n app.listen({port: 4000}, () => {\n console.log(`Server and DB ready at http://localhost:4000${server.graphqlPath}`)\n });\n })\n .catch(err => {\n throw err;\n })\n```\n\n```text\n(parent, args, context, info)\n```\n\n========================================\n\nComments:\n- `info` is undefined. What could be the possible reason? Also, `parent` is also undefined.\n- @Ilyaskarim Please post a new question with the relevant code\n- Please see stackoverflow.com/questions/57136618/…. It could be great if you could give a minute to see the problem.\n- For me, all tricks failed except one. Close text editor and the API development tool you are using ((I used VS Code & Insomnia). Then restart again.","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":165,"estimatedTokens":868}}1134{"id":"stack-56141456","source":"stackoverflow","questionId":56141456,"title":"How do you use useMutation from react-apollo-hook to execute a delete mutation?","tags":["reactjs","graphql","react-apollo","react-hooks","react-apollo-hooks"],"text":"Title: How do you use useMutation from react-apollo-hook to execute a delete mutation?\nTags: reactjs, graphql, react-apollo, react-hooks, react-apollo-hooks\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use the `useMutation` hook from `react-apollo-hook`s to execute a delete mutation, but I'm having difficulty passing the ID value of the post to the mutation hook in the following code:\n\n```\nconst Posts = () => {\n const { data, error, loading } = useQuery(GET_POST)\n const onDeleteHandler = useMutation(DELETE_POST, {\n variables: { id }\n })\n if (loading) return ...loading\n if (error) return Error\n\n return data.posts.map(({id, title, body, location, published, author}) => {\n return (\n \n id: {id}\n\n title: {title}\n\n body: {body}\n\n location: {location}\n\n published: {published}\n\n author: {author.name}\n\n \n Edit\n \n \n Delete\n \n \n )\n }) \n}\n```\n\nI cannot include the `useMutation` inside the `onClick()` property since a hook cannot be used as a callback function. I tried using `const inputRef = useRef()` and passing `inputRef.current.value`, but kept getting undefined.\n\n========================================\n\nTop Answer:\nI guess you could do the same with `useQuery()`.\n\n========================================\n\nCode:\n```text\nconst Posts = () => {\n const { data, error, loading } = useQuery(GET_POST)\n const onDeleteHandler = useMutation(DELETE_POST, {\n variables: { id }\n })\n if (loading) return <div>...loading</div>\n if (error) return <div>Error</div>\n\n return data.posts.map(({id, title, body, location, published, author}) => {\n return (\n <div className=\"card\" key={id}>\n <p>id: {id}</p>\n <p>title: {title}</p>\n <p>body: {body}</p>\n <p>location: {location}</p>\n <p>published: {published}</p>\n <p>author: {author.name}</p>\n <Link to={`/post/${id}/edit`}>\n Edit\n </Link>\n <button \n onClick={onDeleteHandler}>\n Delete\n </button>\n </div>\n )\n }) \n}\n```\n\n```text\nuseMutation\n```\n\n```text\nreact-apollo-hook\n```\n\n```text\nuseMutation\n```\n\n```text\nonClick()\n```\n\n```text\nconst inputRef = useRef()\n```\n\n```text\ninputRef.current.value\n```\n\n```text\nconst onDeleteHandler = useMutation(DELETE_POST)\n```\n\n```text\nonClick={() => onDeleteHandler({ variables: { id } })}>\n```\n\n```text\nconst [onDeleteHandler, { data, loading, error }] = useMutation(DELETE_POST)\n```\n\n```text\nreact-apollo-hooks\n```\n\n```text\nuseMutation\n```\n\n```text\nreact-apollo-hooks\n```\n\n```text\nreact-apollo\n```\n\n```text\nuseQuery()\n```\n\n========================================\n\nComments:\n- I tried this implementation but I keep getting the error : `TypeError: onDeleteHandler is not a function` I call useMutation and the handler just as you have it above.\n- @Avery-DanteHinds please see added note\n- Thanks for the update! However I'm still getting errors when I try delete mutations using the react-apollo hooks. `Uncaught (in promise) Error: Network error: Response not successful: Received status code 400` If you get a chance I would appreciate if you checked out my repo. I don't know where I'm at fault in the code. The useQuery hook and createUser useMutation work but I can not figure out how to delete from the UI\n- @Avery-DanteHinds 400 means your mutation is malformed or otherwise invalid. Check the actual response from the server to determine the cause.","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":147,"estimatedTokens":878}}1135{"id":"stack-48069993","source":"stackoverflow","questionId":48069993,"title":"Is it possible to execute a mutation or query locally at server side with Apollo Server","tags":["node.js","express","graphql","apollo-server"],"text":"Title: Is it possible to execute a mutation or query locally at server side with Apollo Server\nTags: node.js, express, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI would like to know if it is possible to execute a mutation or query locally at server side with Apollo Server.\n\nExample:\n\n1- Endpoint GET /createNew is reached\n\n2- I run a mutation I defined like:\n\n```\napolloserver.mutation(mutation_query).then((response)=>{res.status(200)})\n```\n\n3- A new entry is added to the database and a JSON string is returned to client\n\nDoes something like that exist? Is a `apolloserver` object available at runtime?\n\nI'm using NodeJS + Express\n\n========================================\n\nCode:\n```text\napolloserver.mutation(mutation_query).then((response)=>{res.status(200)})\n```\n\n```text\napolloserver\n```\n\n```text\nimport express from 'express';\nimport { graphql } from 'graphql';\nconst context = require('./context'); //this is the object to be passed to each resolver function\nconst schema = require('./schema'); //this is the object returned by makeExecutableSchema({typeDefs, resolvers})\nconst app = express();\n```\n\n```text\napp.get('/execute', function(req, res){\n var query = `\n query myQueryTitle{\n queryName{\n _id,\n ...\n }\n }\n `;\n\n graphql(schema, query, null, context)\n .then((result) => {\n res.json(result.data.queryName);\n });\n})\n```\n\n```text\nGET /execute\n```\n\n```text\ngraphql\n```\n\n```text\nschema\n```\n\n```text\nrequestString\n```\n\n```text\nquery\n```\n\n```text\ncontext\n```\n\n```text\ngraphqlExpress\n```\n\n========================================\n\nComments:\n- While this works, it's not actually executing through Apollo Server but instead, it just uses the execute method in graphql.js. This is fine as long as you don't use any Apollo middleware (such as Apollo Engine) since they won't run in this case.\n- Is there a solution for that problem @PetrBela - I'm looking into a solution like this - and we are using Apolloe Server π
","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":93,"estimatedTokens":507}}1136{"id":"stack-37804970","source":"stackoverflow","questionId":37804970,"title":"How to dynamically change the network layer in Relay","tags":["graphql","relay"],"text":"Title: How to dynamically change the network layer in Relay\nTags: graphql, relay\nSource: Stack Overflow\n\nQuestion:\nI know relay can inject a network layer when bootstrapping like below:\n\n```\nRelay.injectNetworkLayer(\n new Relay.DefaultNetworkLayer('http://example.com/graphql', {\n headers: {\n Authorization: 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ==',\n },\n })\n);\n```\n\nBut how about if I need to tell what the header is later(like after signing in)?\n\n========================================\n\nTop Answer:\nI found a simple trick. You can pass in headers object and update its pointer value.\n\n```\nconst headers = {\n Authorization: '',\n};\n\nRelay.injectNetworkLayer(\n new Relay.DefaultNetworkLayer('http://example.com/graphql', {\n headers: headers,\n })\n);\n\n// To update the authorization, set the field.\n\nheaders.Authorization = 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ=='\n```\n\n========================================\n\nCode:\n```text\nRelay.injectNetworkLayer(\n new Relay.DefaultNetworkLayer('http://example.com/graphql', {\n headers: {\n Authorization: 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ==',\n },\n })\n);\n```\n\n```text\nexport function setNetworkLayer() {\n return new Promise((resolve, reject) => {\n\n var options = {};\n if (localStorage.authToken) {\n options.headers = {\n Authorization: 'Basic ' + localStorage.authToken\n }\n }\n else {\n options.headers = {};\n }\n Relay.injectNetworkLayer(\n new Relay.DefaultNetworkLayer('http://example.com/graphql', options)\n );\n resolve(options);\n });\n })\n}\n```\n\n```text\nloginUser().then((res) => {\n localStorage.authToken = res.token;\n setNetworkLayer();\n return;\n})\n```\n\n```text\nconst headers = {\n Authorization: '',\n};\n\nRelay.injectNetworkLayer(\n new Relay.DefaultNetworkLayer('http://example.com/graphql', {\n headers: headers,\n })\n);\n\n// To update the authorization, set the field.\n\nheaders.Authorization = 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ=='\n```\n\n========================================\n\nComments:\n- This means delay injectNetworkLayer. But how about if I want to setup networkLayer with empty header(anonymous) first, after signing in setup networkLayer with valid token?\n- What you can do is call setNetworkLayer in your first render() function for your app. If there's no authToken detected in localStorage, then it will set the options variable as an empty object, and set the DefaultNetworkLayer with an empty header. And whenever you need to reset the network layer, you can overwrite the localStorage.authToken variable and call setNetworkLayer() again.\n- I tried to call injectNetworkLayer twice, and got warning as: \"RelayNetworkLayer: Call received to injectImplementation(), but a layer was already injected.\". What's more, the new call doesn't take effect, nor did the first call stop working.\n- Looks like that's a warning that will be resolved in the next release: github.com/facebook/relay/issues/1111. For now, try re-rendering the DOM.render() when needed to load the app initially with the network layer auth token from localStorage like so: mgiroux.me/2016/token-auth-in-relay-app-using-rails\n- Actually the issue above is talking about: injectNetworkLayer will cause the warning, even at the very first time in app. So the 0.9 release introduced injectDefaultNetworkLayer which is used only internally to set the default layer to be '/graphql'. However, what the problem we are facing now is we cannot call injectNetworkLayer twice in app.\n- Very handy! How might you go about updating the value from another file?\n- You can export `headers` variable you used in Relay DefaultNetworkLayer, and set the Authorization anywhere. It's the `headers.Authorization =` part, except you do that in different files.","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":109,"estimatedTokens":955}}1137{"id":"stack-45384163","source":"stackoverflow","questionId":45384163,"title":"Merging GraphQL Resolvers for Apollo Server not working with Object.assign()","tags":["node.js","schema","graphql","resolver","apollo-server"],"text":"Title: Merging GraphQL Resolvers for Apollo Server not working with Object.assign()\nTags: node.js, schema, graphql, resolver, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI am modularizing my schema for a GraphQL API and trying to merge the resolvers without using any 3rd party libraries.\n\nIs there a simple way to do this without `Lodash.merge()` or equivalent?\n\nThe Apollo Documentation says to use a library such as Lodash to `merge()` modularized resolvers. (http://dev.apollodata.com/tools/graphql-tools/generate-schema.html#modularizing)\n\nThe problem seems to be that by their nature, the resolvers contain functions as properties, so they seem to be omitted when I access them via `Object.assign()` or even `JSON.stringify()`.\n\nIf I console.log them, I see: `{\"Query\":{},\"Mutation\":{}}`\n\nHere is what one of the resolvers looks like:\n\n```\nconst productResolvers = {\n Query: {\n myProducts: (root, { userId }, context) => {\n return [\n { id: 1, amount: 100, expiry: '12625383984343', created: '12625383984343' },\n { id: 2, amount: 200, expiry: '12561351347311', created: '12625383984343' },\n { id: 3, amount: 200, expiry: '11346347378333', created: '12625383984343' },\n { id: 4, amount: 350, expiry: '23456234523453', created: '12625383984343' },\n ];\n },\n },\n Mutation: {\n addProduct: (root, { userId }, context) => {\n return { id: 350, amount: 100, expiry: '12625383984343', created: '12625383984343' };\n },\n }\n };\n```\n\nLet's assume there is another one virtually identical called `widgetResolvers`.\n\nHere is a fully functional block of code:\n\n```\nexport const schema = makeExecutableSchema({\n typeDefs: [queries, mutations, productSchema, widgetSchema],\n resolvers\n });\n```\n\nHere is what I'm trying to achieve:\n\n```\nexport const schema = makeExecutableSchema({\n typeDefs: [queries, mutations, productSchema, widgetSchema],\n resolvers: Object.assign({}, productResolvers, widgetResolvers)\n });\n```\n\nI haven't loaded in ability to use rest spread yet (https://babeljs.io/docs/plugins/transform-object-rest-spread/). I suspect it won't work for the same reason `Object.assign()` doesn't work.\n\nOh, and here is why I suspect this merge doesn't work: Why doesn't JSON.stringify display object properties that are functions?\n\n========================================\n\nCode:\n```text\nconst productResolvers = {\n Query: {\n myProducts: (root, { userId }, context) => {\n return [\n { id: 1, amount: 100, expiry: '12625383984343', created: '12625383984343' },\n { id: 2, amount: 200, expiry: '12561351347311', created: '12625383984343' },\n { id: 3, amount: 200, expiry: '11346347378333', created: '12625383984343' },\n { id: 4, amount: 350, expiry: '23456234523453', created: '12625383984343' },\n ];\n },\n },\n Mutation: {\n addProduct: (root, { userId }, context) => {\n return { id: 350, amount: 100, expiry: '12625383984343', created: '12625383984343' };\n },\n }\n };\n```\n\n```text\nexport const schema = makeExecutableSchema({\n typeDefs: [queries, mutations, productSchema, widgetSchema],\n resolvers\n });\n```\n\n```text\nexport const schema = makeExecutableSchema({\n typeDefs: [queries, mutations, productSchema, widgetSchema],\n resolvers: Object.assign({}, productResolvers, widgetResolvers)\n });\n```\n\n```text\nLodash.merge()\n```\n\n```text\nmerge()\n```\n\n```text\nObject.assign()\n```\n\n```text\nJSON.stringify()\n```\n\n```text\n{\"Query\":{},\"Mutation\":{}}\n```\n\n```text\nwidgetResolvers\n```\n\n```text\nObject.assign()\n```\n\n```text\nconst productResolver = {\n Query: { ... β ... },\n Mutation: { ... β ... }\n}\n\nconst widgetResolver = {\n Query: { ... β ... },\n Mutation: { ... β ... }\n}\n\nconst resolvers = {\n Query: Object.assign({}, widgetResolver.Query, productResolver.Query),\n Mutation: Object.assign({}, widgetResolver.Mutation, productResolver.Mutation)\n}\n```\n\n```text\nconst Widget = { ... β ... }\nconst Product = { ... β ... }\n\nconst resolvers = Object.assign(\n {\n Query: Object.assign({}, widgetResolver.Query, productResolver.Query),\n Mutation: Object.assign({}, widgetResolver.Mutation, productResolver.Mutation)\n },\n Widget,\n Product)\n```\n\n```text\nObject.assign()\n```\n\n```text\nmerge()\n```\n\n```text\nObject.assign()\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nQuery\n```\n\n```text\nMutation\n```\n\n```text\nObject.assign()\n```\n\n========================================\n\nComments:\n- I am using Lodash `merge()` until further notice. It works well.\n- Thanks, that is extremely helpful.\n- I will keep Lodash because I suspect that non-recursive nature will troll me one day if I use `Object.assign()` just to keep it native.\n- Yup, Lodash is super useful. I think if you look through their docs, you'll find uses for many of the other methods in the library too. If you want to avoid importing the whole library just to use one method, you can also import the methods one module at a time :)","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":195,"estimatedTokens":1218}}1138{"id":"stack-47028793","source":"stackoverflow","questionId":47028793,"title":"Suppress duplicates in GraphQL response","tags":["graphql"],"text":"Title: Suppress duplicates in GraphQL response\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nHow can I merge any duplicate rows I receive in a request response?\n\nI requested the last 200 books that have been viewed by the user and, in the results, I have duplicates.\n\nThe result looks like this:\n\n```\n{\n \"data\": {\n \"view_book\": [\n {\n \"views\": 4,\n \"book\": {\n \"id\": \"26910093\",\n \"title\": \"Book name 1\",\n }\n },\n {\n \"views\": 7,\n \"book\": {\n \"id\": \"26910093\",\n \"title\": \"Book name 1\",\n }\n },\n ]\n }\n}\n```\n\nSo, is it possible to suppress the duplication with GraphQL?\n\n========================================\n\nTop Answer:\nThe answer, unfortunately, is probably, but you shouldn't. GraphQL should remain an implementation on top of whatever your APIs are, and if your data is returning duplicates, GraphQL had better return it, too. If you've got duplicates, you should filter them in your business-logic layer before handing it back to your GraphQL resolvers.\n\n========================================\n\nCode:\n```text\n{\n \"data\": {\n \"view_book\": [\n {\n \"views\": 4,\n \"book\": {\n \"id\": \"26910093\",\n \"title\": \"Book name 1\",\n }\n },\n {\n \"views\": 7,\n \"book\": {\n \"id\": \"26910093\",\n \"title\": \"Book name 1\",\n }\n },\n ]\n }\n}\n```\n\n========================================\n\nComments:\n- but that will require changing the data model which is not feasible or even possible in some cases","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":71,"estimatedTokens":398}}1139{"id":"stack-61913192","source":"stackoverflow","questionId":61913192,"title":"Does Hasura (GraphQL) supports multiple databases?","tags":["graphql","hasura"],"text":"Title: Does Hasura (GraphQL) supports multiple databases?\nTags: graphql, hasura\nSource: Stack Overflow\n\nQuestion:\nI am implementing a GraphQL server (Hasura), the normal setup looks like this:\n\n```\ndocker run -d --net=host \\\n-e HASURA_GRAPHQL_DATABASE_URL=postgres://username:password@hostname:port/dbname \\\n-e HASURA_GRAPHQL_ENABLE_CONSOLE=true \\\nhasura/graphql-engine:latest\n```\n\nI couldn't find in the docs a way to use multiple databases within the same instance, is it even possible?\n\n========================================\n\nTop Answer:\nIt's currently not possible.\n\nIf you want one graphql endpoint, you can instantiate many Hasura as you need for each tables. One of this Hasura instance could be your main endpoint, and you can add remote schema for each other tables.\n\n========================================\n\nCode:\n```text\ndocker run -d --net=host \\\n-e HASURA_GRAPHQL_DATABASE_URL=postgres://username:password@hostname:port/dbname \\\n-e HASURA_GRAPHQL_ENABLE_CONSOLE=true \\\nhasura/graphql-engine:latest\n```\n\n========================================\n\nComments:\n- It's not possible. Each Hasura engine can connect to only one database at a time.","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":37,"estimatedTokens":289}}1140{"id":"stack-38889450","source":"stackoverflow","questionId":38889450,"title":"Is it possible to use RelayJS and GraphQL without the ReactJS?","tags":["reactjs","graphql","relay","jquery-easyui"],"text":"Title: Is it possible to use RelayJS and GraphQL without the ReactJS?\nTags: reactjs, graphql, relay, jquery-easyui\nSource: Stack Overflow\n\nQuestion:\nI'm trying to figure out if there is a way of using RelayJS and GraphQL without ReactJS. Im quite fond of how those three works in data management and at the same time, im looking forward on using the jeasyUI for the design of my web application. But the problem is jeasyUI doesnt really work well together with reactJS.\n\nIm a newbie on this matter so please, please please, if you guys know any way on how to work on it. Enlighten me please. Any response regarding this would be highly appreciated. Thanks in advance.\n\n========================================\n\nTop Answer:\nAt present facebook only support relay to be used with react or react native + GraphQL. But they are working on it to make it framework agnostic. You can try Apollo Client which is the best alternative for Relay out there and also has lots of cool features, if you want to choose different tech stack other than facebook's.","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":13,"estimatedTokens":262}}1141{"id":"stack-60200177","source":"stackoverflow","questionId":60200177,"title":"What's the difference between GraphQL and rest api","tags":["json","rest","http","graphql"],"text":"Title: What's the difference between GraphQL and rest api\nTags: json, rest, http, graphql\nSource: Stack Overflow\n\nQuestion:\nI want to know what are all reasons of **qraphQL** to be used instead of **rest api**.\n\nAs much I know instead of making multiple requests (to reduce HTTP request), can make a group of HTTP requests in one request using **graphQL**.\n\nCan anybody describe little more, please?\n\nThanks in advance.\n\n========================================\n\nCode:\n```text\nGET /cars/25\nGET /cars/83\n```\n\n```text\nGET /api?query={ car(ids: [25, 83]) { model, manufacturer { address } } }\n```\n\n========================================\n\nComments:\n- Multiple blogs are on internet for this. Please refer and one of them is blog.apollographql.com/…\n- blog.ditectrev.com/blog/software-development/web-services/… or even mine","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":30,"estimatedTokens":209}}1142{"id":"stack-39227457","source":"stackoverflow","questionId":39227457,"title":"*NgFor does not display the data","tags":["angular","httprequest","graphql","ngfor"],"text":"Title: *NgFor does not display the data\nTags: angular, httprequest, graphql, ngfor\nSource: Stack Overflow\n\nQuestion:\nI'm writing my first Angular2 application.\n\nI have a `BankAccountService` that fetches data from my backend server and a `bank-account.component` which uses this service to simply display an unsorted list of the accountNumbers.\n\nDebugging through chrome devtool i was able to see that the data is fetched correctly and stored in the `bankAccounts` data member, but for some reason the `ul` shows nothing.\n\nBankAccountService: \n\n```\nimport { Injectable } from '@angular/core';\nimport {client} from '../app.module';\nimport gql from 'graphql-tag';\nimport {ObservableQuery} from \"apollo-client\";\n\n@Injectable()\nexport class BankAccountService{\n bankAccounts: any[] = [];\n\n constructor() {\n this.queryBankAccounts();\n }\n\n queryBankAccounts(): any{\n let queryObservable: ObservableQuery = client.watchQuery({\n query: gql`\n {\n bankAccounts {\n id\n accountNumber\n userOwners{\n firstName\n }\n bankId\n branchId\n transactions{\n amount\n payerId\n recipientId\n }\n }\n }\n `,\n pollInterval: 50\n });\n\n let subscription = queryObservable.subscribe({\n next: ({ data }) => {\n this.bankAccounts = data;\n },\n error: (error) => {\n console.log('there was an error sending the query', error);\n }\n });\n }\n\n getBankAccounts(){\n return this.bankAccounts;\n }\n}\n```\n\nbank-account.component: \n\n```\nimport {Component} from \"@angular/core\";\nimport {BankAccountService} from \"../services/BankAccountService\";\n\n@Component({\n selector: 'bank-account',\n template: `\n \n {{account.accountNumber}}\n \n `,\n providers: [BankAccountService]\n})\nexport class BankAccountComponent{\n bankAccounts: any[] = [];\n\n constructor(bankAccountService: BankAccountService){\n this.bankAccounts = bankAccountService.getBankAccounts();\n }\n}\n```\n\nWould really appreciate if someone could shed some light, i can't seem to understand my mistake.\n\nThanks in advance\n\n========================================\n\nTop Answer:\nThat's because async function is getting data, but you are trying to display it before it is fetched, therefore, you are iterating through an empty array. You can solve this problem easily by not initializing array (change `bankAccounts: any[] = [];` to `bankAccounts: any[];`) and surrounding your `` tags with ``. That way, `bankAccounts` array will be undefined until data is fetched and your `*ngFor` loop will be executed right after array is populated thanks to `*ngIf` directive.\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@angular/core';\nimport {client} from '../app.module';\nimport gql from 'graphql-tag';\nimport {ObservableQuery} from \"apollo-client\";\n\n@Injectable()\nexport class BankAccountService{\n bankAccounts: any[] = [];\n\n constructor() {\n this.queryBankAccounts();\n }\n\n queryBankAccounts(): any{\n let queryObservable: ObservableQuery = client.watchQuery({\n query: gql`\n {\n bankAccounts {\n id\n accountNumber\n userOwners{\n firstName\n }\n bankId\n branchId\n transactions{\n amount\n payerId\n recipientId\n }\n }\n }\n `,\n pollInterval: 50\n });\n\n let subscription = queryObservable.subscribe({\n next: ({ data }) => {\n this.bankAccounts = data;\n },\n error: (error) => {\n console.log('there was an error sending the query', error);\n }\n });\n }\n\n getBankAccounts(){\n return this.bankAccounts;\n }\n}\n```\n\n```text\nimport {Component} from \"@angular/core\";\nimport {BankAccountService} from \"../services/BankAccountService\";\n\n@Component({\n selector: 'bank-account',\n template: `<ul>\n <li *ngFor=\"let account of bankAccounts\">\n {{account.accountNumber}}\n </li>\n </ul>`,\n providers: [BankAccountService]\n})\nexport class BankAccountComponent{\n bankAccounts: any[] = [];\n\n constructor(bankAccountService: BankAccountService){\n this.bankAccounts = bankAccountService.getBankAccounts();\n }\n}\n```\n\n```text\nBankAccountService\n```\n\n```text\nbank-account.component\n```\n\n```text\nbankAccounts\n```\n\n```text\nul\n```\n\n```text\n//make this observable into a class property\nqueryObservable:ObservableQuery = client.watchQuery({\n ...\n});\n\n//return the observable that will emit the data\ngetBankAccounts():Observable<any[]>{\n return this.queryObservable;\n}\n```\n\n```text\n//don't set it to anything, so the *ngIf will work in the template \nbankAccounts: any[];\n\n//better to do this here than in the constructor\nngOnInit(){\n this.bankAccountService.getAccounts().subscribe(\n data => this.bankAccounts = data\n )\n}\n```\n\n```text\n<!-- only show the list IF the data is available -->\n<ul *ngIf=\"bankAccounts\">\n <li *ngFor=\"let account of bankAccounts\">\n {{account.accountNumber}}\n </li>\n</ul>\n```\n\n```text\ngetBankAccounts()\n```\n\n```text\n*ngIf\n```\n\n```text\nbankAccounts = service.getBankAccounts()\n```\n\n```text\nasync\n```\n\n```text\nbankAccounts: any[] = [];\n```\n\n```text\nbankAccounts: any[];\n```\n\n```text\n<ul>\n```\n\n```text\n<div *ngIf=\"bankAccounts\"></div>\n```\n\n```text\nbankAccounts\n```\n\n```text\n*ngFor\n```\n\n```text\n*ngIf\n```\n\n========================================\n\nComments:\n- Use ngOnInit method to make the call of bankAccountService.getBankAccounts()\n- Thanks for the quick reply, ive tried what you suggested and now it looks like the array is empty\n- Thanks for your reply, seems like you're right, is there a cleaner way or any kind of best practice for this type of stuff? placing `*ngIf` seems a bit dirty\n- Actually, after trying your suggestion it doesn't look like it solves it, I've surrounded the `` with a `` and its still empty.. is there a way to debug the DOM for those parts of angular `ngFor` , `ngIf` etc?\n- I confirm that *ngFor loop is being executed only if the array it uses is not empty.","metadata":{"transformedAt":"2026-08-18T18:32:36.230Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":278,"estimatedTokens":1540}}1143{"id":"stack-62832089","source":"stackoverflow","questionId":62832089,"title":"Is there a scalar type for arrays and maps in graphql for schemas in AWS amplify?","tags":["graphql","aws-amplify"],"text":"Title: Is there a scalar type for arrays and maps in graphql for schemas in AWS amplify?\nTags: graphql, aws-amplify\nSource: Stack Overflow\n\nQuestion:\nI was learning to use AWS amplify with React, and the API it uses is a GraphQL API that leverages AWS AppSync. I'm very new to graphQL and my schema currently is like this. This is the schema inside the amplify app:\n\n```\ntype Note @model {\n id: ID!\n name: String!\n description: String\n title: String\n image: String\n}\n```\n\nTo give you an example, I want to store an array of objects inside components in the Note type like this:\n\n**Code-1**\n\n```\ntype Note @model {\n id: ID!\n name: String!\n description: String\n title: String\n image: String\n components: []\n}\n```\n\nBut reading the docs I got to know there aren't any array scalar types. I know that I can create another table and do it like this instead:\n\n**Code-2**\n\n```\ntype Note @model {\n id: ID!\n name: String!\n description: String\n title: String\n image: String\n components: [elements!]!\n}\n \n type elements @model {\n id: ID!\n item: String!\n}\n```\n\nBut I don't want this as it creates a new table. I just want one table containing id, name, description, title, image and a components array where you can store objects in like shown above in **Code-1**. Is there any possible way to do this? Also whats the role of \"@modal\" in the schema?\n\n========================================\n\nCode:\n```text\ntype Note @model {\n id: ID!\n name: String!\n description: String\n title: String\n image: String\n}\n```\n\n```text\ntype Note @model {\n id: ID!\n name: String!\n description: String\n title: String\n image: String\n components: []\n}\n```\n\n```text\ntype Note @model {\n id: ID!\n name: String!\n description: String\n title: String\n image: String\n components: [elements!]!\n}\n \n type elements @model {\n id: ID!\n item: String!\n}\n```\n\n```text\ntype Note @model {\n id: ID!\n name: String!\n description: String\n title: String\n image: String\n components: AWSJSON\n}\n```\n\n========================================\n\nComments:\n- \"custom JSON scalar\" - check general graphql and amplify docs\n- @xadm Thank you so much. Figured out \"AWSJSON\" can be used, I guess my mistake was looking at the graphql docs instead of the AWS docs.\n- Hi Shiraaz, I got this. What do you think is the issue? \"Variable 'countriesOfDegrees' has an invalid value. Unable to parse [Albania, Antigua and Barbuda] as valid JSON.\"\n- Would need more context on the code.","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":112,"estimatedTokens":607}}1144{"id":"stack-70607882","source":"stackoverflow","questionId":70607882,"title":"What is the difference between GraphQLJSON and GraphQLJSONObject exported by graphql-type-json?","tags":["json","graphql","graphql-js","express-graphql","graphql-tools"],"text":"Title: What is the difference between GraphQLJSON and GraphQLJSONObject exported by graphql-type-json?\nTags: json, graphql, graphql-js, express-graphql, graphql-tools\nSource: Stack Overflow\n\nQuestion:\nFrom the official package documentation:\n\nGraphQLJSON can represent any JSON-serializable value, including\nscalars, arrays, and objects. GraphQLJSONObject represents\nspecifically JSON objects, which covers many practical use cases for\nJSON scalars.\n\nIt sounds a bit confusing as to me both definitions seem quite similar. Can someone please help me understand this better with an example? Thanks in anticipation.\n\nhttps://www.npmjs.com/package/graphql-type-json\n\n========================================\n\nTop Answer:\nThe wording can be confusing. There is a discussion here but I think a couple examples make it easier to understand.\n\n`GraphQLJSON` will accept anything that you could assign as the value side of a key value pair in valid JSON.\n\n```\n// Each line represents valid GraphQLJSON\n3\n\"3\"\n\"foo\"\n{\"foo\": 3}\n{\"foo\": [\"bar\", \"3\"]}\n\n// Invalid GraphQLJSON might be something like this\nfoo\n```\n\nAnd `GraphQLJSONObject` is more strict. It only includes the `object` subset of values contained in `GraphQLJSON` (so no raw strings, numbers, etc.)\n\n```\n// Each line represents valid GraphQLJSONObject\n{\"foo\": 3}\n{\"foo\": [\"bar\", \"3\"]}\n\n// Each line represents invalid GraphQLJSONObject\n3\n\"3\"\n\"foo\"\n```\n\n========================================\n\nCode:\n```text\nGraphQLJSON\n```\n\n```text\nGraphQLJSONObject\n```\n\n```js\n// Each line represents valid GraphQLJSON\n3\n\"3\"\n\"foo\"\n{\"foo\": 3}\n{\"foo\": [\"bar\", \"3\"]}\n\n// Invalid GraphQLJSON might be something like this\nfoo\n```\n\n```js\n// Each line represents valid GraphQLJSONObject\n{\"foo\": 3}\n{\"foo\": [\"bar\", \"3\"]}\n\n// Each line represents invalid GraphQLJSONObject\n3\n\"3\"\n\"foo\"\n```\n\n```text\nGraphQLJSON\n```\n\n```text\nGraphQLJSONObject\n```\n\n```text\nobject\n```\n\n```text\nGraphQLJSON\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":97,"estimatedTokens":479}}1145{"id":"stack-42142046","source":"stackoverflow","questionId":42142046,"title":"Extending query arguments in graphene/graphene_django","tags":["django-models","graphql","graphene-python"],"text":"Title: Extending query arguments in graphene/graphene_django\nTags: django-models, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nHow do I add non-field arguments to a GraphQL query in graphene? Here's an example of a use case. I'd like to be able to do:\n\n```\n{\n hsv(h: 40, s: 128, v: 54) {\n r\n g\n b\n name\n}\n```\n\nwith this Django model:\n\n```\nfrom django.db import models\nfrom django.core.validators import MinValueValidator, MaxValueValidator,\n\nclass Color(models.Model):\n name = models.CharField(\n \"name\",\n max_length=24,\n null=False, blank=False)\n r = models.IntegerField(\n \"red\", null=False, blank=False,\n validators=[MinValueValidator(0), MinValueValidator(255)]\n )\n\n g = models.IntegerField(\n \"green\", null=False, blank=False,\n validators=[MinValueValidator(0), MinValueValidator(255)]\n )\n\n b = models.IntegerField(\n \"blue\", null=False, blank=False,\n validators=[MinValueValidator(0), MinValueValidator(255)]\n )\n```\n\nand this GraphQL object type and Query based on it:\n\n```\nfrom graphene import ObjectType, IntegerField, Field, relay\nfrom graphene_django import DjangoObjectType\n\nfrom .django import Color\nfrom colorsys import hsv_to_rgb\n\nclass ColorNode(DjangoObjectType):\n r = IntegerField()\n g = IntegerField()\n b = IntegerField()\n\n class Meta:\n model = Color\n\nclass Query(ObjectType):\n rgb = relay.node.Field(ColorNode)\n hsv = relay.node.Field(ColorNode)\n named = relay.node.Field(ColorNode)\n\n def resolve_rgb(self, args, context, info):\n if not all(map(lambda x: x in args, ['r', 'g', 'b'])):\n # Arguments missing\n return None\n return Color.objects.get(**args)\n\n def resolve_hsv(self, args, context, info):\n if not all(map(lambda x: x in args, ['h', 's', 'v'])):\n # Arguments missing\n return None\n\n r, g, b = hsv_to_rgb(args['h'], args['s'], args['v'])\n return Color.objects.get(r=r, g=g, b=b)\n\n def resolve_named(self, args, context, info):\n if not 'name' in args:\n # Arguments missing\n return None\n return Color.objects.get(name=args['name'])\n```\n\nIt fails because the arguments aren't accepted. What am I missing?\n\n========================================\n\nCode:\n```text\n{\n hsv(h: 40, s: 128, v: 54) {\n r\n g\n b\n name\n}\n```\n\n```text\nfrom django.db import models\nfrom django.core.validators import MinValueValidator, MaxValueValidator,\n\nclass Color(models.Model):\n name = models.CharField(\n \"name\",\n max_length=24,\n null=False, blank=False)\n r = models.IntegerField(\n \"red\", null=False, blank=False,\n validators=[MinValueValidator(0), MinValueValidator(255)]\n )\n\n g = models.IntegerField(\n \"green\", null=False, blank=False,\n validators=[MinValueValidator(0), MinValueValidator(255)]\n )\n\n b = models.IntegerField(\n \"blue\", null=False, blank=False,\n validators=[MinValueValidator(0), MinValueValidator(255)]\n )\n```\n\n```text\nfrom graphene import ObjectType, IntegerField, Field, relay\nfrom graphene_django import DjangoObjectType\n\nfrom .django import Color\nfrom colorsys import hsv_to_rgb\n\nclass ColorNode(DjangoObjectType):\n r = IntegerField()\n g = IntegerField()\n b = IntegerField()\n\n class Meta:\n model = Color\n\nclass Query(ObjectType):\n rgb = relay.node.Field(ColorNode)\n hsv = relay.node.Field(ColorNode)\n named = relay.node.Field(ColorNode)\n\n def resolve_rgb(self, args, context, info):\n if not all(map(lambda x: x in args, ['r', 'g', 'b'])):\n # Arguments missing\n return None\n return Color.objects.get(**args)\n\n def resolve_hsv(self, args, context, info):\n if not all(map(lambda x: x in args, ['h', 's', 'v'])):\n # Arguments missing\n return None\n\n r, g, b = hsv_to_rgb(args['h'], args['s'], args['v'])\n return Color.objects.get(r=r, g=g, b=b)\n\n def resolve_named(self, args, context, info):\n if not 'name' in args:\n # Arguments missing\n return None\n return Color.objects.get(name=args['name'])\n```\n\n```text\nrgb = relay.node.Field(ColorNode,\n r=graphene.String(),\n g=graphene.String(),\n b=graphene.String())\nhsv = relay.node.Field(ColorNode,\n h=graphene.String(),\n s=graphene.String(),\n v=graphene.String()))\nnamed = relay.node.Field(ColorNode,\n name=graphene.String())\n```\n\n========================================\n\nComments:\n- (Replying to a comment about using Connection and ConnectionField that now appears to have been deleted.) Would you mind putting together a quick answer showing how this works? I've looked over the relay docs and am not understanding how to pass the ConnectionField values into a query.\n- Did they change the way it works? That doesn't seem to work anymore (when I print my schema I still only have `customer(id: ID!): Customer`). Even though I created my field using `graphene.relay.Node.Field(Customer, login=graphene.String())`. I am missing something? (graphene version: 2.1.8).\n- In the code it looks like it should work, not sure why it doesn't.\n- not working for me either in relay, only in the native graphene fields. that link you show seems to be just the latter.\n- There might be some confusion about the difference between `relay.Node.Field` and `relay.node.Field` here. As far as I can tell, the former is a Relay field which doesn't handle extra arguments, and the latter is a plain old field which does (but doesn't have the relay ID).","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":189,"estimatedTokens":1344}}1146{"id":"stack-45291916","source":"stackoverflow","questionId":45291916,"title":"The loader.load() function must be called with a value,but got: undefined","tags":["node.js","graphql"],"text":"Title: The loader.load() function must be called with a value,but got: undefined\nTags: node.js, graphql\nSource: Stack Overflow\n\nQuestion:\nI am following this graphql tutorial, everything was going ok until I try to use dataloaders.\n\nMy server.js is:\n\n```\nconst start = async () => {\n const mongo = await connectMongo();\n\n const buildOptions = async req => {\n const user = await authenticate(req, mongo.Users);\n return {\n context: {\n dataloaders: buildDataloaders(mongo),\n mongo,\n user\n },\n schema\n };\n };\n app.use('/graphql', bodyParser.json(), graphqlExpress(buildOptions));\n app.use(\n '/graphiql',\n graphiqlExpress({\n endpointURL: '/graphql',\n passHeader: `'Authorization': 'bearer token-name@email.com'`\n })\n );\n app.use('/', expressStaticGzip('dist'));\n app.use('/attendance', expressStaticGzip('dist'));\n app.use('/login', expressStaticGzip('dist'));\n\n spdy.createServer(sslOptions, app).listen(process.env.PORT || 8080, error => {\n if (error) {\n console.error(error);\n return process.exit(1);\n } else {\n console.info(\n `App available at https://localhost:${process.env.PORT || 3000}`\n );\n }\n });\n};\n```\n\nMy copy and paste dataloaders.js:\n\n```\nconst DataLoader = require('dataloader');\n\nasync function batchUsers(Users, keys) {\n return await Users.find({ _id: { $in: keys } }).toArray();\n}\n\nmodule.exports = ({ Users }) => ({\n userLoader: new DataLoader(keys => batchUsers(Users, keys), {\n cacheKeyFn: key => key.toString()\n })\n});\n```\n\nAnd my resolvers.js:\n\n```\nexport default {\n Query: {\n allLinks: async (root, data, { mongo: { Links } }) =>\n Links.find({}).toArray()\n },\n Mutation: {\n createLink: async (root, data, { mongo: { Links }, user }) => {\n const newLink = Object.assign({ postedById: user && user._id }, data);\n const response = await Links.insert(newLink);\n return Object.assign({ id: response.insertedIds[0] }, newLink);\n },\n createUser: async (root, data, { mongo: { Users } }) => {\n const newUser = {\n name: data.name,\n email: data.authProvider.email.email,\n password: data.authProvider.email.password\n };\n const response = await Users.insert(newUser);\n return Object.assign({ id: response.insertedIds[0] }, newUser);\n },\n signinUser: async (root, data, { mongo: { Users } }) => {\n const user = await Users.findOne({ email: data.email.email });\n if (data.email.password === user.password) {\n return { token: `token-${user.email}`, user };\n }\n }\n },\n\n Link: {\n id: root => root._id || root.id,\n postedBy: async ({ postedById }, data, { dataloaders: { userLoader } }) => {\n return await userLoader.load(postedById);\n }\n },\n User: {\n id: root => root._id || root.id\n }\n};\n```\n\nWhen I try get my allLinks I got the error:\n\nTypeError: The loader.load() function must be called with a value,but\ngot: undefined.\n\nCan anyone help me?\n\n========================================\n\nCode:\n```text\nconst start = async () => {\n const mongo = await connectMongo();\n\n const buildOptions = async req => {\n const user = await authenticate(req, mongo.Users);\n return {\n context: {\n dataloaders: buildDataloaders(mongo),\n mongo,\n user\n },\n schema\n };\n };\n app.use('/graphql', bodyParser.json(), graphqlExpress(buildOptions));\n app.use(\n '/graphiql',\n graphiqlExpress({\n endpointURL: '/graphql',\n passHeader: `'Authorization': 'bearer token-name@email.com'`\n })\n );\n app.use('/', expressStaticGzip('dist'));\n app.use('/attendance', expressStaticGzip('dist'));\n app.use('/login', expressStaticGzip('dist'));\n\n spdy.createServer(sslOptions, app).listen(process.env.PORT || 8080, error => {\n if (error) {\n console.error(error);\n return process.exit(1);\n } else {\n console.info(\n `App available at https://localhost:${process.env.PORT || 3000}`\n );\n }\n });\n};\n```\n\n```text\nconst DataLoader = require('dataloader');\n\nasync function batchUsers(Users, keys) {\n return await Users.find({ _id: { $in: keys } }).toArray();\n}\n\nmodule.exports = ({ Users }) => ({\n userLoader: new DataLoader(keys => batchUsers(Users, keys), {\n cacheKeyFn: key => key.toString()\n })\n});\n```\n\n```text\nexport default {\n Query: {\n allLinks: async (root, data, { mongo: { Links } }) =>\n Links.find({}).toArray()\n },\n Mutation: {\n createLink: async (root, data, { mongo: { Links }, user }) => {\n const newLink = Object.assign({ postedById: user && user._id }, data);\n const response = await Links.insert(newLink);\n return Object.assign({ id: response.insertedIds[0] }, newLink);\n },\n createUser: async (root, data, { mongo: { Users } }) => {\n const newUser = {\n name: data.name,\n email: data.authProvider.email.email,\n password: data.authProvider.email.password\n };\n const response = await Users.insert(newUser);\n return Object.assign({ id: response.insertedIds[0] }, newUser);\n },\n signinUser: async (root, data, { mongo: { Users } }) => {\n const user = await Users.findOne({ email: data.email.email });\n if (data.email.password === user.password) {\n return { token: `token-${user.email}`, user };\n }\n }\n },\n\n Link: {\n id: root => root._id || root.id,\n postedBy: async ({ postedById }, data, { dataloaders: { userLoader } }) => {\n return await userLoader.load(postedById);\n }\n },\n User: {\n id: root => root._id || root.id\n }\n};\n```\n\n```text\npostedBy\n```\n\n```text\npostedBy\n```\n\n========================================\n\nComments:\n- The only thing that seems to make sense to me is that the user you initially created a link with has been deleted. Is that the case?","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":225,"estimatedTokens":1394}}1147{"id":"stack-60689370","source":"stackoverflow","questionId":60689370,"title":"Multiple schema in Apollo Android","tags":["android","graphql","apollo","apollo-client","graphql-java"],"text":"Title: Multiple schema in Apollo Android\nTags: android, graphql, apollo, apollo-client, graphql-java\nSource: Stack Overflow\n\nQuestion:\nI am using Apollo Client in Android Project. I have 2 schema file and I have put them 2 different directories.\n\n- src/main/graphql/com/example/data/search/schema.json\n\n- src/main/graphql/com/example/data/user/schema.json\n\nBut when I build a project to generate code by Apollo It gives me an error:\n\n **`ApolloGraphQL: By default, only one schema.json file is supported.`**\n\nand suggest me to use **multiple service**\nBuild output:\n\n```\nApolloGraphQL: By default, only one schema.json file is supported. Please use multiple services instead: \n\napollo {\n service(\"search\") {\n sourceFolder = \"/.../app/src/main/graphql/com/example/data/search\" \n }\n\n service(\"customer\") {\n sourceFolder = \"/.../app/src/main/graphql/com/example/data/customer\" \n } \n}\n```\n\nI have also added this to my `build.gradle`(app level) file but still shows the same build error.\n\nPlease suggest me how can I solve this error\n\n========================================\n\nCode:\n```text\nApolloGraphQL: By default, only one schema.json file is supported. Please use multiple services instead: \n\napollo {\n service(\"search\") {\n sourceFolder = \"/.../app/src/main/graphql/com/example/data/search\" \n }\n\n service(\"customer\") {\n sourceFolder = \"/.../app/src/main/graphql/com/example/data/customer\" \n } \n}\n```\n\n```text\nApolloGraphQL: By default, only one schema.json file is supported.\n```\n\n```text\nbuild.gradle\n```\n\n```text\napollo {\n // configure ApolloExtension here\n generateKotlinModels.set(false) // Generate Kotlin models for all services\n\n service(\"search\") {\n sourceFolder.set(\"com/example/data/search\")\n rootPackageName.set(\"com.example.data.search\")\n }\n service(\"customer\") {\n sourceFolder.set(\"com/example/data/customer\")\n rootPackageName.set(\"com.example.data.customer\")\n }\n\n onCompilationUnit {\n // Overwrite some options here for single CompilationUnit if needed\n }\n}\n```\n\n========================================\n\nComments:\n- Hello Abu I wanted to keep separate schemas on basis of build types(debug and prod) and that too dynamically. Could you help me out?\n- I didn't try that yet. One way could be use same `interface` for both `debug` and `prod` implementation.\n- Could you please elaborate","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":87,"estimatedTokens":586}}1148{"id":"stack-61107176","source":"stackoverflow","questionId":61107176,"title":"Filter GraphQL articles by datetime","tags":["graphql","strapi"],"text":"Title: Filter GraphQL articles by datetime\nTags: graphql, strapi\nSource: Stack Overflow\n\nQuestion:\nI'm using Strapi with GraphQL. I need to query articles that have the publish date after the current date.\nThe intention behind this is to allow editors to publish with future dates so they can plan ahead.\nRight now I have only this:\n\n```\nexport const ARTICLES_QUERY = gql`\n query Articles {\n articles(where: { display: true }) {\n id\n slug\n title\n publish\n display\n time_to_read\n article_categories {\n slug\n title\n }\n user {\n username\n name\n }\n cover {\n url\n }\n }\n }\n`\n```\n\nI think I need something like this:\n\n```\nexport const ARTICLES_QUERY = gql`\n query Articles($today: String!) {\n articles(where: { display: true, publish >= $today }) {\n id\n slug\n...\n```\n\nThe format of that string is Strapi's default for the date time input and the result is `\"publish\": \"2020-02-28T02:00:00.000Z\"`\n\nI'm aware this is not the way to go, but it illustrates what I need to acomplish.\n\n========================================\n\nTop Answer:\nLooks like this has changed in the past 3 years. For me, it now looks more like this (Still in Strapi and with GraphQL):\n\n```\nquery ProductsForNewUsers { \n userProducts (filters: {user: {createdAt: {gt: \"2023-07-19T10:55:00\"}}){\n data {\n id\n attributes {\n user {\n data {\n id\n attributes {\n username\n email\n }\n }\n }\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nexport const ARTICLES_QUERY = gql`\n query Articles {\n articles(where: { display: true }) {\n id\n slug\n title\n publish\n display\n time_to_read\n article_categories {\n slug\n title\n }\n user {\n username\n name\n }\n cover {\n url\n }\n }\n }\n`\n```\n\n```text\nexport const ARTICLES_QUERY = gql`\n query Articles($today: String!) {\n articles(where: { display: true, publish >= $today }) {\n id\n slug\n...\n```\n\n```text\n\"publish\": \"2020-02-28T02:00:00.000Z\"\n```\n\n```text\nexport const ARTICLES_QUERY = gql`\n query Articles($today: String!) {\n articles(where: { display: true, publish_lt: $today }) {\n id\n slug\n...\n```\n\n```text\n_lt\n```\n\n```text\n_gt\n```\n\n```graphql\nquery ProductsForNewUsers { \n userProducts (filters: {user: {createdAt: {gt: \"2023-07-19T10:55:00\"}}){\n data {\n id\n attributes {\n user {\n data {\n id\n attributes {\n username\n email\n }\n }\n }\n }\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":155,"estimatedTokens":626}}1149{"id":"stack-59868942","source":"stackoverflow","questionId":59868942,"title":"GraphQL: A schema must have a query operation defined","tags":["graphql"],"text":"Title: GraphQL: A schema must have a query operation defined\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nMy IDE (Phpstorm with JS GraphQL) is giving me the title error for my schema. \n\nI'm new to GraphQL, what should the query be set to if the actual query operation only has a mutation at the root level? \n\nBelow is an actual query taken out of a (Shopify) tutorial for their GraphQL API. I'm copying my local schema definition below which attempted to accommodate its shape.\n\nAs you can see, The query is entirely nested in a mutation so I don't know what a query definition at the root level should even have.\n\n```\n// graphql.ts\n\nimport \"isomorphic-fetch\";\n\nconst buildPricingPlanQuery = (redirectUrl: string) => `mutation {\n appSubscribeCreate(\n name : \"Plan 1\"\n returnUrl : \"${redirectUrl}\"\n test : true\n lineItems : [\n {\n plan : {\n appUsagePricingDetails : {\n cappedAmount : {\n amount : 10\n , currencyCode : USD\n }\n terms : \"Up to 50 products\"\n }\n }\n }\n {\n plan : {\n appRecurringPricingDetails : {\n price : {\n amount : 10\n , currencyCode : USD\n }\n terms : \"some recurring terms\"\n }\n }\n }\n ]\n )\n {\n userErrors {\n field\n message\n }\n confirmationUrl\n appSubscription {\n id\n }\n }\n}`;\n\nexport const requestSubscriptionUrl = async (ctx: any, accessToken: string, shopDomain: string) => {\n const requestUrl = `https://${shopDomain}/admin/api/2019-10/graphql.json`;\n\n const response = await fetch(requestUrl, {\n method : 'post'\n , headers : {\n 'content-type' : \"application/json\"\n , 'x-shopify-access-token' : accessToken\n },\n body : JSON.stringify({query: buildPricingPlanQuery(`https://${shopDomain}`)})\n });\n\n const responseBody = await response.json();\n const confirmationUrl = responseBody\n .data\n .appSubscriptionCreate\n .confirmationUrl;\n\n return confirmationUrl;\n};\n```\n\n```\n// pricingSchema.graphql\n\n# ------------ Minor Types\n\nenum CurrencyCode {\n USD\n EUR\n JPY\n}\n\ntype cappedAmount {\n amount: Int\n currencyCode : CurrencyCode\n}\n\ntype appUsagePricingDetails {\n cappedAmount: cappedAmount\n}\n\ninput PlanInput {\n appUsagePricingDetails: cappedAmount\n terms: String\n}\n\ntype userErrors {\n field: String\n message: String\n}\n\ntype appSubscription {\n id: Int\n}\n\n# ------------ Major Type and Schema definition\n\ntype PricingPlan {\n appSubscribeCreate(\n name: String!\n returnUrl: String!\n test: Boolean\n lineItems: [PlanInput!]!\n ): String\n userErrors: userErrors\n confirmationUrl: String\n appSubscription: appSubscription\n}\n\nschema {\n mutation: PricingPlan\n}\n```\n\n========================================\n\nCode:\n```text\n// graphql.ts\n\nimport \"isomorphic-fetch\";\n\nconst buildPricingPlanQuery = (redirectUrl: string) => `mutation {\n appSubscribeCreate(\n name : \"Plan 1\"\n returnUrl : \"${redirectUrl}\"\n test : true\n lineItems : [\n {\n plan : {\n appUsagePricingDetails : {\n cappedAmount : {\n amount : 10\n , currencyCode : USD\n }\n terms : \"Up to 50 products\"\n }\n }\n }\n {\n plan : {\n appRecurringPricingDetails : {\n price : {\n amount : 10\n , currencyCode : USD\n }\n terms : \"some recurring terms\"\n }\n }\n }\n ]\n )\n {\n userErrors {\n field\n message\n }\n confirmationUrl\n appSubscription {\n id\n }\n }\n}`;\n\n\nexport const requestSubscriptionUrl = async (ctx: any, accessToken: string, shopDomain: string) => {\n const requestUrl = `https://${shopDomain}/admin/api/2019-10/graphql.json`;\n\n const response = await fetch(requestUrl, {\n method : 'post'\n , headers : {\n 'content-type' : \"application/json\"\n , 'x-shopify-access-token' : accessToken\n },\n body : JSON.stringify({query: buildPricingPlanQuery(`https://${shopDomain}`)})\n });\n\n const responseBody = await response.json();\n const confirmationUrl = responseBody\n .data\n .appSubscriptionCreate\n .confirmationUrl;\n\n return confirmationUrl;\n};\n```\n\n```text\n// pricingSchema.graphql\n\n# ------------ Minor Types\n\nenum CurrencyCode {\n USD\n EUR\n JPY\n}\n\ntype cappedAmount {\n amount: Int\n currencyCode : CurrencyCode\n}\n\ntype appUsagePricingDetails {\n cappedAmount: cappedAmount\n}\n\ninput PlanInput {\n appUsagePricingDetails: cappedAmount\n terms: String\n}\n\ntype userErrors {\n field: String\n message: String\n}\n\ntype appSubscription {\n id: Int\n}\n\n# ------------ Major Type and Schema definition\n\ntype PricingPlan {\n appSubscribeCreate(\n name: String!\n returnUrl: String!\n test: Boolean\n lineItems: [PlanInput!]!\n ): String\n userErrors: userErrors\n confirmationUrl: String\n appSubscription: appSubscription\n}\n\nschema {\n mutation: PricingPlan\n}\n```\n\n```text\ntype Query {\n ping: String @deprecated(reason: \"https://stackoverflow.com/questions/59868942/graphql-a-schema-must-have-a-query-operation-defined\")\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":266,"estimatedTokens":1214}}1150{"id":"stack-42168530","source":"stackoverflow","questionId":42168530,"title":"How to return ActiveRecord Relation in GraphQL (Rails)?","tags":["ruby-on-rails","graphql"],"text":"Title: How to return ActiveRecord Relation in GraphQL (Rails)?\nTags: ruby-on-rails, graphql\nSource: Stack Overflow\n\nQuestion:\nGraphQL queries are straight forward to define if you search for record e.g. by its id or exact value (in my case date).\n\nMy query should be returning not one ActiveRecord object but ActiveRecord Relation. How to define it to be consumable by GraphQL?\n\n```\nfield :file_data, !FileDataType, \" Returns records based on given date: format 'yyyy-mm-dd hh:mm:ss'\" do\n argument :created_on, !types.String, \"format 'yyyy-mm-dd hh:mm:ss'\"\n\n resolve -> (obj, args, context) do\n FileData.where(\"created_on > ?\", args[\"created_on\"])\n end\nend\n```\n\nIt works for one object: if I add to the relation 'last':\n\n```\nFileData.where(\"created_on > ?\", args[\"created_on\"]).last\n```\n\nFor many results I get an error in rails console:\n\nNoMethodError (undefined method `attribute_name' [any defined & requested] for FileData::ActiveRecord_Relation:..>\n\nI would appreciate any suggestion.\n\n========================================\n\nCode:\n```text\nfield :file_data, !FileDataType, \" Returns records based on given date: format 'yyyy-mm-dd hh:mm:ss'\" do\n argument :created_on, !types.String, \"format 'yyyy-mm-dd hh:mm:ss'\"\n\n resolve -> (obj, args, context) do\n FileData.where(\"created_on > ?\", args[\"created_on\"])\n end\nend\n```\n\n```text\nFileData.where(\"created_on > ?\", args[\"created_on\"]).last\n```\n\n```text\nfield :file_data, types[FileDataType] do\n ...\nend\n```\n\n```text\ntypes[...]\n```\n\n========================================\n\nComments:\n- Thank you so much! I was considering additional gem (graphql-ruby includes built-in connection support for Array, ActiveRecord::Relations, and Sequel::Datasets) but solution turned to be so simple!\n- I had this same problem. My resolver returned all the records in the table, but my field definition didn't have [] around it. Much appreciated @rmosolgo\n- i need to retrieve single record from the database could anyone please help me with syntax without using block. i am using this syntax field :method_name, [Types::ObjectType],etc","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":64,"estimatedTokens":520}}1151{"id":"stack-45288655","source":"stackoverflow","questionId":45288655,"title":"How to do file uploads with Relay Modern mutations?","tags":["graphql","relay","relaymodern"],"text":"Title: How to do file uploads with Relay Modern mutations?\nTags: graphql, relay, relaymodern\nSource: Stack Overflow\n\nQuestion:\nI'm using `react-relay/compat 1.1.0` and I need to write a mutation with the ability to upload a file.\nIn Relay Classic you can use `getFiles()` to support file uploads in mutations:\n\n```\nclass AddImageMutation extends Relay.Mutation {\n getMutation() {\n return Relay.QL`mutation{ introduceImage }`;\n }\n\n getFiles() {\n return {\n file: this.props.file,\n };\n }\n ...\n}\n```\n\nBut haven't found any trace of functionality for uploading files in Relay Modern docs:\n\n```\nconst {commitMutation} = require('react-relay');\n\ncommitMutation(\n environment: Environment,\n config: {\n mutation: GraphQLTaggedNode,\n variables: Variables,\n onCompleted?: ?(response: ?Object) => void,\n onError?: ?(error: Error) => void,\n optimisticResponse?: ?() => Object,\n optimisticUpdater?: ?(store: RecordSourceSelectorProxy) => void,\n updater?: ?(store: RecordSourceSelectorProxy) => void,\n configs?: Array,\n\n // files: ... ?\n },\n);\n```\n\nIs that supported yet in relay modern? and if so, what's the way of doing it? Thanks.\n\n========================================\n\nTop Answer:\nFound this question as I just had the same one myself.\n\nNot sure of the complete answer yet, but I'm starting to read through the Relay source and based on packages/relay-runtime/mutations/commitRelayModernMutation.js it looks like you can pass `uploadables` to your mutation.\n\n========================================\n\nCode:\n```text\nclass AddImageMutation extends Relay.Mutation {\n getMutation() {\n return Relay.QL`mutation{ introduceImage }`;\n }\n\n getFiles() {\n return {\n file: this.props.file,\n };\n }\n ...\n}\n```\n\n```text\nconst {commitMutation} = require('react-relay');\n\ncommitMutation(\n environment: Environment,\n config: {\n mutation: GraphQLTaggedNode,\n variables: Variables,\n onCompleted?: ?(response: ?Object) => void,\n onError?: ?(error: Error) => void,\n optimisticResponse?: ?() => Object,\n optimisticUpdater?: ?(store: RecordSourceSelectorProxy) => void,\n updater?: ?(store: RecordSourceSelectorProxy) => void,\n configs?: Array<RelayMutationConfig>,\n\n // files: ... ?\n },\n);\n```\n\n```text\nreact-relay/compat 1.1.0\n```\n\n```text\ngetFiles()\n```\n\n```text\nuploadables\n```\n\n```text\nconfig\n```\n\n```text\ncommitMutation\n```\n\n```text\nuploadables\n```\n\n========================================\n\nComments:\n- I don't get how to do it with `useMutation`","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":120,"estimatedTokens":620}}1152{"id":"stack-57013591","source":"stackoverflow","questionId":57013591,"title":"Can we return null for a boolean value in GraphQL response","tags":["graphql"],"text":"Title: Can we return null for a boolean value in GraphQL response\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI have a use case where the value can be \"yes\", \"no\" or \"null\" where \"null\" means \"not present\". Can I use the boolean type in GraphQL to denote this?\n\n========================================\n\nCode:\n```text\n+----------+-------------------+\n| type | allowed values |\n+----------+-------------------+\n| Boolean | true, false, null |\n| Boolean! | true, false |\n+----------+-------------------+\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":18,"estimatedTokens":131}}1153{"id":"stack-43451978","source":"stackoverflow","questionId":43451978,"title":"Does GraphQL support server-side filtering (i.e. building of WHERE-like queries on client side)?","tags":["web-services","graphql","api-design"],"text":"Title: Does GraphQL support server-side filtering (i.e. building of WHERE-like queries on client side)?\nTags: web-services, graphql, api-design\nSource: Stack Overflow\n\nQuestion:\nI'm investigating a possibility to use GraphQL between React.js client application and server application which is built on top of relational SQL database. A query should be created on client side including complex SQL-style statements like:\n\n```\nWHERE Customer.Age BETWEEN 22 AND 25\nAND Order.Status = 'Active'\nOR Product.Name LIKE '%foo%'\n```\n\nIt means the client should usually receive only a small subset of records (for example 10 instead of 10M).\n\nThis looking-good Phil Sturgeon article declares strange things:\n\n I was hoping GraphQL could help clients define their own scopes,\n filtering these includes to be the appropriate data themselves, which\n would help identify the scoped includes the API should add as\n convenience methods.\n\n \n It seems like GraphQL doesn't help API developers in this instance,\n but there does seem to be talk of adding @filter to do this in the\n future.\n\nIn the future? No filtering in GraphQL right now? I continued research and have found this SO question and this amazing interactive Graphcool documentation. Both examples use a feature called `filter` with a set of postfixes like `_gte`:\n\n```\nquery combineMovies {\n allMovies(filter: {\n OR: [{\n AND: [{\n releaseDate_gte: \"2009\"\n }, {\n title_starts_with: \"The Dark Knight\"\n }]\n }, {\n title: \"Inception\"\n }]\n }) {\n title\n releaseDate\n }\n}\n```\n\nHowever, there is no specification for the `filter` keyword at http://graphql.org.\nI even checked Relay docs and have found no good examples of complicated filtering (maybe because of I have no React experience).\n\nPlease clarify GraphQL's abilities to build complex SQL WHERE-like queries. Is it a part of standard or just a weakly supported side feature?\n\n========================================\n\nTop Answer:\nGraphql is a specification and there are different client and server implementations like Apollo, Graphcool, Relay. The code you pasted in your question is client side query and it is a bit complex.In my opinion it is closer to query builder than a query itself. \n\nGraphql queries can be as simple or complex as you like, it is totally up to you assuming you are writing your own server.\n\nYou can send simple key value pairs to your server and build an database query in the resolver function on the server side and feed the query to database to get data. Or you can build well formatted queries on the client side and directly feed these queries to database in your resolver function without even touching it. I think graqhcool chooses second approach.\n\nSo basically three steps involved:\n\n- Client sends some query, basically it is a GET or POST request with serialized text,\n\n- Resolver function on the server picks it up and gets the requested data from the database\n\n- and returns a response hence resolves the request.\n\nSpecification may not speak about filtering because it is implementation detail (it is just a parameter name you use in your post request), though it does, just read pagination section.\n\nFor a starter, specification may be a bit abstract, so starting with implementation server like Apollo Server may be better better approach and easier way to learn graphql.\n\n========================================\n\nCode:\n```text\nWHERE Customer.Age BETWEEN 22 AND 25\nAND Order.Status = 'Active'\nOR Product.Name LIKE '%foo%'\n```\n\n```text\nquery combineMovies {\n allMovies(filter: {\n OR: [{\n AND: [{\n releaseDate_gte: \"2009\"\n }, {\n title_starts_with: \"The Dark Knight\"\n }]\n }, {\n title: \"Inception\"\n }]\n }) {\n title\n releaseDate\n }\n}\n```\n\n```text\nfilter\n```\n\n```text\n_gte\n```\n\n```text\nfilter\n```\n\n```text\nquery allMovies {\n allMovies {\n id\n }\n}\n```\n\n```text\nquery firstMovie {\n allMovies(first: 1) {\n id\n }\n}\n```\n\n```text\nquery darkKnightMovies {\n allMovies(filter: {\n title_contains: \"Dark Knight\"\n }) {\n id\n }\n}\n```\n\n```text\nid\n```\n\n```text\nallMovies\n```\n\n```text\nfirst\n```\n\n```text\nfilter\n```\n\n```text\nallMovies\n```\n\n```text\nallMovies\n```\n\n```text\nallMovies\n```\n\n========================================\n\nComments:\n- This begs the question of what the developer needs to do on the server side to receive the query parameters - I'm really struggling to find information about that","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":172,"estimatedTokens":1098}}1154{"id":"stack-60533674","source":"stackoverflow","questionId":60533674,"title":"Does a graphene django Endpoint expects a X-Csrftoken and CsrfCookie at the same time?","tags":["django","graphql","graphene-python","vue-apollo","graphene-django"],"text":"Title: Does a graphene django Endpoint expects a X-Csrftoken and CsrfCookie at the same time?\nTags: django, graphql, graphene-python, vue-apollo, graphene-django\nSource: Stack Overflow\n\nQuestion:\nUsing:\n\n- Django 3.x [ Django-Filters 2.2.0, graphene-django 2.8.0, graphql-relay 2.0.1 ]\n\n- Vue 2.x [ Vue-Apollo ]\n\nI am testing single page vue appΒ΄s with Django, GraphQL & Vue-Apollo.\n\nIf i use `csrf_exempt` on my view everything works in the frontend. \n\n```\nurlpatterns = [\n\n path(\"graphql\", csrf_exempt(GraphQLView.as_view(graphiql=True))),\n\n```\n\nNow i wanted to CSRF protect my request.\nWithin the process of understanding the CSRF protection, i thought all Django `GraphQLView` needs is to receive the \"value\" of the `X-Csrftoken` in the Request Header. So i focused on sending the `csrf` Value in different ways...via a single view like this\n\n```\npath('csrf/', views.csrf),\npath(\"graphql\", GraphQLView.as_view(graphiql=True)),\n```\n\nor by ensure a cookie with `ensure_csrf_cookie`\n\nAfterwards in my `ApolloClient` i fetch thes Value and send him back with the request Header . \n\nThis i what Django prints when i send a GraphQL request from a Django-Vue page.\n\n```\nForbidden (CSRF token missing or incorrect.): /graphql\n```\n\nParallel i always test with the`graphiql IDE` and these requests still working. I also print everytime the `info.context.headers` value of my query resolver.\n\n```\n{'Content-Length': '400', 'Content-Type': 'application/json',\n'Host': 'localhost:7000', 'Connection': 'keep-alive',\n'Pragma': 'no-cache', 'Cache-Control': 'no-cache', \n'Accept': 'application/json', 'Sec-Fetch-Dest': 'empty', 'X-Csrftoken': 'dvMXuYfAXowxRGtwSVYQmpNcpGrLSR7RuUnc4IbIarjljxACtaozy3Jgp3YOkMGz',\n'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36',\n'Origin': 'http://localhost:7000',\n'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors',\n'Referer': 'http://localhost:7000/graphql', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9,de;q=0.8',\n'Cookie': 'sessionid=jqjvjfvg4sjmp7nkeunebqos8c7onhiz; csrftoken=dvMXuYfAXowxRGtwSVYQmpNcpGrLSR7RuUnc4IbIarjljxACtaozy3Jgp3YOkMGz'}\n```\n\ni recognized that the `GraphQLView IDE` alway puts the `X-Csrftoken` and the `Cookie:..csrftoken.` also in the request. if delete the csrftoken-cookie of a `GraphQLView IDE` before sending the request, i get this\n\n```\nForbidden (CSRF cookie not set.): /graphql\n```\n\nThe IDE shows a long, red report\n\n```\n.... CSRF verification failed. Request aborted.\n\n\\n\\n\\n \nYou are seeing this message because this site requires a CSRF cookie when submitting forms.\nThis cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.\n\n\\n\n```\n\nThe Information of the IDE sayΒ΄s the request needs a CSRF cookie. But all read until now in Forums, DocΒ΄s, was more related to the value itself. Meaning all you need is to send the csrf value within the Header as `X-Csrftoken` or so and the View would do the magic.\n\n**Question**\n\nTherefore my Question is:\n\nDo i have to set the `X-Csrftoken` and the `Cookie:..csrftoken` at the same time in my `ApolloClient` to make a request on my django `GraphQLView` ? \n\nOr is it also possible to simple send only the `X-Csrftoken` without a `csrf-cookie` and vice versa?\n\n========================================\n\nTop Answer:\nWas running into the same issue.\nMy application backend is Django with graphene. My frontend is React.\nI also had 2 issues:\n\ni didn't use the correct graphql url in my frontend apollo createHttpLink. In my django urls.py, my graphql url had \"/\" but i didn't put \"/\" in frontend. Just make sure the urls match exactly.\n\nIn addition to setting csrf token to header, you also have to set the csrf in Cookie object otherwise you will get a forbidden error. See [this][https://github.com/graphql-python/graphene-django/issues/786]. **When the CSRF_USE_SESSIONS settings variable is set to True post requests can not be made as the request will be rejected. This is because the CSRFTOKEN is not provided, because it will not be stored in a cookie.Django will end up giving this warning: Forbidden (CSRF token missing or incorrect.)**:\nThis issue can be prevented by passing the view to **csrf_exempt** in django's **urls.py** file.\n\npath('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True)))\n\nHowever a better solution is to store csrf in global cookie in the frontend in addition to setting it in the header like this:\n\n```\nconst csrftoken = await getCsrfToken();\nconst cookies = new Cookies();\ncookies.set('csrftoken', csrftoken);\n```\n\n(See my index.js code below for full code).\n\n***My index.js file:***\n\n```\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\nimport './custom.scss'\nimport allReducers from './reducer';\nimport {Provider} from 'react-redux';\nimport {BrowserRouter, Route, Routes} from \"react-router-dom\";\nimport {\n ApolloClient,\n InMemoryCache,\n ApolloProvider, from, createHttpLink\n} from \"@apollo/client\";\nimport {createStore} from \"redux\";\nimport {AuthProvider} from \"./utils/auth\";\nimport {setContext} from \"@apollo/client/link/context\";\nimport {ACCESS_TOKEN_KEY} from \"./constants/Constants\";\nimport {onError} from \"@apollo/client/link/error\";\nimport Cookies from \"universal-cookie/es6\";\n\nconst store = createStore(allReducers,\n window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()\n);\n\nlet csrftoken;\n\nasync function getCsrfToken() {\n if (csrftoken) return csrftoken;\n csrftoken = await fetch('http://localhost:8000/csrf/')\n .then(response => response.json())\n .then(data => data.csrfToken)\n return await csrftoken\n}\n\nconst authMiddleware = setContext(async (req, { headers }) => {\n const token = localStorage.getItem(ACCESS_TOKEN_KEY);\n const csrftoken = await getCsrfToken();\n const cookies = new Cookies();\n cookies.set('csrftoken', csrftoken);\n return {\n headers: {\n ...headers,\n 'X-CSRFToken': csrftoken,\n Authorization: token ? `Bearer ${token}` : ''\n },\n };\n});\n\nconst httpLink = createHttpLink({\n uri: 'http://localhost:8000/graphql/',\n credentials: 'include'\n});\n\nconst errorLink = onError(({ graphQLErrors, networkError }) => {\n if (graphQLErrors)\n graphQLErrors.map(({ message, locations, path }) =>\n console.log(\n `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`\n )\n )\n if (networkError) console.log(`[Network error]: ${networkError}`)\n})\n\nconst client2 = new ApolloClient({\n uri: 'http://localhost:8000/graphql/',\n cache: new InMemoryCache(),\n credentials: 'include',\n link: from([authMiddleware, errorLink, httpLink])\n});\n\nReactDOM.render(\n \n \n \n \n \n \n } />\n \n \n \n ,\n ,\n document.getElementById('root')\n);\n```\n\nOn the backend, here are some of the related files:\n\n**urls.py**\n\n```\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('graphql/', GraphQLView.as_view(graphiql=True)),\n path('csrf/', csrf),\n]\n```\n\n**settings.py:**\n\n```\nCORS_ALLOW_CREDENTIALS = True\n\nCORS_ORIGIN_WHITELIST = [\"http://localhost:3000\", ]\nCSRF_TRUSTED_ORIGINS = [\"http://localhost:3000\", ]\n\nCORS_ALLOW_METHODS = [\n 'DELETE',\n 'GET',\n 'OPTIONS',\n 'PATCH',\n 'POST',\n 'PUT',\n]\n\nCORS_ALLOW_HEADERS = [\n \"accept\",\n \"accept-encoding\",\n \"authorization\",\n \"content-type\",\n \"dnt\",\n \"origin\",\n \"user-agent\",\n \"x-csrftoken\",\n \"x-requested-with\",\n]\n```\n\n**views.py** (returns generated csrf token to frontend)\n\n```\nfrom django.http import JsonResponse\nfrom django.middleware.csrf import get_token\nfrom django.shortcuts import render\n\n# Create your views here.\ndef csrf(request):\n return JsonResponse({'csrfToken': get_token(request)})\n```\n\n========================================\n\nCode:\n```text\nurlpatterns = [\n<...>\n path(\"graphql\", csrf_exempt(GraphQLView.as_view(graphiql=True))),\n<...>\n```\n\n```text\npath('csrf/', views.csrf),\npath(\"graphql\", GraphQLView.as_view(graphiql=True)),\n```\n\n```text\nForbidden (CSRF token missing or incorrect.): /graphql\n```\n\n```text\n{'Content-Length': '400', 'Content-Type': 'application/json',\n'Host': 'localhost:7000', 'Connection': 'keep-alive',\n'Pragma': 'no-cache', 'Cache-Control': 'no-cache', \n'Accept': 'application/json', 'Sec-Fetch-Dest': 'empty', 'X-Csrftoken': 'dvMXuYfAXowxRGtwSVYQmpNcpGrLSR7RuUnc4IbIarjljxACtaozy3Jgp3YOkMGz',\n'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36',\n'Origin': 'http://localhost:7000',\n'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors',\n'Referer': 'http://localhost:7000/graphql', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9,de;q=0.8',\n'Cookie': 'sessionid=jqjvjfvg4sjmp7nkeunebqos8c7onhiz; csrftoken=dvMXuYfAXowxRGtwSVYQmpNcpGrLSR7RuUnc4IbIarjljxACtaozy3Jgp3YOkMGz'}\n```\n\n```text\nForbidden (CSRF cookie not set.): /graphql\n```\n\n```text\n.... CSRF verification failed. Request aborted.</p>\\n\\n\\n \n<p>You are seeing this message because this site requires a CSRF cookie when submitting forms.\nThis cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p>\\n\n```\n\n```text\ncsrf_exempt\n```\n\n```text\nGraphQLView\n```\n\n```text\nX-Csrftoken\n```\n\n```text\ncsrf\n```\n\n```text\nensure_csrf_cookie\n```\n\n```text\nApolloClient\n```\n\n```text\ngraphiql IDE\n```\n\n```text\ninfo.context.headers\n```\n\n```text\nGraphQLView IDE\n```\n\n```text\nX-Csrftoken\n```\n\n```text\nCookie:..csrftoken.\n```\n\n```text\nGraphQLView IDE\n```\n\n```text\nX-Csrftoken\n```\n\n```text\nX-Csrftoken\n```\n\n```text\nCookie:..csrftoken\n```\n\n```text\nApolloClient\n```\n\n```text\nGraphQLView\n```\n\n```text\nX-Csrftoken\n```\n\n```text\ncsrf-cookie\n```\n\n```text\nimport Vue from 'vue'\n// import path for the new Apollo Client 3 and Vue-Apollo\nimport { ApolloClient, InMemoryCache } from '@apollo/client/core';\nimport VueApollo from 'vue-apollo'\nimport Cookies from 'js-cookie'\n\n \n// Create the apollo client\nconst apolloClient = new ApolloClient({\n // -------------------\n // # Required Fields #\n // -------------------\n // URI - GraphQL Endpoint\n uri: 'http://127.0.0.1:7000/graphql',\n // Cache\n cache: new InMemoryCache(),\n\n // -------------------\n // # Optional Fields #\n // -------------------\n // DevBrowserConsole\n connectToDevTools: true,\n // Else\n credentials: 'same-origin',\n headers: {\n 'X-CSRFToken': Cookies.get('csrftoken')\n }\n});\n \n// create Vue-Apollo Instance\nconst apolloProvider = new VueApollo({\n defaultClient: apolloClient,\n})\n \n// Install the vue plugin\nVue.use(VueApollo)\n \nexport default apolloProvider\n```\n\n```text\nconst BundleTracker = require(\"webpack-bundle-tracker\");\n\n// hook your apps\nconst pages = {\n 'page_1': {\n entry: './src/page_1.js',\n chunks: ['chunk-vendors']\n },\n 'page_2': {\n entry: './src/page_2.js',\n chunks: ['chunk-vendors']\n },\n}\n\nmodule.exports = {\n pages: pages,\n filenameHashing: false,\n productionSourceMap: false,\n\n // puplicPath: \n // Tells Django where do find the bundle.\n publicPath: '/static/',\n\n // outputDir:\n // The directory where the production build files will be generated - STATICFILES_DIRS\n outputDir: '../dev_static/vue_bundle',\n \n \n chainWebpack: config => {\n\n config.optimization\n .splitChunks({\n cacheGroups: {\n vendor: {\n test: /[\\\\/]node_modules[\\\\/]/,\n name: \"chunk-vendors\",\n chunks: \"all\",\n priority: 1\n },\n },\n });\n\n\n // DonΒ΄t create Templates because we using Django Templates\n Object.keys(pages).forEach(page => {\n config.plugins.delete(`html-${page}`);\n config.plugins.delete(`preload-${page}`);\n config.plugins.delete(`prefetch-${page}`);\n })\n\n // create webpack-stats.json. \n // This file will describe the bundles produced by this build process.\n // used eventually by django-webpack-loader\n config\n .plugin('BundleTracker')\n .use(BundleTracker, [{filename: '/webpack-stats.json'}]);\n\n\n // added to use ApolloQuery Tag (Apollo Components) see vue-apollo documentation\n config.module\n .rule('vue')\n .use('vue-loader')\n .loader('vue-loader')\n .tap(options => {\n options.transpileOptions = {\n transforms: {\n dangerousTaggedTemplateString: true,\n },\n }\n return options\n })\n \n // This will allows us to reference paths to static \n // files within our Vue component as <img src=\"~__STATIC__/logo.png\">\n config.resolve.alias\n .set('__STATIC__', 'static')\n\n // configure a development server for use in non-production modes,\n config.devServer\n .public('http://localhost:8080')\n .host('localhost')\n .port(8080)\n .hotOnly(true)\n .watchOptions({poll: 1000})\n .https(false)\n .headers({\"Access-Control-Allow-Origin\": [\"*\"]})\n \n // DO have Webpack hash chunk filename\n config.output\n .chunkFilename(\"[id].js\")\n },\n\n devServer: {\n writeToDisk: true\n }\n};\n```\n\n```text\n*vue.js\n```\n\n```text\nSTATICFILES_DIRS\n```\n\n```text\nuri\n```\n\n```text\nhttp://127.0.0.1:7000/graphql\n```\n\n```text\nhttp://localhost:7000/graphql\n```\n\n```text\ncredentials\n```\n\n```text\n{% csrf_token %}\n```\n\n```text\njs-cookie\n```\n\n```text\nX-CSRFToken\n```\n\n```text\nvue-apollo.js\n```\n\n```text\nconst csrftoken = await getCsrfToken();\nconst cookies = new Cookies();\ncookies.set('csrftoken', csrftoken);\n```\n\n```text\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\nimport './custom.scss'\nimport allReducers from './reducer';\nimport {Provider} from 'react-redux';\nimport {BrowserRouter, Route, Routes} from \"react-router-dom\";\nimport {\n ApolloClient,\n InMemoryCache,\n ApolloProvider, from, createHttpLink\n} from \"@apollo/client\";\nimport {createStore} from \"redux\";\nimport {AuthProvider} from \"./utils/auth\";\nimport {setContext} from \"@apollo/client/link/context\";\nimport {ACCESS_TOKEN_KEY} from \"./constants/Constants\";\nimport {onError} from \"@apollo/client/link/error\";\nimport Cookies from \"universal-cookie/es6\";\n\nconst store = createStore(allReducers,\n window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()\n);\n\nlet csrftoken;\n\nasync function getCsrfToken() {\n if (csrftoken) return csrftoken;\n csrftoken = await fetch('http://localhost:8000/csrf/')\n .then(response => response.json())\n .then(data => data.csrfToken)\n return await csrftoken\n}\n\n\nconst authMiddleware = setContext(async (req, { headers }) => {\n const token = localStorage.getItem(ACCESS_TOKEN_KEY);\n const csrftoken = await getCsrfToken();\n const cookies = new Cookies();\n cookies.set('csrftoken', csrftoken);\n return {\n headers: {\n ...headers,\n 'X-CSRFToken': csrftoken,\n Authorization: token ? `Bearer ${token}` : ''\n },\n };\n});\n\nconst httpLink = createHttpLink({\n uri: 'http://localhost:8000/graphql/',\n credentials: 'include'\n});\n\nconst errorLink = onError(({ graphQLErrors, networkError }) => {\n if (graphQLErrors)\n graphQLErrors.map(({ message, locations, path }) =>\n console.log(\n `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`\n )\n )\n if (networkError) console.log(`[Network error]: ${networkError}`)\n})\n\n\nconst client2 = new ApolloClient({\n uri: 'http://localhost:8000/graphql/',\n cache: new InMemoryCache(),\n credentials: 'include',\n link: from([authMiddleware, errorLink, httpLink])\n});\n\nReactDOM.render(\n <Provider store={store}>\n <React.StrictMode>\n <ApolloProvider client={client2}>\n <BrowserRouter>\n <AuthProvider>\n <Routes>\n <Route path=\"/*\" element={<App/>} />\n </Routes>\n </AuthProvider>\n </BrowserRouter>\n </ApolloProvider>,\n </React.StrictMode></Provider>,\n document.getElementById('root')\n);\n```\n\n```text\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('graphql/', GraphQLView.as_view(graphiql=True)),\n path('csrf/', csrf),\n]\n```\n\n```text\nCORS_ALLOW_CREDENTIALS = True\n\nCORS_ORIGIN_WHITELIST = [\"http://localhost:3000\", ]\nCSRF_TRUSTED_ORIGINS = [\"http://localhost:3000\", ]\n\nCORS_ALLOW_METHODS = [\n 'DELETE',\n 'GET',\n 'OPTIONS',\n 'PATCH',\n 'POST',\n 'PUT',\n]\n\nCORS_ALLOW_HEADERS = [\n \"accept\",\n \"accept-encoding\",\n \"authorization\",\n \"content-type\",\n \"dnt\",\n \"origin\",\n \"user-agent\",\n \"x-csrftoken\",\n \"x-requested-with\",\n]\n```\n\n```text\nfrom django.http import JsonResponse\nfrom django.middleware.csrf import get_token\nfrom django.shortcuts import render\n\n\n# Create your views here.\ndef csrf(request):\n return JsonResponse({'csrfToken': get_token(request)})\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":42,"totalLines":687,"estimatedTokens":4268}}1155{"id":"stack-57454016","source":"stackoverflow","questionId":57454016,"title":"ApolloClient: Invariant Violation 1 β setup apollo client properly","tags":["javascript","graphql","apollo","apollo-client","apollo-boost"],"text":"Title: ApolloClient: Invariant Violation 1 β setup apollo client properly\nTags: javascript, graphql, apollo, apollo-client, apollo-boost\nSource: Stack Overflow\n\nQuestion:\nI am new to GraphQL and Apollo and I am really struggling with setting up an apolloClient in node.js.\n\nFirst I want to mention that I sucessfully set up an apollo client within nuxt using nuxt's apollo module.\n\nSo I am completely sure that my endpoint and my token are working.\n\nNow I wanted to setup an apollo client within a JavaScript file, which I want to run in node.js.\n\n```\nimport fetch from 'node-fetch'\nimport gql from 'graphql-tag'\nimport { ApolloClient } from 'apollo-client'\nimport { createHttpLink } from 'apollo-link-http'\nimport { setContext } from 'apollo-link-context'\n\nexport default function generateRoutesFromData(\n options = {\n api: [],\n query: '',\n token: '',\n bundle: '',\n homeSlug: 'home',\n errorPrefix: 'error-'\n }\n) {\n const uri = 'https://example.com/api'\n const token =\n '...fPsvYqkheQXXmlWgb...'\n\n const httpLink = createHttpLink({ uri, fetch })\n\n const authLink = setContext((_, { headers }) => {\n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n authorization: `Bearer ${token}`\n }\n }\n })\n\n const GET_PAGES = gql`\n {\n helloWorld\n }\n `\n\n const client = new ApolloClient({\n link: authLink.concat(httpLink),\n fetch\n })\n\n client\n .query({\n query: GET_PAGES\n })\n .then(result => {\n console.log('result: ', result)\n })\n .catch(error => {\n console.log('error: ', error)\n })\n\n // for now just return array with a test string\n // later on: return all uris fetched via graphql\n return ['/test']\n}\n```\n\nIf I run this in node I get the following error:\n\n FATAL Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages) 00:05:36\n\n \n Invariant Violation: Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages)\n\n \n at new InvariantError (packages/.../node_modules/ts-invariant/lib/invariant.js:16:28)\n\n \n at new ApolloClient (packages/.../node_modules/apollo-client/bundle.umd.js:2483:55)\n\n \n at generateRoutesFromData (packages/.../src/routes/generateRoutesFromData.js:41:18)\n at Object. (nuxt.config.js:158:10)\n at Generator.next ()\n\nI googled for about 1.5h and did not make any progress...\nThe error message is very cryptic and I don't know what I could do.\n\nI must say the whole documentation arount apollo is pretty confusing.\nApollo-boost and which wraps apollo client all other stuff. Different ways of authenticating etc.\n\nI found this page:\nhttps://www.apollographql.com/docs/react/advanced/boost-migration/\nBut it seems quite complex and I am not sure, if this will even help me with anything...\n\nAny help with this is much appreciated!\nCheers\nm\n\n========================================\n\nCode:\n```text\nimport fetch from 'node-fetch'\nimport gql from 'graphql-tag'\nimport { ApolloClient } from 'apollo-client'\nimport { createHttpLink } from 'apollo-link-http'\nimport { setContext } from 'apollo-link-context'\n\nexport default function generateRoutesFromData(\n options = {\n api: [],\n query: '',\n token: '',\n bundle: '',\n homeSlug: 'home',\n errorPrefix: 'error-'\n }\n) {\n const uri = 'https://example.com/api'\n const token =\n '...fPsvYqkheQXXmlWgb...'\n\n const httpLink = createHttpLink({ uri, fetch })\n\n const authLink = setContext((_, { headers }) => {\n // return the headers to the context so httpLink can read them\n return {\n headers: {\n ...headers,\n authorization: `Bearer ${token}`\n }\n }\n })\n\n const GET_PAGES = gql`\n {\n helloWorld\n }\n `\n\n const client = new ApolloClient({\n link: authLink.concat(httpLink),\n fetch\n })\n\n client\n .query({\n query: GET_PAGES\n })\n .then(result => {\n console.log('result: ', result)\n })\n .catch(error => {\n console.log('error: ', error)\n })\n\n // for now just return array with a test string\n // later on: return all uris fetched via graphql\n return ['/test']\n}\n```\n\n```text\nconst client = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache(), // <-- ADD ME\n})\n```\n\n```text\ncache\n```\n\n```text\nNODE_ENV\n```\n\n```text\nproduction\n```\n\n========================================\n\nComments:\n- Thank you. I assume that the nuxt env is not available at that point, so maybe that's the cause...","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":193,"estimatedTokens":1090}}1156{"id":"stack-38297058","source":"stackoverflow","questionId":38297058,"title":"Additional arguments to \"connectionArgs\" Relay js","tags":["javascript","graphql","relayjs","graphql-js"],"text":"Title: Additional arguments to \"connectionArgs\" Relay js\nTags: javascript, graphql, relayjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nFor example I have connection type: \n\n```\nlet usersType = new GraphQLObjectType({\n name: 'Users',\n description: 'users array',\n fields: () => ({\n array: {\n type: userConnection,\n description: 'all users',\n args: connectionArgs,\n searchFor: {\n type: GraphQLString\n },\n resolve: (root, args) => {\n return connectionFromArray(get(), args);\n }\n }\n })\n});\n```\n\nin this case in query I can specify only (first, last, after, before) arguments, but what if I need to pass some additional arguments like userName etc. is that possible? \n\nbasically I need something like: \n\n```\nquery {\n array (first: 1, userName: \"name\")\n}\n```\n\nand in users type I can handle request like:\n\n```\nresolve: (root, args) => connectionFromArray(get(args.userName), args.args)\n```\n\n========================================\n\nCode:\n```text\nlet usersType = new GraphQLObjectType({\n name: 'Users',\n description: 'users array',\n fields: () => ({\n array: {\n type: userConnection,\n description: 'all users',\n args: connectionArgs,\n searchFor: {\n type: GraphQLString\n },\n resolve: (root, args) => {\n return connectionFromArray(get(), args);\n }\n }\n })\n});\n```\n\n```text\nquery {\n array (first: 1, userName: \"name\")\n}\n```\n\n```text\nresolve: (root, args) => connectionFromArray(get(args.userName), args.args)\n```\n\n```text\nargs: {\n ...connectionArgs,\n searchFor: { type: GraphQLString }\n}\n```\n\n```text\nresolve: (root, args) => {\n // if the field argument 'searchFor' exists\n if (args.searchFor) {\n ...\n }\n ...\n}\n```\n\n```text\nconnectionArgs\n```\n\n```text\nresolve\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":100,"estimatedTokens":452}}1157{"id":"stack-53897364","source":"stackoverflow","questionId":53897364,"title":"SyntaxError: Unexpected token < in JSON at position 0 when testing in Graphiql","tags":["javascript","node.js","express","graphql","express-graphql"],"text":"Title: SyntaxError: Unexpected token < in JSON at position 0 when testing in Graphiql\nTags: javascript, node.js, express, graphql, express-graphql\nSource: Stack Overflow\n\nQuestion:\nI am learning GraphQL and am new to the technology. I am unable to figure out the cause for this syntax error. When I am testing it on graphiql it throws an unexpected token syntax error\n\nHere is my server.js:\n\n```\nconst express = require(\"express\");\nconst graphqlHTTP = require(\"express-graphql\");\nconst schema = require(\"./schema\");\n\nconst app = express();\napp.get(\n \"/graphql\",\n graphqlHTTP({\n schema: schema,\n graphiql: true\n })\n);\n\napp.listen(4000, () => {\n console.log(\"Server listening to port 4000...\");\n});\n```\n\nHere is my schema:\n\n```\nconst {\n GraphQLObjectType,\n GraphQLString,\n GraphQLInt,\n GraphQLSchema,\n GraphQLList,\n GraphQLNotNull\n} = require(\"graphql\");\n\n// HARD CODED DATA\nconst customers = [\n { id: \"1\", name: \"John Doe\", email: \"jdoe@gmail.com\", age: 35 },\n { id: \"2\", name: \"Kelly James\", email: \"kellyjames@gmail.com\", age: 28 },\n { id: \"3\", name: \"Skinny Pete\", email: \"skinnypete@gmail.com\", age: 31 }\n];\n\n// CUSTOMER TYPE\nconst CustomerType = new GraphQLObjectType({\n name: \"Customer\",\n fields: () => ({\n id: { type: GraphQLString },\n name: { type: GraphQLString },\n email: { type: GraphQLString },\n age: { type: GraphQLInt }\n })\n});\n\n// ROOT QUERY\nconst RootQuery = new GraphQLObjectType({\n name: \"RootQueryType\",\n fields: {\n customer: {\n type: CustomerType,\n args: {\n id: { type: GraphQLString }\n },\n resolve(parentValue, args) {\n for (let i = 0; i Can someone point me in the right direction? I can't figure out the problem here?\n\n========================================\n\nTop Answer:\nIn my case this error message was caused by a stupid error, so probably my story will be useful for someone:\n\nInstead of having JSON value with `{\"query\":\"graphqlQueryHere ...\"}` I just posted the plain graphQL query instead of JSON. Please take a look that you don't do the same.\n\n========================================\n\nCode:\n```text\nconst express = require(\"express\");\nconst graphqlHTTP = require(\"express-graphql\");\nconst schema = require(\"./schema\");\n\nconst app = express();\napp.get(\n \"/graphql\",\n graphqlHTTP({\n schema: schema,\n graphiql: true\n })\n);\n\napp.listen(4000, () => {\n console.log(\"Server listening to port 4000...\");\n});\n```\n\n```text\nconst {\n GraphQLObjectType,\n GraphQLString,\n GraphQLInt,\n GraphQLSchema,\n GraphQLList,\n GraphQLNotNull\n} = require(\"graphql\");\n\n// HARD CODED DATA\nconst customers = [\n { id: \"1\", name: \"John Doe\", email: \"jdoe@gmail.com\", age: 35 },\n { id: \"2\", name: \"Kelly James\", email: \"kellyjames@gmail.com\", age: 28 },\n { id: \"3\", name: \"Skinny Pete\", email: \"skinnypete@gmail.com\", age: 31 }\n];\n\n// CUSTOMER TYPE\nconst CustomerType = new GraphQLObjectType({\n name: \"Customer\",\n fields: () => ({\n id: { type: GraphQLString },\n name: { type: GraphQLString },\n email: { type: GraphQLString },\n age: { type: GraphQLInt }\n })\n});\n\n// ROOT QUERY\nconst RootQuery = new GraphQLObjectType({\n name: \"RootQueryType\",\n fields: {\n customer: {\n type: CustomerType,\n args: {\n id: { type: GraphQLString }\n },\n resolve(parentValue, args) {\n for (let i = 0; i < customers.length; i++) {\n if (customers[i].id == args.id) {\n return customers[i];\n }\n }\n }\n },\n customers: {\n type: new GraphQLList(CustomerType),\n resolve(parentValue, args) {\n return customers;\n }\n }\n }\n});\n\nmodule.exports = new GraphQLSchema({\n query: RootQuery\n});\n```\n\n```text\napp.use('/graphql', graphqlHTTP({schema, graphiql: true}))\n```\n\n```text\nexpress-middleware\n```\n\n```text\napp.use\n```\n\n```text\napp.get\n```\n\n```text\nPOST\n```\n\n```text\n/graphql\n```\n\n```text\napp.get\n```\n\n```text\nPOST\n```\n\n```text\nPOST\n```\n\n```text\n{\"query\":\"graphqlQueryHere ...\"}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":197,"estimatedTokens":973}}1158{"id":"stack-51042516","source":"stackoverflow","questionId":51042516,"title":"how to use graphiql when route are secured?","tags":["symfony","graphql","api-platform.com","graphiql"],"text":"Title: how to use graphiql when route are secured?\nTags: symfony, graphql, api-platform.com, graphiql\nSource: Stack Overflow\n\nQuestion:\ni have an application based on api-platform with secured route using JWT (and the LexikJWTBundle). With the Swagger interface it's easy to call secured route providing a valid bearer. But with GraphiQL i don't see anything about security so when a call a secured route it fails.\n\nAny idea ? or shall we prevent graphiql usage in dev ?\n\nThanks\n\n========================================\n\nTop Answer:\nThe primary question is answered, but I found this question when looking for how to automatically set the Authorization header based on an authentication request. GraphiQL has a preflight script option in settings where you can make an authentication request and set it into a variable to be used in the shared headers.\n\nIt wasn't obvious to me where to find this. It is available in the settings menu within the explorer tab, not the connection settings.\n\n========================================\n\nComments:\n- I don't think GraphiQL supports auth/custom headers. You could also use browser extensions to add custom headers.\n- i didn't thought at extension, it's not universal, but i could give it a try\n- Update as of August 2021 - the \"Request Headers\" button may be on the bottom left of the web browser interface and might not look much like a button. This is using express-graphql. It took me a minute to find it.\n- Write `{ \"Authorization\": \"Bearer eyJ...\" }` in the HTTP headers section.\n- I cant load graphiql without getting the error though? Is there a way around that so I can even enter the header override?","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":26,"estimatedTokens":414}}1159{"id":"stack-58005711","source":"stackoverflow","questionId":58005711,"title":"How to write test for graphene graphql in django","tags":["python","django","graphql"],"text":"Title: How to write test for graphene graphql in django\nTags: python, django, graphql\nSource: Stack Overflow\n\nQuestion:\nPlease can anyone help in testing graphene and graphql with django \n\nI tried using built-in django test but it didn't see my file\nI used pytest but it complaining of ModuleNotFoundError when importing my schema\nI will like someone to show me a course on advanced python\n\n```\nclass Query(ObjectType):\n calculate_price = Float(margin=Float(), exchangeRate=String(\n ), saleType=Argument(SaleType, required=True))\n\n def resolve_calculate_price(self, info, **kwargs):\n margin = kwargs.get('margin')\n exchangeRate = kwargs.get('exchangeRate')\n saleType = kwargs.get('saleType')\n\n request_from_coindesk = requests.get(\n url='https://api.coindesk.com/v1/bpi/currentprice.json')\n json_result_from_coindesk = json.dumps(request_from_coindesk.text)\n coindesk_result = json.loads(json_result_from_coindesk)\n result = json.loads(coindesk_result)\n\n rate_to_calculate = result[\"bpi\"][\"USD\"][\"rate_float\"]\n\n if saleType == SaleType.sell:\n calculated_value = (margin/100) * rate_to_calculate\n new_rate = (rate_to_calculate - calculated_value) * 360\n print(18, new_rate)\n return new_rate\n elif saleType == SaleType.buy:\n calculated_value = (margin/100) * rate_to_calculate\n new_rate = (rate_to_calculate - calculated_value) * 360\n print(19, new_rate)\n return new_rate\n else:\n raise GraphQLError('please saleType can either be buy or sell')\n```\n\n```\n#my test file\nfrom graphene.test import Client\nfrom buy_coins.schema import schema\n\ndef test_hey():\n client = Client(schema)\n executed = client.execute('''calculatePrice(margin, exchangeRate, saleType)''', context={\n 'margin': '1.2', 'exchangeRate': 'USD', 'saleType': 'sell'})\n assert executed == {\n \"data\": {\n \"calculatePrice\": 3624484.7302560005\n }\n }\n```\n\nI want to be able to test all possible cases.\nI want to understand the module import issue\nI want someone to refer an advanced python course\n\n========================================\n\nCode:\n```text\nclass Query(ObjectType):\n calculate_price = Float(margin=Float(), exchangeRate=String(\n ), saleType=Argument(SaleType, required=True))\n\n def resolve_calculate_price(self, info, **kwargs):\n margin = kwargs.get('margin')\n exchangeRate = kwargs.get('exchangeRate')\n saleType = kwargs.get('saleType')\n\n request_from_coindesk = requests.get(\n url='https://api.coindesk.com/v1/bpi/currentprice.json')\n json_result_from_coindesk = json.dumps(request_from_coindesk.text)\n coindesk_result = json.loads(json_result_from_coindesk)\n result = json.loads(coindesk_result)\n\n rate_to_calculate = result[\"bpi\"][\"USD\"][\"rate_float\"]\n\n if saleType == SaleType.sell:\n calculated_value = (margin/100) * rate_to_calculate\n new_rate = (rate_to_calculate - calculated_value) * 360\n print(18, new_rate)\n return new_rate\n elif saleType == SaleType.buy:\n calculated_value = (margin/100) * rate_to_calculate\n new_rate = (rate_to_calculate - calculated_value) * 360\n print(19, new_rate)\n return new_rate\n else:\n raise GraphQLError('please saleType can either be buy or sell')\n```\n\n```text\n#my test file\nfrom graphene.test import Client\nfrom buy_coins.schema import schema\n\n\n\ndef test_hey():\n client = Client(schema)\n executed = client.execute('''calculatePrice(margin, exchangeRate, saleType)''', context={\n 'margin': '1.2', 'exchangeRate': 'USD', 'saleType': 'sell'})\n assert executed == {\n \"data\": {\n \"calculatePrice\": 3624484.7302560005\n }\n }\n```\n\n```text\nfrom buy_coins.schema import Query\nfrom django.test.testcases import TestCase\nimport graphene\n\nclass AnExampleTest(TestCase):\n\n def setUp(self):\n super().setUp()\n self.query = \"\"\"\n query {\n reporter {\n id\n }\n }\n \"\"\"\n\n def test_an_example(self):\n schema = graphene.Schema(query=Query)\n result = schema.execute(query)\n self.assertIsNone(result.errors)\n self.assertDictEqual({\"reporter\": {\"id\": \"1\"}}, result.data)\n```\n\n```text\ngraphene-django\n```\n\n========================================\n\nComments:\n- In case of someone is using graphql_jwt: stackoverflow.com/questions/62360456/…","metadata":{"transformedAt":"2026-08-18T18:32:36.231Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":148,"estimatedTokens":1102}}1160{"id":"stack-56423772","source":"stackoverflow","questionId":56423772,"title":"Unknown type \"Upload\" in Apollo Server 2.6","tags":["node.js","graphql","apollo-server"],"text":"Title: Unknown type \"Upload\" in Apollo Server 2.6\nTags: node.js, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI want to upload a file through GraphQL, and followed this article.\n\nHere's the my schema:\n\n```\nextend type Mutation {\n bannerAdd(\n title: String!\n image: Upload\n ): ID\n}\n```\n\nHowever when I run the app, this gives me this error:\n\n Unknown type \"Upload\". Did you mean \"Float\"?\n\nFollowed above article, Apollo Server will automatically generate Upload scalar, but why this is happening?\n\nAlso define Upload scalar manually also not working:\n\n```\nscalar Upload\n\n...\n```\n\nGives me this error:\n\n Error: There can be only one type named \"Upload\".\n\nSeems nothing wrong with my code. Is there an anything that I missed? Using Node@10.14.2, Apollo Server@2.6.1, Apollo Server Express@2.6.1 and polka@0.5.2.\n\nAny advice will very appreciate it.\n\n========================================\n\nTop Answer:\nFix this problem with `GraphQLUpload` of Apollo Server for create a custom scalar called `FileUpload`.\n\n### Server setup with Apollo Server:\n\n```\nconst {ApolloServer, gql, GraphQLUpload} = require('apollo-server');\n\nconst typeDefs = gql`\n scalar FileUpload\n\n type File {\n filename: String!\n mimetype: String!\n encoding: String!\n }\n\n type Query {\n uploads: [File]\n }\n\n type Mutation {\n singleUpload(file: FileUpload!): File!\n }\n`;\n\nconst resolvers = {\n FileUpload: GraphQLUpload,\n Query: {\n uploads: (parent, args) => {},\n },\n Mutation: {\n singleUpload: async (_, {file}) => {\n const {createReadStream, filename, mimetype, encoding} = await file;\n const stream = createReadStream();\n\n // Rest of your code: validate file, save in your DB and static storage\n\n return {filename, mimetype, encoding};\n },\n },\n};\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n});\n\nserver.listen().then(({url}) => {\n console.log(`π Server ready at ${url}`);\n});\n```\n\n### Client Setup with Apollo Client and React.js:\n\nYou need to install the apollo-upload-client package too.\n\n```\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport { ApolloClient, InMemoryCache, ApolloProvider, gql, useMutation } from '@apollo/client';\nimport { createUploadLink } from 'apollo-upload-client';\n\nconst httpLink = createUploadLink({\n uri: 'http://localhost:4000'\n});\n\nconst client = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache()\n});\n\nconst UPLOAD_FILE = gql`\n mutation uploadFile($file: FileUpload!) {\n singleUpload(file: $file) {\n filename\n mimetype\n encoding\n }\n }\n`;\n\nfunction FileInput() {\n const [uploadFile] = useMutation(UPLOAD_FILE);\n\n return (\n \n validity.valid && uploadFile({variables: {file}})\n }\n />\n );\n}\n\nfunction App() {\n return (\n \n \n \n \n \n );\n}\n\nReactDOM.render(\n \n \n ,\n document.getElementById('root')\n);\n```\n\n========================================\n\nCode:\n```text\nextend type Mutation {\n bannerAdd(\n title: String!\n image: Upload\n ): ID\n}\n```\n\n```text\nscalar Upload\n\n...\n```\n\n```text\nimport { GraphQLUpload } from 'graphql-upload';\n\nexport const resolvers = {\n FileUpload: GraphQLUpload\n};\n```\n\n```text\nimport { ApolloLink, split } from 'apollo-link';\nimport { createHttpLink } from 'apollo-link-http';\nimport { createUploadLink } from 'apollo-upload-client';\n\n// Create HTTP Link\nconst httpLink = createHttpLink({\n uri: ...,\n credentials: 'include'\n});\n\n// Create File Upload Link\nconst isFile = value =>\n (typeof File !== 'undefined' && value instanceof File) || (typeof Blob !== 'undefined' && value instanceof Blob);\nconst isUpload = ({ variables }) => Object.values(variables).some(isFile);\nconst uploadLink = createUploadLink({\n uri: ...\n credentials: 'include'\n});\n\nconst terminatingLink = (isUpload, uploadLink, httpLink);\n\nconst link = ApolloLink.from([<Some Other Link...>, <Another Other Link...>, terminatingLink]);\n\nconst apolloClient = new ApolloClient({\n link,\n ...\n});\n```\n\n```js\nconst server = new ApolloServer({\n schema: makeExecutableSchema({ typeDefs, resolvers })\n})\n```\n\n```js\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n})\n```\n\n```text\nschema\n```\n\n```text\ntypeDefs\n```\n\n```text\nresolvers\n```\n\n```text\nscalar Upload\n```\n\n```text\nscalar Upload\n```\n\n```js\nconst {ApolloServer, gql, GraphQLUpload} = require('apollo-server');\n\nconst typeDefs = gql`\n scalar FileUpload\n\n type File {\n filename: String!\n mimetype: String!\n encoding: String!\n }\n\n type Query {\n uploads: [File]\n }\n\n type Mutation {\n singleUpload(file: FileUpload!): File!\n }\n`;\n\nconst resolvers = {\n FileUpload: GraphQLUpload,\n Query: {\n uploads: (parent, args) => {},\n },\n Mutation: {\n singleUpload: async (_, {file}) => {\n const {createReadStream, filename, mimetype, encoding} = await file;\n const stream = createReadStream();\n\n // Rest of your code: validate file, save in your DB and static storage\n\n return {filename, mimetype, encoding};\n },\n },\n};\n\nconst server = new ApolloServer({\n typeDefs,\n resolvers,\n});\n\nserver.listen().then(({url}) => {\n console.log(`π Server ready at ${url}`);\n});\n```\n\n```js\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport { ApolloClient, InMemoryCache, ApolloProvider, gql, useMutation } from '@apollo/client';\nimport { createUploadLink } from 'apollo-upload-client';\n\nconst httpLink = createUploadLink({\n uri: 'http://localhost:4000'\n});\n\nconst client = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache()\n});\n\n\nconst UPLOAD_FILE = gql`\n mutation uploadFile($file: FileUpload!) {\n singleUpload(file: $file) {\n filename\n mimetype\n encoding\n }\n }\n`;\n\nfunction FileInput() {\n const [uploadFile] = useMutation(UPLOAD_FILE);\n\n return (\n <input\n type=\"file\"\n required\n onChange={({target: {validity, files: [file]}}) =>\n validity.valid && uploadFile({variables: {file}})\n }\n />\n );\n}\n\nfunction App() {\n return (\n <ApolloProvider client={client}>\n <div>\n <FileInput/>\n </div>\n </ApolloProvider>\n );\n}\n\nReactDOM.render(\n <React.StrictMode>\n <App/>\n </React.StrictMode>,\n document.getElementById('root')\n);\n```\n\n```text\nGraphQLUpload\n```\n\n```text\nFileUpload\n```\n\n========================================\n\nComments:\n- Please edit your question to include your ApolloServer configuration.\n- I tried this and got the following error: \"Result: Failure Exception: Worker was unable to load function graphql: 'Error: Unknown type \"FileUpload\". Did you mean \"TokenPayload\"?'\"","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":361,"estimatedTokens":1611}}1161{"id":"stack-57619453","source":"stackoverflow","questionId":57619453,"title":"NodeJS/GraphQL: Trying to use a custom DateTime scalar and I'm getting an error","tags":["node.js","graphql","graphql-js"],"text":"Title: NodeJS/GraphQL: Trying to use a custom DateTime scalar and I'm getting an error\nTags: node.js, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nI'm following a tutorial where the teacher is using a `String` type for his `createdAt` fields and suggested that if we wanted, to use a custom scalar type for a stronger typed `DateTime` field so I'm trying to do just that.\n\nI'm getting the following error: `Error: Unknown type \"GraphQLDateTime\".`\n\nHere is the offending code:\n\n```\nconst { gql } = require('apollo-server')\nconst { GraphQLDateTime } = require('graphql-iso-date')\n\nmodule.exports = gql`\n type Post {\n id: ID!\n username: String!\n body: String!\n createdAt: GraphQLDateTime!\n }\n type User {\n id: ID!\n email: String!\n token: String!\n username: String!\n createdAt: GraphQLDateTime!\n }\n input RegisterInput {\n username: String!\n password: String!\n confirmPassword: String!\n email: String!\n }\n type Query {\n getPosts: [Post]\n getPost(postId: ID!): Post\n }\n type Mutation {\n register(registerInput: RegisterInput): User\n login(username: String!, password: String!): User!\n createPost(body: String!): Post!\n deletePost(postId: ID!): String!\n }\n`\n```\n\nI have added the `graphql-iso-date` library and VSCode's intellisense is picking that up so I know that's not the issue. It's also indicating that `GraphQLDateTime` is not being used anywhere in the file even though I'm referencing it.\n\nI know this is probably an easy fix but I'm still new to NodeJS and GraphQL in the context of NodeJS. Any idea what I'm doing wrong? Also is there another DateTime scalar that might be more preferable (Best practices are always a good idea.) Thanks!\n\n========================================\n\nCode:\n```text\nconst { gql } = require('apollo-server')\nconst { GraphQLDateTime } = require('graphql-iso-date')\n\nmodule.exports = gql`\n type Post {\n id: ID!\n username: String!\n body: String!\n createdAt: GraphQLDateTime!\n }\n type User {\n id: ID!\n email: String!\n token: String!\n username: String!\n createdAt: GraphQLDateTime!\n }\n input RegisterInput {\n username: String!\n password: String!\n confirmPassword: String!\n email: String!\n }\n type Query {\n getPosts: [Post]\n getPost(postId: ID!): Post\n }\n type Mutation {\n register(registerInput: RegisterInput): User\n login(username: String!, password: String!): User!\n createPost(body: String!): Post!\n deletePost(postId: ID!): String!\n }\n`\n```\n\n```text\nString\n```\n\n```text\ncreatedAt\n```\n\n```text\nDateTime\n```\n\n```text\nError: Unknown type \"GraphQLDateTime\".\n```\n\n```text\ngraphql-iso-date\n```\n\n```text\nGraphQLDateTime\n```\n\n```text\nscalar DateTime\n```\n\n```text\nconst { GraphQLDateTime } = require('graphql-iso-date')\n\nconst resolvers = {\n /* your other resolvers */\n DateTime: GraphQLDateTime,\n}\n```\n\n```text\napollo-server\n```\n\n```text\ngraphql-tools\n```\n\n```text\nDateTime\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":140,"estimatedTokens":720}}1162{"id":"stack-49918978","source":"stackoverflow","questionId":49918978,"title":"GraphQL queries in Django returning None","tags":["python","django","graphql","graphene-python"],"text":"Title: GraphQL queries in Django returning None\nTags: python, django, graphql, graphene-python\nSource: Stack Overflow\n\nQuestion:\nI am trying to use graphQL queries in django. Basically I have two apps, my 'api' app which contains everything I need to make the queries and another one called 'frontend' from which I call the api to use these queries.\n\nI can use the GraphQL view to type queries in it and it works perfectly, but whenever I try to make the query, I get this: \"OrderedDict([('users', None)])\"\n\nResult of my query in the GraphQl view\n\nThe code:\n\nIn 'api' my **schema.py**:\n\n```\nimport graphene\nimport graphql_jwt\nfrom graphene import relay, ObjectType, AbstractType, List, String, Field,InputObjectType\nfrom graphene_django import DjangoObjectType\nfrom graphene_django.filter import DjangoFilterConnectionField\nfrom datetime import date, datetime\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import get_user_model\n\n....\n\nclass Query(graphene.ObjectType):\n me = graphene.Field(UserType)\n users = graphene.List(UserType)\n profile = relay.Node.Field(ProfileNode)\n all_profiles = DjangoFilterConnectionField(ProfileNode)\n\n def resolve_users(self, info):\n ### Returns all users ###\n user = info.context.user\n if user.is_anonymous:\n raise Exception('Not logged!')\n if not user.is_superuser:\n raise Exception('premission denied')\n return User.objects.all()\n\n def resolve_me(self, info):\n ### Returns logged user ###\n user = info.context.user\n if user.is_anonymous:\n raise Exception('Not logged!')\n return user\n\n def resolve_all_profiles(self, info, **kwargs):\n ### Returns all profiles ###\n return Profile.objects.all()\n\n.....\n\ndef execute(my_query):\n schema = graphene.Schema(query=Query)\n return schema.execute(my_query)\n```\n\nAnd the **views.py** that calls the app 'api' in my app frontend:\n\n```\nfrom django.shortcuts import render\nimport graphene\nfrom api import schema\nfrom django.contrib.auth import authenticate\n\ndef accueil(request):\n\n if request.user.is_authenticated:\n check = \"I am logged\"\n else:\n check = \"I am not logged\"\n\n result = schema.execute(\"\"\"query {\n users {\n id\n username\n }\n }\"\"\")\n\n return render(request, 'frontend/accueil.html', {'result' : result.data, 'check' : check})\n```\n\n**The template :**\n\n```\n\n### OTC\n\n the users are : {{result}}\n\n{{check}}\n\nlogin\nlogout\n```\n\nand finally:\n\n**The web page result**\n\nand the error in the console:\n\n```\nAn error occurred while resolving field Query.users\nTraceback (most recent call last):\n File \"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py\", line 311, in resolve_or_error\n return executor.execute(resolve_fn, source, info, **args)\n File \"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executors/sync.py\", line 7, in execute\n return fn(*args, **kwargs)\n File \"/home/victor/poc2/poc2/api/schema.py\", line 67, in resolve_users\n user = info.context.user\nAttributeError: 'NoneType' object has no attribute 'user'\nTraceback (most recent call last):\n File \"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py\", line 330, in complete_value_catching_error\n exe_context, return_type, field_asts, info, result)\n File \"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py\", line 383, in complete_value\n raise GraphQLLocatedError(field_asts, original_error=result)\ngraphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'user'\n```\n\n========================================\n\nCode:\n```text\nimport graphene\nimport graphql_jwt\nfrom graphene import relay, ObjectType, AbstractType, List, String, Field,InputObjectType\nfrom graphene_django import DjangoObjectType\nfrom graphene_django.filter import DjangoFilterConnectionField\nfrom datetime import date, datetime\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import get_user_model\n\n....\n\nclass Query(graphene.ObjectType):\n me = graphene.Field(UserType)\n users = graphene.List(UserType)\n profile = relay.Node.Field(ProfileNode)\n all_profiles = DjangoFilterConnectionField(ProfileNode)\n\n def resolve_users(self, info):\n ### Returns all users ###\n user = info.context.user\n if user.is_anonymous:\n raise Exception('Not logged!')\n if not user.is_superuser:\n raise Exception('premission denied')\n return User.objects.all()\n\n def resolve_me(self, info):\n ### Returns logged user ###\n user = info.context.user\n if user.is_anonymous:\n raise Exception('Not logged!')\n return user\n\n def resolve_all_profiles(self, info, **kwargs):\n ### Returns all profiles ###\n return Profile.objects.all()\n\n.....\n\ndef execute(my_query):\n schema = graphene.Schema(query=Query)\n return schema.execute(my_query)\n```\n\n```text\nfrom django.shortcuts import render\nimport graphene\nfrom api import schema\nfrom django.contrib.auth import authenticate\n\n\ndef accueil(request):\n\n if request.user.is_authenticated:\n check = \"I am logged\"\n else:\n check = \"I am not logged\"\n\n result = schema.execute(\"\"\"query {\n users {\n id\n username\n }\n }\"\"\")\n\n return render(request, 'frontend/accueil.html', {'result' : result.data, 'check' : check})\n```\n\n```text\n<h1>OTC</h1>\n<p> the users are : {{result}}</p>\n<br/>\n<p>{{check}}</p>\n<a href=\"{%url 'login' %}\">login</a>\n<a href=\"{%url 'logout' %}\">logout</a>\n```\n\n```text\nAn error occurred while resolving field Query.users\nTraceback (most recent call last):\n File \"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py\", line 311, in resolve_or_error\n return executor.execute(resolve_fn, source, info, **args)\n File \"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executors/sync.py\", line 7, in execute\n return fn(*args, **kwargs)\n File \"/home/victor/poc2/poc2/api/schema.py\", line 67, in resolve_users\n user = info.context.user\nAttributeError: 'NoneType' object has no attribute 'user'\nTraceback (most recent call last):\n File \"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py\", line 330, in complete_value_catching_error\n exe_context, return_type, field_asts, info, result)\n File \"/home/victor/myenv/lib/python3.5/site-packages/graphql/execution/executor.py\", line 383, in complete_value\n raise GraphQLLocatedError(field_asts, original_error=result)\ngraphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'user'\n```\n\n```text\nresult = schema.execute('{ name }', context_value={'name': 'Syrus'})\n```\n\n```text\nresult = schema.execute(query, context_value=request)\n```\n\n```text\nschema.execute\n```\n\n```text\nschema.execute\n```\n\n```text\naccueil\n```\n\n```text\ninfo.context\n```\n\n```text\nNone\n```\n\n========================================\n\nComments:\n- What are you passing as `info` in resolve_users?\n- Why are you making a graphQL query from a inside Django view?\n- @kartikmaji the methods resolve_* are automatically called by the calls Query , so it's the Query class that passes `info` i don't handle it\n- @MarkChackerian the graphQL query is made in the api.schema.execute() i'm just passing the string of the query in the views\n- oh boi, that's it, thanks a lot dude ! (and yes i'm writting a test client ;) )","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":258,"estimatedTokens":1857}}1163{"id":"stack-55865515","source":"stackoverflow","questionId":55865515,"title":"Getting complete query string from inside of resolver","tags":["node.js","graphql","apollo","apollo-server"],"text":"Title: Getting complete query string from inside of resolver\nTags: node.js, graphql, apollo, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm new to nodejs and apollo server, so don't judge me.\n\nProblem sounds exactly same as title: \"how to get graphql string inside resolver function?\".\n\nActually, you have four args in every resolver: parent, args, context, info.\nSome info here: https://www.apollographql.com/docs/apollo-server/essentials/data#type-signature\n\nI made my mind to write function, that gathers nested object inside context to regenerate query string. Why I need it? Good question. I'm writing microservice, so when i got nested query to field which is outside from current microservice I pass query by http.\n\nMy resolver:\n\n```\neventByID: async (root, args, context) => {\n const event = await EventModel.findById(root.id);\n event.creator = await nestedContextProvider(context, 'creator', event.creator);\n return eventFascade(event); //just facade for object - nothing serious\n},\n```\n\nIt refers to nestedContextProvider for solving nested context:\n\n```\nconst nestedQueryTraverser = (nestedQueryArray) => {\n const nestedQueryTraversed = nestedQueryArray.selectionSet.selections.map(element => (\n element.selectionSet === undefined\n ? element.name.value\n : `${element.name.value}{${nestedQueryTraverser(element)}}`));\n return nestedQueryTraversed;\n};\n\nconst nestedContextProvider = async (context, checkField, ID) => {\n if (context.operation.selectionSet.selections[0].selectionSet.selections\n .find(selector => selector.name.value === checkField)) {\n let nestedFieldsArr = context.operation.selectionSet.selections[0]\n .selectionSet.selections.find(selector => selector.name.value === checkField);\n nestedFieldsArr = nestedQueryTraverser(nestedFieldsArr);\n const a = (await users(ID, nestedFieldsArr));\n return a.data.usersByIDs[0];\n }\n return ID;\n};\n```\n\nSo it works for me, but I know there must be better solution.\n\nAny ideas?\n\n========================================\n\nCode:\n```text\neventByID: async (root, args, context) => {\n const event = await EventModel.findById(root.id);\n event.creator = await nestedContextProvider(context, 'creator', event.creator);\n return eventFascade(event); //just facade for object - nothing serious\n},\n```\n\n```text\nconst nestedQueryTraverser = (nestedQueryArray) => {\n const nestedQueryTraversed = nestedQueryArray.selectionSet.selections.map(element => (\n element.selectionSet === undefined\n ? element.name.value\n : `${element.name.value}{${nestedQueryTraverser(element)}}`));\n return nestedQueryTraversed;\n};\n\nconst nestedContextProvider = async (context, checkField, ID) => {\n if (context.operation.selectionSet.selections[0].selectionSet.selections\n .find(selector => selector.name.value === checkField)) {\n let nestedFieldsArr = context.operation.selectionSet.selections[0]\n .selectionSet.selections.find(selector => selector.name.value === checkField);\n nestedFieldsArr = nestedQueryTraverser(nestedFieldsArr);\n const a = (await users(ID, nestedFieldsArr));\n return a.data.usersByIDs[0];\n }\n return ID;\n};\n```\n\n```text\nconst { print } = require('graphql')\n\nfunction anyResolver (parent, args, context, info) {\n const operationString = print(info.operation)\n // Fragments are not included in the operation, but we still need to print\n // them otherwise our document will reference non-existing fragments\n const fragmentsString = Object.keys(info.fragments)\n .map(fragmentName => print(info.fragments[fragmentName]))\n .join('\\n\\n')\n const documentString = `${operationString}\\n\\n${fragmentsString}`\n}\n```\n\n```text\ngraphql\n```\n\n```text\nprint\n```\n\n========================================\n\nComments:\n- FWIW, you may want to look into creating executable, remote schemas and then stitching them together rather than handling delegating the field resolution yourself.\n- Great! By the way, it is necessary to admit, that if you have context directive in instance of `new ApolloServer` you'll have `info` in third, but not in fourth arg of resolver. But `print` of `graphql` makes the job. Thank you Daniel!","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":112,"estimatedTokens":1032}}1164{"id":"stack-52221692","source":"stackoverflow","questionId":52221692,"title":"Understanding Apollo client caching and optimistic UI in AWS AppSync JavaScript SDK","tags":["javascript","graphql","apollo"],"text":"Title: Understanding Apollo client caching and optimistic UI in AWS AppSync JavaScript SDK\nTags: javascript, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement caching in Apollo client with the AWS AppSync JavaScript SDK but I am struggling to understand first the best way to use the cache and second what if any changes I need to make to adapt the Apollo V2 tutorials to work with the AppSync SDK. \n\nWith regards to using the cache, I have a list of objects that I get, I then want to view and modify a single object from this list. There are lots of tutorials on how to update something in a list, but I would rather run a second query that gets a single object by its ID so that the page will always work without having to go through the list first. \n\nIs the cache smart enough to know that object X got through queries Y and Z is the same object and will be updated at the same time? If not, is there any documentation on how to write an update that will update the object in the list and by itself at the same time?\n\nIf no documentation exists then I will try and work it out on my own and post the code (because it will most likely not work).\n\nWith regards to the second question I have got the application working and querying the API using Amplify for authentication but I am unsure as to how to correctly implement the cache. Do I need to specify the cache when creating the client or does the SDK have a built-in cache? How do I access the cache? Is it just by querying the client as in these tutorials? https://www.apollographql.com/docs/react/advanced/caching.html\n\n========================================\n\nCode:\n```text\ncacheOptions\n```\n\n```text\n__typename\n```\n\n```text\nid\n```\n\n```text\n__typename\n```\n\n```text\nid\n```\n\n```text\nid\n```\n\n```text\ndataIdFromObject\n```\n\n```text\nreadQuery\n```\n\n```text\nwriteQuery\n```\n\n```text\nupdate\n```\n\n========================================\n\nComments:\n- Wow, thank you so much that is an incredible answer! I had been thinking that moving to the plain Apollo client was a good idea for a while now and this just confirms it.","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":62,"estimatedTokens":524}}1165{"id":"stack-49320858","source":"stackoverflow","questionId":49320858,"title":"mongodb _id with graphql and document.toObject()","tags":["javascript","mongodb","mongoose","graphql","graphql-js"],"text":"Title: mongodb _id with graphql and document.toObject()\nTags: javascript, mongodb, mongoose, graphql, graphql-js\nSource: Stack Overflow\n\nQuestion:\nLet's use a basic mongodb query that returns one item:\n\n```\nconst result = await db.myCollection.findById('xxxx')\nreturn result;\n```\n\nThis query result given to graphql works fine.\n\nBut now, if I return a `result.toObject()`, it's not working anymore.\n\nI got this following error: \n\n```\n\"message\": \"Cannot return null for non-nullable field MyCollection.id.\"\n```\n\nWhy with `toObject()`, the mapping between `_id` and `id` can't be done?\n\n========================================\n\nCode:\n```text\nconst result = await db.myCollection.findById('xxxx')\nreturn result;\n```\n\n```text\n\"message\": \"Cannot return null for non-nullable field MyCollection.id.\"\n```\n\n```text\nresult.toObject()\n```\n\n```text\ntoObject()\n```\n\n```text\n_id\n```\n\n```text\nid\n```\n\n```text\nresult.toObject({ virtuals: true })\n```\n\n```text\n_id\n```\n\n```text\nid\n```\n\n```text\ntoObject\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":67,"estimatedTokens":248}}1166{"id":"stack-54414395","source":"stackoverflow","questionId":54414395,"title":"GraphQL filters in GatsbyJS","tags":["graphql","gatsby"],"text":"Title: GraphQL filters in GatsbyJS\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI'm having trouble understanding how to write filters for GraphQL queries in GatsbyJS.\n\nThis works:\n\n```\nfilter: { contentType: { in: [\"post\", \"page\"] }\n```\n\nI basically need the reverse of that, like:\n\n```\nfilter: { \"post\" in: { contentTypes } } // where contentTypes is array\n```\n\nThat doesn't work because \"NAME is expected\" (where \"post\" is in my example).\n\nAfter going through GatsbyJS docs I found this:\n\n```\nelemMatch: short for element match, this indicates that the field you are filtering will return an array of elements, on which you can apply a filter using the previous operators\n\nfilter:{\n packageJson:{\n dependencies:{\n elemMatch:{\n name:{\n eq:\"chokidar\"\n }\n }\n }\n }\n}\n```\n\nGreat! That's what I need! So I try that, and I get:\n\n```\nerror GraphQL Error Field \"elemMatch\" is not defined by type markdownRemarkConnectionFrontmatterTagsQueryList_2.\n```\n\nKeywords defined in markdownRemarkConnectionFrontmatterTagsQueryList_2 are:\n\n- eq: string | null;\n\n- ne: string | null;\n\n- regex: string | null;\n\n- glob: string | null;\n\n- in: Array | null;\n\nWhy am I limited to these keywords when more keywords such as `elemMatch` are mentioned in docs? Why am I not allowed to use the filter structure \"element in: { array }\"?\n\nHow can I create this filter?\n\n========================================\n\nCode:\n```text\nfilter: { contentType: { in: [\"post\", \"page\"] }\n```\n\n```text\nfilter: { \"post\" in: { contentTypes } } // where contentTypes is array\n```\n\n```text\nelemMatch: short for element match, this indicates that the field you are filtering will return an array of elements, on which you can apply a filter using the previous operators\n\nfilter:{\n packageJson:{\n dependencies:{\n elemMatch:{\n name:{\n eq:\"chokidar\"\n }\n }\n }\n }\n}\n```\n\n```text\nerror GraphQL Error Field \"elemMatch\" is not defined by type markdownRemarkConnectionFrontmatterTagsQueryList_2.\n```\n\n```text\nelemMatch\n```\n\n```text\n{\n allMarkdownRemark(filter:{\n frontmatter:{\n categories: {\n in: [\"historical\"]\n }\n }\n }) {\n edges {\n node {\n id\n frontmatter {\n categories\n }\n }\n }\n }\n}\n```\n\n```text\ncomments: { elemMatch: { id: { eq: \"1\" } } }\n```\n\n```text\n// only show plugins which have \"@babel/runtime\" as a dependency\n{\n allSitePlugin (filter:{\n packageJson:{\n dependencies: {\n elemMatch: {\n name: {\n eq: \"@babel/runtime\"\n }\n }\n }\n }\n }) {\n edges {\n node {\n name\n version\n packageJson {\n dependencies {\n name\n }\n }\n }\n }\n }\n}\n```\n\n```text\ncategories\n```\n\n```text\ncategories\n```\n\n```text\nelemMatch\n```\n\n```text\ncomments: [{ id: \"1\", content: \"\" }, { id: \"2\", content: \"\"}]\n```\n\n```text\ncomment\n```\n\n========================================\n\nComments:\n- The first query you gave works in the toy examples, but it doesn't work in the real case. I'm getting error `GraphQL Error Variable \"$tag\" of type \"String\" used in position expecting type \"[String]\".` The exact filter I used here was `filter: { frontmatter: { tags: { in: $tag } } }` which looks identical to your query.\n- Hey @AtteJuvonen! my bad, have you tried `tags: {in: [$tag] }`?\n- Thanks, it works! This is really surprising. I would have expected a filter for \"[a,b] in [b]\" to return false (when all elements in [a,b] are not found in [b]), but it does return true, like I want it to.\n- Glad it helps! I also think it is a bit unintuitive. Also it seems like when you use query variable, itβs more nitpicking about filter keyword typing. Let me edit the answer","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":177,"estimatedTokens":932}}1167{"id":"stack-74875792","source":"stackoverflow","questionId":74875792,"title":"File extension for GraphQL specs","tags":["graphql"],"text":"Title: File extension for GraphQL specs\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI found this documentation https://the-guild.dev/graphql/modules/docs/essentials/type-definitions but I wonder if there can be any other file extensions for graphql specs.\n\n========================================\n\nCode:\n```text\n.graphql\n```\n\n```text\n@graphql-tools/load-files\n```\n\n```text\n['gql', 'graphql', 'graphqls', 'ts', 'js']\n```\n\n```text\n.js\n```\n\n```text\n.ts\n```\n\n```text\nutf-8\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":33,"estimatedTokens":120}}1168{"id":"stack-44223592","source":"stackoverflow","questionId":44223592,"title":"Relay Compiler not generating .graphql files","tags":["graphql","relayjs","relay"],"text":"Title: Relay Compiler not generating .graphql files\nTags: graphql, relayjs, relay\nSource: Stack Overflow\n\nQuestion:\nModule not found: Error: Can't resolve './**generated**/GetAllCities.graphql'\n\nthe component:\n\n```\nexport class Map extends React.Component {\n21 constructor(props){\n22 super(props);\n23 };\n\n 24 render(){\n 25 return(\n 26 \n 27 \n 32 {\n 44 if (error) {\n 45 return {error.message};\n 46 } else if (props) {\n 47 console.log(props);\n 48 return {props.data.id};\n 49 }\n 50 return Loading;\n 51 }\n 52 }\n 53 />\n 54 \n```\n\nthe relay-compiler command:\n\n```\n11 \"relay\": \"relay-compiler --src ./src --schema ./data/schema.graphql --extensions=js,jsx\",\n```\n\nthe schema:\n\n```\n1 # A city to be used on the map\n 2 type City {\n 3 id: Int!\n 4 lat: Float\n 5 lng: Float\n 6 todo: [ToDo]\n 7 }\n 8 \n 9 # Mutations for the To Do List\n 10 type Mutation {\n 11 createToDo(city_id: Int!, text: String!): ToDo\n 12 }\n 13 \n 14 # An array of Cities\n 15 type Query {\n 16 cities: [City]\n 17 city(id: Int): City\n 18 }\n 19 \n 20 # A To Do for a city\n 21 type ToDo {\n 22 city_id: Int!\n 23 text: String\n 24 likes: Int\n 25 id: Int!\n 26 }\n```\n\nthe babelrc file:\n\n```\n1 {\n 2 \"plugins\": [\n 3 [\"relay\", {\n 4 \"compat\": true,\n 5 \"schema\": \"./data/schema.graphql\",\n 6 \"enforceSchema\": true,\n 7 \"suppressWarnings\": false,\n 8 \"debug\": false,\n 9 }]\n 10 ],\n 11 \"presets\": [\"react\", \"es2015\", \"es2016\", \"es2017\"]\n 12 }~\n```\n\nthe major issue is yarn run relay or npm run relay does not generate the **generated** GetAllCities.graphql\n\nalso get no error. it worked before with a fragment container. renaming the file to .js also doesn't work.\n\n========================================\n\nTop Answer:\nanswer was to change the packages.conf script to:\n\n\"relay\": \"relay-compiler --src ./src --schema ./data/schema.graphql --extensions jsx\"\n\nit now only works on jsx files but it does see them\n\n========================================\n\nCode:\n```text\nexport class Map extends React.Component {\n21 constructor(props){\n22 super(props);\n23 };\n\n\n 24 render(){\n 25 return(\n 26 <div id='map'>\n 27 <GoogleMapReact\n 28 bootstrapURLKeys={{key: ''}}\n 29 defaultCenter={this.props.center}\n 30 defaultZoom={this.props.zoom}\n 31 >\n 32 <QueryRenderer\n 33 environment={environment}\n 34 query={graphql`\n 35 query GetAllCities {\n 36 cities {\n 37 id\n 38 lat\n 39 }\n 40 }\n 41 `}\n 42 render={\n 43 ({error, props}) => {\n 44 if (error) {\n 45 return <div>{error.message}</div>;\n 46 } else if (props) {\n 47 console.log(props);\n 48 return <div>{props.data.id}</div>;\n 49 }\n 50 return <div>Loading</div>;\n 51 }\n 52 }\n 53 />\n 54 </GoogleMapReact>\n```\n\n```text\n11 \"relay\": \"relay-compiler --src ./src --schema ./data/schema.graphql --extensions=js,jsx\",\n```\n\n```text\n1 # A city to be used on the map\n 2 type City {\n 3 id: Int!\n 4 lat: Float\n 5 lng: Float\n 6 todo: [ToDo]\n 7 }\n 8 \n 9 # Mutations for the To Do List\n 10 type Mutation {\n 11 createToDo(city_id: Int!, text: String!): ToDo\n 12 }\n 13 \n 14 # An array of Cities\n 15 type Query {\n 16 cities: [City]\n 17 city(id: Int): City\n 18 }\n 19 \n 20 # A To Do for a city\n 21 type ToDo {\n 22 city_id: Int!\n 23 text: String\n 24 likes: Int\n 25 id: Int!\n 26 }\n```\n\n```text\n1 {\n 2 \"plugins\": [\n 3 [\"relay\", {\n 4 \"compat\": true,\n 5 \"schema\": \"./data/schema.graphql\",\n 6 \"enforceSchema\": true,\n 7 \"suppressWarnings\": false,\n 8 \"debug\": false,\n 9 }]\n 10 ],\n 11 \"presets\": [\"react\", \"es2015\", \"es2016\", \"es2017\"]\n 12 }~\n```\n\n```text\n\"relay\": \"relay-compiler --src ./src --schema ./data/schema.graphql --extensions=js --extensions=jsx\"\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":194,"estimatedTokens":988}}1169{"id":"stack-36036956","source":"stackoverflow","questionId":36036956,"title":"Separate graphql/relay backend and frontend","tags":["reactjs","graphql","relay","sangria"],"text":"Title: Separate graphql/relay backend and frontend\nTags: reactjs, graphql, relay, sangria\nSource: Stack Overflow\n\nQuestion:\nI would like to separate my backend and my frontend with different projects using relay. The reason I'm doing this is because I'm using a particular relay/graphql backend, sangria and would like to keep the frontend development separate from the Scala development.\n\nWould it be possible to connect a react relay frontend application on one server communicating to another graphql server backend. It seems everywhere that relay assume that its endpoint is on the same host with endpoint /graphql\n\n========================================\n\nCode:\n```text\nRelay.injectNetworkLayer(\n new Relay.DefaultNetworkLayer('http://example.com/graphql')\n);\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":17,"estimatedTokens":193}}1170{"id":"stack-52786220","source":"stackoverflow","questionId":52786220,"title":"how to fix graphql mutations typename errors","tags":["javascript","graphql","graphql-js","apollo-client"],"text":"Title: how to fix graphql mutations typename errors\nTags: javascript, graphql, graphql-js, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI try to make a GraphQl mutation using apollo graphQl client. \n\n**This makes an `error 500` when the mutation variables contains `___typename` properties** (which obviously don't exist in the graphQl schema).\n\nTo fix that it is possible to set `addTypename: false` in the graphQl client config: \n\n```\nconst graphqlClient = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache({\n addTypename: false\n })\n})\n```\n\nNow the mutation almost worksβ¦ \n\nBut there is a new error: `You're using fragments in your queries, but either don't have the addTypename: true option set in Apollo Client, or you are trying to write a fragment to the store without the __typename. Please turn on the addTypename option and include __typename when writing fragments so that Apollo Client can accurately match fragments.`\n\n**So how should the graphQl client be configured to handle mutations?** \n\nfor now I use a cleanup function found here: \n\n```\nconst removeTypename = (value) => {\n if (value === null || value === undefined) {\n return value;\n } else if (Array.isArray(value)) {\n return value.map(v => removeTypename(v));\n } else if (typeof value === 'object') {\n const newObj = {};\n Object.keys(value).forEach(key => {\n if (key !== '__typename') {\n newObj[key] = removeTypename(value[key]);\n }\n });\n return newObj;\n }\n return value;\n};\n```\n\nbut it feels hacky. Is there something built-in graphql client?\n\n========================================\n\nTop Answer:\nTaking the value of some query and then plugging it mutation as a variable is an atypical scenario, so there's not an easy solve for what you're trying to do. While you can configure your client instance to omit the `__typename` field from your results, an object's `__typename` (along with its `id` or `_id`) are used as cache keys -- omitting it is going to cause some unexpected behavior if it doesn't outright break things.\n\nBy far the best approach to this is just to manipulate the query result before passing it in as a variable. I think something like this should do the trick:\n\n```\nfunction stripTypenames (value) {\n if (Array.isArray(value)) {\n return value.map(stripTypenames)\n } else if (value !== null && typeof(value) === \"object\") {\n const newObject = {}\n for (const property in value) {\n if (property !== '__typename') {\n newObject[property] = stripTypenames(value[property])\n }\n }\n return newObject\n } else {\n return value\n }\n}\n```\n\nOn a side note, unless you're using client-side data (i.e. `apollo-link-state`) it's hard to image a situation where you would fetch some data from the server and then have to feed that same data into a mutation. If the data exists on the server already, it should be sufficient to pass in an id for it and retrieve it server-side. If you're having to jump through these sort of hoops, it may be an indicator that the API itself needs to change.\n\n========================================\n\nCode:\n```text\nconst graphqlClient = new ApolloClient({\n link: authLink.concat(httpLink),\n cache: new InMemoryCache({\n addTypename: false\n })\n})\n```\n\n```text\nconst removeTypename = (value) => {\n if (value === null || value === undefined) {\n return value;\n } else if (Array.isArray(value)) {\n return value.map(v => removeTypename(v));\n } else if (typeof value === 'object') {\n const newObj = {};\n Object.keys(value).forEach(key => {\n if (key !== '__typename') {\n newObj[key] = removeTypename(value[key]);\n }\n });\n return newObj;\n }\n return value;\n};\n```\n\n```text\nerror 500\n```\n\n```text\n___typename\n```\n\n```text\naddTypename: false\n```\n\n```text\nYou're using fragments in your queries, but either don't have the addTypename: true option set in Apollo Client, or you are trying to write a fragment to the store without the __typename. Please turn on the addTypename option and include __typename when writing fragments so that Apollo Client can accurately match fragments.\n```\n\n```text\nconst omitTypename = (key, value) => {\n return key === '__typename' ? undefined : value\n}\n\nconst omitTypenameLink = new ApolloLink((operation, forward) => {\n if (operation.variables) {\n operation.variables = JSON.parse(\n JSON.stringify(operation.variables),\n omitTypename\n )\n }\n return forward(operation)\n})\n```\n\n```text\nconst link = ApolloLink.from([authLink, omitTypenameLink, httpLink])\nconst cache = new InMemoryCache()\n\nconst graphqlClient = new ApolloClient({\n link,\n cache\n})\n```\n\n```text\nfunction stripTypenames (value) {\n if (Array.isArray(value)) {\n return value.map(stripTypenames)\n } else if (value !== null && typeof(value) === \"object\") {\n const newObject = {}\n for (const property in value) {\n if (property !== '__typename') {\n newObject[property] = stripTypenames(value[property])\n }\n }\n return newObject\n } else {\n return value\n }\n}\n```\n\n```text\n__typename\n```\n\n```text\n__typename\n```\n\n```text\nid\n```\n\n```text\n_id\n```\n\n```text\napollo-link-state\n```\n\n========================================\n\nComments:\n- Are you trying to use the data returned by another query as one of your mutation's variables? Otherwise, it's not clear when the variables passed to a mutation would contain a `__typename` field.\n- yes exactly. The `___typename` were added from a previous query\n- thank you for the explanation. But I don't get how this is an atypical scenario: I fetch an `article` from the server, the user modify some fields from the article and then post back the `article` as a mutation. What is atypical here?\n- Conceptually, the type returned by a query and the input type used as an argument are completely different things, even if as Javascript objects they one or more fields. Just like you can't use types and input types interchangeably within a schema, there shouldn't be an expectation that they can be used interchangeably client-side.\n- Come to think of it, you could encapsulate the above logic inside a custom ApolloLink to automatically transform *any* variables you send. That might be the way to go.\n- Ok thank you very much for the explanation. I would really appreciate an example of the custom apollo link encapsulation.\n- oh! and, do you think it's better to remove the `___typename` just after the object is fetched, or is it better to remove them jsut before to send the murtation? (the former sounds cleaner to me)\n- Be careful with this approach, if there is anything that is not a JS primitive like a File or a Blob, that will be removed (as in cast to the closest stringifiable value like {}) and never be sent as part of the graphQl call, this was the cause of a bad afternoon for me !\n- @MatteoHertel I would appreciate it if you could your method of removing typenames without losing File or Blob data.\n- @FaureHu I've added a full version here github.com/apollographql/apollo-feature-requests/issues/… case that breaks here's the code ``` function stripTypenames(obj: any, propToDelete: string) { for (const property in obj) { if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) { delete obj.property; const newData = stripTypenames(obj[property], propToDelete); obj[property] = newData; } else { if (property === propToDelete) { delete obj[property]; } } } return obj; } ```","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":200,"estimatedTokens":1852}}1171{"id":"stack-76090560","source":"stackoverflow","questionId":76090560,"title":"Streaming data using HotChocolate GraphQl for .NET project - all results at once instead of one by one problem","tags":[".net","graphql","stream","hotchocolate","minimal-apis"],"text":"Title: Streaming data using HotChocolate GraphQl for .NET project - all results at once instead of one by one problem\nTags: .net, graphql, stream, hotchocolate, minimal-apis\nSource: Stack Overflow\n\nQuestion:\nI'm using C#, .NET7 minimal API and HotChocolate GraphQl. I'm trying to setup graphQl simple query endpoint which will be able to return stream like this:\n\n```\npublic async IAsyncEnumerable GetDummyNumbers()\n{\n for (var i = 0; i It works as is but even though it's IAsyncEnumerable, by default it's waiting until all values are resolved and then sends all of them at once to the client.\n\nSolutions I've found which could've been partially useful:\n\n- There is '@stream' directive for GraphQl but it's not working out of the box, probably some configuration or implementation is required but I didn't find resources how to achieve this.\n\n- Subscriptions could work but it's not exactly what I need, because I don't need real-time data, I need only to stream data per request.\n\nI tried to check official package documentation but I didn't find anything which would help me resolve that. Also looking for any similar problem or examples didn't gave me an answer.\n\nI would appreciate any help which will get me closer to solution when I can call this endpoint and get results immediately when available one by one.\n\n========================================\n\nCode:\n```text\npublic async IAsyncEnumerable<string> GetDummyNumbers()\n{\n for (var i = 0; i < 10; i++)\n {\n await Task.Delay(TimeSpan.FromSeconds(1));\n yield return i.ToString();\n }\n}\n```\n\n```csharp\nservices.AddGraphQLServer()\n .ModifyOptions(o =>\n {\n o.EnableStream = true;\n })\n .AddQueryType<Query>()\n ...\n```\n\n```csharp\npublic class Query\n{\n [StreamResult]\n public async IAsyncEnumerable<Result> GetDummyNumbers()\n {\n for (var i = 0; i < 5; i++)\n {\n await Task.Delay(TimeSpan.FromSeconds(1));\n yield return new Result(i);\n }\n }\n\n public record Result(int id);\n}\n```\n\n```text\nquery test {\n dummyNumbers @stream {\n id\n }\n}\n```\n\n```text\n[StreamResult]\n```\n\n```text\n@stream\n```\n\n========================================\n\nComments:\n- I tried the same code and it doesn't work. I tried the latest HotChocholate 14 to 16.","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":571}}1172{"id":"stack-48897001","source":"stackoverflow","questionId":48897001,"title":"How can I add computed state to graph objects in React Apollo?","tags":["javascript","reactjs","graphql","apollo","react-apollo"],"text":"Title: How can I add computed state to graph objects in React Apollo?\nTags: javascript, reactjs, graphql, apollo, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI really like the graphQL pattern of having components request their own data, but some data properties are expensive to compute and so I want to localize the logic (and code) to do so.\n\n```\nfunction CheaterList({ data: { PlayerList: players } }) {\n return (\n \n {players && players.map(({ name, isCheater }) => (\n \n- {name} seems to be a {isCheater ? 'cheater' : 'normal player'}\n ))}\n \n );\n}\n\nexport default graphql(gql`\n query GetList {\n PlayerList {\n name,\n isCheater\n }\n }\n`)(CheaterList);\n```\n\nThe schema looks like:\n\n```\ntype Queries {\n PlayerList: [Player]\n}\n\ntype Player {\n name: String,\n kills: Integer,\n deaths: Integer\n}\n```\n\nAnd so I want to add the `isCheater` property to Player and have its code be:\n\n```\nfunction computeIsCheater(player: Player){\n // This is a simplified version of what it actually is for the sake of the example\n return player.deaths == 0 || (player.kills / player.deaths) > 20;\n}\n```\n\nHow would I do that?\n\nAnother way of phrasing this would be: how do I get the isCheater property to look as though it came from the backend? (However, if an optimistic update were applied the function should rerun on the new data)\n\n========================================\n\nCode:\n```text\nfunction CheaterList({ data: { PlayerList: players } }) {\n return (\n <ul>\n {players && players.map(({ name, isCheater }) => (\n <li key={name}>{name} seems to be a {isCheater ? 'cheater' : 'normal player'}</li>\n ))}\n </ul>\n );\n}\n\nexport default graphql(gql`\n query GetList {\n PlayerList {\n name,\n isCheater\n }\n }\n`)(CheaterList);\n```\n\n```text\ntype Queries {\n PlayerList: [Player]\n}\n\ntype Player {\n name: String,\n kills: Integer,\n deaths: Integer\n}\n```\n\n```text\nfunction computeIsCheater(player: Player){\n // This is a simplified version of what it actually is for the sake of the example\n return player.deaths == 0 || (player.kills / player.deaths) > 20;\n}\n```\n\n```text\nisCheater\n```\n\n```text\nimport { withClientState } from 'apollo-link-state';\n\nconst stateLink = withClientState({\n cache, //same cache object you pass to the client constructor\n resolvers: linkStateResolvers,\n});\n\nconst client = new ApolloClient({\n cache,\n link: ApolloLink.from([stateLink, new HttpLink()]),\n});\n```\n\n```text\nconst linkStateResolvers = {\n Player: {\n isCheater: (player, args, ctx) => {\n return player.deaths == 0 || (player.kills / player.deaths) > 20\n }\n }\n}\n```\n\n```text\nexport default graphql(gql`\n query GetList {\n PlayerList {\n name\n kills\n deaths\n isCheater @client\n }\n }\n`)(CheaterList);\n```\n\n```text\napollo-client\n```\n\n```text\n@client\n```\n\n```text\napollo-link-state\n```\n\n```text\napollo-link-state\n```\n\n========================================\n\nComments:\n- According to the docs it looks like you can pass a second argument to `graphql` to pass computed properties?\n- @Varinder thats how you pass properties to the query which is different than what I'm asking here.\n- True, would Arbitrary Transformation be of any help?\n- No, thats the equivalent of computing the property value from within the component itself. I would like each component to only declare that it needs `Player { isCheater }` and then have the data appear, similar to how it would if the data were coming from a remote.","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":163,"estimatedTokens":865}}1173{"id":"stack-48725049","source":"stackoverflow","questionId":48725049,"title":"Connect Gatsby with Postgres","tags":["postgresql","graphql","gatsby"],"text":"Title: Connect Gatsby with Postgres\nTags: postgresql, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI would like to pull data from Postgres to Gatsby using graphql. I have written node.js server, but i cannot find way to use it in gatsby.\n(https://github.com/gstuczynski/graphql-postgres-test)\nHave you any ideas?\n\n========================================\n\nTop Answer:\nThe `gatsby-source-pg` module connects directly to your database and adds the tables/views/functions/etc to Gatsby's GraphQL API. To use it, install the module:\n\n```\nyarn add gatsby-source-pg\n```\n\nthen add to to the plugin list in `gatsby-config.js`:\n\n```\nmodule.exports = {\n plugins: [\n /* ... */\n {\n resolve: \"gatsby-source-pg\",\n options: {\n connectionString: \"postgres://localhost/my_db\",\n },\n },\n ],\n};\n```\n\n*The connection string can also include username/password, host, port and SSL if you need to connect to remote database; e.g.: `postgres://pg_user:pg_pass@pg_host:5432/pg_db?ssl=1`*\n\nYou can query it in your components using the root `postgres` field, e.g.:\n\n```\n{\n postgres {\n allPosts {\n nodes {\n id\n title\n authorId\n userByAuthorId {\n id\n username\n }\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n plugins: [\n {\n resolve: 'gatsby-source-graphql', // <- Configure plugin\n options: {\n typeName: 'HASURA',\n fieldName: 'hasura', // <- fieldName under which schema will be stitched\n createLink: () =>\n createHttpLink({\n uri: `https://my-graphql.herokuapp.com/v1alpha1/graphql`, // <- Configure connection GraphQL url\n headers: {},\n fetch,\n }),\n refetchInterval: 10, // Refresh every 10 seconds for new data\n },\n },\n ]\n}\n```\n\n```text\nconst Index = ({ data }) => (\n <div>\n <h1>My Authors </h1>\n <AuthorList authors={data.hasura.author} />\n </div>\n)\nexport const query = graphql`\n query AuthorQuery {\n hasura { # <- fieldName as configured in the gatsby-config\n author { # Normal GraphQL query\n id\n name\n }\n }\n }\n```\n\n```text\ngatsby-source-graphql\n```\n\n```text\nyarn add gatsby-source-pg\n```\n\n```js\nmodule.exports = {\n plugins: [\n /* ... */\n {\n resolve: \"gatsby-source-pg\",\n options: {\n connectionString: \"postgres://localhost/my_db\",\n },\n },\n ],\n};\n```\n\n```graphql\n{\n postgres {\n allPosts {\n nodes {\n id\n title\n authorId\n userByAuthorId {\n id\n username\n }\n }\n }\n }\n}\n```\n\n```text\ngatsby-source-pg\n```\n\n```text\ngatsby-config.js\n```\n\n```text\npostgres://pg_user:pg_pass@pg_host:5432/pg_db?ssl=1\n```\n\n```text\npostgres\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":153,"estimatedTokens":671}}1174{"id":"stack-75636898","source":"stackoverflow","questionId":75636898,"title":"How to set header key and value with go packages : shurcooL/graphql or hasura/go-graphql-client?","tags":["go","graphql","http-headers","hasura"],"text":"Title: How to set header key and value with go packages : shurcooL/graphql or hasura/go-graphql-client?\nTags: go, graphql, http-headers, hasura\nSource: Stack Overflow\n\nQuestion:\nSo I want to query datas from Graphql server via Go with either shurcool or hasura go client (Go packages), but the datas server required something like 'x-hasura-admin-secret' key and value includes inside a request header.\n\nThere's no mentioned in the both packages docs of how to do this (set header key & value), it only mentioned how to set access token.\n\n========================================\n\nCode:\n```golang\nimport (\n \"net/http\"\n graphql \"github.com/hasura/go-graphql-client\"\n)\n\nfunc gqlInit() {\n client := graphql.NewClient(\"your graphql url here\", nil)\n client = client.WithRequestModifier(func(r *http.Request) {\n r.Header.Set(\"x-hasura-admin-secret\", \"secret\")\n })\n}\n```\n\n```golang\nimport (\n \"net/http\"\n graphql \"github.com/shurcooL/graphql\"\n)\n\ntype hasuraAuthTransport struct {\n secret string\n}\n\nfunc (h hasuraAuthTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {\n req.Header.Set(\"x-hasura-admin-secret\", h.secret)\n return http.DefaultTransport.RoundTrip(req)\n}\n\nfunc gqlInit() {\n client := graphql.NewClient(\"your graphql url here\", &http.Client{\n Transport: hasuraAuthTransport{secret: \"secret\"},\n })\n}\n```\n\n```text\nWithRequestModifier\n```\n\n```text\n*http.Client\n```\n\n========================================\n\nComments:\n- So this means you have to create a new client for every request right with the shurcooL package.\n- @NickN. no, one http client for every graphql client. you can re-use the client for the next request","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":61,"estimatedTokens":423}}1175{"id":"stack-32615683","source":"stackoverflow","questionId":32615683,"title":"fetching additional information for a particular list item in relay/graphql","tags":["graphql","relayjs","graphql-js"],"text":"Title: fetching additional information for a particular list item in relay/graphql\nTags: graphql, relayjs, graphql-js\nSource: Stack Overflow\n\nQuestion:\nUsing Relay and GraphQL, let's say that I have a schema that returns a viewer, and an embedded list of associated documents. The root query (composed with fragments) would look like something like this:\n\n```\nquery Root {\n viewer {\n id,\n name,\n groups {\n edges {\n node {\n id,\n name,\n }\n }\n }\n }\n}\n```\n\nThis will allow me to display the user, and a list of all of its associated groups. \n\nNow let's say that I want the user to be able to click on that list item, and have it expand to show the comments associated with that particular list item. How should I restructure my query for the relay route such that I can receive those comments? If I add a comments edge to my groups edge, then won't it fetch the comments for all of the groups?\n\n```\nquery Root {\n viewer {\n id,\n name,\n groups {\n edges {\n node {\n id,\n name,\n comments {\n edges {\n node {\n id,\n content\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\nOr should I alter the route query to find a specific group?\n\n```\nquery Root {\n group(id: \"someid\"){\n id,\n name,\n comments {\n edges {\n node {\n id,\n content\n }\n }\n }\n },\n viewer {\n id,\n name,\n groups {\n edges {\n node {\n id,\n name,\n }\n }\n }\n }\n}\n```\n\nMy concern is, in particular, using this within the context of `relay`. I.e., how can I efficiently construct a route query that will only fetch the comments for the expanded list item (or items), while still taking advantage of the cached data that already exists, and will be updated when doing mutations? The above example might work for a specific expanded group, but I'm not sure how I could expand multiple groups simultaneously without fetching those fields for *all* of the group items.\n\n========================================\n\nCode:\n```text\nquery Root {\n viewer {\n id,\n name,\n groups {\n edges {\n node {\n id,\n name,\n }\n }\n }\n }\n}\n```\n\n```text\nquery Root {\n viewer {\n id,\n name,\n groups {\n edges {\n node {\n id,\n name,\n comments {\n edges {\n node {\n id,\n content\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n```text\nquery Root {\n group(id: \"someid\"){\n id,\n name,\n comments {\n edges {\n node {\n id,\n content\n }\n }\n }\n },\n viewer {\n id,\n name,\n groups {\n edges {\n node {\n id,\n name,\n }\n }\n }\n }\n}\n```\n\n```text\nrelay\n```\n\n```js\nGroup = Relay.createContainer(Group, {\n initialVariables: {\n numCommentsToShow: 10,\n showComments: false,\n },\n fragments: {\n group: () => Relay.QL`\n fragment on Group {\n comments(first: $numCommentsToShow) @include(if: $showComments) {\n edges {\n node {\n content,\n id,\n },\n },\n },\n id,\n name,\n }\n `,\n },\n});\n```\n\n```js\nclass Group extends React.Component {\n _handleShowCommentsClick() {\n this.props.relay.setVariables({showComments: true});\n }\n renderComments() {\n return this.props.group.comments\n ? <Comments comments={this.props.group.comments} />\n : <button onClick={this._handleShowCommentsClick}>Show comments</button>;\n }\n render() {\n return (\n <div>\n ...\n {this.renderComments()}\n </div>\n ); \n }\n}\n```\n\n```text\n@skip\n```\n\n```text\n@include\n```\n\n```text\nthis.props.group.comments\n```\n\n```text\nthis.props.relay.setVariables({showComments: true})\n```\n\n========================================\n\nComments:\n- For interest's sake: github.com/facebook/relay/commit/…\n- Is there a way to fetch additional data for a single item in a list query (*edges*)? **Why?** Im trying to seamlessly transit/scale list item to a single item view. I've tested all kind of strategies but I can't find a way.\n- Yes. At the moment you want to show the single item view, you will have come to know the item's ID. At that point, the single item view should roll up to a **node** query at the root. `node(id: $itemID) { ${Component.getFragment('item')} }`. Since the item will already be in the store from the **edges** fetch, no additional network request will be required.\n- Yes, this is what I currently have but that's the problem - two different, isolated views and queries and I can't find a way to smootly animate list to single item with this setup. Please look at this dribbble GIF. **React part is simple**, I'll just calculate the screen size on click and scale the list item to full-screen which pushes other list items out of viewport but how to fetch additional data for that item? I can't use `node()` query as second query for same list component or can I?\n- @Solo, can you make a new question on Stack Overflow about this? My answer is too long for a comment.\n- Sure, here's my question.","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":235,"estimatedTokens":1246}}1176{"id":"stack-71132413","source":"stackoverflow","questionId":71132413,"title":"FetchError: graphql failed, reason: unable to verify the first certificate","tags":["node.js","typescript","http","https","graphql"],"text":"Title: FetchError: graphql failed, reason: unable to verify the first certificate\nTags: node.js, typescript, http, https, graphql\nSource: Stack Overflow\n\nQuestion:\ni'm using the graphql-request npm package in order to use graphql in my software.\ni have the following line in my code:\n\n```\nconst client: GraphQLClient = new GraphQLClient(process.env.OCEAN_ENDPOINT, {});\nclient.setHeaders({ Authorization: `Bearer: ${token}` });\n```\n\nand then i want to fire a request i use:\n\n```\nawait client.request(query, variables);\n```\n\nuntil two days ago my endpoint was an http url, but now it changed to https and from that moment i'm getting this error:\n\n```\nFetchError: request to https://{graphqlEndpoint}/v1/graphql failed, reason: unable to verify the first certificate\n```\n\nhas anyone faced this issue before?\n\n========================================\n\nCode:\n```text\nconst client: GraphQLClient = new GraphQLClient(process.env.OCEAN_ENDPOINT, {});\nclient.setHeaders({ Authorization: `Bearer: ${token}` });\n```\n\n```text\nawait client.request(query, variables);\n```\n\n```text\nFetchError: request to https://{graphqlEndpoint}/v1/graphql failed, reason: unable to verify the first certificate\n```\n\n========================================\n\nComments:\n- Does this answer your question? Error: unable to verify the first certificate in nodejs","metadata":{"transformedAt":"2026-08-18T18:32:36.232Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":47,"estimatedTokens":333}}1177{"id":"stack-46108769","source":"stackoverflow","questionId":46108769,"title":"Apollo GraphQL: How to Set Up Secure Websockets?","tags":["websocket","graphql","apollo","apollo-client","apollo-server"],"text":"Title: Apollo GraphQL: How to Set Up Secure Websockets?\nTags: websocket, graphql, apollo, apollo-client, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm setting up my dev system to use `https`, and Chrome is complaining about my websocket not begin secure:\n\n VM4965:161 Mixed Content: The page at 'https://mywebsite.io/' was\n loaded over HTTPS, but attempted to connect to the insecure WebSocket\n endpoint 'ws://mywebsite.io:4000/subscriptions'. This request has\n been blocked; this endpoint must be available over WSS.\n\nHere's my current server-side setup for WS, based on the Apollo docs:\n\n```\nconst localHostString = 'mywebsite.io'; \nconst pubsub = new PubSub();\n\n// additional context you use for your resolvers, if any\nconst context = {connectors: connectors};\n\n//SET UP APOLLO QUERY / MUTATIONS / PUBSUB\n//start a graphql server with Express handling a possible Meteor current user\ncreateApolloServer({\n schema,\n context\n});\n\nconst METEOR_PORT = 3000;\nconst GRAPHQL_PORT = 4000;\nconst server = express();\n\nserver.use('*', cors({ origin: `https://${localHostString}:${METEOR_PORT}` }));\n\nserver.use('/graphql', bodyParser.json(), graphqlExpress({\n schema,\n context\n}));\n\nserver.use('/graphiql', graphiqlExpress({\n endpointURL: '/graphql',\n subscriptionsEndpoint: `ws://${localHostString}:${GRAPHQL_PORT}/subscriptions`\n}));\n\n// Wrap the Express server\nconst ws = createServer(server);\nws.listen(GRAPHQL_PORT, () => {\n console.log(`GraphQL Server is now running on http://${localHostString}:${GRAPHQL_PORT}`);\n console.log(`GraphiQL available at http://${localHostString}:${GRAPHQL_PORT}/graphiql`);\n // Set up the WebSocket for handling GraphQL subscriptions\n new SubscriptionServer({\n execute,\n subscribe,\n schema\n }, {\n server: ws,\n path: '/subscriptions',\n });\n});\n```\n\nHow can I update this so as to use WSS rather than WS websockets?\n\nThanks in advance to all for any info.\n\n========================================\n\nCode:\n```text\nconst localHostString = 'mywebsite.io'; \nconst pubsub = new PubSub();\n\n// additional context you use for your resolvers, if any\nconst context = {connectors: connectors};\n\n//SET UP APOLLO QUERY / MUTATIONS / PUBSUB\n//start a graphql server with Express handling a possible Meteor current user\ncreateApolloServer({\n schema,\n context\n});\n\nconst METEOR_PORT = 3000;\nconst GRAPHQL_PORT = 4000;\nconst server = express();\n\nserver.use('*', cors({ origin: `https://${localHostString}:${METEOR_PORT}` }));\n\nserver.use('/graphql', bodyParser.json(), graphqlExpress({\n schema,\n context\n}));\n\nserver.use('/graphiql', graphiqlExpress({\n endpointURL: '/graphql',\n subscriptionsEndpoint: `ws://${localHostString}:${GRAPHQL_PORT}/subscriptions`\n}));\n\n// Wrap the Express server\nconst ws = createServer(server);\nws.listen(GRAPHQL_PORT, () => {\n console.log(`GraphQL Server is now running on http://${localHostString}:${GRAPHQL_PORT}`);\n console.log(`GraphiQL available at http://${localHostString}:${GRAPHQL_PORT}/graphiql`);\n // Set up the WebSocket for handling GraphQL subscriptions\n new SubscriptionServer({\n execute,\n subscribe,\n schema\n }, {\n server: ws,\n path: '/subscriptions',\n });\n});\n```\n\n```text\nhttps\n```\n\n```text\nsubscriptionsEndpoint: `ws://${localHostString}:${GRAPHQL_PORT}/subscriptions\n```\n\n```text\nsubscriptionsEndpoint: `wss://${localHostString}:${GRAPHQL_PORT}/subscriptions\n```\n\n```text\nws\n```\n\n```text\nwss\n```\n\n========================================\n\nComments:\n- you had any luck with the problem?\n- Yes. At the time I solved it, for development purposes only, by using ngrok. I set up a separate ngrok URL for https and for wss. Ngrok handled calls to those secure URLs by serving data from my local dev system, which was still on http and ws. HOWEVER when I tried that recently with my latest server/client code and with the latest Apollo libraries, I was seeing errors in Firefox, with some ngrok packages not loading. Currently I'm putting my app on Galaxy. For dev purposes using https/wss, I'll probably have to install an SSL certificate on my local dev system.","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":140,"estimatedTokens":1023}}1178{"id":"stack-41727923","source":"stackoverflow","questionId":41727923,"title":"GraphQL field's resolver not getting called","tags":["express","graphql","apollo-server"],"text":"Title: GraphQL field's resolver not getting called\nTags: express, graphql, apollo-server\nSource: Stack Overflow\n\nQuestion:\nI'm using apollo-server and testing using GraphiQL in my browser. I set up my resolvers based on Apollo's GitHunt-API example, but the resolver on the field \"review.extraStuff\" never gets called. \n\n### Resolver\n\n```\nconst rootResolvers = {\n review(root, args, context) {\n console.log('resolving review');\n return {'HasErrors': true}\n }\n}\n\nconst extraStuff = (root, args, context) => {\n console.log('resolving extraStuff');\n return \"yes\";\n}\n\nrootResolvers.review.extraStuff = extraStuff;\n\nexport default {\n RootQuery: rootResolvers\n};\n```\n\n### Schema\n\n```\nconst Review = `\n type Review {\n HasErrors: Boolean\n extraStuff: String\n }\n`\n\nconst RootQuery = `\n type RootQuery {\n review(id: String!): Review\n }\n`;\n\nconst SchemaDefinition = `\n schema {\n query: RootQuery\n }\n`;\n```\n\n### Query result from GraphiQL\n\nhttps://i.sstatic.net/Q6ZdV.png\n\n### Additional Info\n\nI know that Apollo is aware of my extraStuff resolver because if I set \"requireResolversForNonScalar\" to true, I don't get a message telling me extraStuff is missing a resolve function. I've added logging to both the schema and the apolloExpress middleware and learned nothing.\n\n========================================\n\nCode:\n```text\nconst rootResolvers = {\n review(root, args, context) {\n console.log('resolving review');\n return {'HasErrors': true}\n }\n}\n\nconst extraStuff = (root, args, context) => {\n console.log('resolving extraStuff');\n return \"yes\";\n}\n\nrootResolvers.review.extraStuff = extraStuff;\n\nexport default {\n RootQuery: rootResolvers\n};\n```\n\n```text\nconst Review = `\n type Review {\n HasErrors: Boolean\n extraStuff: String\n }\n`\n\nconst RootQuery = `\n type RootQuery {\n review(id: String!): Review\n }\n`;\n\nconst SchemaDefinition = `\n schema {\n query: RootQuery\n }\n`;\n```\n\n```text\nconst rootResolvers = {\n review(root, args, context) {\n console.log('resolving review');\n return {'HasErrors': true}\n }\n}\n\nconst reviewResolvers = {\n extraStuff(root, args, context) {\n console.log('resolving extraStuff');\n return \"yes\";\n }\n}\n\nexport default {\n RootQuery: rootResolvers\n Review: reviewResolvers\n};\n```\n\n========================================\n\nComments:\n- extrastuff is a string and therefore a scalar\n- So, you're saying that \"requireResolversForNonScalar\" wouldn't catch it? That would make sense.\n- @w00t Care to elaborate at all? I'm looking through the graphql-tools source code because my problem seems to be in makeExecutableSchema. It looks like scalar fields are treated differently, but I'm still not clear what my exact problem is.\n- try making the field an object and see if you can make it work that way? Unfortunately I haven't actually tried graphql-tools yet :)","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":132,"estimatedTokens":723}}1179{"id":"stack-68962977","source":"stackoverflow","questionId":68962977,"title":"Filtering on an ACF Post Object-field in wordpress in Gatsby and GraphQL","tags":["wordpress","graphql","gatsby","advanced-custom-fields"],"text":"Title: Filtering on an ACF Post Object-field in wordpress in Gatsby and GraphQL\nTags: wordpress, graphql, gatsby, advanced-custom-fields\nSource: Stack Overflow\n\nQuestion:\nThis is up question on Querying wordpress with meta queries from Gatsby\n\nAfter a bit debugging I've gathered, and please correct me if I'm wrong, that Gatsby on build downloads the entire data structure and caches it. So all the GraphQL queries are performed against the cache. This makes all adjustments I try to make to wordpress (for example https://www.wpgraphql.com/2020/04/14/query-posts-based-on-advanced-custom-field-values-by-registering-a-custom-where-argument/) useless. I'm confined to using the filter argument for my GraphQL queries in Gatsby.\n\nConsider the following query:\n\n```\nquery Test {\n allWpPage(filter: {pagesGeo: {}}) {\n edges {\n node {\n pagesGeo {\n genericPage {\n ... on WpPage {\n id\n }\n }\n hreflangValue\n }\n }\n }\n }\n}\n```\n\nIn this case I want to filter on genericPage, but it's not in the list of available filters in the GraphiQL query tester.\n\nIn Wordpress the custom field generic_page is defined with the help of advanced custom fields and it's of the field type 'Post Object'. As you can see I'm able to query the field just fine, and it would be easy for me to create a meta query in Wordpress to filter on the field. It would looks something like:\n\n```\n$query_args['meta_query'] = [\n \"relation\" => \"OR\",\n [\n 'key' => 'generic_page',\n 'value' => $postObjectId,\n 'compare' => '='\n ],\n [\n 'key' => 'generic_page',\n 'value' => $postObjectId2,\n 'compare' => '='\n ],\n];\n```\n\nIs there a way to make it possible for me to filter on genericPage in Gatsby?\n\nIf not, are there any alternative solutions for me to extract the data I need?\n\n========================================\n\nCode:\n```text\nquery Test {\n allWpPage(filter: {pagesGeo: {}}) {\n edges {\n node {\n pagesGeo {\n genericPage {\n ... on WpPage {\n id\n }\n }\n hreflangValue\n }\n }\n }\n }\n}\n```\n\n```text\n$query_args['meta_query'] = [\n \"relation\" => \"OR\",\n [\n 'key' => 'generic_page',\n 'value' => $postObjectId,\n 'compare' => '='\n ],\n [\n 'key' => 'generic_page',\n 'value' => $postObjectId2,\n 'compare' => '='\n ],\n];\n```\n\n```php\nadd_action( 'graphql_register_types', function() {\n register_graphql_field( 'Page', 'genericPage', [\n 'type' => 'Integer',\n 'description' => 'generic_page meta value',\n 'resolve' => function( \\WPGraphQL\\Model\\Post $post ) {\n return (int) get_post_meta( $post->databaseId, 'generic_page', true );\n }\n ] );\n});\n```\n\n```text\npagesGeo\n```\n\n```text\ngeneric_page\n```\n\n```text\npage\n```\n\n```text\nfilter.pagesGeo.genericPage\n```\n\n```text\nfilter.genericPage\n```\n\n```text\ngenericPage\n```\n\n```text\nfunctions.php\n```\n\n```text\ngeneric_page\n```\n\n```text\ndatabaseId\n```\n\n```text\n2\n```\n\n```text\n82\n```\n\n```text\nin\n```\n\n```text\ndata.allWpPage.nodes\n```\n\n```text\ngenericPage\n```\n\n```text\npagesGeo.genericPage.databaseId\n```\n\n```text\ngatsby develop\n```\n\n========================================\n\nComments:\n- Since you are using ACF for fields you will need this - wpgraphql.com/acf . As an additional note, don't forget to go to check Show in GraphQL at the very bottom of the ACF page when editing your custom fields. Read this for more info - stackoverflow.com/questions/63647590/…\n- @MartinMirchev Thanks for the answer. I have the plugin and the field is shown in GraphQL. As you can see from my schema, the GenericPage field can be selected. However, I can't filter on it. Might be that it's not perceived as a node?\n- I think you must register the argument first. wpgraphql.com/2020/04/14/…\n- @MartinMirchev If you look at my linked question you can see that a \"where\"-filter is restricted in Gatsby. But, as far as I can gather, Gatsby downloads all the data during build and then runs the GraphQL-queries on that cache. So if I register a new where argument in Wordpress, that won't affect the queries in Gatsby. If you have been able to do this, please provide a code example so that I can try and mimic it.\n- This was just the kind of workaround I was looking for, and a great explanatory answer. Two thumbs up and bounty rewarded. Sidenote: I was using the same plugins as you plugins as you mentioned. It does seem like you should be able to do a \"filter.pagesGeo.genericPage\" but somewhere there's a bug. I might issue a bug report with the `gatsby-source-wordpress`-plugin. Thank you for you help.\n- Thank you so much for this. How would I modify this to filter by a custom field on the post object? I'm not working with Pages. I've tried register_graphql_field('Post', 'clientId') but no luck...","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":177,"estimatedTokens":1197}}1180{"id":"stack-69400123","source":"stackoverflow","questionId":69400123,"title":"How do I make Graphql Code Generator for typescript make its enums into pascal case instead of snake case?","tags":["javascript","typescript","graphql","graphql-codegen","pascalcasing"],"text":"Title: How do I make Graphql Code Generator for typescript make its enums into pascal case instead of snake case?\nTags: javascript, typescript, graphql, graphql-codegen, pascalcasing\nSource: Stack Overflow\n\nQuestion:\nCurrently, the enums that Graphql Code Generator produces looks like this\n\n```\nexport enum Test_Type {\n Test: 'TEST',\n}\n```\n\nhowever I want the generated enums to be in pascal case like this:\n\n```\nexport enum TestType {\n Test: 'TEST',\n}\n```\n\nEdit, my codegen.yml:\n\n```\noverwrite: true\ngenerates:\n src/graphql/generated/graphql.ts:\n schema: ${API_ENDPOINT}\n documents: ['src/graphql/**/*.graphql', 'src/graphql/**/*.gql']\n plugins:\n - 'typescript'\n - 'typescript-operations'\n - 'typescript-react-apollo'\n ./graphql.schema.json:\n schema: ${API_ENDPOINT}\n plugins:\n - 'introspection'\nhooks:\n afterAllFileWrite:\n - prettier --write\n```\n\nThe schema for the enum is\n\n```\nenum TEST_TYPE {\n TEST\n}\n```\n\n========================================\n\nCode:\n```text\nexport enum Test_Type {\n Test: 'TEST',\n}\n```\n\n```text\nexport enum TestType {\n Test: 'TEST',\n}\n```\n\n```text\noverwrite: true\ngenerates:\n src/graphql/generated/graphql.ts:\n schema: ${API_ENDPOINT}\n documents: ['src/graphql/**/*.graphql', 'src/graphql/**/*.gql']\n plugins:\n - 'typescript'\n - 'typescript-operations'\n - 'typescript-react-apollo'\n ./graphql.schema.json:\n schema: ${API_ENDPOINT}\n plugins:\n - 'introspection'\nhooks:\n afterAllFileWrite:\n - prettier --write\n```\n\n```text\nenum TEST_TYPE {\n TEST\n}\n```\n\n```text\nconfig:\n namingConvention: change-case-all#pascalCase\n```\n\n```text\ncodegen.yml\n```\n\n========================================\n\nComments:\n- graphql-code-generator.com/docs/getting-started/…? Please add the graphql schema containing the enum as well as your codegen.yaml configuration, otherwise we're unable to help you.\n- @Bergi I edited the post to my codegen.yml . I don't think I can provide the graphql schema since that's private. Is it necessary in this case since I'm asking a general question that's not related to the actual schemas?\n- Thanks. Not the entire schema, only the `enum TestType = TEST`\n- @Bergi I've included the schema for that enum. thanks in advance for your help.","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":106,"estimatedTokens":558}}1181{"id":"stack-32618424","source":"stackoverflow","questionId":32618424,"title":"Where do you put the CSRF token in Relay/GraphQL?","tags":["laravel","reactjs","csrf","graphql","relayjs"],"text":"Title: Where do you put the CSRF token in Relay/GraphQL?\nTags: laravel, reactjs, csrf, graphql, relayjs\nSource: Stack Overflow\n\nQuestion:\nI am trying to get Relay and GraphQL set up with my Laravel server. I have successfully set Laravel up to serve GraphQL.\n\nIn the past, to make ajax calls with jQuery I added the following to my master.blade.php:\n\n```\n\n```\n\nand the following to my main.js file:\n\n```\n$.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n});\n```\n\nMy GraphQL endpoint is currently returning token mismatch exception. It seems to me that Relay needs to pass the csrf-token to the server in a similar manner as jQuery.ajax. Where does it go?\n\n========================================\n\nCode:\n```text\n<meta name=\"csrf-token\" content=\"{{ csrf_token() }}\">\n```\n\n```text\n$.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n});\n```\n\n```js\nRelay.injectNetworkLayer(\n new Relay.DefaultNetworkLayer('/graphql', {\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content'),\n },\n })\n);\n```\n\n```text\nRelay.DefaultNetworkLayer\n```\n\n```text\ninit\n```\n\n```text\nfetch(input, init)\n```\n\n========================================\n\nComments:\n- how are you using Relay with graphql-laravel ? I think that it need to be compatible with Relay . opened a issue github.com/Folkloreatelier/laravel-graphql/issues/9\n- Thanks! So easy! I was stuck thinking that I needed to grab the dom attr('content') without jQuery.\n- If you don't want to use jQuery at all, you can get the token using `document.querySelector('meta[name=\"csrf-token\"]').getAttribu‌​te('content')`","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":68,"estimatedTokens":421}}1182{"id":"stack-36583360","source":"stackoverflow","questionId":36583360,"title":"GraphQL is returning \"Names must match\" error when the Key is of type integer","tags":["graphql"],"text":"Title: GraphQL is returning \"Names must match\" error when the Key is of type integer\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to use `GraphQL` with a legacy service which returns a JSON with some of the keys as integer. Here is an example,\n\n```\n{\n \"id\": 1234,\n \"image\": {\n \"45\": \"image1url\",\n \"90\": \"image2url\"\n },\n \"name\": \"I am legacy server\"\n}\n```\n\nWhen I tried to define `\"45`\" as `GraphQL` field,\n\n```\nvar imageType = new graphql.GraphQLObjectType({\n name: 'Image',\n fields: {\n 45: { type: graphql.GraphQLString },\n 90: { type: graphql.GraphQLString }\n }\n});\n```\n\nI am getting the following error,\n\n Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"45\" does not`.\n\nHow can we handle keys as integer scenario?\n\n========================================\n\nCode:\n```text\n{\n \"id\": 1234,\n \"image\": {\n \"45\": \"image1url\",\n \"90\": \"image2url\"\n },\n \"name\": \"I am legacy server\"\n}\n```\n\n```text\nvar imageType = new graphql.GraphQLObjectType({\n name: 'Image',\n fields: {\n 45: { type: graphql.GraphQLString },\n 90: { type: graphql.GraphQLString }\n }\n});\n```\n\n```text\nGraphQL\n```\n\n```text\n\"45\n```\n\n```text\nGraphQL\n```\n\n```text\nvar imageType = new graphql.GraphQLObjectType({\n name: 'Image',\n fields: {\n size45: { \n type: graphql.GraphQLString,\n resolve: (parent) => parent['45'],\n },\n size90: { \n type: graphql.GraphQLString,\n resolve: (parent) => parent['90']\n }\n }\n});\n```\n\n```text\nresolve\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":91,"estimatedTokens":366}}1183{"id":"stack-48094695","source":"stackoverflow","questionId":48094695,"title":"How to pass root parameters in the resolver function of a nested query?","tags":["reactjs","graphql","apollo"],"text":"Title: How to pass root parameters in the resolver function of a nested query?\nTags: reactjs, graphql, apollo\nSource: Stack Overflow\n\nQuestion:\nI have a query of the following nature\n\n```\nCategory1(name: $cat1){\n Category2(secondName: $cat2){\n secondName\n }}\n```\n\nMy schema is like so:\n\n```\nconst Query = new GraphQLObjectType({\nname: 'Query',\nfields: {\n Category1: {\n type: new GraphQLList(Category1Type),\n args: { name },\n resolve: resolveCategory1\n }}\n})\n```\n\nAnd then the Category1Type is defined as:\n\n```\nconst Category1Type = new GraphQLObjectType({\n name: 'Category1',\n description: '<>',\n fields: () => ({\n name: { type: GraphQLString },\n category2: {\n type: new GraphQLList(CategoryType2),\n args: { secondName },\n resolve: resolveCategory2\n }\n })\n});\n```\n\nFor simplicity sake, assume category2 is like so:\n\n```\nconst Category2Type = new GraphQLObjectType({\n name: 'Category2',\n description: '<>',\n fields: () => ({\n name: { type: GraphQLString },\n })\n});\n```\n\nNow I want to fetch all Category2 items under Category1 with option to filter, like so:\n\n```\nCategory1(name: $name){\n name\n category2(name: $name){\n name \n}}\n```\n\nMy resolvers are defined like so:\n\n```\n# Category1 resolver\n function cat1resolve (root, args) {\nreturn SELECT * from data WHERE category1_name = args.name\n}\n\n # Category2 resolver\n function cat2Resolve (root, args) {\nreturn SELECT * from data WHERE category1_name = rootargs.name and categort2_name = args.secondName }\n```\n\nNow the problem is that the 'resolver' for cat2Resolve is not able to see or receive the rootargs.name for me to do this kind of filtering.\n\n========================================\n\nCode:\n```text\nCategory1(name: $cat1){\n Category2(secondName: $cat2){\n secondName\n }}\n```\n\n```text\nconst Query = new GraphQLObjectType({\nname: 'Query',\nfields: {\n Category1: {\n type: new GraphQLList(Category1Type),\n args: { name },\n resolve: resolveCategory1\n }}\n})\n```\n\n```text\nconst Category1Type = new GraphQLObjectType({\n name: 'Category1',\n description: '<>',\n fields: () => ({\n name: { type: GraphQLString },\n category2: {\n type: new GraphQLList(CategoryType2),\n args: { secondName },\n resolve: resolveCategory2\n }\n })\n});\n```\n\n```text\nconst Category2Type = new GraphQLObjectType({\n name: 'Category2',\n description: '<>',\n fields: () => ({\n name: { type: GraphQLString },\n })\n});\n```\n\n```text\nCategory1(name: $name){\n name\n category2(name: $name){\n name \n}}\n```\n\n```text\n# Category1 resolver\n function cat1resolve (root, args) {\nreturn SELECT * from data WHERE category1_name = args.name\n}\n\n # Category2 resolver\n function cat2Resolve (root, args) {\nreturn SELECT * from data WHERE category1_name = rootargs.name and categort2_name = args.secondName }\n```\n\n```text\nconst category1id = get(info, 'operation.selectionSet.selections[0].arguments[0].value.value')\n```\n\n```text\nmakeExecutableSchema\n```\n\n```text\ninfo\n```\n\n```text\nget\n```\n\n```text\nCategory1\n```\n\n```text\nArray.find\n```\n\n========================================\n\nComments:\n- Sounds like a problem with your schema. Please update your question to include the schema, or at least the parts relevant to those three types.\n- Thanks for updating the question :) So to clarify, the issue you're facing is not the error you mentioned before, but that the resolver for Category2 is not working as expected? It would be helpful for you to include the actual resolver code, and the unexpected behavior you're seeing when you run the query.\n- @DanielRearden I have tried to explain the exact operation further","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":178,"estimatedTokens":911}}1184{"id":"stack-72155421","source":"stackoverflow","questionId":72155421,"title":"What is the difference between file and allFile in the GraphQL query in Gatsby?","tags":["graphql","gatsby"],"text":"Title: What is the difference between file and allFile in the GraphQL query in Gatsby?\nTags: graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nIn my GraphiQL explorer, it appears that I can query `file` or `allFile`, but I don't really understand what the difference between the two is. In fact, every query appears to be \"duplicated\" in this manner. Can someone explain, or point me to some documentation that explains the difference and when I should use one over the other? https://i.sstatic.net/72eY7.png\n\n========================================\n\nCode:\n```text\nfile\n```\n\n```text\nallFile\n```\n\n```text\nallFile\n```\n\n```text\nall\n```\n\n```text\nfile\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\nfile\n```\n\n```text\nallFile\n```\n\n```text\nnodes\n```\n\n```text\nfile\n```\n\n```text\nallMdx\n```\n\n```text\nmdx\n```\n\n```text\nallSite\n```\n\n```text\nsite\n```\n\n```text\nallMdx\n```\n\n```text\ngatsby-plugin-mdx\n```\n\n```text\ngatsby-node.js\n```\n\n```text\nallMdx\n```\n\n```text\ncreatePage\n```\n\n```text\nallMdx\n```\n\n```text\nmdx\n```\n\n```text\nmdx\n```\n\n```text\nallMdx\n```\n\n```text\nmdx\n```\n\n```text\nslug\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- The GraphiQL results for `file` appears to be the first node in the results from the `allFile` query results unless you specify some filter criteria to choose a specific one.","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":118,"estimatedTokens":330}}1185{"id":"stack-68930253","source":"stackoverflow","questionId":68930253,"title":"Calling a custom method in a Graphene python resolver","tags":["python","graphql","graphene-python","graphene-django"],"text":"Title: Calling a custom method in a Graphene python resolver\nTags: python, graphql, graphene-python, graphene-django\nSource: Stack Overflow\n\nQuestion:\nHello I simply want to avoid repeating code for each query, and I was wondering if I could call a method from inside a resolver a such:\n\n```\n# pseudo code\nclass Query(graphene.ObjectType):\n\n field = graphene.Field(SomeType)\n\n def do_boring_task(parent, info, arg):\n \n return \"I did something\"\n\n def resolve_field(parent, info):\n\n did_something = parent.do_boring_task(arg) # I always get a \"graphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'do_boring_task'\" error\n\nIs it possible to do that the way I described it, or is this something that should be done using middleware?\n\nThanks\n\n========================================\n\nCode:\n```text\n# pseudo code\nclass Query(graphene.ObjectType):\n\n field = graphene.Field(SomeType)\n\n def do_boring_task(parent, info, arg):\n \n return \"I did something\"\n\n def resolve_field(parent, info):\n\n did_something = parent.do_boring_task(arg) # <-- is this possible ?\n \n # do something here\n\n return resolved_fields\n```\n\n```py\ndef do_boring_task(args):\n return \"I did something\"\n\nclass Query(graphene.ObjectType):\n field = graphene.Field(SomeType)\n\n def resolve_field(parent, info):\n did_something = do_boring_task(arg) \n # do something here\n return resolved_fields\n```\n\n```text\ngraphene.ObjectType\n```\n\n```text\nresolve_field\n```\n\n```text\ndo_boring_task\n```\n\n```text\nresolve_field\n```\n\n```text\nparent\n```\n\n```text\nself\n```\n\n```text\ndo_boring_task\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":87,"estimatedTokens":413}}1186{"id":"stack-70450379","source":"stackoverflow","questionId":70450379,"title":"Gatsby graphql query for GatsbyImage to use a local image from project","tags":["reactjs","graphql","gatsby","gatsby-image"],"text":"Title: Gatsby graphql query for GatsbyImage to use a local image from project\nTags: reactjs, graphql, gatsby, gatsby-image\nSource: Stack Overflow\n\nQuestion:\nI'd just like to use an image using GatsbyImage component.\n\nNormally you do it using ``.\nHow is it done with **GatsbyImage**, so i can send an image using props.\n\n========================================\n\nTop Answer:\nAfter `npm init gatsby`, `'src/images'` folder is created and this is the basic **root of the relative path** which is set by default in `gatsby.config.js`\n\n```\n{\n resolve: 'gatsby-source-filesystem',\n options: {\n name: 'images',\n path: `./src/images/`,\n }\n}\n```\n\nSo put your img.jpg to images folder and query by using relative path\n\n```\nconst data = useStaticQuery(graphql`\n {\n file(relativePath: { eq: \"free-time.jpg\" }) {\n childImageSharp {\n gatsbyImageData\n }\n }\n }\n`);\n```\n\nand insert it to GatsbyImage\n\n```\nconst img = getImage(data.file);\n\n \n```\n\n========================================\n\nCode:\n```text\n<img src='./img.jpg'/>\n```\n\n```text\n{\n resolve: `gatsby-source-filesystem`,\n options: {\n name: `componentImages`,\n path: `${__dirname}/src/components`,\n },\n},\n```\n\n```text\nimage: file(relativePath: {eq: \"free-time.jpg\"}) {\n childImageSharp {\n gatsbyImageData\n }\n }\n```\n\n```text\nGatsbyImage\n```\n\n```text\ngatsby-config.js\n```\n\n```text\ngatsby-source-filesystem\n```\n\n```text\ngatsby develop\n```\n\n```text\nlocalhost:8000/___graphql\n```\n\n```text\n{\n resolve: 'gatsby-source-filesystem',\n options: {\n name: 'images',\n path: `./src/images/`,\n }\n}\n```\n\n```text\nconst data = useStaticQuery(graphql`\n {\n file(relativePath: { eq: \"free-time.jpg\" }) {\n childImageSharp {\n gatsbyImageData\n }\n }\n }\n`);\n```\n\n```text\nconst img = getImage(data.file);\n\n <GatsbyImage image={img} />\n```\n\n```text\nnpm init gatsby\n```\n\n```text\n'src/images'\n```\n\n```text\ngatsby.config.js\n```\n\n========================================\n\nComments:\n- What's the output? What's the error? Do you have `img` data in the `ChildComp`? Is the `useStaticQuery` fetching the proper data?\n- `data` is `null`?If so, this is where the issue is... Well, try to provide a Sandbox or similar, it's impossible to guess what's wrong in your structure with dummy data that is not showing the code structure (`data.something` is not present in the query, etc)\n- yup, so i added the link to the question","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":138,"estimatedTokens":607}}1187{"id":"stack-68015320","source":"stackoverflow","questionId":68015320,"title":"cannot query field \"allMdx\" on type \"Query\"","tags":["reactjs","graphql","gatsby"],"text":"Title: cannot query field \"allMdx\" on type \"Query\"\nTags: reactjs, graphql, gatsby\nSource: Stack Overflow\n\nQuestion:\nI'm new in GraphiQl, I'm flowing tutorials from here\n\nAnd also I'm new to Gatsby, after all requirement plugin install (guide from gatsby offical doc) when I want to go on this link: `http://localhost:8000/___graphql` then show me an error on `allMdx` if I hover on it.\n\nlike this: https://i.sstatic.net/tCC34.png\n\nbut official document everything is ok, I don't know where is my problem.\n\nany update issue!\n\nI have used `gatsby v3`\n\nalso my initial query not match with this\n\nAny suggestion please.\n\n========================================\n\nCode:\n```text\nhttp://localhost:8000/___graphql\n```\n\n```text\nallMdx\n```\n\n```text\ngatsby v3\n```\n\n```text\nnpm install gatsby-source-filesystem\n```\n\n```text\nmodule.exports = {\n siteMetadata: {\n title: \"My First Gatsby Site\",\n },\n plugins: [\n \"gatsby-plugin-gatsby-cloud\",\n \"gatsby-plugin-image\",\n \"gatsby-plugin-sharp\",\n {\n resolve: \"gatsby-source-filesystem\",\n options: {\n name: `blog`,\n path: `${__dirname}/blog`, // <-- the folder where you have the .mdx files\n }\n },\n ],\n};\n```\n\n```text\n{\n resolve: `gatsby-plugin-mdx`,\n options: {\n defaultLayouts: {\n posts: require.resolve(\"./src/components/blog-layout.js\"),\n default: require.resolve(\"./src/components/layout.js\"),\n },\n },\n},\n```\n\n```text\nlocalhost:8000/___graphql\n```\n\n```text\nallMdx\n```\n\n```text\nallFile\n```\n\n```text\nallDirectory\n```\n\n```text\ngatsby-config.js\n```\n\n```text\n/blog\n```\n\n```text\nallMdx\n```\n\n```text\ngatsby clean && gatsby develop\n```\n\n```text\ngatsby-plugin-mdx\n```\n\n```text\ngatsby clean\n```\n\n========================================\n\nComments:\n- I did everything above, but not the `gatsby clean`. Only restarting the server did not work. But after doing `gatsby clean` first then `gatsby develop` it works. They should totally add this on their docs.","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":116,"estimatedTokens":487}}1188{"id":"stack-71828943","source":"stackoverflow","questionId":71828943,"title":"How to handle error format in Redux-toolkit rtk-query graphql application","tags":["reactjs","graphql","redux-thunk","redux-toolkit","rtk-query"],"text":"Title: How to handle error format in Redux-toolkit rtk-query graphql application\nTags: reactjs, graphql, redux-thunk, redux-toolkit, rtk-query\nSource: Stack Overflow\n\nQuestion:\nI'm developing an application based on redux-toolkit rtk-query and graphql.\nI use graphql-codegen to generate the reducers starting from the graphql schema and everything working as expected.\n\nNow i have a problem to handle errors. Has i understand redux-toolkit raise custom error with a specific format like this\n\n```\n{\n name: \"Error\",\n message: \"System error\",\n stack:\n 'Error: System error: {\"response\":{\"errors\":[{\"message\":\"System error\",\"locations\":[{\"line\":3,\"column\":3}],\"path\":[\"completaAttivita\"],\"extensions\":{\"errorCode\":505,\"classification\":\"VALIDATION\",\"errorMessage\":\"Messaggio di errore\",\"verboseErrorMessage\":\"it.cmrc.sid.backend.exception.CustomException: I riferimenti contabili non sono piΓΉ validi\",\"causedBy\":\"No Cause!\"}}],\"data\":{\"completaAttivita\":null},\"status\":200,\"headers\":{\"map\":{\"content-length\":\"398\",\"content-type\":\"application/json\"}}},\"request\":{\"query\":\"\\\\n mutation completaAttivita($taskName: TipoAttivita, $taskId: String, $determinaId: BigInteger, $revisione: Boolean, $nota: NotaInputInput, $avanzaStatoDetermina: Boolean, $attribuzioniOrizzontali: AttribuzioniOrizzontaliInputInput, $firmaInput: FirmaInputInput, $roles: [String]) {\\\\n completaAttivita(\\\\n taskName: $taskName\\\\n taskId: $taskId\\\\n determinaId: $determinaId\\\\n revisione: $revisione\\\\n nota: $nota\\\\n avanzaStatoDetermina: $avanzaStatoDetermina\\\\n attribuzioniOrizzontali: $attribuzioniOrizzontali\\\\n firmaInput: $firmaInput\\\\n roles: $roles\\\\n ) {\\\\n id\\\\n }\\\\n}\\\\n \",\"variables\":{\"taskId\":\"24ac495b-46ca-42f4-9be2-fd92f0398114\",\"determinaId\":1342,\"taskName\":\"firmaDirigente\",\"firmaInput\":{\"username\":\"fdfs\",\"password\":\"fdsf\",\"otp\":\"fdsdf\"}}}}\\n at eval (webpack-internal:///../../node_modules/graphql-request/dist/index.js:354:31)\\n at step (webpack-internal:///../../node_modules/graphql-request/dist/index.js:63:23)\\n at Object.eval [as next] (webpack-internal:///../../node_modules/graphql-request/dist/index.js:44:53)\\n at fulfilled (webpack-internal:///../../node_modules/graphql-request/dist/index.js:35:58)'\n};\n```\n\nBut my graphql endpoint return this\n\n```\n{\n errors: [\n {\n message: \"System error\",\n locations: [{ line: 3, column: 3 }],\n path: [\"completaAttivita\"],\n extensions: {\n errorCode: 505,\n classification: \"VALIDATION\",\n errorMessage: \"Messaggio di errore\",\n verboseErrorMessage:\n \"it.cmrc.sid.backend.exception.CustomException: Messaggio di errore\",\n causedBy: \"No Cause!\"\n }\n }\n ],\n data: { completaAttivita: null }\n};\n```\n\nUsing rtk-query and the autogenerated client i have no access to the complete response from server.\nAnd i need to extract the error messagge in the exceptions object.\n\nFrom redix-toolkit documentation i understand that i need to catch the error and call `rejectwithvalue()` from a `createAsyncThunk` but i dont'undertand of to do that.\n\nHere the base api object\n\n```\nimport { createApi } from '@reduxjs/toolkit/query/react';\nimport { graphqlRequestBaseQuery } from './base-request';\nimport { GraphQLClient } from 'graphql-request';\nimport { getSession } from 'next-auth/react';\n\nexport const client = new GraphQLClient(\n `${process.env.NEXT_PUBLIC_API_URL}/graphql`,\n {\n credentials: 'same-origin',\n headers: {\n Accept: 'application/json'\n }\n }\n);\n\nexport const api = createApi({\n baseQuery: graphqlRequestBaseQuery({\n client,\n prepareHeaders: async (headers, { getState }) => {\n const session = await getSession();\n if (session) {\n headers.set('Authorization', `Bearer ${session?.access_token}`);\n }\n\n return headers;\n }\n }),\n endpoints: () => ({}),\n refetchOnMountOrArgChange: true\n});\n```\n\n========================================\n\nTop Answer:\nYou can always write a wrapper around your baseQuery to reformat it:\n\n```\nconst originalBaseQuery = graphqlRequestBaseQuery(...)\n\nconst wrappedBaseQuery = async (...args) => {\n const result = await originalBaseQuery(...args);\n if (result.error) {\n // modify `result.error` here however you want\n }\n return result\n}\n```\n\nIt could also be necessary that you need to try..catch for that:\n\n```\nconst originalBaseQuery = graphqlRequestBaseQuery(...)\n\nconst wrappedBaseQuery = async (...args) => {\n try {\n return await originalBaseQuery(...args);\n } catch (e) {\n // modify your error here\n return { error: e.foo.bar }\n }\n}\n```\n\nI think this just slipped by when I was writing `graphqlRequestBaseQuery` and so far nobody has asked about it. If you have found a nice pattern of handling this, a pull request against `graphqlRequestBaseQuery` would also be very welcome.\n\n========================================\n\nCode:\n```text\n{\n name: \"Error\",\n message: \"System error\",\n stack:\n 'Error: System error: {\"response\":{\"errors\":[{\"message\":\"System error\",\"locations\":[{\"line\":3,\"column\":3}],\"path\":[\"completaAttivita\"],\"extensions\":{\"errorCode\":505,\"classification\":\"VALIDATION\",\"errorMessage\":\"Messaggio di errore\",\"verboseErrorMessage\":\"it.cmrc.sid.backend.exception.CustomException: I riferimenti contabili non sono piΓΉ validi\",\"causedBy\":\"No Cause!\"}}],\"data\":{\"completaAttivita\":null},\"status\":200,\"headers\":{\"map\":{\"content-length\":\"398\",\"content-type\":\"application/json\"}}},\"request\":{\"query\":\"\\\\n mutation completaAttivita($taskName: TipoAttivita, $taskId: String, $determinaId: BigInteger, $revisione: Boolean, $nota: NotaInputInput, $avanzaStatoDetermina: Boolean, $attribuzioniOrizzontali: AttribuzioniOrizzontaliInputInput, $firmaInput: FirmaInputInput, $roles: [String]) {\\\\n completaAttivita(\\\\n taskName: $taskName\\\\n taskId: $taskId\\\\n determinaId: $determinaId\\\\n revisione: $revisione\\\\n nota: $nota\\\\n avanzaStatoDetermina: $avanzaStatoDetermina\\\\n attribuzioniOrizzontali: $attribuzioniOrizzontali\\\\n firmaInput: $firmaInput\\\\n roles: $roles\\\\n ) {\\\\n id\\\\n }\\\\n}\\\\n \",\"variables\":{\"taskId\":\"24ac495b-46ca-42f4-9be2-fd92f0398114\",\"determinaId\":1342,\"taskName\":\"firmaDirigente\",\"firmaInput\":{\"username\":\"fdfs\",\"password\":\"fdsf\",\"otp\":\"fdsdf\"}}}}\\n at eval (webpack-internal:///../../node_modules/graphql-request/dist/index.js:354:31)\\n at step (webpack-internal:///../../node_modules/graphql-request/dist/index.js:63:23)\\n at Object.eval [as next] (webpack-internal:///../../node_modules/graphql-request/dist/index.js:44:53)\\n at fulfilled (webpack-internal:///../../node_modules/graphql-request/dist/index.js:35:58)'\n};\n```\n\n```text\n{\n errors: [\n {\n message: \"System error\",\n locations: [{ line: 3, column: 3 }],\n path: [\"completaAttivita\"],\n extensions: {\n errorCode: 505,\n classification: \"VALIDATION\",\n errorMessage: \"Messaggio di errore\",\n verboseErrorMessage:\n \"it.cmrc.sid.backend.exception.CustomException: Messaggio di errore\",\n causedBy: \"No Cause!\"\n }\n }\n ],\n data: { completaAttivita: null }\n};\n```\n\n```text\nimport { createApi } from '@reduxjs/toolkit/query/react';\nimport { graphqlRequestBaseQuery } from './base-request';\nimport { GraphQLClient } from 'graphql-request';\nimport { getSession } from 'next-auth/react';\n\nexport const client = new GraphQLClient(\n `${process.env.NEXT_PUBLIC_API_URL}/graphql`,\n {\n credentials: 'same-origin',\n headers: {\n Accept: 'application/json'\n }\n }\n);\n\nexport const api = createApi({\n baseQuery: graphqlRequestBaseQuery({\n client,\n prepareHeaders: async (headers, { getState }) => {\n const session = await getSession();\n if (session) {\n headers.set('Authorization', `Bearer ${session?.access_token}`);\n }\n\n return headers;\n }\n }),\n endpoints: () => ({}),\n refetchOnMountOrArgChange: true\n});\n```\n\n```text\nrejectwithvalue()\n```\n\n```text\ncreateAsyncThunk\n```\n\n```js\ngraphqlRequestBaseQuery<CustomErrorFormat>\n```\n\n```js\n...\n customErrors: (props: ClientError) => CustomErrorFormat\n...\n```\n\n```js\nimport { createApi } from '@reduxjs/toolkit/query/react';\nimport { graphqlRequestBaseQuery } from '@rtk-query/graphql-request-base-query';\nimport { ClientError, GraphQLClient } from 'graphql-request';\nimport { getSession } from 'next-auth/react';\n\nexport const client = new GraphQLClient(\n `${process.env.NEXT_PUBLIC_API_URL}/graphql`,\n {\n credentials: 'same-origin',\n headers: {\n Accept: 'application/json'\n }\n }\n);\n\nexport const api = createApi({\n baseQuery: graphqlRequestBaseQuery<\n Partial<ClientError & { errorCode: number }>\n >({\n client,\n prepareHeaders: async (headers, { getState }) => {\n const session = await getSession();\n if (session) {\n headers.set('Authorization', `Bearer ${session?.access_token}`);\n }\n\n return headers;\n },\n customErrors: ({ name, stack, response }) => {\n const { errorMessage = '', errorCode = 500 } = response?.errors?.length\n ? response?.errors[0]?.extensions\n : {};\n\n return {\n name,\n message: errorMessage,\n errorCode,\n stack\n };\n }\n }),\n endpoints: () => ({}),\n refetchOnMountOrArgChange: true\n});\n```\n\n```js\nconst originalBaseQuery = graphqlRequestBaseQuery(...)\n\nconst wrappedBaseQuery = async (...args) => {\n const result = await originalBaseQuery(...args);\n if (result.error) {\n // modify `result.error` here however you want\n }\n return result\n}\n```\n\n```js\nconst originalBaseQuery = graphqlRequestBaseQuery(...)\n\nconst wrappedBaseQuery = async (...args) => {\n try {\n return await originalBaseQuery(...args);\n } catch (e) {\n // modify your error here\n return { error: e.foo.bar }\n }\n}\n```\n\n```text\ngraphqlRequestBaseQuery\n```\n\n```text\ngraphqlRequestBaseQuery\n```\n\n========================================\n\nComments:\n- where you able to solve this problem? I'm facing the the same thing\n- I opened a pull request to try to solve this github.com/reduxjs/redux-toolkit/pull/2232\n- @Federico npmjs.com/package/@rtk-query/graphql-request-base-query\n- Thanks for your response. Unfortunately your suggestion not resolve my problem. Anyway i will sumbit a pull request to customize the error object in `graphqlRequestBaseQuery`.","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":287,"estimatedTokens":2533}}1189{"id":"stack-73195073","source":"stackoverflow","questionId":73195073,"title":"How to update nested structures in apollo cache using cache.modify","tags":["graphql","apollo-client","apollo-cache-inmemory"],"text":"Title: How to update nested structures in apollo cache using cache.modify\nTags: graphql, apollo-client, apollo-cache-inmemory\nSource: Stack Overflow\n\nQuestion:\n```\nfragment commentFragment on Comment {\n id\n text\n galleryId\n commentUser {\n id\n firstName\n lastName\n }\n}\n\nfragment galleryFragment on Gallery {\n id\n path\n label\n comments {\n ...commentFragment\n }\n \n}\n```\n\nWe first retrieve the getGalleries using the following gql :\n\n```\nquery getGalleries($filters: galleryFilterInput) {\n getGalleries(filters: $filters) {\n galleries {\n ...galleryFragment\n }\n cursor\n hasMore\n }\n}\n```\n\nNow when the user enters a comment on a single gallery item we run the following mutation :\n\n```\nmutation addCommentMutation($input: addCommentInput!) {\n addComment(input: $input) {\n ...commentFragment\n }\n}\n```\n\nNow, we were previously using `refetchQueries` to update the Galleries but we have now decided to use `cache.modify` however we are having problem with updating the galleries\n\n```\nupdate: (cache, data: any) => {\n cache.modify({\n fields: {\n getGalleries(existing, { readField }) {\n const comment = data.data.addComment;\n const newEventRef = cache.writeFragment({\n fragment: commentFragment,\n data: comment,\n fragmentName: \"commentFragment\",\n });\n\n const index = existing.galleries.findIndex(\n aGallery => aGallery.id === comment.galleryId\n );\n\n if (index !== -1) {\n const existingCommentRef = readField(\"comments\", existing.galleries[index]) \n as readonly Reference;\n const newCommentsRefs = [...existingCommentRef, newRef];\n cache.writeFragment({\n id: \"Gallery:\" + readField(\"id\", existing.galleries[index]),\n fragment: gql`\n fragment comments on Gallery {\n comments {\n ...commentFragment\n }\n }\n `,\n data: newCommentsRefs,\n });\n\n }\n\n return existing;\n },\n },\n });\n },\n```\n\nI am unsure how I update the newCommentsRefs in that Gallery\n\n========================================\n\nCode:\n```text\nfragment commentFragment on Comment {\n id\n text\n galleryId\n commentUser {\n id\n firstName\n lastName\n }\n}\n\nfragment galleryFragment on Gallery {\n id\n path\n label\n comments {\n ...commentFragment\n }\n \n}\n```\n\n```text\nquery getGalleries($filters: galleryFilterInput) {\n getGalleries(filters: $filters) {\n galleries {\n ...galleryFragment\n }\n cursor\n hasMore\n }\n}\n```\n\n```text\nmutation addCommentMutation($input: addCommentInput!) {\n addComment(input: $input) {\n ...commentFragment\n }\n}\n```\n\n```text\nupdate: (cache, data: any) => {\n cache.modify({\n fields: {\n getGalleries(existing, { readField }) {\n const comment = data.data.addComment;\n const newEventRef = cache.writeFragment({\n fragment: commentFragment,\n data: comment,\n fragmentName: \"commentFragment\",\n });\n\n const index = existing.galleries.findIndex(\n aGallery => aGallery.id === comment.galleryId\n );\n\n if (index !== -1) {\n const existingCommentRef = readField(\"comments\", existing.galleries[index]) \n as readonly Reference;\n const newCommentsRefs = [...existingCommentRef, newRef];\n cache.writeFragment({\n id: \"Gallery:\" + readField(\"id\", existing.galleries[index]),\n fragment: gql`\n fragment comments on Gallery {\n comments {\n ...commentFragment\n }\n }\n `,\n data: newCommentsRefs,\n });\n\n }\n\n return existing;\n },\n },\n });\n },\n```\n\n```text\nrefetchQueries\n```\n\n```text\ncache.modify\n```\n\n```text\nupdate(cache, data) {\n\n const comment = data.data.addComment;\n cache.writeFragment({\n fragment: commentFragment,\n data: comment,\n fragmentName: \"commentFragment\",\n });\n\n const gallery: Gallery = cache.readFragment({\n id: `Gallery:${comment.galleryId}`,\n fragment: galleryFragment,\n fragmentName: 'galleryFragment'\n });\n if (gallery) { \n const newComments = [...gallery.comments, comment]\n cache.writeFragment({\n id: `Gallery:${comment.galleryId}`,\n fragment: galleryFragment,\n fragmentName: 'galleryFragment',\n data: { ...gallery, comments: newComments }\n });\n }\n }\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":218,"estimatedTokens":1128}}1190{"id":"stack-68484669","source":"stackoverflow","questionId":68484669,"title":"SpringBoot GraphQL request execution timeout issue","tags":["java","spring-boot","graphql"],"text":"Title: SpringBoot GraphQL request execution timeout issue\nTags: java, spring-boot, graphql\nSource: Stack Overflow\n\nQuestion:\nI have used Spring boot with graphQL (version 11.1.0) and it's working fine but it throws a timeout error when request execution time exceeds the 30s.\n\nError:\n\n```\nGraphQL execution canceled because timeout of 30000 millis was reached. The following query was being executed when this happened:\n// query\nCannot write GraphQL response, because the HTTP response is already committed. It most likely timed out.\n```\n\nCan anyone tell me how can we configure timeout in graphQL?\n\n========================================\n\nCode:\n```text\nGraphQL execution canceled because timeout of 30000 millis was reached. The following query was being executed when this happened:\n// query\nCannot write GraphQL response, because the HTTP response is already committed. It most likely timed out.\n```\n\n```text\ngraphql.servlet.async-timeout\n```\n\n```text\napplication.yml\n```\n\n```text\napplication.properties\n```\n\n========================================\n\nComments:\n- I'm using 14.1.0 graphql kickstart version and setting this property is not overriding the default timeout","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":42,"estimatedTokens":294}}1191{"id":"stack-68524064","source":"stackoverflow","questionId":68524064,"title":"I got an error while running dist file in nestjs project, please help me","tags":["node.js","typescript","graphql","backend","nestjs"],"text":"Title: I got an error while running dist file in nestjs project, please help me\nTags: node.js, typescript, graphql, backend, nestjs\nSource: Stack Overflow\n\nQuestion:\n```\n(node:8356) UnhandledPromiseRejectionWarning: Error: No type definitions were found with the specified file name patterns: \"./**/*.graphql\". Please make sure there is at least one file that matches the given patterns.\n at GraphQLTypesLoader. (E:\\NestJS\\Template_Login\\teample-api-backend-nestjs\\backend\\node_modules\\@nestjs\\graphql\\dist\\graphql-types.loader.js:38:23)\n at Generator.next ()\n at fulfilled (E:\\NestJS\\Template_Login\\teample-api-backend-nestjs\\backend\\node_modules\\tslib\\tslib.js:114:62)\n at processTicksAndRejections (internal/process/task_queues.js:97:5)\n(node:8356) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async \nfunction without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)\n(node:8356) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n========================================\n\nTop Answer:\nhttps://docs.nestjs.com/cli/monorepo#assets\n\nThere is `assets` option in nestjs.\nThis is the right way to do it in nestjs.\n\n========================================\n\nCode:\n```text\n(node:8356) UnhandledPromiseRejectionWarning: Error: No type definitions were found with the specified file name patterns: \"./**/*.graphql\". Please make sure there is at least one file that matches the given patterns.\n at GraphQLTypesLoader.<anonymous> (E:\\NestJS\\Template_Login\\teample-api-backend-nestjs\\backend\\node_modules\\@nestjs\\graphql\\dist\\graphql-types.loader.js:38:23)\n at Generator.next (<anonymous>)\n at fulfilled (E:\\NestJS\\Template_Login\\teample-api-backend-nestjs\\backend\\node_modules\\tslib\\tslib.js:114:62)\n at processTicksAndRejections (internal/process/task_queues.js:97:5)\n(node:8356) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async \nfunction without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)\n(node:8356) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\nassets\n```\n\n========================================\n\nComments:\n- Very nice, Thank you very much!\n- Thanks. I think that this solution is the better because it is integrate with the framework.\n- I confirm this resolves the issue","metadata":{"transformedAt":"2026-08-18T18:32:36.233Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":48,"estimatedTokens":773}}1192{"id":"stack-59713245","source":"stackoverflow","questionId":59713245,"title":"apollo client returning undefined in initial reload in react native","tags":["javascript","react-native","graphql","react-apollo","apollo-client"],"text":"Title: apollo client returning undefined in initial reload in react native\nTags: javascript, react-native, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI'm trying to fetch some data from my cache. In initial reload data prop returns undefined but if I fast reload the app (react native fast reload) data prop has the value I want. I can not understand why it is returning undefined in initial reload. One case might be I'm calling the query before the cache is initialised. I have consoled the local cache and it shows values but the query is retuning undefined.\n\nMy client setup in client.js\n\n```\nconst dev = {\n base_url: BASE_URL\n};\n\nconst httpLink = createHttpLink({\n uri: dev.base_url\n});\n\nconst errorLink = onError(({ graphQLErrors, networkError, response }) => {\n if (graphQLErrors) {\n // do something with graphql error\n console.log(graphQLErrors);\n }\n if (networkError) {\n // do something with network error\n console.log(networkError);\n // console.log('network not available');\n }\n if (response) {\n console.log(response);\n }\n});\nconst cache = new InMemoryCache();\n\nconst setupPersistedCache = async () => {\n const persistor = new CachePersistor({\n cache,\n storage: AsyncStorage\n });\n\n // Read the current schema version from AsyncStorage.\n const currentVersion = await AsyncStorage.getItem(SCHEMA_VERSION_KEY);\n\n console.log('currentVersion', currentVersion);\n\n if (currentVersion && currentVersion === SCHEMA_VERSION) {\n // If the current version matches the latest version,\n // we're good to go and can restore the cache.\n console.log('not migrating cache');\n await persistor.restore();\n } else {\n // Otherwise, we'll want to purge the outdated persisted cache\n // and mark ourselves as having updated to the latest version.\n console.log('migrating cache');\n await persistor.purge();\n await AsyncStorage.setItem(SCHEMA_VERSION_KEY, SCHEMA_VERSION);\n\n cache.writeData({\n data: {\n ...initialState\n }\n });\n\n await persistCache({\n cache,\n storage: AsyncStorage,\n debug: true\n });\n }\n // console.log(cache.data);\n};\n\nsetupPersistedCache();\n\nconst link = ApolloLink.from([errorLink, httpLink]);\n\nconst client = new ApolloClient({\n defaults: initialState,\n link,\n cache,\n resolvers\n});\n\nexport default client;\n```\n\nMy initialState.js\n\n```\nexport default {\n language: 'bd'\n};\n```\n\nMy index.js\n\n```\nconst AppProvider = () => {\n const [loaded, setLoaded] = useState(false);\n\n const configureCache = async () => {\n try {\n const cache = new InMemoryCache();\n await persistCache({\n cache,\n storage: AsyncStorage,\n debug: true\n });\n console.log(cache.data);\n } catch (error) {\n console.error('Error restoring Apollo cache', error);\n }\n };\n\n useEffect(() => {\n configureCache()\n .then(() => {\n setLoaded(true);\n })\n .catch(() => {\n setLoaded(false);\n });\n }, []);\n useEffect(() => {\n SplashScreen.hide();\n }, []);\n\n return (\n <>\n {loaded ? (\n \n \n \n ) : (\n \n \n \n )}\n \n );\n};\n\nAppRegistry.registerComponent(appName, () => AppProvider);\n```\n\nMy query \n\n```\nexport const getLangQuery = gql`\n query getLang {\n language @client\n }\n`;\n```\n\nI'm trying to get the data like this in my root page.\n\n```\nconst { loading, error, data } = useQuery(getLangQuery);\n const [setLanguage, result] = useMutation(setLangQuery);\n\n const language = data;\n console.log(language);\n```\n\n========================================\n\nTop Answer:\n`data` is always initially undefined, even if the result is fetched from the cache instead of the server. Once the data is loaded, its persisted in component state, so even if the component rerenders, the data does not have to be fetched from the cache again. A Fast Refresh just triggers a rerender -- it does not reload your whole app -- so any component state, including `data` in this case, is persisted.\n\n========================================\n\nCode:\n```text\nconst dev = {\n base_url: BASE_URL\n};\n\nconst httpLink = createHttpLink({\n uri: dev.base_url\n});\n\nconst errorLink = onError(({ graphQLErrors, networkError, response }) => {\n if (graphQLErrors) {\n // do something with graphql error\n console.log(graphQLErrors);\n }\n if (networkError) {\n // do something with network error\n console.log(networkError);\n // console.log('network not available');\n }\n if (response) {\n console.log(response);\n }\n});\nconst cache = new InMemoryCache();\n\nconst setupPersistedCache = async () => {\n const persistor = new CachePersistor({\n cache,\n storage: AsyncStorage\n });\n\n // Read the current schema version from AsyncStorage.\n const currentVersion = await AsyncStorage.getItem(SCHEMA_VERSION_KEY);\n\n console.log('currentVersion', currentVersion);\n\n if (currentVersion && currentVersion === SCHEMA_VERSION) {\n // If the current version matches the latest version,\n // we're good to go and can restore the cache.\n console.log('not migrating cache');\n await persistor.restore();\n } else {\n // Otherwise, we'll want to purge the outdated persisted cache\n // and mark ourselves as having updated to the latest version.\n console.log('migrating cache');\n await persistor.purge();\n await AsyncStorage.setItem(SCHEMA_VERSION_KEY, SCHEMA_VERSION);\n\n cache.writeData({\n data: {\n ...initialState\n }\n });\n\n await persistCache({\n cache,\n storage: AsyncStorage,\n debug: true\n });\n }\n // console.log(cache.data);\n};\n\nsetupPersistedCache();\n\nconst link = ApolloLink.from([errorLink, httpLink]);\n\nconst client = new ApolloClient({\n defaults: initialState,\n link,\n cache,\n resolvers\n});\n\nexport default client;\n```\n\n```text\nexport default {\n language: 'bd'\n};\n```\n\n```text\nconst AppProvider = () => {\n const [loaded, setLoaded] = useState(false);\n\n const configureCache = async () => {\n try {\n const cache = new InMemoryCache();\n await persistCache({\n cache,\n storage: AsyncStorage,\n debug: true\n });\n console.log(cache.data);\n } catch (error) {\n console.error('Error restoring Apollo cache', error);\n }\n };\n\n useEffect(() => {\n configureCache()\n .then(() => {\n setLoaded(true);\n })\n .catch(() => {\n setLoaded(false);\n });\n }, []);\n useEffect(() => {\n SplashScreen.hide();\n }, []);\n\n return (\n <>\n {loaded ? (\n <ApolloProvider client={client}>\n <Root />\n </ApolloProvider>\n ) : (\n <View style={{\n flex: 1,\n justifyContent: 'center',\n alignItems: 'center'\n }}\n >\n <TextComponent\n content=\"Loading\"\n size={fonts.fs24}\n family={fonts.medium}\n color={colors.white}\n />\n </View>\n )}\n </>\n );\n};\n\nAppRegistry.registerComponent(appName, () => AppProvider);\n```\n\n```text\nexport const getLangQuery = gql`\n query getLang {\n language @client\n }\n`;\n```\n\n```text\nconst { loading, error, data } = useQuery(getLangQuery);\n const [setLanguage, result] = useMutation(setLangQuery);\n\n const language = data;\n console.log(language);\n```\n\n```text\npersistCache\n```\n\n```text\ndata\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- Very helpful, thank you. Some examples directly destructure data with checking it's defined.","metadata":{"transformedAt":"2026-08-18T18:32:36.235Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":347,"estimatedTokens":1806}}1193{"id":"stack-69012446","source":"stackoverflow","questionId":69012446,"title":"Documenting Graphql schema using Nestjs Code-first approach","tags":["typescript","graphql","nestjs","nest"],"text":"Title: Documenting Graphql schema using Nestjs Code-first approach\nTags: typescript, graphql, nestjs, nest\nSource: Stack Overflow\n\nQuestion:\nIs there a way to add comments to mutations and queries of your schema generated through code first approach of Nestjs?\n\n========================================\n\nCode:\n```text\n@ObjectType( {description : 'My class') )\nClass Person {\n @Field ( () => ID, { description : ' ID of the user' } ) \n Id: number\n}\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.235Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":17,"estimatedTokens":115}}1194{"id":"stack-68237544","source":"stackoverflow","questionId":68237544,"title":"How to cache auth()->user() with relationship like role in Laravel cache to reduce calls to DB?","tags":["laravel","caching","graphql","laravel-lighthouse"],"text":"Title: How to cache auth()->user() with relationship like role in Laravel cache to reduce calls to DB?\nTags: laravel, caching, graphql, laravel-lighthouse\nSource: Stack Overflow\n\nQuestion:\nI am building an application that is using lighthouse-php. Because I have constantly set various policies for different users, I constantly query for user model with a role relationship in different parts applications, and for this reason, would want to store the users in the Redis database and query from there instead.\nI read couple of articles that I found on the internet such as: laravel-cache-authuser; creating-a-caching-user-provider-for-laravel/; caching-the-laravel-user-provider-with-a-decorator/, reviewed code in here laravel-auth-user, and kind of understood the concept but struggling to understand laravel deep enough to find a suitable solution...\n\nFor example, I am struggling to understand how to store `User` with `Role` relationship inside event method in UserObserver, it's clear how to do it with one Model but not with a relationship attached.\n\nI had a sense that I should do something like that:\n\n```\nclass UserObserver\n{\n /**\n * @param User $user\n */\n public function saved(User $user)\n {\n $user->load('role');\n Cache::put(\"user.$user->id\", $user, 60);\n }\n}\n```\n\nBut this way I make 2 calls to the DB, rather than having the relationship pre-loaded. How could I preload the relationship in the events arguments. I tried to add `protected $with = ['role']` so that child model/relationship always loaded. But no matter what I make more calls to DB either to retrieve Role or to retrieve User and Role.\n\nHe is some simplified code samples from my project lighthouse-php.\n\nschema.graphql:\n\n```\ntype SomeType {\n someMethod(args: [String!]): [Model!] @method @can(ability: \"isAdmin\", model: \"App\\\\Models\\\\User\")\n}\n\ntype User {\n id: ID\n name: String\n role: Role @belongsTo\n}\n\ntype Role {\n id: ID!\n name: String!\n label: String!\n users: [User!] @hasMany\n}\n```\n\nUser Model with role relationship:\n\n```\nclass User extends Authenticatabl {\n public function role(): BelongsTo\n {\n return $this->belongsTo(Role::class);\n }\n}\n```\n\nUser Policy that is used on some of the graphql type fields:\n\n```\nclass UserPolicy\n{\n use HandlesAuthorization;\n\n public function isAdmin(): Response\n {\n $user = auth()->user();\n\n return $user->role->name === 'admin'\n ? $this->allow()\n : $this->deny('permission denied');\n }\n\n public function isManager(): Response\n {\n $user = auth()->user();\n $this->allow();\n\n return $user->role->name === 'manager' || $user->role->name === 'admin'\n ? $this->allow()\n : $this->deny('Permission Denied');\n }\n\n}\n```\n\nLighouse custom Query Class for resolving fields via methods.\n\n```\nclass SomeType {\n public function someMethod(): string\n {\n // this triggers db call rather than receiving `role->name` from redis along with user\n return auth()->user()->role->name;\n }\n}\n```\n\nIf I make graphql query that looks something like this (please see below) it causes role relationship to be loaded from db, instead of cache.\n\n```\nquery {\n user {\n id\n name\n role {\n id\n name\n }\n }\n}\nPlease help.\n```\n\n========================================\n\nTop Answer:\nyou can store your auth user with your relation using Session.\n\nexample :\n\n```\n$auth = Auth::User();\nSession::put('user',$auth);\n\nSession::put('relation',$auth->relation);\n```\n\nMay it help you\n\n========================================\n\nCode:\n```php\nclass UserObserver\n{\n /**\n * @param User $user\n */\n public function saved(User $user)\n {\n $user->load('role');\n Cache::put(\"user.$user->id\", $user, 60);\n }\n}\n```\n\n```text\ntype SomeType {\n someMethod(args: [String!]): [Model!] @method @can(ability: \"isAdmin\", model: \"App\\\\Models\\\\User\")\n}\n\ntype User {\n id: ID\n name: String\n role: Role @belongsTo\n}\n\ntype Role {\n id: ID!\n name: String!\n label: String!\n users: [User!] @hasMany\n}\n```\n\n```php\nclass User extends Authenticatabl {\n public function role(): BelongsTo\n {\n return $this->belongsTo(Role::class);\n }\n}\n```\n\n```php\nclass UserPolicy\n{\n use HandlesAuthorization;\n\n public function isAdmin(): Response\n {\n $user = auth()->user();\n\n return $user->role->name === 'admin'\n ? $this->allow()\n : $this->deny('permission denied');\n }\n\n public function isManager(): Response\n {\n $user = auth()->user();\n $this->allow();\n\n return $user->role->name === 'manager' || $user->role->name === 'admin'\n ? $this->allow()\n : $this->deny('Permission Denied');\n }\n\n}\n```\n\n```text\nclass SomeType {\n public function someMethod(): string\n {\n // this triggers db call rather than receiving `role->name` from redis along with user\n return auth()->user()->role->name;\n }\n}\n```\n\n```text\nquery {\n user {\n id\n name\n role {\n id\n name\n }\n }\n}\nPlease help.\n```\n\n```text\nUser\n```\n\n```text\nRole\n```\n\n```text\nprotected $with = ['role']\n```\n\n```text\n<?php \n\nuse Illuminate\\Support\\Facades\\Cache; \n\nclass User extends Authenticatabl {\n\n public function role(): BelongsTo\n {\n return $this->belongsTo(Role::class);\n }\n\n public static function getRoleCacheKey(User $user): string\n {\n return sprintf('user-%d-role', $user->id);\n }\n\n // Define accessor for caching purposes\n public function getRoleAttribute(): Collection\n {\n if ($this->relationLoaded('role')) {\n return $this->getRelationValue('role');\n }\n \n // Replace 3600 for the amount of seconds you would like to cache\n $role = Cache::remember(User::getRoleCacheKey($this), 3600, function () {\n return $this->getRelationValue('role');\n });\n\n $this->setRelation('role', $role);\n\n return $role;\n }\n}\n```\n\n```text\n// In User model\npublic static function forgetRoleCaching(User $user): bool\n{\n return Cache::forget(sprintf(User::getRoleCacheKey($user));\n}\n```\n\n```text\nclass UserObserver\n{\n /**\n * @param User $user\n */\n public function saved(User $user)\n {\n // in case user role is cached forever\n User::forgetRoleCaching($user);\n\n $user->load('role'); // will trigger the accessor an should cache again\n Cache::put(\"user.$user->id\", $user, 60);\n }\n}\n```\n\n```text\naccessor\n```\n\n```text\nrole\n```\n\n```text\nUser\n```\n\n```text\nrememberForever()\n```\n\n```text\n$auth = Auth::User();\nSession::put('user',$auth);\n\nSession::put('relation',$auth->relation);\n```\n\n```text\n<?php\n\nreturn [\n 'role' => ''\n];\n```\n\n```text\nconfig(['user.role' => $example_role]);\n```\n\n```text\nconfig('user.role');\n```\n\n========================================\n\nComments:\n- Yes but, I am trying to store the whole object in the model with relationship","metadata":{"transformedAt":"2026-08-18T18:32:36.235Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":347,"estimatedTokens":1699}}1195{"id":"stack-61627956","source":"stackoverflow","questionId":61627956,"title":"How to generate classes for GraphQL API (AWS AppSync) using Amplify","tags":["graphql","aws-amplify","aws-appsync","aws-amplify-cli"],"text":"Title: How to generate classes for GraphQL API (AWS AppSync) using Amplify\nTags: graphql, aws-amplify, aws-appsync, aws-amplify-cli\nSource: Stack Overflow\n\nQuestion:\nI have a GraphQL API on AWS AppSync pushed by another person and want to connect to it and fetch data in my Android application. According to AWS documentation, to integrate the API with my app I should execute 3 following commands:\n\n```\nnpm install -g @aws-amplify/cli\n amplify init\n amplify add codegen --apiId xxxxxx\n```\n\nAfter that, I need to generate Java classes based on the graphql schema. I execute `amplify codegen models` but get an error \"**No AppSync API configured. Please add an API**\". If execute `amplify add api`, I get \"**You already have an AppSync API in your project. Use the \"amplify update api\" command to update your existing AppSync API.**\"\n\nWhy can't I generate classes? \n\naws-amplify/cli v4.18.1\n\n========================================\n\nTop Answer:\nTry running `amplify pull` to pull down the latest backend environment before running `amplify codegen models`.\n\n========================================\n\nCode:\n```text\nnpm install -g @aws-amplify/cli\n amplify init\n amplify add codegen --apiId xxxxxx\n```\n\n```text\namplify codegen models\n```\n\n```text\namplify add api\n```\n\n```text\namplify pull\n```\n\n```text\namplify codegen models\n```\n\n========================================\n\nComments:\n- `amplify pull` fails with the error: \"Error: EPERM: operation not permitted, stat '..\\amplify\\backend'\"\n- interesting, could you show me your directory and where you're running `amplify pull` from?\n- I ran it from the Android Studio project root. I found out what the problem was, thanks for your help mate.","metadata":{"transformedAt":"2026-08-18T18:32:36.235Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":55,"estimatedTokens":423}}1196{"id":"stack-61468812","source":"stackoverflow","questionId":61468812,"title":"Aggregating fields in graphene/django queries","tags":["python","django","graphql","graphene-django"],"text":"Title: Aggregating fields in graphene/django queries\nTags: python, django, graphql, graphene-django\nSource: Stack Overflow\n\nQuestion:\nI am writing a graphene/django ORM query, where I need to aggregate the values of a particular field on all my query result objects and return it with the query. Not quite sure how to do that, as this involves some post-processing. Would appreciate it if someone can offer some guidance.\n\nHere's some sample code. Django model class 'Market' has an integer field 'num_vendors'. The Graphene wrapper is 'MarketNode' that wraps around the 'Market' model class:\n\nModel class:\n\n```\nclass Market(models.Model):\n num_vendors = models.IntegerField(....)\n```\n\nGraphene class:\n\n```\nclass MarketNode(DjangoObjectType):\n Meta:\n model: Market\n```\n\nI'd like the query to return 'market_count' (there are multiple markets) and 'vendor_count' (sum of all 'vendors' across all markets). So the query would look like:\n\n```\nallMarkets {\n market_count\n vendor_count\n edges {\n node {\n ...\n ...\n num_vendors\n ...\n }\n }\n}\n```\n\nFor the market_count, I am following this example (this works fine):\nhttps://github.com/graphql-python/graphene-django/wiki/Adding-counts-to-DjangoFilterConnectionField\n\nFor vendor_count (across all markets), I assume I need to iterate over the results and add all the num_vendors fields, after the query is complete and resolved. How can I achieve this? This must be a fairly common-use case, so I am sure graphene provides some hooks to do this.\n\n========================================\n\nCode:\n```text\nclass Market(models.Model):\n num_vendors = models.IntegerField(....)\n```\n\n```text\nclass MarketNode(DjangoObjectType):\n Meta:\n model: Market\n```\n\n```text\nallMarkets {\n market_count\n vendor_count\n edges {\n node {\n ...\n ...\n num_vendors\n ...\n }\n }\n}\n```\n\n```text\nclass MarketConnection(graphene.relay.Connection):\n class Meta:\n node = Market\n\n market_count = graphene.Int(required=True)\n vendor_count = graphene.Int(required=True)\n\n def resolve_market_count(self, info, **kwargs):\n return self.iterable.count() if isinstance(self.iterable, QuerySet) else len(self.iterable)\n\n def resolve_vendor_count(self, info, **kwargs):\n if isinstance(self.iterable, QuerySet):\n return self.iterable.aggregate(Count(\"vendor\"))\n return sum([market.num_vendors for market in self.iterable])\n```\n\n```text\nclass MarketNode(DjangoObjectType):\n class Meta:\n model: Market\n connection_class: MarketConnection\n```","metadata":{"transformedAt":"2026-08-18T18:32:36.235Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":98,"estimatedTokens":636}}1197{"id":"stack-67736607","source":"stackoverflow","questionId":67736607,"title":"How to Process Uploaded Image with Graphql Apollo with SharpJS in NodeJS?","tags":["node.js","graphql","apollo-server","sharp"],"text":"Title: How to Process Uploaded Image with Graphql Apollo with SharpJS in NodeJS?\nTags: node.js, graphql, apollo-server, sharp\nSource: Stack Overflow\n\nQuestion:\nI have a graphql mutation that gets an image from the frontend, and that then is processed and optimized on my server.\n\nBut I can't figure out how to pass my image to sharp.\n\nHere is my code:\n\n```\nconst Mutation = {\n createImage: async (_, { data }) => {\n const { file } = data\n const image = await file\n\n console.log(image)\n\n const sharpImage = sharp(image)\n }\n}\n```\n\nI know the code doesn't work and `sharp` throws an error saying that the input is invalid. So how can I work with `createReadStream` and to create an instance of `sharp`?\n\nWhen I `console.log(image)`, here is what I see:\n\n```\nimage {\n filename: 'image.png',\n mimetype: 'image/png',\n encoding: '7bit',\n createReadStream: [Function: createReadStream]\n}\n```\n\nThanks a lot in advance!\n\n========================================\n\nTop Answer:\nApollo recommends using signed URLs rather than uploading files via mutations. https://www.apollographql.com/blog/backend/file-uploads/file-upload-best-practices/\n\nThis is due to CSRF risks and performance impacts, especially as an app scales. For an app which properly handles the CSRF risks, uploading a file via a mutation should be fine.\n\n========================================\n\nCode:\n```js\nconst Mutation = {\n createImage: async (_, { data }) => {\n const { file } = data\n const image = await file\n\n console.log(image)\n\n const sharpImage = sharp(image)\n }\n}\n```\n\n```text\nimage {\n filename: 'image.png',\n mimetype: 'image/png',\n encoding: '7bit',\n createReadStream: [Function: createReadStream]\n}\n```\n\n```text\nsharp\n```\n\n```text\ncreateReadStream\n```\n\n```text\nsharp\n```\n\n```text\nconsole.log(image)\n```\n\n```js\nconst { GraphQLUpload } = require('graphql-upload');\n\nconst server = new ApolloServer({\n resolvers: {\n Upload: GraphQLUpload,\n }\n})\n```\n\n```js\n// this is a utility function to promisify the stream and store the image in a buffer, which then is passed to sharp\nconst streamToBuffer = (stream) => {\n const chunks = [];\n return new Promise((resolve, reject) => {\n stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));\n stream.on('error', (err) => reject(err));\n stream.on('end', () => resolve(Buffer.concat(chunks)));\n })\n}\n\nconst Mutation = {\n createImage: async (_, { data }) => {\n const { file } = data\n const { createReadStream } = await file\n\n const imageBuffer = await streamToBuffer(createReadStream())\n\n const sharpImage = sharp(imageBuffer)\n }\n}\n```\n\n```text\nscalar Upload\n```\n\n```text\ntypeDefs\n```\n\n```text\nUpload\n```\n\n========================================\n\nComments:\n- stream != buffer ?\n- @xadm Thanks for your input. I know that stream is not a buffer. I was just trying to provide some example to work with. I am trying to understand how to use `createReadStream` and process the image with `sharp`\n- check args ... file is ready as awaited (and if passed corectly, of course) ... console.log image or file ... stackoverflow.com/a/61452904/6124657\n- @xadm when I pass the awaited file result to sharp, I still get `[Error: Input file is missing]`.I added the result of the `console.log` of the awaited file to my question\n- it seams you can use stream ... stackoverflow.com/a/61786860/6124657\n- @xadm thanks for your help! I researched a lot and eventually found all the pieces that made my graphql resolver work. I posted my answer below. Thanks again!","metadata":{"transformedAt":"2026-08-18T18:32:36.235Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":141,"estimatedTokens":891}}1198{"id":"stack-66614351","source":"stackoverflow","questionId":66614351,"title":"Usage of helmet in default configuration blocks graphql playground to open","tags":["graphql"],"text":"Title: Usage of helmet in default configuration blocks graphql playground to open\nTags: graphql\nSource: Stack Overflow\n\nQuestion:\n```\napp.use(xss());//safety against XSS attack or Cross Site Scripting attacks\n\napp.use(helmet());\nhttpServer.listen(process.env.PORT || 4000, () => {\n console.log(\n `π Server ready at http://localhost:${process.env.PORT || 4000}${\n server.graphqlPath\n `π Server ready at http://localhost:${process.env.PORT || 4000}${server.graphqlPath\n }`\n );\n console.log(\n `π Subscriptions ready at ws://localhost:${process.env.PORT || 4000}${\n server.subscriptionsPath\n \n }`\n );\n });\n```\n\nI am using graphQL and helmet at the same time. I think which is stopping my graphQL api playground. THIS MY CODE I CANT RESOLVE PLS HELP.\nenter image description here\n\n========================================\n\nCode:\n```text\napp.use(xss());//safety against XSS attack or Cross Site Scripting attacks\n\napp.use(helmet());\nhttpServer.listen(process.env.PORT || 4000, () => {\n console.log(\n `π Server ready at http://localhost:${process.env.PORT || 4000}${\n server.graphqlPath\n `π Server ready at http://localhost:${process.env.PORT || 4000}${server.graphqlPath\n }`\n );\n console.log(\n `π Subscriptions ready at ws://localhost:${process.env.PORT || 4000}${\n server.subscriptionsPath\n \n }`\n );\n });\n```\n\n```text\napp.use(helmet({ contentSecurityPolicy: (process.env.NODE_ENV === 'production') ? undefined : false }));\n```\n\n========================================\n\nComments:\n- github.com/graphql/graphql-playground/issues/…","metadata":{"transformedAt":"2026-08-18T18:32:36.235Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":59,"estimatedTokens":404}}1199{"id":"stack-59660178","source":"stackoverflow","questionId":59660178,"title":"Overcome endless looping when executing useQuery (ApolloClient) by defining a new client","tags":["reactjs","graphql","react-apollo","apollo-client"],"text":"Title: Overcome endless looping when executing useQuery (ApolloClient) by defining a new client\nTags: reactjs, graphql, react-apollo, apollo-client\nSource: Stack Overflow\n\nQuestion:\nI need to define \"client\" when running \"useQuery\", but I get endless looping.\n\nI wrote the code as below:\n\n```\nconst QueryKTP = gql`\n query {\n documents(transactionId:\"${transactionId}\", input: [\n {documentType:\"KTP\"}\n ]){\n documentResponses{\n documentType\n documentBase64\n }\n responseDescription\n responseCode\n message\n }\n }`\n\nconst anotherClient = new ApolloClient({\n uri: \"https://my-url/online-service/graphql\"\n});\n\nconst { data, loading } = useQuery(QueryKTP, {client: anotherClient});\n```\n\nIf I change the script above to be like below (remove new client), looping no longer occurs.\n\n```\nconst { data, loading } = useQuery(QueryKTP);\n```\n\nWhat do I need to fix? Thank you\n\n========================================\n\nTop Answer:\nIn my case I had multiple different graphUri dependent on the network selection of my app. The issue for me was that I was using the example code ApolloWrapper as such,\n\n```\nconst ApolloWrapper: (uri: string) => ApolloClient | Error = (\n uri: string\n) => {\n try {\n return new ApolloClient({\n link: link.concat(createHttpLink({ uri: uri })),\n cache: new InMemoryCache(),\n });\n } catch (err) {\n console.error(\"Failed to connect to client\");\n return Error(err);\n }\n};\n```\n\nand then using it as\n\n```\nconst GraphProvider: ({ children }: GProps) => any = ({ children }: GProps) => {\n const client = Client.ApolloWrapper(config?.graphUri ?? \"\");\n return (\n }>\n {children}\n \n );\n};\n```\n\nwhere of course the default uri here is '' which resolves to nothing.\n\nWith this config when it was trying to instantiate the httpLink it was obviously erroring. This was also the case for any other network issue like it couldnt resolve. I didn't notice the issue until adding some error checking to useQuery and found the loop.\n\nThe fix for me was as simple as memoising graphUri so it doesnt continuosly throw the error cause a rerender, throw the error cause a rerender etc. Replacing the wrapper as followed so that it only creates a new instance of the client when the uri changes. Am not sure if I missed a super simple solution in the Apollo docs but none of their stuff seemed to work.\n\n```\nconst ApolloWrapper: (uri: string) => ApolloClient | Error = (\n uri: string\n) => {\n const client = useMemo(() => {\n try {\n return new ApolloClient({\n link: link.concat(createHttpLink({ uri: uri })),\n cache: new InMemoryCache(),\n });\n } catch (err) {\n console.error(\"Failed to connect to client\");\n return Error(err);\n }\n }, [uri]);\n return client;\n};\n```\n\n========================================\n\nCode:\n```text\nconst QueryKTP = gql`\n query {\n documents(transactionId:\"${transactionId}\", input: [\n {documentType:\"KTP\"}\n ]){\n documentResponses{\n documentType\n documentBase64\n }\n responseDescription\n responseCode\n message\n }\n }`\n\nconst anotherClient = new ApolloClient({\n uri: \"https://my-url/online-service/graphql\"\n});\n\nconst { data, loading } = useQuery(QueryKTP, {client: anotherClient});\n```\n\n```text\nconst { data, loading } = useQuery(QueryKTP);\n```\n\n```text\nexport default function MyComponent () {\n const anotherClient = new ApolloClient({\n uri: \"https://my-url/online-service/graphql\"\n });\n const { data, loading } = useQuery(QueryKTP, {client: anotherClient});\n}\n```\n\n```text\nconst anotherClient = new ApolloClient({\n uri: \"https://my-url/online-service/graphql\"\n});\nexport default function MyComponent () {\n const { data, loading } = useQuery(QueryKTP, {client: anotherClient});\n}\n```\n\n```text\nnew ApolloClient\n```\n\n```text\nnew\n```\n\n```text\nnew Date()\n```\n\n```text\nconst anotherClient = new ApolloClient({\n link: new HttpLink({\n uri: 'https://my-url/online-service/graphql'\n })\n});\n```\n\n```text\nanotherClient\n```\n\n```text\nHttpLink\n```\n\n```text\nApolloClient\n```\n\n```text\nconst ApolloWrapper: (uri: string) => ApolloClient<any> | Error = (\n uri: string\n) => {\n try {\n return new ApolloClient({\n link: link.concat(createHttpLink({ uri: uri })),\n cache: new InMemoryCache(),\n });\n } catch (err) {\n console.error(\"Failed to connect to client\");\n return Error(err);\n }\n};\n```\n\n```text\nconst GraphProvider: ({ children }: GProps) => any = ({ children }: GProps) => {\n const client = Client.ApolloWrapper(config?.graphUri ?? \"\");\n return (\n <ApolloProvider client={client as ApolloClient<any>}>\n {children}\n </ApolloProvider>\n );\n};\n```\n\n```text\nconst ApolloWrapper: (uri: string) => ApolloClient<any> | Error = (\n uri: string\n) => {\n const client = useMemo(() => {\n try {\n return new ApolloClient({\n link: link.concat(createHttpLink({ uri: uri })),\n cache: new InMemoryCache(),\n });\n } catch (err) {\n console.error(\"Failed to connect to client\");\n return Error(err);\n }\n }, [uri]);\n return client;\n};\n```\n\n========================================\n\nComments:\n- I still get looping over and over.\n- Confirming that this helped me. TYVM!\n- \"guys often meet the same bug with an infinite loop, when they use new Date() in the render function\" probably saved me hours. Thx !","metadata":{"transformedAt":"2026-08-18T18:32:36.235Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":231,"estimatedTokens":1307}}1200{"id":"stack-64491441","source":"stackoverflow","questionId":64491441,"title":"Reset useLazyQuery after called once","tags":["react-native","graphql","react-apollo"],"text":"Title: Reset useLazyQuery after called once\nTags: react-native, graphql, react-apollo\nSource: Stack Overflow\n\nQuestion:\nI'm using `useLazyQuery` to trigger a query on a button click. After the query is called once, the results (data, error, etc) are passed to the component render on each render. This is problematic for example when the user enters new text input to change what caused the error: the error message keeps reapearing. So I would like to \"clear\" the query (eg. when user types new data into TextInput) so the query results return to there inital state (everything `undefined`) and the error message goes away.\n\nI can't find any clear way to do this in the Apollo docs, so how could I do that?\n\n(I though of putting the query in the parent component so it does not update on each rerender, but I'd rather not do that)\n\nThis is how I have my component currently setup:\n\n```\nimport { useLazyQuery } from 'react-apollo'\n\n// ...\n\nconst [inputValue, setInputValue] = useState('')\n\nconst [getUserIdFromToken, { called, loading, data, error }] = useLazyQuery(deliveryTokenQuery, {\n variables: {\n id: inputValue.toUpperCase(),\n },\n})\n\nuseEffect(() => {\n if (data && data.deliveryToken) {\n onSuccess({\n userId: data.deliveryToken.vytal_user_id,\n token: inputValue,\n })\n }\n}, [data, inputValue, onSuccess])\n\n// this is called on button tap\nconst submitToken = async () => {\n Keyboard.dismiss()\n getUserIdFromToken()\n}\n\n// later in the render...\n\n {\n setInputValue(val)\n if (called) {\n // clean/reset query here? \n```\n\n========================================\n\nCode:\n```text\nimport { useLazyQuery } from 'react-apollo'\n\n// ...\n\nconst [inputValue, setInputValue] = useState('')\n\nconst [getUserIdFromToken, { called, loading, data, error }] = useLazyQuery(deliveryTokenQuery, {\n variables: {\n id: inputValue.toUpperCase(),\n },\n})\n\nuseEffect(() => {\n if (data && data.deliveryToken) {\n onSuccess({\n userId: data.deliveryToken.vytal_user_id,\n token: inputValue,\n })\n }\n}, [data, inputValue, onSuccess])\n\n// this is called on button tap\nconst submitToken = async () => {\n Keyboard.dismiss()\n getUserIdFromToken()\n}\n\n// later in the render...\n\n<TextInput\n onChangeText={(val) => {\n setInputValue(val)\n if (called) {\n // clean/reset query here? <----------------------\n }\n })\n/>\n```\n\n```text\nuseLazyQuery\n```\n\n```text\nundefined\n```\n\n```js\nconst [inputValue, setInputValue] = useState('')\nconst [codeError, setCodeError] = useState<string | undefined>()\n\nconst [getUserIdFromToken, { loading }] = useLazyQuery(deliveryTokenQuery, {\n onCompleted: ({ deliveryToken }) => {\n onSuccess({\n userId: deliveryToken.vytal_user_id,\n token: inputValue,\n })\n },\n onError: (e) => {\n if (e.graphQLErrors && e.graphQLErrors[0] === 'DELIVERY_TOKEN_NOT_FOUND') {\n return setCodeError('DELIVERY_TOKEN_NOT_FOUND')\n }\n return setCodeError('UNKNOWN')\n },\n})\n\nconst submitToken = () => {\n Keyboard.dismiss()\n getUserIdFromToken({\n variables: {\n id: inputValue\n },\n })\n}\n```\n\n```text\nonCompleted\n```\n\n```text\nonError\n```\n\n========================================\n\nComments:\n- don't use effect, use `onCompleted`, pass variables in `submitToken`, not in query def\n- This works but the problem is that `loading` updates before `onCompleted`/`onError` get called which results in a \"flash\" of undesired render state.","metadata":{"transformedAt":"2026-08-18T18:32:36.235Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":142,"estimatedTokens":844}}