question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I've been searching for days on how to layout a rundeck workflow with job dependencies. what I need to do is to have 3 jobs: job-1 and job-2 are scheduled to run in parallel while job-3 will only be triggered after the completion of both job-1, and job-2. assuming that job-1 and job-2 have different execution times. I tried using job state conditionals to do that but it seems that the condition if not met will halt or fail only. My idea is to halt the execution until all the parent jobs completes and then resume the workflow.
You can achieve this by compiling a master job which includes 2 steps: step: job-1 and job-2 as a sub-job which includes both (run in parallel if node oriented execution is selected) step: job-3 But not all 3 in in the same flow.
Rundeck
36,291,321
13
I'm attempting to set up Apollo GraphQL support in a new React project, but when I try to compile a query using gql I keep receiving the error: Syntax Error: Expected Name, found } This is generated by the following code: import gql from 'graphql-tag' const query = gql` { user(id: 5) { firstName lastName } } ` console.log(query) I'm basing this code off the example code found here: https://github.com/apollographql/graphql-tag What is the Name referred to in the error message? Does anyone know what I'm doing wrong here?
This error occurs mostly when there are unclosed curly braces or when some fields are not properly defined while calling the query.
Apollo
48,331,103
92
I don't have any previous experience with *MQs and I'm looking to build knowledge on JMS and message queues in general. That way, I wonder whether I should start with ActiveMQ or just "ignore" it altogether and start by teaching myself Apollo. Is Apollo as feature-complete as ActiveMQ? Does it implement JMS 2.0 (I see that ActiveMQ got stuck with 1.1)? Will I be missing something really important? Also, how does Kafka compare to these two solutions?
Apache ActiveMQ is a great workhorse full of features and nice stuff. It's not the fastest MQ software around but fast enough for most use cases. Among features are flexible clustring, fail-over, integrations with different application servers, security etc. Apache Apollo is an attempt to write a new core for ActiveMQ to cope with a large amount of clients and messages. It does not have all nice and convenient feature of ActiveMQ but scales a lot better. Apache Apollo is a really fast MQ implementation when you give it a large multi-core server and thousands of concurrent connections. It has a nice, simple UI, but is not a "one-size-fits-all" solution. It seems that there is an attempt ongoing to merge a number of ActiveMQ features with HornetQ under the name ActiveMQ Artemis. HornetQ has JMS2.0 support, so my humble guess is that it's likely to appear in ActiveMQ 6.x. JIRA, Github Kafka is a different beast. It's a very simple message broker intended to scale persistent publish subscribe (topics) as fast as possible over multiple servers. For small-medium sized deployments, Kafka is probably not the best option. It also has it's way to do things to achieve the high throughput, so you have to trade a lot in terms of flexibility to get high distributed throughput. If you are new to the area of MQ and brokers, I guess Kafka is overkill. On the other hand - if you have a decent sized server cluster and wonder how to push as many messages as possible through it - give Kafka a spin!
Apollo
27,666,943
71
I'm learning GraphQL now and while walking through tutorial I met behavior that I can't understand. Let's say we have defined type in schema: type Link { id: ID! url: String! description: String! postedBy: User votes: [Vote!]! } Due 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: { "url": "youtube.com", "votes": [] }, { "url": "agar.io", "votes": [] } So 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). Thanks!
Non-null means exactly what it sounds like -- not null. An empty array is not null -- it's still returning a value. Here is a summary table: declaration accepts: | null | [] | [null] | [{foo: 'BAR'}] ------------------------------------------------------------------------ [Vote!]! | no | yes | no | yes [Vote]! | no | yes | yes | yes [Vote!] | yes | yes | no | yes [Vote] | yes | yes | yes | yes [Vote!]! means that the field (in this case votes) cannot return null and that it must resolve to an array and that none of the individuals items inside that array can be null. So [] and [{}] and [{foo: 'BAR'}] would all be valid (assuming foo is non-null). However, the following would throw: [{foo: 'BAR'}, null] [Vote]! means that the field cannot return null, but any individual item in the returned list can be null. [Vote!] means that the entire field can be null, but if it does return a value, it needs to be an array and each item in that array cannot be null. [Vote] means that the entire field can be null, but if it does return a value, it needs to be an array. However, any member of the array may also be null. If you need to verify whether an array is empty, you have to do so within your resolver logic. If you want GraphQL to still throw when an array is empty, just have your resolver return a rejected Promise. For more information your can read the list and non-null section of the GraphQL introduction or take a look at the spec.
Apollo
46,770,501
69
How do you prevent a nested attack against an Apollo server with a query such as: { authors { firstName posts { title author { firstName posts{ title author { firstName posts { title [n author] [n post] } } } } } } } In other words, how can you limit the number of recursions being submitted in a query? This could be a potential server vulnerability.
As of the time of writing, there isn't a built-in feature in GraphQL-JS or Apollo Server to handle this concern, but it's something that should definitely have a simple solution as GraphQL becomes more popular. This concern can be addressed with several approaches at several levels of the stack, and should also always be combined with rate limiting, so that people can't send too many queries to your server (this is a potential issue with REST as well). I'll just list all of the different methods I can think of, and I'll try to keep this answer up to date as these solutions are implemented in various GraphQL servers. Some of them are quite simple, and some are more complex. Query validation: In every GraphQL server, the first step to running a query is validation - this is where the server tries to determine if there are any serious errors in the query, so that we can avoid using actual server resources if we can find that there is some syntax error or invalid argument up front. GraphQL-JS comes with a selection of default rules that follow a format pretty similar to ESLint. Just like there is a rule to detect infinite cycles in fragments, one could write a validation rule to detect queries with too much nesting and reject them at the validation stage. Query timeout: If it's not possible to detect that a query will be too resource-intensive statically (perhaps even shallow queries can be very expensive!), then we can simply add a timeout to the query execution. This has a few benefits: (1) it's a hard limit that's not too hard to reason about, and (2) this will also help with situations where one of the backends takes unreasonably long to respond. In many cases, a user of your app would prefer a missing field over waiting 10+ seconds to get a response. Query whitelisting: This is probably the most involved method, but you could compile a list of allowed queries ahead of time, and check any incoming queries against that list. If your queries are totally static (you don't do any dynamic query generation on the client with something like Relay) this is the most reliable approach. You could use an automated tool to pull query strings out of your apps when they are deployed, so that in development you write whatever queries you want but in production only the ones you want are let through. Another benefit of this approach is that you can skip query validation entirely, since you know that all possible queries are valid already. For more benefits of static queries and whitelisting, read this post: https://dev-blog.apollodata.com/5-benefits-of-static-graphql-queries-b7fa90b0b69a Query cost limiting: (Added in an edit) Similar to query timeouts, you can assign a cost to different operations during query execution, for example a database query, and limit the total cost the client is able to use per query. This can be combined with limiting the maximum parallelism of a single query, so that you can prevent the client from sending something that initiates thousands of parallel requests to your backend. (1) and (2) in particular are probably something every GraphQL server should have by default, especially since many new developers might not be aware of these concerns. (3) will only work for certain kinds of apps, but might be a good choice when there are very strict performance or security requirements.
Apollo
37,337,466
64
Is it possible to have a define a field as Date or JSON in my graphql schema ? type Individual { id: Int name: String birthDate: Date token: JSON } actually the server is returning me an error saying : Type "Date" not found in document. at ASTDefinitionBuilder._resolveType (****node_modules\graphql\utilities\buildASTSchema.js:134:11) And same error for JSON... Any idea ?
Have a look at custom scalars: https://www.apollographql.com/docs/graphql-tools/scalars.html create a new scalar in your schema: scalar Date type MyType { created: Date } and create a new resolver: import { GraphQLScalarType } from 'graphql'; import { Kind } from 'graphql/language'; const resolverMap = { Date: new GraphQLScalarType({ name: 'Date', description: 'Date custom scalar type', parseValue(value) { return new Date(value); // value from the client }, serialize(value) { return value.getTime(); // value sent to the client }, parseLiteral(ast) { if (ast.kind === Kind.INT) { return parseInt(ast.value, 10); // ast value is always in string format } return null; }, }) };
Apollo
49,693,928
60
Let's say my graphql server wants to fetch the following data as JSON where person3 and person5 are some id's: "persons": { "person3": { "id": "person3", "name": "Mike" }, "person5": { "id": "person5", "name": "Lisa" } } Question: How to create the schema type definition with apollo? The 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. As you see persons is not an Iterable, so the following won't work as a graphql type definition I did with apollo: type Person { id: String name: String } type Query { persons(area: String): [Person] } The keys in the persons object may always be different. One 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?
GraphQL relies on both the server and the client knowing ahead of time what fields are available available for each type. In some cases, the client can discover those fields (via introspection), but for the server, they always need to be known ahead of time. So to somehow dynamically generate those fields based on the returned data is not really possible. You could utilize a custom JSON scalar (graphql-type-json module) and return that for your query: type Query { persons(area: String): JSON } By utilizing JSON, you bypass the requirement for the returned data to fit any specific structure, so you can send back whatever you want as long it's properly formatted JSON. Of course, there's significant disadvantages in doing this. For example, you lose the safety net provided by the type(s) you would have previously used (literally any structure could be returned, and if you're returning the wrong one, you won't find out about it until the client tries to use it and fails). You also lose the ability to use resolvers for any fields within the returned data. But... your funeral :) As an aside, I would consider flattening out the data into an array (like you suggested in your question) before sending it back to the client. If you're writing the client code, and working with a dynamically-sized list of customers, chances are an array will be much easier to work with rather than an object keyed by id. If you're using React, for example, and displaying a component for each customer, you'll end up converting that object to an array to map it anyway. In designing your API, I would make client usability a higher consideration than avoiding additional processing of your data.
Apollo
46,562,561
48
I was going through the documentation of Apollo React hooks. And saw there are two queries hooks to use for which is useQuery and useLazyQuery I was reading this page. https://www.apollographql.com/docs/react/api/react/hooks/ Can someone explain me what is the difference between them and in which case it should be used.
When useQuery is called by the component, it triggers the query subsequently. But when useLazyQuery is called, it does not trigger the query subsequently, and instead return a function that can be used to trigger the query manually. It is explained on this page: https://www.apollographql.com/docs/react/data/queries/#manual-execution-with-uselazyquery When 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? The useLazyQuery hook is perfect for executing queries in response to events other than component rendering. This hook acts just like useQuery, with one key exception: when useLazyQuery is called, it does not immediately execute its associated query. Instead, it returns a function in its result tuple that you can call whenever you're ready to execute the query.
Apollo
63,681,650
45
I have a queries file that looks like this: import {gql} from 'react-apollo'; const queries = { getApps: gql` { apps { id name } } `, getSubjects: gql` { subjects { id name } } ` }; export default queries; I then import this file to my React component: import React, {Component} from 'react' import queries from './queries' class Test extends Component { ... } export default graphql(queries.getSubjects)(graphql(queries.getApps)(Test)); This will only get data for one of the queries (getApps) and not both. If I do one at a time so that it looks like this: export default graphql(queries.getSubjects)(Test); then it works but I don't have my other query. Yes, I have tested both separately and they work. How do I get it so that both queries show up in my props.data?
My preferred way is to use the compose functionality of the apollo client (docu). EDIT: If you have more than one query you should name them. So in your case, it could look like this: import React, {Component} from 'react' import queries from './queries' import { graphql, compose } from 'react-apollo'; class Test extends Component { ... render() { ... console.log(this.props.subjectsQuery, this.props.appsQuery); // should show both ... } } export default compose( graphql(queries.getSubjects, { name: "subjectsQuery" }), graphql(queries.getApps, { name: "appsQuery" }), )(Test);
Apollo
43,380,704
44
I tried changing the addTypeName: false in the Apollo client in GraphQL apollo.create({ link: httpLinkWithErrorHandling, cache: new InMemoryCache({ addTypename: false }), defaultOptions: { watchQuery: { fetchPolicy: 'network-only', errorPolicy: 'all' } } But it works and it throws the following messages in the console fragmentMatcher.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. , Could not find __typename on Fragment PopulatedOutageType and fragmentMatcher.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. even if i change false to true new InMemoryCache({ addTypename: true }), the mutations start failing because of the unwanted typename in the mutation is there any way to resolve this issue
Cleaning Unwanted Fields From GraphQL Responses In the above thread, I have posted the answer for this problem please refer to it
Apollo
55,259,856
42
If 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? type Address { line1: String city: String state: String zip: String } fragment NameAndAddress on Person, Business { name: String address: Address } type Business { ...NameAndAddress hours: String } type Customer { ...NameAndAddress customerSince: Date }
Fragments 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. If 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: const nameAndAddress = ` name: String address: Address ` const typeDefs = ` type Business { ${nameAndAddress} hours: String } type Customer { ${nameAndAddress} customerSince: Date } ` Alternatively, there are libraries out there, like graphql-s2s, that allow you to use type inheritance.
Apollo
48,940,240
41
I'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. 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. If 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. withData.js import withApollo from 'next-with-apollo'; import ApolloClient from 'apollo-boost'; import { endpoint } from '../config'; function createClient({ headers }) { return new ApolloClient({ uri: endpoint, request: operation => { operation.setContext({ fetchOptions: { credentials: 'include' }, headers }); }, // local data clientState: { resolvers: { Mutation: {} }, defaults: {} } }); } export default withApollo(createClient); _app.js import App from 'next/app'; import { ApolloProvider } from 'react-apollo'; import Page from '../components/Page'; import { Overlay } from '../components/styles/Overlay'; import withData from '../lib/withData'; class MyApp extends App { static async getInitialProps({ Component, ctx }) { let pageProps = {}; if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx); } // this exposes the query to the user pageProps.query = ctx.query; return { pageProps }; } render() { const { Component, apollo, pageProps } = this.props; return ( <ApolloProvider client={apollo}> <Overlay id="page-overlay" /> <Page> <Component {...pageProps} /> </Page> </ApolloProvider> ); } } export default withData(MyApp);
In my case, I found that I had react-apollo@3.0.1 installed as well as @apollo/react-hooks@3.0.0. Removing @apollo/react-hooks and just relying on react-apollo fixed the invariant issue for me. Make sure that you aren't using any mismatched versions in your lock file or package.json This is what someone said in a GitHub issue thread, which, was the case for me too. Make sure you try it!
Apollo
58,475,780
39
I 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. Is there a generic way to add a custom header to all requests that are sent by my polling client?
Two Solutions There are two ways to do that. One is quick and easy and will work for a specific query with some limitation, and the other is a general solution that is safer and can work for multiple queries. Quick and Easy Solution Advantages it's quick and... easy When you configure your query you can configure it using its options field, that has a context field. The value of context will be processed by the network chain. The context itself is not sent to the server, but if you add a headers field to it, it will be used in the HTTP request. Example: const someQuery = graphql(gql`query { ... }`, { options: { context: { headers: { "x-custom-header": "pancakes" // this header will reach the server } }, // ... other options } }) General Solution using a Network Link middleware With Apollo you can add an Apollo Link that will act as a middleware and add a custom header to the request based on the context that was set by your query operation. From the docs: Apollo Client has a pluggable network interface layer, which can let you configure how queries are sent over HTTP Read more about Apollo Link, the network link and Middleware concepts. Advantages: The middleware's logic can be used by any graphql operation (you set the condition) Your queries don't need to "care" or know about HTTP headers You can do more processing before deciding if and what headers to add to the request. and more.. Setting the context Same as the quick and easy solution, only this time we don't set the headers directly: { options: { context: { canHazPancakes: true //this will not reach the server } } } Adding the middleware Apollo has a specific middleware for setting the context apollo-link-context (the same can be achieved with a more general middleware). import {setContext} from 'apollo-link-context' //... const pancakesLink = setContext((operation, previousContext) => { const { headers, canHazPancakes } = previousContext if (!canHazPancakes) { return previousContext } return { ...previousContext, headers: { ...headers, "x-with-pancakes": "yes" //your custom header } } }) Don't forget to concat it to the network chain somewhere before your http link const client = new ApolloClient({ // ... link: ApolloLink.from([ pancakesLink, <yourHttpLink> ]) }) There is another useful example in the docs: using a middleware for authentication. That's it! You should get some pancakes from the server now. Hope this helps.
Apollo
48,558,681
35
I am currently loading the GraphQL schema using a separate .graphql file, but it is encapsulated within strings: schema.graphql const schema = ` type CourseType { _id: String! name: String! } type Query { courseType(_id: String): CourseType courseTypes: [CourseType]! } ` module.exports = schema Then using it for the apollo-server: index.js const { ApolloServer, makeExecutableSchema } = require('apollo-server') const typeDefs = require('./schema.graphql') const resolvers = { ... } const schema = makeExecutableSchema({ typeDefs: typeDefs, resolvers }) const server = new ApolloServer({ schema: schema }) server.listen().then(({ url }) => { console.log(`Server ready at ${url}.`) }) Is there any way to simply load a .graphql that looks as such? schema.graphql type CourseType { _id: String! name: String! } type Query { courseType(_id: String): CourseType courseTypes: [CourseType]! } Then 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.
If you define your type definitions inside a .graphql file, you can read it in one of several ways: 1.) Read the file yourself: const { readFileSync } = require('fs') // we must convert the file Buffer to a UTF-8 string const typeDefs = readFileSync(require.resolve('./type-defs.graphql')).toString('utf-8') 2.) Utilize a library like graphql-tools to do it for you: const { loadDocuments } = require('@graphql-tools/load'); const { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader'); // this can also be a glob pattern to match multiple files! const typeDefs = await loadDocuments('./type-defs.graphql', { file, loaders: [ new GraphQLFileLoader() ] }) 3.) Use a babel plugin or a webpack loader import typeDefs from './type-defs.graphql'
Apollo
62,290,875
35
I am using a watchQuery or query in Apollo-Angular (graphql) How is the logic and difference of the watchQuery and query
query is something you just query for once, you can consider it as an equivalent of GET. watchQuery is something you constantly keep a watch on query, whenever that query will be refetched or the data related to that query is changed from anywhere else, this method will keep on emitting the updated data. It's really simple, you can read the docs here.
Apollo
49,618,392
33
Apollo link offers an error handler onError Issue: Currently, we wish to refresh oauth tokens when they expires during an apollo call and we are unable to execute an async fetch request inside the onError properly. Code: initApolloClient.js import { ApolloClient } from 'apollo-client'; import { onError } from 'apollo-link-error'; import { ApolloLink, fromPromise } from 'apollo-link'; //Define Http link const httpLink = new createHttpLink({ uri: '/my-graphql-endpoint', credentials: 'include' }); //Add on error handler for apollo link return new ApolloClient({ link: ApolloLink.from([ onError(({ graphQLErrors, networkError, operation, forward }) => { if (graphQLErrors) { //User access token has expired if(graphQLErrors[0].message==="Unauthorized") { //We assume we have both tokens needed to run the async request if(refreshToken && clientToken) { //let's refresh token through async request return fromPromise( authAPI.requestRefreshToken(refreshToken,clientToken) .then((refreshResponse) => { let headers = { //readd old headers ...operation.getContext().headers, //switch out old access token for new one authorization: `Bearer ${refreshResponse.access_token}`, }; operation.setContext({ headers }); //Retry last failed request return forward(operation); }) .catch(function (error) { //No refresh or client token available, we force user to login return error; }) ) } } } } } }), What happens is: Initial graphQL query runs and fails due to unauthorization The onError function of ApolloLink is executed. The promise to refresh the token is executed. The onError function of ApolloLink is executed again?? The promise to refresh the token is completed. The initial graphQL query result is returned and its data is undefined Between step 5 and 6, apollo doesn't re-run the initial failed graphQL query and hence the result is undefined. Errors from console: Uncaught (in promise) Error: Network error: Error writing result to store for query: query UserProfile($id: ID!) { UserProfile(id: $id) { id email first_name last_name } __typename } } The solution should allow us to: Run an async request when an operation fails Wait for the result of the request Retry failed operation with data from the request's result Operation should succeed to return its intended result
I'm refreshing the token this way (updated OP's): import { ApolloClient } from 'apollo-client'; import { onError } from 'apollo-link-error'; import { ApolloLink, Observable } from 'apollo-link'; // add Observable // Define Http link const httpLink = new createHttpLink({ uri: '/my-graphql-endpoint', credentials: 'include' }); // Add on error handler for apollo link return new ApolloClient({ link: ApolloLink.from([ onError(({ graphQLErrors, networkError, operation, forward }) => { // User access token has expired if (graphQLErrors && graphQLErrors[0].message === 'Unauthorized') { // We assume we have both tokens needed to run the async request if (refreshToken && clientToken) { // Let's refresh token through async request return new Observable(observer => { authAPI.requestRefreshToken(refreshToken, clientToken) .then(refreshResponse => { operation.setContext(({ headers = {} }) => ({ headers: { // Re-add old headers ...headers, // Switch out old access token for new one authorization: `Bearer ${refreshResponse.access_token}` || null, } })); }) .then(() => { const subscriber = { next: observer.next.bind(observer), error: observer.error.bind(observer), complete: observer.complete.bind(observer) }; // Retry last failed request forward(operation).subscribe(subscriber); }) .catch(error => { // No refresh or client token available, we force user to login observer.error(error); }); }); } } }) ]) });
Apollo
50,965,347
33
I am building an application using: MySQL as the backend database Apollo GraphQL server as a query layer for that database Sequelize as the ORM layer between GraphQL and MySQL As 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 Graphql Type: type Person { id: ID! firstName: String middleName: String lastName: String createdAt: String updatedAt: String } Sequelize connector export const Person = sequelize.define('person', { firstName: { type: Sequelize.STRING }, middleName: { type: Sequelize.STRING }, lastName: { type: Sequelize.STRING }, }); GraphQL resolver: Query: { person(_, args) { return Person.findById(args.id); } So 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. How 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?
ID is a scalar type described in the GraphQL specification (working draft October 2016): The ID type is serialized in the same way as a String; however, it is not intended to be human‐readable. While it is often numeric, it should always serialize as a String. Your observation 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. is aligned with the specification about result coercion: GraphQL is agnostic to ID format, and serializes to string to ensure consistency across many formats ID could represent and input coercion: When expected as an input type, any string (such as "4") or integer (such as 4) input value should be coerced to ID as appropriate for the ID formats a given GraphQL server expects How should I be handling this value in the client? When working with ID results, treat them as strings. When using ID inputs (in GraphQL variables or input parameters for mutations or queries), you can either use integers or strings. Should I always convert it to an integer as soon as I get it from GraphQL? That's highly depending on your application. There is no general rule that dictates a clear "yes" or "no" here. Should I modify my sequelize code to store the ID value as a string? No, that's not required. The GraphQL specification about the ID type does not cover how you store the ids, only how a GraphQL server is expected to treat ID input and output. It's up to the GraphQL layer to ensure this behaviour. How ids are handled in the actual storage is up to the storage layer. Is there a correct way to proceed when using GraphQL IDs like this? I hope the above answers also answer this question :)
Apollo
47,874,344
32
I 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): export default compose( graphql(firstQuery, { name: 'firstQuery' }), graphql(secondQuery, { name: 'secondQuery' , options: (ownProps) => ({ variables: { var1: *getValueFromFirstQuery* } }) }) )(withRouter(TestPage)) I 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.
The props added by your firstQuery component will be available to the component below (inside) it, so you can do something like: export default compose( graphql(firstQuery, { name: 'firstQuery' }), graphql(secondQuery, { name: 'secondQuery', skip: ({ firstQuery }) => !firstQuery.data, options: ({firstQuery}) => ({ variables: { var1: firstQuery.data.someQuery.someValue } }) }) )(withRouter(TestPage)) Notice that we use skip to skip the second query unless we actually have data from the first query to work with. Using the Query Component If you're using the Query component, you can also utilize the skip property, although you also have the option to return something else (like null or a loading indicator) inside the first render props function: <Query query={firstQuery}> {({ data: { someQuery: { someValue } = {} } = {} }) => ( <Query query={secondQuery} variables={{var1: someValue}} skip={someValue === undefined} > {({ data: secondQueryData }) => ( // your component here )} </Query> Using the useQuery Hook You can also use skip with the useQuery hook: const { data: { someQuery: { someValue } = {} } = {} } = useQuery(firstQuery) const variables = { var1: someValue } const skip = someValue === undefined const { data: secondQueryData } = useQuery(secondQuery, { variables, skip }) Mutations Unlike queries, mutations involve specifically calling a function in order to trigger the request. This function returns a Promise that will resolve with the results of the mutation. That means, when working with mutations, you can simply chain the resulting Promises: const [doA] = useMutation(MUTATION_A) const [doB] = useMutation(MUTATION_B) // elsewhere const { data: { someValue } } = await doA() const { data: { someResult } } = await doB({ variables: { someValue } })
Apollo
49,317,582
31
I want to define a mutation using graphql. My mutation is getting an object as argument. So I defined the new Object in the schema and in the resolver using GraphQLObjectType. However I m getting this error : Error: Agreement.name defined in resolvers, but not in schema Any idea ? Here is my Schema definition const typeDefs = ` type Agreement { id: Int } type Mutation { agreementsPost(agreement: Agreement) : String } `; And Here is my resolver : const appResolvers = { Agreement: new GraphQLObjectType({ name: 'Agreement', fields: { id: { type: GraphQLInt }, } }), Mutation: { agreementsPost(root, args) { return axios.post("....").then(res => res.data); }, }
Couple of things to fix here. First, to use an object as an argument, you have to define it as an input (or GraphQLInputObjectType) in your schema -- you cannot use a regular type (or GraphQLObjectType) as an argument. So your type definitions need to look something like this: type Mutation { agreementsPost(agreement: Agreement): String } input Agreement { id: Int } If you already have an Agreement type, you'll need to name your input something else. It's a good convention to just append Input to whatever your type name is: type Mutation { agreementsPost(agreement: AgreementInput): String } type Agreement { id: Int } input AgreementInput { id: Int } This should be sufficient to allow you to pass in an AgreementInput object as an argument to your mutation. You don't need to add Agreement or AgreementInput to your resolvers (in fact, inputs are not "resolved" by GraphQL, so adding a resolver for an input is not possible). That said, your resolvers object should not need to incorporate any of the type constructors provided by the graphql package -- Apollo constructs a GraphQLSchema object from your resolvers and type definitions for you when you call makeExecutableSchema. If your type definitions include the types Foo and Bar, your resolvers object might look something like this: const resolvers = { Foo: { someFooProperty: (foo, args, context, info) => {} }, Bar: { someBarProperty: (bar, args, context, info) => {} someOtherBarProperty: (bar, args, context, info) => {} }, Query: { someQuery: (root, args, context, info) => {} }, Mutation: { someMutation: (root, args, context, info) => {} }, } Notice how each property in the resolvers object matches one of the types defined in your schema (including Query and Mutation). The value of each of those properties is itself an object, with each property mapping to one of the fields defined for that particular type. Each field's value is your resolve function. The reason for the error you're seeing is that you've effectively told makeExecutableSchema to add resolvers to two fields on the Agreement type -- name and fields -- neither of which are actually in your schema according to your type definitions. You can read more about how to generate a schema using Apollo here. You may see examples out there of generating a schema "programatically" using just GraphQL.js by defining a GraphQLSchema object and passing that to your middleware instead. There's pros and cons to both approaches, but using makeExecutableSchema is generally easier and less error-prone. Either way, it's good to know how to generate a schema programatically, but you should not mix the two!
Apollo
49,990,427
31
Just a basic apollo query request this.client.query({ query: gql` { User(okta: $okta){ id } }` }).then(result => { this.setState({userid: result.data.User}); console.log(this.state.userid.id) }).catch(error => { this.setState({error: <Alert color="danger">Error</Alert>}); }); The question is, how/where to set the $okta variable. Didn't find a solution on Stackoverflow or Google - would be great if someone could help me:)
It should be something like this: const query = gql` query User($okta: String) { User(okta: $okta){ id } } `; client.query({ query: query, variables: { okta: 'some string' } }) The documentation for Apollo client with all the details can be found here: https://www.apollographql.com/docs/react/api/apollo-client.html#ApolloClient.query
Apollo
51,522,902
30
I am working in Apollo, GraphQL and Nuxtjs project, when setting up Apollo configuration I got this Warning: link.js:38 Error: You are calling concat on a terminating link, which will have no effect at new LinkError (linkUtils.js:41) at concat (link.js:38) at ApolloLink.webpackJsonp../node_modules/apollo-link/lib/link.js.ApolloLink.concat (link.js:65) at link.js:13 at Array.reduce (<anonymous>) at from (link.js:13) at createApolloClient (index.js:58) at webpackJsonp../.nuxt/apollo-module.js.__webpack_exports__.a (apollo-module.js:66) at _callee2$ (index.js:140) at tryCatch (runtime.js:62) Here is my code: import { InMemoryCache } from 'apollo-cache-inmemory'; import { createHttpLink } from 'apollo-link-http'; import { ApolloLink } from 'apollo-link'; export default ({ store, env }) => { const httpLink = new createHttpLink({ uri: env.GRAPH_BASE_URL }); // middleware const middlewareLink = new ApolloLink((operation, forward) => { const token = store.getters['user/GET_TOKEN']; if (token) { operation.setContext({ headers: { authorization: `Bearer ${token}` } }); } return forward(operation); }); const link = middlewareLink.concat(httpLink); return { link, cache: new InMemoryCache() } }; I Searched on Google for any similar issue, I found this one https://github.com/Akryum/vue-cli-plugin-apollo/issues/47 but it did not help me. I tried to change: const link = middlewareLink.concat(httpLink); to: const link = Apollo.from([middlewareLink, httpLink]); but it still gives me the same warning, any help please
The solution for me is putting Http Link at the end of the Apollo Link array (used when you're creating the Apollo Client). ... const param = { link: ApolloLink.from([ onError(...) =>..., authLink..., new HttpLink({ uri: '/graphql', credentials: 'same-origin' }) ]), cache: ..., connectToDevTools: ... } new ApolloClient(param); I'm using these libraries: apollo-client apollo-cache-inmemory apollo-link apollo-link-http apollo-link-context apollo-link-error
Apollo
51,840,201
30
graphql schema like this: type User { id: ID! location: Location } type Location { id: ID! user: User } Now, the client sends a graphql query. Theoretically, the User and Location can circular reference each other infinitely. I 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. This 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. So, 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. Maybe do not allow circular reference is a better idea? I prefer to sending another query and doing multiple operations in one query. It's much more simple. Update I 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.
It depends. It's useful to remember that the same solution can be a good pattern in some contexts and an antipattern in others. The value of a solution depends on the context that you use it. — Martin Fowler It's a valid point that circular references can introduce additional challenges. As you point out, they are a potential security risk in that they enable a malicious user to craft potentially very expensive queries. In my experience, they also make it easier for client teams to inadvertently overfetch data. On the other hand, circular references allow an added level of flexibility. Running with your example, if we assume the following schema: type Query { user(id: ID): User location(id: ID): Location } type User { id: ID! location: Location } type Location { id: ID! user: User } it's clear we could potentially make two different queries to fetch effectively the same data: { # query 1 user(id: ID) { id location { id } } # query 2 location(id: ID) { id user { id } } } If the primary consumers of your API are one or more client teams working on the same project, this might not matter much. Your front end needs the data it fetches to be of a particular shape and you can design your schema around those needs. If the client always fetches the user, can get the location that way and doesn't need location information outside that context, it might make sense to only have a user query and omit the user field from the Location type. Even if you need a location query, it might still not make sense to expose a user field on it, depending on your client's needs. On the flip side, imagine your API is consumed by a larger number of clients. Maybe you support multiple platforms, or multiple apps that do different things but share the same API for accessing your data layer. Or maybe you're exposing a public API designed to let third-party apps integrate with your service or product. In these scenarios, your idea of what a client needs is much blurrier. Suddenly, it's more important to expose a wide variety of ways to query the underlying data to satisfy the needs of both current clients and future ones. The same could be said for an API for a single client whose needs are likely to evolve over time. It's always possible to "flatten" your schema as you suggest and provide additional queries as opposed to implementing relational fields. However, whether doing so is "simpler" for the client depends on the client. The best approach may be to enable each client to choose the data structure that fits their needs. As with most architectural decisions, there's a trade-off and the right solution for you may not be the same as for another team. If you do have circular references, all hope is not lost. Some implementations have built-in controls for limiting query depth. GraphQL.js does not, but there's libraries out there like graphql-depth-limit that do just that. It'd be worthwhile to point out that breadth can be just as large a problem as depth -- regardless of whether you have circular references, you should look into implementing pagination with a max limit when resolving Lists as well to prevent clients from potentially requesting thousands of records at a time. As @DavidMaze points out, in addition to limiting the depth of client queries, you can also use dataloader to mitigate the cost of repeatedly fetching the same record from your data layer. While dataloader is typically used to batch requests to get around the "n+1 problem" that arises from lazily loading associations, it can also help here. In addition to batching, dataloader also caches the loaded records. That means subsequent loads for the same record (inside the same request) don't hit the db but are fetched from memory instead.
Apollo
53,863,934
28
I'm having a trouble with Graphql and Apollo Client. I always created different responses like 401 code when using REST but here I don't know how to do a similar behavior. When I get the response, I want it to go to the catch function. An example of my front-end code: client.query({ query: gql` query TodoApp { todos { id text completed } } `, }) .then(data => console.log(data)) .catch(error => console.error(error)); Can anybody help me?
The way to return errors in GraphQL (at least in graphql-js) is to throw errors inside the resolve functions. Because HTTP status codes are specific to the HTTP transport and GraphQL doesn't care about the transport, there's no way for you to set the status code there. What you can do instead is throw a specific error inside your resolve function: age: (person, args) => { try { return fetchAge(person.id); } catch (e) { throw new Error("Could not connect to age service"); } } GraphQL errors get sent to the client in the response like so: { "data": { "name": "John", "age": null }, "errors": [ { "message": "Could not connect to age service" } ] } If the message is not enough information, you could create a special error class for your GraphQL server which includes a status code. To make sure that status code gets included in your response, you'll have to specify the formatError function when creating the middleware: app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: myGraphQLSchema, formatError: (err) => ({ message: err.message, status: err.status }), }));
Apollo
42,937,502
27
Currently I have a useLazyQuery hook which is fired on a button press (part of a search form). The 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). So 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. Not 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? This 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. const AddCardSidebar = props => { const [searching, toggleSearching] = useState(false); const [searchParams, setSearchParams] = useState({ name: '' }); const [searchResults, setSearchResults] = useState([]); const [selectedCard, setSelectedCard] = useState(); const [searchCardsQuery, searchCardsQueryResponse] = useLazyQuery(SEARCH_CARDS, { variables: { searchParams }, onCompleted() { setSearchResults(searchCardsQueryResponse.data.searchCards.cards); } }); ... return ( <div> <h1>AddCardSidebar</h1> <div> {searchResults.length !== 0 && searchResults.map(result => { return ( <img key={result.scryfall_id} src={result.image_uris.small} alt={result.name} onClick={() => setSelectedCard(result.scryfall_id)} /> ); })} </div> <form> ... <button type='button' onClick={() => searchCardsQuery()}> Search </button> </form> ... </div> ); };
You 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. With the above example, the solution would be: function DelayedQuery() { const [dog, setDog] = useState(null); const [getDogPhoto] = useLazyQuery(GET_DOG_PHOTO, { onCompleted: data => setDog(data.dog) }) return ( <div> {dog && <img src={dog.displayImage} />} <button onClick={() => getDogPhoto({ variables: { breed: 'bulldog' }})} > Click me! </button> </div> ); }
Apollo
57,499,553
27
I 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). When defining a GraphQL mutation I have to define the mutation return type. What should be the mutation return type? input QueueInput { "The queue uuid" uuid: String! } deleteQueue(input: QueueInput!): ???????? I 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.
A field in GraphQL must always have a type. GraphQL has the concept of null but null is not itself a type -- it simply represents the lack of value. There is no "void" type in GraphQL. However, types are nullable by default, so regardless of a field's type, your resolver can return nothing and the field will simply resolve to null. So you can just do type Mutation { deleteQueue(input: QueueInput!): Boolean #or any other type } Or if you want a scalar that specifically represents null, you can create your own. const { GraphQLScalarType } = require('graphql') const Void = new GraphQLScalarType({ description: 'Void custom scalar', name: 'Void', parseLiteral: (ast) => null, parseValue: (value) => null, serialize: (value) => null, }) and then do type Mutation { deleteQueue(input: QueueInput!): Void } That said, it's common practice to return something. For deletions, it's common to return either the deleted item or at least its ID. This helps with cache-management on the client side. It's also becoming more common to return some kind of mutation payload type to better encapsulate client errors. There's any number of fields you could include on a "payload" type like this: type Mutation { deleteQueue(input: QueueInput!): DeleteQueuePayload } type DeleteQueuePayload { # the id of the deleted queue queueId: ID # the queue itself queue: Queue # a status string status: String # or a status code status: Int # or even an enum status: Status # or just include the client error # with an appropriate code, internationalized message, etc. error: ClientError # or an array of errors, if you want to support validation, for example errors: [ClientError!]! } DeleteQueuePayload could even be a union of different types, enabling the client to use the __typename to determine the result of the mutation. What information you expose, however, depend on your specific needs, and what specific pattern you employ is boils down to opinion. See here and here for additional discussion and examples.
Apollo
58,889,341
24
I was thinking about ways of implementing graphql response that would contain both an error and data. Is it possible to do so without creating a type that would contain error? e.g. Mutation addMembersToTeam(membersIds: [ID!]! teamId: ID!): [Member] adds members to some team. Suppose this mutation is called with the following membersIds: [1, 2, 3]. Members with ids 1 and 2 are already in the team, so an error must be thrown that these members cannot be added, but member with an id 3 should be added as he is not in the team. I was thinking about using formatResponse but seems that I can't get an error there. Is it possible to solve this problem without adding error field to the return type?
Is it possible to solve this problem without adding error field to the return type? Unfortunately, no. A resolver can either return data, or return null and throw an error. It cannot do both. To clarify, it is possible to get a partial response and some errors. A simple example: const typeDefs = ` type Query { foo: Foo } type Foo { a: String b: String } ` const resolvers = { Query: { foo: () => {}, } Foo: { a: () => 'A', b: () => new Error('Oops!'), } } In this example, querying both fields on foo will result in the following response: { "data": { "foo": { "a": "A", "b": null } }, "errors": [ { "message": "Oops", "locations": [ { "line": 6, "column": 5 } ], "path": [ "foo", "b" ] } ] } In this way, it's possible to send back both data and errors. But you cannot do so for the same field, like in your question. There's a couple of ways around this. As you point out, you could return the errors as part of the response, which is usually how this is done. You could then use formatResponse, walk the resulting data, extract any errors and combine them with them with any other GraphQL errors. Not optimal, but it may get you the behavior you're looking for. Another alternative is to modify the mutation so it takes a single memberId. You can then request a separate mutation for each id you're adding: add1: addMemberToTeam(memberId: $memberId1 teamId: $teamId): { id } add2: addMemberToTeam(memberId: $memberId2 teamId: $teamId): { id } add3: addMemberToTeam(memberId: $memberId3 teamId: $teamId): { id } This can be trickier to handle client-side, and is of course less efficient, but again might get you the expected behavior.
Apollo
52,778,096
22
this is my first discussion post here. I have learned Apollo + GraphQL through Odyssey. Currently, I am building my own project using Next.js which required fetching data from 2 GraphQL endpoints. My problem: How can I fetch data from multiple GraphQL endpoints with ApolloClient? Below is my code for my first endpoint: 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;
What you are trying to accomplish is kinda against Apollo's "One Graph" approach. Take a look at gateways and federation - https://www.apollographql.com/docs/federation/ With that being said, some hacky solution is possible but you will need to maintain a more complex structure and specify the endpoint in every query, which undermines the built-in mechanism and might cause optimization issues. //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'}}) This package seems to do what you want: https://github.com/habx/apollo-multi-endpoint-link Also, check the discussion here: https://github.com/apollographql/apollo-client/issues/84
Apollo
69,629,051
22
I am working on a react app with react-apollo calling data through graphql when I check in browser network tab response it shows all elements of the array different but what I get or console.log() in my app then all elements of array same as the first element. I don't know how to fix please help
The reason this happens is because the items in your array get "normalized" to the same values in the Apollo cache. AKA, they look the same to Apollo. This usually happens because they share the same Symbol(id). If you print out your Apollo response object, you'll notice that each of the objects have Symbol(id) which is used by Apollo cache. Your array items probably have the same Symbol(id) which causes them to repeat. Why does this happen? By default, Apollo cache runs this function for normalization. export function defaultDataIdFromObject(result: any): string | null { if (result.__typename) { if (result.id !== undefined) { return `${result.__typename}:${result.id}`; } if (result._id !== undefined) { return `${result.__typename}:${result._id}`; } } return null; } Your array item properties cause multiple items to return the same data id. In my case, multiple items had _id = null which caused all of these items to be repeated. When this function returns null the docs say InMemoryCache will fall back to the path to the object in the query, such as ROOT_QUERY.allPeople.0 for the first record returned on the allPeople root query. This is the behavior we actually want when our array items don't work well with defaultDataIdFromObject. Therefore the solution is to manually configure these unique identifiers with the dataIdFromObject option passed to the InMemoryCache constructor within your ApolloClient. The following worked for me as all my objects use _id and had __typename. const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache({ dataIdFromObject: o => (o._id ? `${o.__typename}:${o._id}`: null), }) });
Apollo
48,840,223
21
Im trying to figure out how to use apollo-link-http with apollo-upload-client. Both 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 => const uploadLink = createUploadLink({ uri: process.env.REACT_APP_GRAPHQL_URL }); const httpLink = new HttpLink({ uri: process.env.REACT_APP_GRAPHQL_URL }); const client = new ApolloClient({ link: ApolloLink.from([ authLink, logoutLink, stateLink, uploadLink, httpLink ]), cache, }); Any help? I have not much experience with Apollo/Graphql, but I would like to use the file upload component.
You do not need the http link if you use apollo-upload-client with version higher than 6. You can try like this: const uploadLink = createUploadLink({ uri: process.env.REACT_APP_GRAPHQL_URL }); const client = new ApolloClient({ link: ApolloLink.from([ authLink, logoutLink, stateLink, uploadLink ]), cache, });
Apollo
49,507,035
21
I'm trying to reset the store after logout in my react-apollo application. So I've created a method called "logout" which is called when I click on a button (and passed by the 'onDisconnect' props). To do that I've tried to follow this example : https://www.apollographql.com/docs/react/recipes/authentication.html But in my case I want LayoutComponent as HOC (and it's without graphQL Query). Here is my component : import React, {Component} from 'react'; import { withApollo, graphql } from 'react-apollo'; import { ApolloClient } from 'apollo-client'; import AppBar from 'material-ui/AppBar'; import Sidebar from 'Sidebar/Sidebar'; import RightMenu from 'RightMenu/RightMenu'; class Layout extends Component { constructor(props) { super(props); } logout = () => { client.resetStore(); alert("YOUHOU"); } render() { return ( <div> <AppBar title="myApp" iconElementRight={<RightMenu onDisconnect={ this.logout() } />} /> </div> ); } } export default withApollo(Layout); The issue here is that 'client' is not defined and I can't logout properly. Do you have any idea to help me to handle this situation or an example/best practices to logout from apollo client ? Thanks by advance
If you need to clear your cache and don't want to fetch all active queries you can use: client.cache.reset() client being your Apollo client. Keep in mind that this will NOT trigger the onResetStore event.
Apollo
48,887,480
20
I am using apollo-server and apollo-graphql-tools and I have following schema type TotalVehicleResponse { totalCars: Int totalTrucks: Int } type RootQuery { getTotalVehicals(color: String): TotalVehicleResponse } schema { query: RootQuery } and Resolver functions are like this { RootQuery: { getTotalVehicals: async (root, args, context) => { // args = {color: 'something'} return {}; }, TotalVehicleResponse: { totalCars: async (root, args, conext) => { // args is empty({}) here ......... ......... }, totalTrucks: async (root, args, conext) => { // args is empty({}) here ......... ......... } } } } My question is that how can I access args which is available in root resolver(getTotalVehicals) in any of the child resolvers?
args refer strictly to the arguments provided in the query to that field. If you want values to be made available to child resolvers, you can simply return them from the parent resolver, however, this isn't a good solution since it introduces coupling between types. const resolvers = { RootQuery: { getTotalVehicles: async (root, args, context) => { return { color: args.color }; }, }, TotalVehicleResponse: { totalCars: async (root, args, context) => { // root contains color here const color = root.color; // Logic to get totalCars based on color const totalCars = await getTotalCarsByColor(color); return totalCars; }, totalTrucks: async (root, args, context) => { // root contains color here const color = root.color; // Logic to get totalTrucks based on color const totalTrucks = await getTotalTrucksByColor(color); return totalTrucks; } } } Update 06/2024 In hindsight, I would have answered this question differently. GraphQL offers endless flexibility with very few guardrails and it is very easy to design schema and resolver patterns that are tightly coupled. The question asked here is a symptom of a design that does exactly that. At the time when this question was asked and answered, the trend for typed schemas was still in its infancy, but nowadays, with fully typed schemas, it is easier to fall into good patterns. 1. Add arguments to the fields The simplest solution is to add the arguments to the fields that require them, thereby providing access to the args in the associated resolver. Adding this to the schema in question would look like the following: type TotalVehicleResponse { totalCars(color: String): Int totalCars(color: String): Int totalTrucks(color: String): Int } type Query { getTotalVehicles(color: String): TotalVehicleResponse } When multiple fields require the same argument, you may find the query becomes verbose and repetitive. This is managed using query variables. The query might look as follows: query($color: String) { getTotalVehicles(color: $color) { totalCars(color: $color) totalTrucks(color: $color) } } This approach is preferable to my original answer since it removes the tight coupling between schema types and resolvers, but it doesn't make for a pleasant consumable API. 2. Schema Design Principles The real issue here is one of schema design. Good schema design eliminates tight coupling between types and enables reuse across the schema. Type Resolvers and Field Resolvers I tend to think of resolvers in two classes: Type Resolvers: Fields that return an object type. Field Resolvers: Fields that return scalar values (e.g., String, Int). Consider the following schema: type Query { car(id: ID!): Car! # Type resolver carsByColor(color: String!): [Car!] # Type resolver with argument brands: [Brand!] # Type resolver } type Car { id: ID! brand: Brand! # Type resolver model: String color: String } type Brand { id: ID! name: String cars(color: String): [Car!] # Type resolver with argument } Example Query Using the above schema, here’s an example query to get cars by a specific color and the brand of each car: query($color: String!) { # Type resolver with argument carsByColor(color: $color) { id model color brand { id name # Type resolver with argument cars(color: $color) { id model color } } } } Resolver Implementation The goal is to have consistency across the schema for a given type. Wherever a type is resolved, we should return a known type. For example, a car object should always return an identifier or typed parent object. This provides us with guarantees that wherever a car is presented as a parent, it is of a known type, and therefore has expected properties, e.g., ID which can be used to compute other fields, or fetch related entities. The effect is that it enables simple and reusable data fetching patterns to fulfil types as they are requested. const resolvers = { Query: { car: async (_, args) => { const car = await getCar(args.id); return car; }, carsByColor: async (_, args) => { const cars = await getCarsByColor(args.color); return cars; }, brands: async () => { const brands = await getAllBrands(); return brands; } }, Car: { brand: async (parent) => { const brand = await getBrand(parent.brandId); return brand; } }, Brand: { cars: async (parent, args) => { const cars = await getCarsByBrandAndColor(parent.id, args.color); return cars; } } }; Notice that only the type resolvers have been implemented in this example. Field resolvers are gnerally only necessary when their results are either computed or fetched from a different source. In most cases, simply relating the types and resolver type resolvers will achieve the desired result.
Apollo
48,382,897
19
I am using <Mutation /> component which has Render Prop API & trying to do Optimistic Response in the UI. So far I have this chunk in an _onSubmit function - createApp({ variables: { id: uuid(), name, link }, optimisticResponse: { __typename: "Mutation", createApp: { __typename: "App", id: negativeRandom(), name, link } } }); And my <Mutation /> component looks like - <Mutation mutation={CREATE_APP} update={(cache, { data: { createApp } }) => { const data = cache.readQuery({ query: LIST_APPS }); if (typeof createApp.id == "number") { data.listApps.items.push(createApp); cache.writeQuery({ query: LIST_APPS, data }); } }} > {/* some code here */} </Mutation> I know that update function in <Mutation /> runs twice, once when optimisticResponse is ran & second time when server response comes back. On the first time, I give them id as a number. Checkout createApp in optimisticResponse where id: negativeRandom() That's why my update prop in <Mutation /> 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. But 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. I think there might 3 problems - Either the update function does not run when local state is pushed I've tried making fetchPolicy equal to cache-and-network & cache-first but it didn't work too. The __typename in optimisticResponse. Idk if Mutation is the correct value, so I tried AppConnection too but it still does not work. The 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 - Note: Same thing works with React. Here's a link to React Repo - https://github.com/deadcoder0904/react-darkmodelist
Apparently this was a bug in Apollo or React Apollo package. Don't know which bug or was it just for React Native but I just updated my dependencies & solved it without changing any code You can check out the full code at https://github.com/deadcoder0904/react-native-darkmode-list
Apollo
50,603,994
19
Hy 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. I am adding the header as, let apolloAuth: ApolloClient = { let configuration = URLSessionConfiguration.default // Add additional headers as needed configuration.httpAdditionalHeaders = ["Authorization" : self.singleTonInstance.token] configuration.httpAdditionalHeaders = ["channel" : "mobile"] let url = URL(string: "http://xxx/graphql")! return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration)) }() Anyone please help me to find out how to add headers with Apollo GraphQL.
UPDATE: Solution for "Apollo Client v0.41.0" and "Swift 5" I 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 import Foundation import Apollo class Network { static let shared = Network() private(set) lazy var apollo: ApolloClient = { let cache = InMemoryNormalizedCache() let store1 = ApolloStore(cache: cache) let authPayloads = ["Authorization": "Bearer <<TOKEN>>"] let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = authPayloads let client1 = URLSessionClient(sessionConfiguration: configuration, callbackQueue: nil) let provider = NetworkInterceptorProvider(client: client1, shouldInvalidateClientOnDeinit: true, store: store1) let url = URL(string: "https://<HOST NAME>/graphql")! let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: url) return ApolloClient(networkTransport: requestChainTransport, store: store1) }() } class NetworkInterceptorProvider: DefaultInterceptorProvider { override func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] { var interceptors = super.interceptors(for: operation) interceptors.insert(CustomInterceptor(), at: 0) return interceptors } } class CustomInterceptor: ApolloInterceptor { func interceptAsync<Operation: GraphQLOperation>( chain: RequestChain, request: HTTPRequest<Operation>, response: HTTPResponse<Operation>?, completion: @escaping (Swift.Result<GraphQLResult<Operation.Data>, Error>) -> Void) { request.addHeader(name: "Authorization", value: "Bearer <<TOKEN>>") print("request :\(request)") print("response :\(String(describing: response))") chain.proceedAsync(request: request, response: response, completion: completion) } }
Apollo
55,395,589
19
I have made a bunch of React component calling GraphQL using the Query component and everything is working fine. In one component I need to have some initial data from the database, but without any visual representation. I 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. How do I go about getting this data from the database without a component? I can't find any documentation on how to solve this problem. But I can't be the only one doing this. Is ApolloConsumer or ApolloProvider the answer to my problems? I'm working with conferences and sessions. A conference runs over a couple of days and each day has a number of sessions. What 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. My sessions page: import React from 'react'; import FullWidthTabs from '../components/Sessions'; import SessionTab from '../components/SessionTab'; import BwAppBar2 from '../components/BwAppBar2'; import ConferenceDays from '../components/ConferenceDays'; class SessionsPage extends React.Component { static async getInitialProps() { console.log("GetInitProps SessionsPage"); } render() { let a = ConferenceDays(); return ( <div> <BwAppBar2 /> {a} <FullWidthTabs days={['2018-06-11', '2018-06-12', '2018-06-13']} day1={ < SessionTab conferenceId = "57" day = '2018-06-11' / > } day2={ < SessionTab conferenceId = "57" day = '2018-06-12' / > } day3={ < SessionTab conferenceId = "57" day = '2018-06-13' / > }> </FullWidthTabs> </div> ); } } export default (SessionsPage); Here the dates have been hardcoded in the page just for testing. But 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: import React, { Component } from 'react' import { graphql } from 'react-apollo' import { Query } from 'react-apollo' import gql from 'graphql-tag' import Link from '@material-ui/core/Link'; import { useQuery } from "react-apollo-hooks"; import conferencesQuery from '../queries/conferences' import { Table, Head, Cell } from './Table' import ConferenceCard from './ConferenceCard'; import Grid from '@material-ui/core/Grid'; import Paper from '@material-ui/core/Paper'; import moment from 'moment'; const CONFERENCE_QUERY = gql` query conference($conferenceId : ID!){ conference(id: $conferenceId){ title start_date end_date } } ` let index = 0; let loopDate = 0; let dates = []; let conferenceId = 57; const ConferenceDays = () => ( <Query query={CONFERENCE_QUERY} variables={{conferenceId}}> {({ loading, error, data }) => { if (loading) return <div>Fetching</div> if (error) return <div>Error</div> const startDate = moment(data.conference.start_date, 'x'); const endDate = moment(data.conference.end_date, 'x'); for (loopDate = parseInt(data.conference.start_date); loopDate < parseInt(data.conference.end_date); loopDate += 86400000) { let aDate = moment(loopDate, 'x'); dates.push(aDate.format('YYYY-MM-DD').toString()); } console.log(dates); return(dates); }} </Query>); export default ConferenceDays But is this approach incorrect? Would it be more correct to lift the ConferenceDates component up in the hierarchy? Kim
You could separate the creation of the ApolloClient to a separate file and use an init function to access the client outside of React components. import React from 'react'; import { ApolloClient, HttpLink, InMemoryCache, } from "@apollo/client"; let apolloClient; const httpLink = new HttpLink({ uri: "http://localhost:4000/graphql", credentials: "same-origin", }); function createApolloClient() { return new ApolloClient({ link: httpLink, cache: new InMemoryCache(), }); } export function initializeApollo() { const _apolloClient = apolloClient ?? createApolloClient(); if (!apolloClient) apolloClient = _apolloClient; return _apolloClient; } export function useApollo() { const store = useMemo(() => initializeApollo(initialState), [initialState]); return store; } Then you would use this outside components like this: const client = initializeApollo() const res = await client.query({ query: MY_QUERY, variables: {}, }) I didn't try this myself, but I think this you an idea on how to go about this and how to access the ApolloClient.
Apollo
56,340,948
18
I have been reviewing the Apollo documentation but I do not see information of how to go about handling server errors in the Apollo client. For example, suppose that the server either: Times out Becomes unreachable Unexpectedly fails How should this be handled in the client? Apollo currently fails with errors such as: Unhandled (in react-apollo) Error: GraphQL error: Cannot ... I'd like to avoid this happening and handling these errors. How can I do so using React Apollo? For reference: I am currently using React-Apollo and Redux.
Errors are passed along in the error field on your component props: http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error function MyComponent({ data }) { if (data.error) { return <div>Error!</div>; } else { // ... } } export default graphql(gql`query { ... }`)(MyComponent); That message is printed if we detect that there was an error and the error field was not accessed in the component. You could write a higher-order component to handle errors in a generic way, so that you can wrap all of your components with that.
Apollo
43,646,789
17
I 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. I 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? Thanks.
GraphQL mutations are simply HTTP POST requests to a GraphQL endpoint. You can easily send one using any HTTP library such as request or axios. For example, this mutation, mutation ($id: Int!) { upvotePost(postId: $id) { id } } and query variable, $id = 1 is an HTTP POST request with a JSON payload of { "query": "mutation ($id: Int!) { upvotePost(postId: $id) { id } } ", "variables": { "id": 1 } } Take note that query is your GraphQL query as a string. Using axios as an example, you can send this to your server using something like this, axios({ method: 'post', url: '/graphql', // payload is the payload above data: payload, });
Apollo
45,920,986
17
We are currently moving from Relay to React Apollo 2.1 and something I'm doing seems fishy. Context: Some components must only be rendered if the user is authenticated (via an API key), so there is an Authenticator component guarding the rest of the tree. In App.js, it gets used like this (obviously all snippets below are minimal examples): import React from 'react'; import Authenticator from './Authenticator'; import MyComponent from './MyComponent'; export default function App({ apiKey }) { return ( <Authenticator apiKey={apiKey} render={({ error, token }) => { if (error) return <div>{error.message}</div>; if (token) return <MyComponent token={token} />; return <div>Authenticating...</div>; }} /> ); } If authentication succeeds, MyComponent gets rendered. Authentication sends the authentication mutation to the server when rendered/mounted for the first time and calls the render prop accordingly. Authentication.js looks as such: import gql from 'graphql-tag'; import React from 'react'; import { Mutation } from 'react-apollo'; const AUTH_MUTATION = gql`mutation Login($apiKey: String!) { login(apiKey: $apiKey) { token } }`; export default function Authenticator({ apiKey, render }) { return ( <Mutation mutation={AUTH_MUTATION} variables={{ apiKey }}> {(login, { data, error, called }) => { if (!called) login(); // ⚠️ This seems sketchy ⚠️ const token = (data && data.login.token) || undefined; return render({ error, token }); }} </Mutation> ); } That if (!called) login(); is what is giving me pause. If I don't specify if (!called), the UI becomes epileptic and sends thousands of requests (which makes sense, calling login() causes render() to re-run), but is that how it's supposed to be used? It seems like the Query component equivalent differs in that simply rendering it emits the request. and I am wondering if there is a way to apply the same mechanism to Mutation, which requires calling the mutate function as part of the render prop. The Relay equivalent of the snippet above does exactly what React Apollo's Query does on Mutation: // Authentication.js import React from 'react'; import { graphql, QueryRenderer } from 'react-relay'; import { Environment } from 'relay-runtime'; // Hiding out all the `Environment`-related boilerplate const environment = return new Environment(/* ... */); const AUTH_MUTATION = graphql`mutation Login($apiKey: String!) { login(apiKey: $apiKey) { token } }`; export default function Authenticator({ apiKey, render }) { return ( <QueryRenderer query={AUTH_MUTATION} variables={{ apiKey }} render={render} /> ); } // App.js import React from 'react'; import Authenticator from './Authenticator'; import MyComponent from './MyComponent'; export default function App({ apiKey }) { return ( <Authenticator apiKey={apiKey} render={({ error, props }) => { if (error) return <div>{error.message}</div>; if (props) return <MyComponent token={props.loginAPI.token)} />; return <div>Authenticating...</div>; }} /> ); }
Right or wrong, Apollo makes some assumptions about how queries and mutations are used. By convention queries only fetch data while mutations, well, mutate data. Apollo takes that paradigm one step further and assumes that mutations will happen in response to some sort of action. So, like you observed, Query fetches the query on mount, while Mutation passes down a function to actually fetch the mutation. In that sense, you've already deviated from how these components are "supposed to be used." I don't think there's anything outright wrong with your approach -- assuming called never gets reset, your component should behave as intended. As an alternative, however, you could create a simple wrapper component to take advantage of componentDidMount: class CallLogin extends React.Component { componentDidMount() { this.props.login() } render() { // React 16 return this.props.children // Old School :) // return <div>{ this.props.children }</div> } } export default function Authenticator({ apiKey, render }) { return ( <Mutation mutation={AUTH_MUTATION} variables={{ apiKey }}> {(login, { data, error }) => { const token = (data && data.login.token) || undefined; return ( <CallLogin login={login}> {render({ error, token })} </CallLogin> ) }} </Mutation> ); }
Apollo
49,456,738
17
I'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. So the question is: are there any best practices on implementing Apollo graphql server with typescript or what should I avoid at least?
I wrote a small library and a CLI for this. It generates TypeScript typings for both server (according to your schema) and client (according to your schema and GraphQL documents). It also generates resolvers signature and very customizable. You can try it here: https://github.com/dotansimha/graphql-code-generator The idea behind it was to allow the developer to get the most out of GraphQL and the generated typings, and making it easier to customize the generated output.
Apollo
50,905,873
17
const httpLink = createHttpLink({ uri: 'http://localhost:3090/' }) const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }) client.query({ query: gql` query users { email } `, }) .then(data => console.log(data)) .catch(error => console.error(error)); This 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
The graphql endpoint you are posting your queries to is missing the /graphql. So your server probably returns an html document containing the 404 error message that starts with < from <html.... Apollo tries to parse that as the query result and fails to do so. Check that httpLink is actually localhost:3090/graphql. Also the syntax of a query is either: { users { email } } or if you want to name the query: query Users { users { email } }
Apollo
53,209,623
17
I have written a GraphQL query which like the one below: { posts { author { comments } comments } } I want to know how can I get the details about the requested child fields inside the posts resolver. I want to do it to avoid nested calls of resolvers. I am using ApolloServer's DataSource API. I can change the API server to get all the data at once. I am using ApolloServer 2.0 and any other ways of avoiding nested calls are also welcome.
You'll need to parse the info object that's passed to the resolver as its fourth parameter. This is the type for the object: type GraphQLResolveInfo = { fieldName: string, fieldNodes: Array<Field>, returnType: GraphQLOutputType, parentType: GraphQLCompositeType, schema: GraphQLSchema, fragments: { [fragmentName: string]: FragmentDefinition }, rootValue: any, operation: OperationDefinition, variableValues: { [variableName: string]: any }, } You could transverse the AST of the field yourself, but you're probably better off using an existing library. I'd recommend graphql-parse-resolve-info. There's a number of other libraries out there, but graphql-parse-resolve-info is a pretty complete solution and is actually used under the hood by postgraphile. Example usage: posts: (parent, args, context, info) => { const parsedResolveInfo = parseResolveInfo(info) console.log(parsedResolveInfo) } This will log an object along these lines: { alias: 'posts', name: 'posts', args: {}, fieldsByTypeName: { Post: { author: { alias: 'author', name: 'author', args: {}, fieldsByTypeName: ... } comments: { alias: 'comments', name: 'comments', args: {}, fieldsByTypeName: ... } } } } You can walk through the resulting object and construct your SQL query (or set of API requests, or whatever) accordingly.
Apollo
54,984,035
17
I'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. const PlayerQuery = gql`query PlayerQuery($trackId: Int!, $duration: Int!, $language: String!) { subtitle(trackId: $trackId, duration: $duration) { id, lines { text time } } translation(trackId: $trackId, language: $language, subtitleId: ???) { lines { translation original } } }`; So in the query above translation needs subtitleId as an argument which is returned by the subtitle query. I'm using Apollo both on the client and on the server.
That's a great question because it illustrates a significant difference between REST/RPC style APIs and GraphQL. In REST style APIs the objects that you return only contain metadata about how to fetch more data, and the API consumer is expected to know how to run the JOINs over those tables. In your example, you have a subtitle and a translation that you need to JOIN using the ID property. In GraphQL, objects rarely exists in isolation and the relationships encoded into the schema itself. You didn't post your schema but from the looks of it, you created a translation object and a subtitle object and exposed them both in your root query. My guess is that it looks something like this: const Translation = new GraphQLObjectType({ name: "Translation", fields: { id: { type: GraphQLInt }, lines: { type: Lines } } }); const SubTitle = new GraphQLObjectType({ name: "SubTitle", fields: { lines: { type: Lines } } }); const RootQuery = new GraphQLObjectType({ name: "RootQuery", fields: { subtitle: { type: SubTitle }, translation: { type: Translation } } }); module.exports = new GraphQLSchema({ query: RootQuery }); What you should do instead, is to make a relationship to translations INSIDE OF subtitle like this. The goal of GraphQL is to first create a graph or relationships in your data, then to figure out how to expose entry points to that data. GraphQL lets you select arbitrary sub-trees in a graph. const Translation = new GraphQLObjectType({ name: "Translation", fields: { id: { type: GraphQLInt }, lines: { type: Lines } } }); const SubTitle = new GraphQLObjectType({ name: "SubTitle", fields: { lines: { type: Lines } translations: { type: Translation, resolve: () => { // Inside this resolver you should have access to the id you need return { /*...*/ } } } } }); const RootQuery = new GraphQLObjectType({ name: "RootQuery", fields: { subtitle: { type: SubTitle } } }); module.exports = new GraphQLSchema({ query: RootQuery }); Note: For clarity, I left out the arguments fields and any additional resolvers. I'm sure your code will be a bit more sophisticated, I just wanted to illustrate the point :).
Apollo
45,242,250
16
I'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. Suppose that I have this schema : interface FoodType { id: String type: String composition: [Ingredient] } type Pizza implements FoodType { id: String type: String pizzaType: String toppings: [String] size: String composition: [Ingredient] } type Salad implements FoodType { id: String type: String vegetarian: Boolean dressing: Boolean composition: [Ingredient] } type BasicFood implements FoodType { id: String type: String composition: [Ingredient] } type Ingredient { name: String qty: Float units: String } Now, I'd like to create new food items, so I started doing something like this : type Mutation { addPizza(input:Pizza):FoodType addSalad(input:Salad):FoodType addBasic(input:BasicFood):FoodType } This did not work for 2 reasons : If I want to pass an object as parameter, this one must be an "input" type. But "Pizza", "Salad" and "BasicFood" are just "type". An input type cannot implement an interface. So, I need to modify my previous schema like this : interface FoodType { id: String type: String composition: [Ingredient] } type Pizza implements FoodType { id: String type: String pizzaType: String toppings: [String] size: String composition: [Ingredient] } type Salad implements FoodType { id: String type: String vegetarian: Boolean dressing: Boolean composition: [Ingredient] } type BasicFood implements FoodType { id: String type: String composition: [Ingredient] } type Ingredient { name: String qty: Float units: String } type Mutation { addPizza(input: PizzaInput): FoodType addSalad(input: SaladInput): FoodType addBasic(input: BasicInput): FoodType } input PizzaInput { type: String pizzaType: String toppings: [String] size: String composition: [IngredientInput] } input SaladInput { type: String vegetarian: Boolean dressing: Boolean composition: [IngredientInput] } input BasicFoodInput { type: String composition: [IngredientInput] } input IngredientInput { name: String qty: Float units: String } So, here I defined my 3 creation methods for Pizza, Salad and Basic food. I need to define 3 input types (one for each food) And I also need to define a new input type for Ingredients. It makes lot of duplication. Are you ok with that? Or there is a better way to deal with this? Thank you
There's a handful of things you could do. For example, if you were to declare your schema programatically, you can get away with something like this: const getPizzaFields = (isInput = false) => { const fields = { type: { type: GraphQLString } pizzaType: { type: GraphQLString } toppings: { type: new GraphQLList(GraphQLString) } size: { type: GraphQLString } composition: { type: isInput ? new GraphQLList(IngredientInput) : new GraphQLList(Ingredient) } } if (!isInput) fields.id = { type: GraphQLString } return fields } const Pizza = new GraphQLObjectType({ name: 'Pizza', fields: () => getFields() }) const PizzaInput = new GraphQLObjectType({ name: 'Pizza', fields: () => getFields(true) }) Or if your objects/inputs follow a similar pattern, you could even write a function for generating inputs from types: const transformObject = (type) => { const input = Object.assign({}, type) input.fields.composition.type = new GraphQLList(IngredientInput) delete input.fields.id return input } Alternatively, when defining your schema using makeExecutableSchema, you could do: const commonPizzaFields = ` type: String pizzaType: String toppings: [String] size: String ` const schema = ` type Pizza { id: String ${commonPizzaFields} composition: [Ingredient] } input PizzaInput { ${commonPizzaFields} composition: [IngredientInput] } ` The problem with all of these approaches is that while they technically may make your code more DRY, they also reduce your schema's readability, which in my opinion makes it even more error-prone than the duplication itself. It's also important to understand that while syntactically, a Type and an Input type may appear the same, functionally they are not. For example, a field on a type may have arguments: type Pizza { toppings(filter: ToppingTypeEnum): [String] } Input Type fields do not have arguments, so you would not be able to utilize the same syntax for a toppings field in both a Pizza Type and its counterpart PizzaInput Input Type. Personally, I would bite the bullet and just write out both the types and the inputs like you've already done. The only thing I would do differently is grouping them together (listing your type than your input), so that any differences between the two are easy to spot. But your mileage may very :)
Apollo
48,277,651
16
In my component, I have this code: componentDidMount () { // Setup subscription listener const { client, match: { params: { groupId } } } = this.props client.subscribe({ query: HOMEWORK_IN_GROUP_SUBSCRIPTION, variables: { groupId }, }).subscribe({ next ({ data }) { const cacheData = client.cache.readQuery({ query: GET_GROUP_QUERY, variables: { groupId }, }) const homeworkAlreadyExists = cacheData.group.homeworks.find( homework => homework._id == data.homeworkInGroup._id ) if (!homeworkAlreadyExists) { client.cache.writeQuery({ query: GET_GROUP_QUERY, variables: { groupId }, data: { ...cacheData, group: { ...cacheData.group, homeworks: [ ...cacheData.group.homeworks, data.homeworkInGroup, ], }, }, }) } }, }) } The problem is that this component will re-subscribe when mounted and will mantain subscribed even if unmounted. How can I unsubscribe my component?
client.subscribe({ ... }).subscribe({ ... }) will return an instance for your subscription, that you can use to unsubscribe. So something like: componentDidMount () { // Setup subscription listener // (...) this.querySubscription = client.subscribe({ // (...) }).subscribe({ // (...) }) } componentWillUnmount () { // Unsibscribe subscription this.querySubscription.unsubscribe(); } You can get some inspiration by looking at how react-apollo manages this situation looking at their code base. NOTE: My best advice would be to use Subscription component, that will manage everything for you.
Apollo
51,477,002
16
I am trying to run a graphql Query but it keeps giving me the "TypeError: String cannot represent value:" error. The schema for my query: type User { active: Boolean! email: String! fullname: String! description: String! tags: [String!]! } type Query { getAllUsers: [User]! } My resolver: Query: { getAllUsers: (_, __, { dataSources }) => { return dataSources.userAPI.getAllUsers(); } } userAPI: getAllUsers() { const params = { TableName: 'Users', Select: 'ALL_ATTRIBUTES' }; return new Promise((resolve, reject) => { dynamodb.scan(params, function(err, data) { if (err) { console.log('Error: ', err); reject(err); } else { console.log('Success'); resolve(data.Items); } }); }); } The query: query getAllUsers{ getAllUsers{ email } } Since my email is a string, the error I'm getting is "String cannot represent value".
What's returned inside your resolver should match the shape specified by your schema. If your User schema is type User { active: Boolean! email: String! fullname: String! description: String! tags: [String!]! } then the array of Users you return should look like this: [{ active: true, email: 'kaisinnn@li.com', fullname: 'Kaisin Li', description: 'Test', tags: ['SOME_TAG'] }] The data you're actually returning is shaped much differently: [{ active: { BOOL: true }, description: { S: 'Test' }, fullname: { S: 'Kaisin Li' }, email: { S: 'kaisinnn@li.com' }, }] You need to either map over the array you're getting from the scan operation and transform the result into the correct shape, or write a resolver for each individual field. For example: const resolvers = { User: { active: (user) => user.active.BOOL, description: (user) => user.description.S, // and so on } }
Apollo
58,636,833
16
As we know a react component is re-rendered when it's props or state changes. Now i'm using useQuery from react-apollo package like below: import { gql, useQuery } from '@apollo/client'; const getBookQuery = gql` { books { name } } `; function BookList() { const { loading, error, data} = useQuery(getBookQuery); if(loading) return <p>Loading....</p> if(error) return <p>Ops! Something went wrong</p> return ( <> <ul> {data.books.map(book => ( <li key={book.name}>{book.name}</li> ))} </ul> </> ) } export default BookList; When i run the code above, we first get Loading... in DOM which is then updated to list containing query data (once it arrives). But how does react know to re-render my component once data is received from query. Are these data, loading and error properties mapped to component props and they are updating? If so, why doesn't chrome dev tools show any props for this BookList component? Can someone explain how is this useQuery custom hook working here?
A good way of figuring out (roughly) what is happening in useQuery is to consider how you'd do it yourself, e.g. const MyComponent = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(async () => { try { setLoading(true); const data = await GraphQL.request(getBookQuery); setData(data); } catch (ex) { setError(ex); } finally { setLoading(false); } }, []); if(loading) return <p>Loading....</p> if(error) return <p>Ops! Something went wrong</p> return ( <> <ul> {data.books.map(book => ( <li key={book.name}>{book.name}</li> ))} </ul> </> ); }; In the above you can see your component has state (not props) data, loading and error which causes your component to re-render. You can then imagine this logic was wrapped in your own useQuery hook: const useQuery = (query, variables) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(async () => { try { setLoading(true); const data = await GraphQL.request(query, variables); setData(data); } catch (ex) { setError(ex); } finally { setLoading(false); } }, []); return { data, loading, error }; } const MyComponent = () => { const { data, loading, error } = useQuery(getBookQuery); if(loading) return <p>Loading....</p> if(error) return <p>Ops! Something went wrong</p> return ( <> <ul> {data.books.map(book => ( <li key={book.name}>{book.name}</li> ))} </ul> </> ); }; So ultimately your component is re-rendering because it does have data, loading and error held in MyComponent state, it's just abstracted away.
Apollo
66,090,104
16
Intended outcome: MockedProvider should mock my createPost mutation. Actual outcome: Error: No more mocked responses for the query: mutation... How to reproduce the issue: I have a very simple repository. I also created a separate branch with example commit which is breaking the apollo mock provider. 1) Mutation definition is here: https://github.com/developer239/react-apollo-graphql/blob/create-post-integration-tests/src/modules/blog/gql.js#L23 export const CREATE_POST = gql` mutation createPost($title: String!, $text: String!) { createPost(title: $title, text: $text) { id title text } } ` 2) The fake request is here: https://github.com/developer239/react-apollo-graphql/blob/create-post-integration-tests/test/utils/gql-posts.js#L68 export const fakeCreatePostSuccess = { request: { query: CREATE_POST, variables: { title: 'Mock Title', text: 'Mock lorem ipsum text. And another paragraph.', } }, result: { data: { createPost: { id: '1', title: 'Mock Title', text: 'Mock lorem ipsum text. And another paragraph.', }, }, }, 3) 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 <Mutation mutation={CREATE_POST} update={updatePostCache} onCompleted={({ createPost: { id } }) => push(`/posts/${id}`)} > {mutate => ( <> <H2>Create New Post</H2> <PostForm submit={values => mutate({ variables: values })} /> </> )} </Mutation> 4) 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 describe('on form submit', () => { it('should handle success', async () => { const renderer = renderApp(<App />, ROUTE_PATHS.createPost, [ fakeCreatePostSuccess, ]) const { formSubmitButton } = fillCreatePostForm(renderer) fireEvent.click(formSubmitButton) await waitForElement(() => renderer.getByTestId(POST_DETAIL_TEST_ID)) expect(renderer.getByTestId(POST_DETAIL_TEST_ID)).toBeTruthy() }) }) It seems that I followed all steps from the official documentation but I still can't make this work. Do you have any suggestions? 🙂
In the official docs its stated we should add addTypename={false} to the <MockedProvider>. And when I looked at the error message I could see that the __typename was added to the query it was looking for. Something like: { Error: Network error: No more mocked responses for the query: query getDog($dogId: ID!) { dog(dogId: $dogId) { name __typename } } So after removing addTypename={false} I got another error: Missing field __typename in { "name": "dog" } Now when adding a __typename to my mocked response it started working. e.g. const mocks = [ { request: { query: dogQuery, variables: { dogId: 1, }, }, result: { data: { dog: { name: 'dog', __typename: 'Dog', }, }, }, }, ];
Apollo
55,904,192
15
I have the following react-apollo-wrapped GraphQL query: user(id: 1) { name friends { id name } } As semantically represented, it fetches the user with ID 1, returns its name, and returns the id and name of all of its friends. I then render this in a component structure like the following: graphql(ParentComponent) -> UserInfo -> ListOfFriends (with the list of friends passed in) This is all working for me. However, I wish to be able to refetch the list of friends for the current user. I 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, user(id: 1) { name foo1 foo2 foo3 foo4 foo5 ... friends { id name } } Whilst the only thing I wish to refetch is the list of friends. What 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. Thanks in advance.
I don't know why you question is downvoted because I think it is a very valid question to ask. One of GraphQL's selling points is "fetch less and more at once". A client can decide very granually what it needs from the backend. Using deeply nested graphlike queries that previously required multiple endpoints can now be expressed in a single query. At the same time over-fetching can be avoided. Now you find yourself with a big query, everything loads at once and there are no n+1 query waterfalls. But now you know that a few fields in your big query are subject to change from now and then and you want to actively update the cache with new data from the server. Apollo offers the refetch field but it loads the whole query which clearly is overfetching that was sold to me as not being a concern anymore in GraphQL. Let me offer some solutions: Premature Optimisation? The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming. - Donald Knuth Sometimes we try to optimise too much without measuring first. Write it the easy way first and then see if it is really an issue. What exactly is slow? The network? A particular field in the query? The sheer size of the query? After you analized what exactly is slow we can start looking into improving: Refetch and include/skip directives Using directives you can exclude fields from a query depending on variables. The refetch function can specify different variables than the initial query. This way you can exclude fields when you refetch the query. Splitting up Queries Single page apps are a great idea. The HTML is generated client side and the page does not have to make expensive trips to the server to render a new page. But soon SPAs got to big and code splitting became an issue. And now we are basically back to server side rendering and splitting the app into pages. The same might apply to GraphQL. Sometimes queries are too big and should be split. You could split up the queries for UserInfo and ListOfFriends. Inside of the cache the fields will be merged. With query batching both queries will be send in the same request and a GraphQL server that implements per request resource caching correctly (e.g. with Dataloader) will barely notice a difference. Subscriptions Maybe you are ready to use subscriptions already. Subscriptions send updates from the server for fields that have changed. This way you could subscribe to a user's friends and get updates in real time. The good news is that Apollo Client, Relay and many server implementations offer support for subscriptions already. The bad news is that it needs websockets that usually put different requirements on your technology stack than pure HTTP. withApollo() -> this.client.query This should only be your last resort! Using react-apollo's withApollo higher order component you can directly inject the ApolloClient instance. You can now execute queries using this.client.query(). { user(id: 1) { friendlist { ... } } } can be used to just fetch the friend list and update the cache which will lead to an update of your component. This might look like what you want but can haunt you in later stages of the app.
Apollo
48,067,366
14
I'm completely stuck on an Apollo problem, for which I've opened a GitHub issue and had zero response on. I'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. But for some reason, my code is not working like this. I'm getting two update() calls, both with the optimistic data. Here's a repo that demonstrates this behavior: https://github.com/ffxsam/apollo-update-bug yarn && yarn dev Open in browser, open console Enter some text and hit enter Repeat above Notice the error in the console about duplicate keys. This is happening because the temporary ID "??" is not being replaced with the real UUID (optional) You can open Vue DevTools if available and inspect the data to see it's incorrect
I was doing some digging and I think I found the source of the problem. Unfortunately, I don't have a solution. In short, the problem might be with a network link called OfflineLink that is used by aws-appsync. Explanation aws-appsync has an ApolloLink called OfflineLink that intervenes with the request function. What happens is something like this: you call $apollo.mutate(...) ApolloClient.QueryManager initializes the mutation that triggers your update the first time with the optimistic response. That is happening inside ApolloClient data store, markMutationInit calls markMutationResult that calls your update. The graphql operation executes and reaches the OfflineLink in the network chain. OfflineLink creates a new observer and dispatches the mutation info as an action. The next line of OfflineLink calls the observer's next function with the optimisticResponse as if it was the execution result! This triggers your update the second time with the result which is actually the optimisticResponse. OfflineLink calls the observer's complete which resolves your promise. console.log('done!'... Meanwhile, OfflineLink prevents the original mutation from even sending the request, and a new mutation is generated and sent with the options you've given it.
Apollo
48,942,175
14
The actual HTTP server instance can be killed with server.close(callback), but I'm not sure what will happen with any pending WebSocket operations (mutations or queries being run through WebSockets). Since http.Server doesn't really know anything about the WebSocket operations, it probably ignores them. How to properly make sure that when SIGTERM is received, the server stops accepting new requests/webSocket connections, finishes the pending ones and then closes? Couldn't really find anything about this with Google.
Assuming based on the year this question was asked that you are asking about ApolloServer v2. Apollo Server instance does provide stop function which as per documentation waits for all the background tasks running. So it will wait for existing queries to complete before terminating the server. The method is available for v3 as well. ApolloServer.stop() is an async method that tells all of Apollo Server's background tasks to complete. It calls and awaits all serverWillStop plugin handlers (including the usage reporting plugin's handler, which sends a final usage report to Apollo Studio). This method takes no arguments. If your server is a federated gateway, stop also stops gateway-specific background activities, such as polling for updated service configuration. In some circumstances, Apollo Server calls stop automatically when the process receives a SIGINT or SIGTERM signal. See the stopOnTerminationSignals constructor option for details. If you're using the apollo-server package (which handles setting up an HTTP server for you), this method first stops the HTTP server. Specifically, it: Stops listening for new connections Closes idle connections (i.e., connections with no current HTTP request) Closes active connections whenever they become idle Waits for all connections to be closed If any connections remain active after a grace period (10 seconds by default), Apollo Server forcefully closes those connections. You can configure this grace period with the stopGracePeriodMillis constructor option. If you're using a middleware package instead of apollo-server, you should stop your HTTP server before calling ApolloServer.stop().
Apollo
60,640,145
14
Context This question is related to my other question, How to handle apollo client errors crashing page render in Nuxt? , but I'll try to keep this isolated since I'd like this question focused only on Nuxt (minus apollo). However, I decided to ask this separate since I'm looking for an entirely different response/solution. The problem I'm currently maintaining a production Nuxt/Vue app that is using the @nuxt/apollo module to make GraphQL requests. The problem, is that every now and then, the GraphQL server we rely on goes down and returns an HTML error page, which crashes the Apollo client. But because we're loading Apollo as a nuxt module, it crashes the page render pipeline as well. Giving us a generic server error page that looks like this; Server error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. And the following stack trace: ERROR Network error: Unexpected token < in JSON at position 0 08:11:04 at new ApolloError (node_modules/apollo-client/bundle.umd.js:92:26) at node_modules/apollo-client/bundle.umd.js:1588:34 at node_modules/apollo-client/bundle.umd.js:2008:15 at Set.forEach (<anonymous>) at node_modules/apollo-client/bundle.umd.js:2006:26 at Map.forEach (<anonymous>) at QueryManager.broadcastQueries (node_modules/apollo-client/bundle.umd.js:2004:20) at node_modules/apollo-client/bundle.umd.js:1483:29 at processTicksAndRejections (node:internal/process/task_queues:94:5) However, none of this stack trace allows us to see where nuxt is throwing the error, so we can handle it. What we tried We've exhausted all our options looking into this issue for the past couple of weeks. We first tried to solve it by handling the error directly at Apollo level using all 3 apollo library abstractions's error handling solutions: @nuxt/apollo module vue-apollo apollo-client If you'd like to read up more on that (even though its kind of irrelevant to this question), you can read more on my original question here However, right now I'd prefer to know if there's a way to somehow handle these page render errors either by: Making the errors fail silently, so the page still renders as normal Allowing us to redirect to another page. Since the apollo nuxt module we are using currently isn't working for that, I'd like to know if Nuxt supports some kind of way to handle errors. It didn't help much that Nuxt's documentation is pretty limited when it comes to error handling. At best, it has information regarding the error pages and how to redirect to the error pages using context.error. But it doesn't have a dedicated page on how to catch common errors. I have a feeling Nuxt hooks could be the answer, but documentation on them is hard to navigate and also sparse. The most complete information source I found on nuxt error handling was this article, Error handling in NuxtJS, of which nothing suggested worked for us. Summary Our nuxt app is crashing when the @nuxt/apollo nuxt module we are using crashes. We'd like to know if there's some kind of standard nuxt way of catching it, or if the only solution possible is just migrating our entire app to not use @nuxt/apollo module and use the ES6 promise syntax and load apollo-client manually into the app as a standalone library that's not deeply integrated into the nuxt lifecycle.
EDIT: I myself think that the problem lies somewhere in the Vue Apollo plugin or Nuxt Apollo module and how errors are handled there. I would think you can handle the error directly at the Apollo module but that is not possible in SSR. You have to keep in mind that you probably need another solution for both CSR as well as for SSR. In short, what happens is that the renderRoute fails and because of this SSR ends up in the default errorMiddleware of Nuxt. 1: Calling Apollo query directly, this gives you full control over the error handling for that page and will work for both CSR and for SSR export default { mounted() { if (!this.books.length) { // client side this.fetchBooks() } }, serverPrefetch() { this.fetchBooks() }, methods: { fetchBooks() { this.$apollo .query({ query: gql` query books { books { title author test } } `, }) .catch((e) => { console.log(e) }) .then((data) => { /// set books }) }, }, } 2: Add a errorMiddleware hook and handle the error there. This only works for SSR. Important to understand is that rendering failed so you have to redirect or render another page. //nuxt.config.js hooks: { render: { errorMiddleware(app) { app.use((error, req, res, next) => { res.writeHead(307, { Location: '/network-error', }) res.end() }) }, }, }, 3: Return false in the error method of Apollo, This only works for CSR export default { apollo: { books: { query() { return gql` query books { books { title author test } } ` }, error() { return false }, }, }, }
Apollo
66,030,282
14
This must be user error, but I've got an app with a simple currentUser query that looks at a JWT for an id, looks it up, and returns the appropriate user. I can look at devtools and see that it's in the cache as __ref:User:19 export const CURRENT_USER_QUERY = gql` query{ currentUser { id fullName email } } ` But in my component, when I do const { currentUser } = client.readQuery({ query: CURRENT_USER_QUERY }); it (intermittently) blows up because: Cannot destructure property 'currentUser' of 'client.readQuery(...)' as it is null. User:19 exists and is all the stuff I need. I hit reload, and that same page works. I have my default error policy set to "all" in the client. This is version 3.3.11 of the client. Chrome v88.04, for what that's worth. React 17.01. Am I missing something here? Should that not return a value synchronously (and dependably) if that item's in the cache? Is there a better way to deal with that situation? I'm trying to move this app away from storing things in redux or some context provider since it's already being handled by Apollo. Seems redundant to have that responsibility handled by a bunch of different things.
I was facing issues with .readQuery() last night. I was getting null returned everytime, though the logic was right. I was calling .readQuery() within a component I imported into my React page. What ended up being my issue is that I was not updating the same query I made in the "parent" react page as the one in the component. I don't know if this is the same problem you're running into, but I thought I'd leave this here for perpetuity and perspective.
Apollo
66,696,029
14
I'm new to Next.js and have some questions about client-side rendering and server-side rendering in Next.js I see there are two ways to fetch data on Next.js. One of them is to use the useQuery hook but that is only callable on the React component function. Does it mean that it only runs when rendering the page from the client-side? I read a post about how to connect apolloClient to Next.js. It said that always create a new instance of apolloClient for SSR and only create one instance of apolloClient for CSR Here is the example code export function initializeApollo(initialState = null) { const _apolloClient = apolloClient ?? createApolloClient(); // If your page has Next.js data fetching methods that use Apollo Client, // the initial state gets hydrated here if (initialState) { // Get existing cache, loaded during client side data fetching const existingCache = _apolloClient.extract(); // Restore the cache using the data passed from // getStaticProps/getServerSideProps combined with the existing cached data _apolloClient.cache.restore({ ...existingCache, ...initialState }); } // For SSG and SSR always create a new Apollo Client if (typeof window === "undefined") return _apolloClient; // Create the Apollo Client once in the client if (!apolloClient) apolloClient = _apolloClient; return _apolloClient; } Can anyone explain that? I'm sorry if the questions are silly
In Next JS: SSR - Server side rendering - getServerSideProps SSG - Static site generated - getStaticPaths & getStaticProps CSR - Client side rendering - everything else It is important to note that SSG functions are run server-side. On the client, you only want to create a single global instance of Apollo Client. Creating multiple instances of Apollo Client will make it challenging to keep things in sync with the client. This difficulty is because the Apollo Cache, Apollo Link, etc., will all be stored in different instances of Apollo Client. In Next, it is common to place the global instance of Apollo Client on the page _app.js and use the Apollo Provider. On the other client-side pages, you'd use the useQuery hook that calls your single global instance. The server-side (SSR) functions getStaticProps or getServerSideProps do not have access to the client instance of Apollo, client instance of Next, or other server-side functions. Because of this, you must define your Apollo connection on every page that uses getStaticPaths, getStaticProps, or getServerSideProps and needs access to the Apollo client or it will not be available to the server-side calls. Since the first rule of hooks is that they must only be called at the top level (client-side), you cannot use them in server-side functions. No, you cannot run useQuery in the Next SSR or SSG functions. The example you provide is keeping the cache in sync and is outdated in how it is defining the client. Here is a simplified example more along the lines of the official docs. graphqlClient.js import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'; // Used server and client side - can't use react hooks export const graphqlClient = new ApolloClient({ cache: new InMemoryCache(), link: new HttpLink({ uri: 'YOUR_GQL_ENDPOINT', }), ssrMode: typeof window === 'undefined', }); _app.js - a single instance that all client pages use because it wraps the whole app import graphqlClient from 'my/path/graphqlClient'; const App = ({ Component, pageProps }) => { const client = graphqlClient(); return ( <ApolloProvider client={client}> <Component {...pageProps} /> </ApolloProvider> ); }; Every page/component that is client-side that can use the useQuery hook because Apollo Client is wrapping the app in _app.js Client-side query import { gql, useQuery } from '@apollo/client'; const About = () => { const { data } = useQuery(YOUR_QUERY); // uses your single instance defined in _app.js return ( ... ) } Every page that uses SSR or SSG functions and needs access to Apollo must instantiate a new instance of Apollo. SSG import graphqlClient from 'my/path/graphqlClient'; //does not have access to _app.js or client and must define new Apollo Client instance export const getStaticProps = async () => { const client = graphqlClient();// const { data } = await client.query({query: YOUR_QUERY}); }; export const getStaticPaths = async () => { const client = graphqlClient(); const { data } = await client.query({query: YOUR_QUERY}); }; SSR import graphqlClient from 'my/path/graphqlClient'; //does not have access to _app.js or client and must define new Apollo Client instance export const getServerSideProps = async () => { const client = graphqlClient(); const { data } = await client.query({query: YOUR_QUERY}); }; Lastly, to simplify things you can use graphql-code-generator to auto-generate Apollo query, mutation, etc. hooks (and types for TS users) as well as server-side compatible query and mutation functions for Next.js.
Apollo
67,163,527
14
Recently 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. Here is an example taken from https://dev-blog.apollodata.com/tutorial-graphql-subscriptions-client-side-40e185e4be76#0a8f const messagesSubscription = gql` subscription messageAdded($channelId: ID!) { messageAdded(channelId: $channelId) { id text } } ` componentWillMount() { this.props.data.subscribeToMore({ document: messagesSubscription, variables: { channelId: this.props.match.params.channelId, }, updateQuery: (prev, {subscriptionData}) => { if (!subscriptionData.data) { return prev; } const newMessage = subscriptionData.data.messageAdded; // don't double add the message if (!prev.channel.messages.find((msg) => msg.id === newMessage.id)) { return Object.assign({}, prev, { channel: Object.assign({}, prev.channel, { messages: [...prev.channel.messages, newMessage], }) }); } else { return prev; } } }); } But 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. Is there any way using Apollo GraphQL client to handle subscriptions, without being inside a React Component?
Turns out it is the subscribe method. I found a description here: https://dev-blog.apollodata.com/graphql-subscriptions-in-apollo-client-9a2457f015fb#eeba ApolloClient.subscribe takes a query and variables, and returns an observable. We then call subscribe on the observable, and give it a next function which will call updateQuery. updateQuery specifies how we want our query result to be updated when given the subscription result. subscribe(repoName, updateQuery){ // call the "subscribe" method on Apollo Client this.subscriptionObserver = this.props.client.subscribe({ query: SUBSCRIPTION_QUERY, variables: { repoFullName: repoName }, }).subscribe({ next(data) { // ... call updateQuery to integrate the new comment // into the existing list of comments }, error(err) { console.error('err', err); }, }); }
Apollo
45,113,394
13
I'm attempting to wait for the result of a stream with my Apollo Server. My resolver looks like this. async currentSubs() { try { const stream = gateway.subscription.search(search => { search.status().is(braintree.Subscription.Status.Active); }); const data = await stream.pipe(new CollectObjects()).collect(); return data; } catch (e) { console.log(e); throw new Meteor.Error('issue', e.message); } }, This 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. How can I troubleshoot this & where is the 30 second timeout coming from? It only fails when the results take longer. I'm using https://github.com/mrdaniellewis/node-stream-collect to collect the results from the stream. Error coming in from the try catch: I20180128-13:09:26.872(-7)? { proxy: I20180128-13:09:26.872(-7)? { error: 'Post http://127.0.0.1:26474/graphql: net/http: request canceled (Client.Timeout exceeded while awaiting headers)', I20180128-13:09:26.872(-7)? level: 'error', I20180128-13:09:26.873(-7)? msg: 'Error sending request to origin.', I20180128-13:09:26.873(-7)? time: '2018-01-28T13:09:26-07:00', I20180128-13:09:26.873(-7)? url: 'http://127.0.0.1:26474/graphql' } }
Had this same problem and was a pretty simple solution. My calls were lasting a bit over 30 seconds and the default timeout was returning 503s as well so I increased that. Assuming you're using apollo-engine (this may be true for some other forms of Apollo), you can set your engine configs like so: export function startApolloEngine() { const engine = new Engine({ engineConfig: { stores: [ { name: "publicResponseCache", memcache: { url: [environmentSettings.memcache.server], keyPrefix: environmentSettings.memcache.keyPrefix } } ], queryCache: { publicFullQueryStore: "publicResponseCache" }, reporting: { disabled: true } }, // GraphQL port graphqlPort: 9001, origin: { requestTimeout: "50s" }, // GraphQL endpoint suffix - '/graphql' by default endpoint: "/my_api_graphql", // Debug configuration that logs traffic between Proxy and GraphQL server dumpTraffic: true }); engine.start(); app.use(engine.expressMiddleware()); } Notice the part where I specify origin: { requestTimeout: "50s" } That alone is what fixed it for me. Hope this helps! You can find more information about that here
Apollo
48,490,312
13
I am using React Router 4 for routing and Apollo Client for data fetching & caching. I need to implement a PrivateRoute and redirection solution based on the following criteria: The pages a user is permitted to see are based on their user status, which can be fetched from the server, or read from the cache. The user status is essentially a set of flags we use to understand where the user is in our funnel. Example flags: isLoggedIn, isOnboarded, isWaitlisted etc. No page should even begin to render if the user's status does not permit them to be on that page. For example, if you aren't isWaitlisted, you are not supposed to see the waitlist page. When users accidentally find themselves on these pages, they should be redirected to a page that is suitable for their status. The redirection should also be dynamic. For example, say you try to view your user profile before you are isLoggedIn. Then we need to redirect you to the login page. However, if you are isLoggedIn but not isOnboarded, we still don't want you to see your profile. So we want to redirect you to the onboarding page. All of this needs to happen on the route level. The pages themselves should be kept unaware of these permissions & redirections. In conclusion, we need a library that given the user status data, can compute whether a user can be on a certain page compute where they need to be redirected to dynamically do these before rendering any page do these on the route level I'm already working on a general-use library, but it has its shortcomings right now. I'm seeking opinions on how one should approach this problem, and whether there are established patterns to achieve this goal. Here is my current approach. This is not working because the data the getRedirectPath needs is in the OnboardingPage component. Also, I can't wrap the PrivateRoute with the HOC that could inject the props required to compute the redirect path because that would not let me use it as a child of the Switch React Router component as it stops being a Route. <PrivateRoute exact path="/onboarding" isRender={(props) => { return props.userStatus.isLoggedIn && props.userStatus.isWaitlistApproved; }} getRedirectPath={(props) => { if (!props.userStatus.isLoggedIn) return '/login'; if (!props.userStatus.isWaitlistApproved) return '/waitlist'; }} component={OnboardingPage} />
General Approach I would create an HOC to handle this logic for all of your pages. // privateRoute is a function... const privateRoute = ({ // ...that takes optional boolean parameters... requireLoggedIn = false, requireOnboarded = false, requireWaitlisted = false // ...and returns a function that takes a component... } = {}) => WrappedComponent => { class Private extends Component { componentDidMount() { // redirect logic } render() { if ( (requireLoggedIn && /* user isn't logged in */) || (requireOnboarded && /* user isn't onboarded */) || (requireWaitlisted && /* user isn't waitlisted */) ) { return null } return ( <WrappedComponent {...this.props} /> ) } } Private.displayName = `Private(${ WrappedComponent.displayName || WrappedComponent.name || 'Component' })` hoistNonReactStatics(Private, WrappedComponent) // ...and returns a new component wrapping the parameter component return Private } export default privateRoute Then you only need to change the way you export your routes: export default privateRoute({ requireLoggedIn: true })(MyRoute); and you can use that route the same way you do today in react-router: <Route path="/" component={MyPrivateRoute} /> Redirect Logic How you set this part up depends on a couple factors: How you determine whether a user is logged in, onboarded, waitlisted, etc. Which component you want to be responsible for where to redirect to. Handling user status Since you're using Apollo, you'll probably just want to use graphql to grab that data in your HOC: return graphql(gql` query ... `)(Private) Then you can modify the Private component to grab those props: class Private extends Component { componentDidMount() { const { userStatus: { isLoggedIn, isOnboarded, isWaitlisted } } = this.props if (requireLoggedIn && !isLoggedIn) { // redirect somewhere } else if (requireOnboarded && !isOnboarded) { // redirect somewhere else } else if (requireWaitlisted && !isWaitlisted) { // redirect to yet another location } } render() { const { userStatus: { isLoggedIn, isOnboarded, isWaitlisted }, ...passThroughProps } = this.props if ( (requireLoggedIn && !isLoggedIn) || (requireOnboarded && !isOnboarded) || (requireWaitlisted && !isWaitlisted) ) { return null } return ( <WrappedComponent {...passThroughProps} /> ) } } Where to redirect There are a few different places you can handle this. Easy way: routes are static If a user is not logged in, you always want to route to /login?return=${currentRoute}. In this case, you can just hard code those routes in your componentDidMount. Done. The component is responsible If you want your MyRoute component to determine the path, you can just add some extra parameters to your privateRoute function, then pass them in when you export MyRoute. const privateRoute = ({ requireLoggedIn = false, pathIfNotLoggedIn = '/a/sensible/default', // ... }) // ... Then, if you want to override the default path, you change your export to: export default privateRoute({ requireLoggedIn: true, pathIfNotLoggedIn: '/a/specific/page' })(MyRoute) The route is responsible If you want to be able to pass in the path from the routing, you'll want to receive props for these in Private class Private extends Component { componentDidMount() { const { userStatus: { isLoggedIn, isOnboarded, isWaitlisted }, pathIfNotLoggedIn, pathIfNotOnboarded, pathIfNotWaitlisted } = this.props if (requireLoggedIn && !isLoggedIn) { // redirect to `pathIfNotLoggedIn` } else if (requireOnboarded && !isOnboarded) { // redirect to `pathIfNotOnboarded` } else if (requireWaitlisted && !isWaitlisted) { // redirect to `pathIfNotWaitlisted` } } render() { const { userStatus: { isLoggedIn, isOnboarded, isWaitlisted }, // we don't care about these for rendering, but we don't want to pass them to WrappedComponent pathIfNotLoggedIn, pathIfNotOnboarded, pathIfNotWaitlisted, ...passThroughProps } = this.props if ( (requireLoggedIn && !isLoggedIn) || (requireOnboarded && !isOnboarded) || (requireWaitlisted && !isWaitlisted) ) { return null } return ( <WrappedComponent {...passThroughProps} /> ) } } Private.propTypes = { pathIfNotLoggedIn: PropTypes.string } Private.defaultProps = { pathIfNotLoggedIn: '/a/sensible/default' } Then your route can be rewritten to: <Route path="/" render={props => <MyPrivateComponent {...props} pathIfNotLoggedIn="/a/specific/path" />} /> Combine options 2 & 3 (This is the approach that I like to use) You can also let the component and the route choose who is responsible. You just need to add the privateRoute params for paths like we did for letting the component decide. Then use those values as your defaultProps as we did when the route was responsible. This gives you the flexibility of deciding as you go. Just note that passing routes as props will take precedence over passing from the component into the HOC. All together now Here's a snippet combining all the concepts from above for a final take on the HOC: const privateRoute = ({ requireLoggedIn = false, requireOnboarded = false, requireWaitlisted = false, pathIfNotLoggedIn = '/login', pathIfNotOnboarded = '/onboarding', pathIfNotWaitlisted = '/waitlist' } = {}) => WrappedComponent => { class Private extends Component { componentDidMount() { const { userStatus: { isLoggedIn, isOnboarded, isWaitlisted }, pathIfNotLoggedIn, pathIfNotOnboarded, pathIfNotWaitlisted } = this.props if (requireLoggedIn && !isLoggedIn) { // redirect to `pathIfNotLoggedIn` } else if (requireOnboarded && !isOnboarded) { // redirect to `pathIfNotOnboarded` } else if (requireWaitlisted && !isWaitlisted) { // redirect to `pathIfNotWaitlisted` } } render() { const { userStatus: { isLoggedIn, isOnboarded, isWaitlisted }, pathIfNotLoggedIn, pathIfNotOnboarded, pathIfNotWaitlisted, ...passThroughProps } = this.props if ( (requireLoggedIn && !isLoggedIn) || (requireOnboarded && !isOnboarded) || (requireWaitlisted && !isWaitlisted) ) { return null } return ( <WrappedComponent {...passThroughProps} /> ) } } Private.propTypes = { pathIfNotLoggedIn: PropTypes.string, pathIfNotOnboarded: PropTypes.string, pathIfNotWaitlisted: PropTypes.string } Private.defaultProps = { pathIfNotLoggedIn, pathIfNotOnboarded, pathIfNotWaitlisted } Private.displayName = `Private(${ WrappedComponent.displayName || WrappedComponent.name || 'Component' })` hoistNonReactStatics(Private, WrappedComponent) return graphql(gql` query ... `)(Private) } export default privateRoute I'm using hoist-non-react-statics as suggested in the official documentation.
Apollo
48,692,649
13
I have a <Query /> in my Home.js file Home.js <Query query={GET_TODOS_BY_PRODUCT} variables={{ id: state.get("selectedProduct.id"), completed: true }} > {({ data: { product } }) => { return <Main todos={product.todos} hashtag={product.hashtag} />; }} </Query> In my Main.js file I have <Mutation /> component - Main.js <Mutation key={v4()} mutation={SWITCH_SELECTED_PRODUCT} refetchQueries={() => { console.log("refetchQueries", product.id); return { query: GET_TODOS_BY_PRODUCT, variables: { id: product.id } }; }} > {switchSelectedProduct => ( <Product onClick={() => { switchSelectedProduct({ variables: { id: product.id, name: product.name } }); }} highlight={ data.selectedProduct ? product.name === data.selectedProduct.name : i === 0 } > <Name>{product.name}</Name> </Product> )} </Mutation> When switchSelectedProduct is called inside <Mutation /> component, it runs refetchQueries as I see the console.log("refetchQueries", product.id); statement but I don't see the updated results in the <Query /> component in Home.js file. How do I tell <Query /> component in Home.js to get notified when refetchQueries is run in Main.js file? Any suggestions?
From docs: refetchQueries: (mutationResult: FetchResult) => Array<{ query: DocumentNode, variables?: TVariables} | string>, so probably you need to return an array instead of just the object <Mutation key={v4()} mutation={SWITCH_SELECTED_PRODUCT} refetchQueries={() => { console.log("refetchQueries", product.id) return [{ query: GET_TODOS_BY_PRODUCT, variables: { id: product.id } }]; }} >
Apollo
51,695,337
13
I am currently using the vue-apollo package for Apollo client with VueJs stack with django and graphene-python for my GraphQl API. I have a simple setup with vue-apollo below: import Vue from 'vue' import { ApolloClient } from 'apollo-client' import { HttpLink } from 'apollo-link-http' import { InMemoryCache } from 'apollo-cache-inmemory' import VueApollo from 'vue-apollo' import Cookies from 'js-cookie' const httpLink = new HttpLink({ credentials: 'same-origin', uri: 'http://localhost:8000/api/', }) // Create the apollo client const apolloClient = new ApolloClient({ link: httpLink, cache: new InMemoryCache(), connectToDevTools: true, }) export const apolloProvider = new VueApollo({ defaultClient: apolloClient, }) // Install the vue plugin Vue.use(VueApollo) I 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: ''' import gql from "graphql-tag"; import CREATE_USER from "@/graphql/NewUser.gql"; export default { data() { return { test: "" }; }, methods: { authenticateUser() { this.$apollo.mutate({ mutation: CREATE_USER, variables: { email: "test@example.com", password: "pa$$word", username: "testuser" } }).then(data => { console.log(result) }) } } }; NewUser.gql mutation createUser($email: String!, $password: String!, $username: String!) { createUser (username: $name, password: $password, email: $email) user { id username email password } } returns with the error response below: POST http://localhost:8000/api/ 400 (Bad Request) ApolloError.js?d4ec:37 Uncaught (in promise) Error: Network error: Response not successful: Received status code 400 Regular queries in my vue app, however, work fine resolving the right response, except mutations, so this has me really baffled
400 errors generally mean there's something off with the query itself. In this instance, you've defined (and you're passing in) a variable called $username -- however, your query references it as $name on line 2.
Apollo
52,247,877
13
Schema: type TrackUser { id: ID! @unique createdAt: DateTime! user: User #note there is no `!` } type User { id: ID! @unique name: String! @unique } I want to get Alls TrackUser where User is not null. What would be the query?
This would be a possible query: query c { trackUsers(where: { NOT: [{ user: null }] }) { name } } Here you can see how it looks in the Playground. I added a name to Trackuser in the datamodel in order to be able to create it from that side without a user.
Apollo
54,313,128
13
In tutorial https://www.howtographql.com/vue-apollo/1-getting-started/ there is presented new HttpLink syntax, but in official docs https://www.apollographql.com/docs/link/links/http/ function createHttpLink is applied. None of these two sources describes the differences between these methods.
There is no fundamental difference between the two. If you look at the apollo-link-http package source here, you can see that the exported createHttpLink method returns a new instance of the ApolloLink class initialized with the options you passed to createHttpLink (lines 62-194). At the end of the same file, you can see that the package also exports the HttpLink class, which extends the ApolloLink class (lines 256-261): export class HttpLink extends ApolloLink { public requester: RequestHandler; constructor(opts?: HttpLink.Options) { super(createHttpLink(opts).request); } } As you can see from the code above, when you create an apollo http link by creating a new instance of the HttpLink class, the options you pass to the constructor are internally passed on to createHttpLink, which returns an instance of ApolloLink as mentioned above, and that instance's RequestHandler is passed on to (i.e. copied) to the new HttpLink instance's parent, which is also an instance of ApolloLink (see lines 96-124 here for a peek at ApolloLink's own constructor). Note that the apollo-link-http package's own docs do NOT mention the new HttpLink syntax, so I would stick to the createHttpLink syntax for future compatibility.
Apollo
56,663,103
13
I'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. I 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 App.js: import React from "react"; import ApolloClient from "apollo-boost"; import { ApolloProvider } from "react-apollo"; import BookList from "./components/BookList"; import AddBook from "./components/AddBook"; //apollo client setup const client = new ApolloClient({ uri: "http://localhost:4000/graphql" }); function App() { return ( <ApolloProvider client={client}> <div className="main"> <h1>My Reading List</h1> <BookList /> <AddBook /> </div> </ApolloProvider> ); } export default App; queries.js: import { gql } from "apollo-boost"; const getBooksQuery = gql` { books { name id } } `; const getAuthorsQuery = gql` { authors { name id } } `; const addBookMutation = gql` mutation { addBook(name: "", genre: "", authorId: "") { name id } } `; export { getAuthorsQuery, getBooksQuery, addBookMutation }; AddBooks.js: import React, { Component } from "react"; import { graphql } from "react-apollo"; import { compose } from "recompose"; // import * as compose from "lodash"; import { getAuthorsQuery, addBookMutation } from "../queries/queries"; class AddBook extends Component { state = { name: "", genre: "", authorId: "" }; displayAuthors = () => { let data = this.props.data; if (data.loading) { return <option>loading authors...</option>; } else { return data.authors.map(author => { return ( <option key={author.id} value={author.id}> {author.name} </option> ); }); } }; submitForm(e) { e.preventDefault(); console.log(this.state); } render() { return ( <form onSubmit={this.submitForm.bind(this)}> <div className="field"> <label>Book name: </label> <input type="text" onChange={e => { this.setState({ name: e.target.value }); }} /> </div> <div className="field"> <label>Genre: </label> <input type="text" onChange={e => { this.setState({ genre: e.target.value }); }} /> </div> <div className="field"> <label>Author: </label> <select onChange={e => { this.setState({ authorId: e.target.value }); }} > <option>Select author</option> {this.displayAuthors()} </select> </div> <button>+</button> </form> ); } } export default compose( graphql(getAuthorsQuery, { name: "getAuthorsQuery" }), graphql(addBookMutation, { name: "addBookMutation" }) )(AddBook); I 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.
compose was removed from React Apollo 3.0.0. If you want to use the same HOC pattern, feel free to use the same copy of lodash's flowRight. Install lodash in your client folder npm install lodash and use this to import compose from lodash (use a capital R in flowRight) import {flowRight as compose} from 'lodash'; Reference for the braking changes
Apollo
57,445,294
13
I'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: However, 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. As 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: And when I try to console.log the req.cookies, I get nothing, which is to be one of the benefits of using the cookieParser. My ApolloServer implementation is as follows: const server = new ApolloServer({ typeDefs: schema resolvers, dataSources: () => ({ // ... }), context: ({req, res}) => ({ models, session: req.session, req, res }), // ... and the rest is not important }); Creating a "custom" cookie header could do the trick, such as somecookie: <key>=<value>, 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?
After extensive searching, documentation reading and etc. I figured out how I could make this work. In the GraphQL playground settings (gear icon), located in the upper right corner of the window: I changed the line "request.credentials" to "include" and SAVING the settings in the UI. Read more here. This line is taken directly from the documentation: 'request.credentials': 'omit', // possible values: 'omit', 'include', 'same-origin' Then following that, I opened the developer tools window (usually F12), went to the tab Application. In here I simply added a cookie as seen in the screenshot. That cookie was sent together with my request.
Apollo
68,114,615
13
Is there a global loading flag available anywhere for react-apollo client? I have a “page wrapper” component that i’d like to apply ui effects to after all the child components have received their data. I have set up apollo with redux so have ready access to the store (http://dev.apollodata.com/react/redux.html) I could quite easily dispatch state changes from each component that receives data from apollo but I'd like this page wrapper component to not have any knowledge of its children nor their queries. I have investigated using withApollo - http://dev.apollodata.com/react/higher-order-components.html#withApollo - but don't see an api for a global is loading.
I've just released a library that solves this for Apollo 2: react-apollo-network-status. The gist is: import React, {Fragment} from 'react'; import ReactDOM from 'react-dom'; import {ApolloClient} from 'apollo-client'; import {createNetworkStatusNotifier} from 'react-apollo-network-status'; import {createHttpLink} from 'apollo-link-http'; const { NetworkStatusNotifier, link: networkStatusNotifierLink } = createNetworkStatusNotifier(); const client = new ApolloClient({ link: networkStatusNotifierLink.concat(createHttpLink()) }); // Render the notifier along with the app. The // `NetworkStatusNotifier` can be placed anywhere. const element = ( <Fragment> <NetworkStatusNotifier render={({loading, error}) => ( <div> {loading && <p>Loading …</p>} {error && <p>Error: {JSON.stringify(error)}</p>} </div> )} /> <ApolloProvider client={client}> <App /> </ApolloProvider> </Fragment> ); const node = document.getElementById('root'); ReactDOM.render(element, node);
Apollo
43,964,957
12
I 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?
The reason for this is that ApolloClient, like Relay, uses a global store to cache your data on the client. In order to do this for you, global ids are required. For some reason, global ids are not something people think about, and in fact, it is something people complain about when switching to Relay all the time. ApolloClient has a clever solution for this! (Apollo team correct me if I am wrong) They allow you to define how your records get keyed in the store! By default, it uses the typename and id to create a the kind of global IDs that Relay suggests you create. This is why they need the typename. Since you are turning off the typename in the query, Apollo will do some smart stuff to try and figure out the type (and thus the key in the store). This smart stuff can lead to problems for you down the road. If you want to create your own global ids instead of using all this smart stuff, you can specify it like so: const cache = new InMemoryCache({ dataIdFromObject: object => object.key || null }); https://www.apollographql.com/docs/react/advanced/caching.html#normalization
Apollo
45,509,228
12
If we look at the todos example, imagine that the application had multiple views (a TodoList page and another page). So instead of "todos" directly referring to an array of todo items, at the top level of the state/store/cache it would actually just be a view with some of its own state. Inside that view, we'd define the list of todo items and visibility filter - so the state/store/cache would NOT be looking like this: { todos: [TodoItem] 0:▾TodoItem:0 completed: false id: 0 text: "hh" visibilityFilter: "SHOW_ALL" } but as: { scenes: { TodoList: { todos: [TodoItem] 0:▾TodoItem:0 completed: false id: 0 text: "hh" visibilityFilter: "SHOW_ALL" }, SomeOtherView: { /* other state */} } } It might even be isolated in its own data "module", like proposed here: https://medium.com/@alexmngn/how-to-use-redux-on-highly-scalable-javascript-applications-4e4b8cb5ef38 : { scenes: { TodoList: { data: { todos: [TodoItem] 0:▾TodoItem:0 completed: false id: 0 text: "hh" } visibilityFilter: "SHOW_ALL" }, SomeOtherView: { /* other state */} } } application wide state would be store a level further out: { // App global state lives as long as the app data: { /* App global relevant data */}, someglobalstate: true, scenes: { TodoList: { // "view state" lives as long as the view is active, and resets when navigated away from data: { todos: [TodoItem] 0:▾TodoItem:0 completed: false id: 0 text: "migrate from redux to apollo-link-state" } visibilityFilter: "SHOW_ALL" }, SomeOtherView: { /* other state */} } } We can achieve this easily with reducer composition in Redux, like this: Starting from the inside: todos would have its own reducer which is combined in the data reducer, which is combined in the TodoList reducer with the key "data". The TodoList reducer would then again be combined in the scenes reducer and so forth up to the top, to make the nested state reflect the folder structure of the project. But how would something like this be possible with apollo-link-state and resolvers without defining everything in a single "TodoList" resolver? Additional question: How would you clear the TodoList state once you navigate away? In Redux I guess you'd trigger an actions which would clear the given slice of the state. P.S. "apollo-link-state" & "apollo-link" tags are missing in stackoverflow. Maybe someone with rep > 1500 could add those?
I have the same question. It seems that apollo-link-state expect a function at the top level of the resolver, so it is not possible to created nested structures as it would be in a Redux store. As the introduction post says, though, it is expected that apollo-link-state would manage only roughly 20% of the state, the rest being fetched data from the GraphQL Server. So it might not make sense to split the local state as much as it makes senses to split a Redux store. For now, I've settled on using prefixes for the main domains of the local state.
Apollo
48,064,706
12
Hi everyone I am a bit stuck on a problem with apollo-angular and apollo-link-error. I've tried a few different ways and I can't seem to catch any errors client-side in my angular web app. I posted my attempts below. Any suggestions or an extra set of eyes would be much appreciated. Basically all I am trying to do is when an error occurs to prompt my user about the problem. If anyone has some alternate npm package other than apollo-link-error I am all ears. Attempt 1: export class AppModule { constructor (apollo: Apollo, httpLink: HttpLink) { apollo.create({ link: httpLink.create({ uri: 'http://localhost:8080/graphql' }), cache: new InMemoryCache() }); const error = onError(({ networkError }) => { const networkErrorRef:HttpErrorResponse = networkError as HttpErrorResponse; if (networkErrorRef && networkErrorRef.status === 401) { console.log('Prompt User', error); } }); } } Attempt 2: export class AppModule { constructor (apollo: Apollo, httpLink: HttpLink) { apollo.create({ link: httpLink.create({ uri: 'http://localhost:8080/graphql' }), cache: new InMemoryCache() }); const error = onError(({networkError}) => { if (networkError.status === 401) { console.log('Prompt User', error); } }); } } Attempt 3: export class AppModule { constructor (apollo: Apollo, httpLink: HttpLink) { apollo.create({ link: httpLink.create({ uri: 'http://localhost:8080/graphql' }), cache: new InMemoryCache() }); const link = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) graphQLErrors.map(({ message, locations, path }) => console.log( `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`, ), ); if (networkError) console.log(`[Network error]: ${networkError}`); }); } }
You can see apollo-link-error as a middleware so you have to add it to the fetching process in the apollo client. Meaning that you have to create another apollo link which combines both the http and the error link: import { ApolloLink } from 'apollo-link'; import { HttpLink } from 'apollo-link-http'; import { onError } from 'apollo-link-error'; ... const errorLink = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) graphQLErrors.map(({ message, locations, path }) => console.log( `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`, ), ); if (networkError) console.log(`[Network error]: ${networkError}`); }); } } const httpLink = new HttpLink({ uri: "http://localhost:8080/graphql" }); const httpLinkWithErrorHandling = ApolloLink.from([ errorLink, httpLink, ]); apollo.create({ link: httpLinkWithErrorHandling, cache: new InMemoryCache() }); ...
Apollo
49,420,667
12
AppSync uses MQTT over WebSockets for its subscription, yet Apollo uses WebSockets. Neither Subscription component or subscribeForMore in Query component works for me when using apollo with AppSync. One AppSync feature that generated a lot of buzz is its emphasis on real-time data. Under the hood, AppSync’s real-time feature is powered by GraphQL subscriptions. While Apollo bases its subscriptions on WebSockets via subscriptions-transport-ws, subscriptions in GraphQL are actually flexible enough for you to base them on another messaging technology. Instead of WebSockets, AppSync’s subscriptions use MQTT as the transport layer. Is there any way to make use of AppSync while still using Apollo?
Ok, here is how it worked for me. You'll need to use aws-appsync SDK (https://github.com/awslabs/aws-mobile-appsync-sdk-js) to use Apollo with AppSync. Didn't have to make any other change to make subscription work with AppSync. Configure ApolloProvider and client: // App.js import React from 'react'; import { Platform, StatusBar, StyleSheet, View } from 'react-native'; import { AppLoading, Asset, Font, Icon } from 'expo'; import AWSAppSyncClient from 'aws-appsync' // <--------- use this instead of Apollo Client import {ApolloProvider} from 'react-apollo' import { Rehydrated } from 'aws-appsync-react' // <--------- Rehydrated is required to work with Apollo import config from './aws-exports' import { SERVER_ENDPOINT, CHAIN_ID } from 'react-native-dotenv' import AppNavigator from './navigation/AppNavigator'; const client = new AWSAppSyncClient({ url: config.aws_appsync_graphqlEndpoint, region: config.aws_appsync_region, auth: { type: config.aws_appsync_authenticationType, apiKey: config.aws_appsync_apiKey, // jwtToken: async () => token, // Required when you use Cognito UserPools OR OpenID Connect. token object is obtained previously } }) export default class App extends React.Component { render() { return <ApolloProvider client={client}> <Rehydrated> <View style={styles.container}> <AppNavigator /> </View> </Rehydrated> </ApolloProvider> } Here is how the subscription in a component looks like: <Subscription subscription={gql(onCreateBlog)}> {({data, loading})=>{ return <Text>New Item: {JSON.stringify(data)}</Text> }} </Subscription>
Apollo
52,960,709
12
I have a set of mutations that trigger the local state of certain types of popups. They're generally set up like this: openDialog: (_, variables, { cache }) => { const data = { popups: { ...popups, dialog: { id: 'dialog', __typename: 'Dialog', type: variables.type } } }; cache.writeData({ data: data }); return null; } And the defaults I pass in look like: const defaults = { popups: { __typename: TYPENAMES.POPUPS, id, message: null, modal: null, menu: null, dialog: null } }; The way they're used in my React code is with a Mutation wrapper component, like so: const OPEN_ALERT_FORM = gql` mutation AlertOpenDialog($type: String!) { openDialog(type: $type) @client } `; class Alert extends Component { render() { return ( <Mutation mutation={OPEN_ALERT_FORM} variables={{ type: ALERT_FORM }}> {openDialog => { return ( <Button classes="alert-button" onClick={openDialog} label="Trigger Alert" /> ); }} </Mutation> ); } } For 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: Network error: Missing selection set for object of type Dialog returned for query field dialog ...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: Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. I'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. What 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.
Solution 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: { popups @client { id dialog } } you must declare some fields to fetch inside dialog, for example id: { popups @client { id dialog { id } } }
Apollo
53,215,803
12
I'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. Let's examine both in this example where the current user, me, has many invitations. Root queries me { id name } invitations { id message } The resolver for invitations returns invitations for the current user. Nested query me { id name invitations { id message } } These 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. What is the recommended way to design GraphQL queries?
I'd say it really depends on the case. Personally, I treat nested properties as a context: if the API consumer wants to fetch mine notifications, then it's me { notifications { ... } }, not notifications { ... }. If it makes sense to have a top-level key, for example, there's a concept of global notifications (not user-dependent), then go for it. If every user has own notifications (which I assume is true), then me of type User should have it, as every User does. Such generalization encourages reusable thinking: an admin panel, where user(id: ...) { ... } is being used instead of me { ... }, can use the same UI code for free. As a rule of thumb, it's better to think about consuming that API, not providing it.
Apollo
54,026,744
12
My frontend is localhost:3000, and my GraphQL server is localhost:3333. I've used react-apollo to query/mutate in JSX land, but haven't made a query/mutation from Express yet. I'd like to make the query/mutation here in my server.js. server.get('/auth/github/callback', (req, res) => { // send GraphQL mutation to add new user }); Below seems like the right direction, but I'm getting TypeError: ApolloClient is not a constructor: const express = require('express'); const next = require('next'); const ApolloClient = require('apollo-boost'); const gql = require('graphql-tag'); // setup const client = new ApolloClient({ uri: 'http://localhost:3333/graphql' }); const app = next({dev}); const handle = app.getRequestHandler(); app .prepare() .then(() => { const server = express(); server.get('/auth/github/callback', (req, res) => { // GraphQL mutation client.query({ query: gql` mutation ADD_GITHUB_USER { signInUpGithub( email: "email@address.com" githubAccount: "githubusername" githubToken: "89qwrui234nf0" ) { id email githubToken githubAccount } } `, }) .then(data => console.log(data)) .catch(error => console.error(error)); }); server.listen(3333, err => { if (err) throw err; console.log(`Ready on http://localhost:3333`); }); }) .catch(ex => { console.error(ex.stack); process.exit(1); }); This post mentions Apollo as the solution, but doesn't give an example. How do I call a GraphQL mutation from Express server :3000 to GraphQL :3333?
This is more likely to be what you're looking for: const { createApolloFetch } = require('apollo-fetch'); const fetch = createApolloFetch({ uri: 'https://1jzxrj179.lp.gql.zone/graphql', }); // Example # 01 fetch({ query: '{ posts { title } }', }).then(res => { console.log(res.data); }); // Example # 02 // You can also easily pass variables for dynamic arguments fetch({ query: ` query PostsForAuthor($id: Int!) { author(id: $id) { firstName posts { title votes } } } `, variables: { id: 1 }, }).then(res => { console.log(res.data); }); Taken from this post, might be helpful to others as well: https://www.apollographql.com/blog/graphql/examples/4-simple-ways-to-call-a-graphql-api/
Apollo
54,559,928
12
I am trying to do a very basic query via React with Apollo. When 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: Network error: Unexpected end of JSON input The query is: query { category(id: 3) { id children { id name } } } This is my component import React, { Component } from 'react'; import { Query } from 'react-apollo'; import gql from 'graphql-tag'; const CATEGORIES_LIST = gql` query CATEGORIES_LIST { category(id: 3) { id children { id name } } } `; class Cat extends Component { render() { return ( <div> <p>Items!</p> <Query query={CATEGORIES_LIST}> {payload => { console.log(payload); return <p>fetch done!</p>; }} </Query> </div> ) } } export default Cat; While the GraphiQL response is with the exact same request { "data": { "category": { "id": 3, "children": [ { "id": 4, "name": "Bags" }, { "id": 5, "name": "Fitness Equipment" }, { "id": 6, "name": "Watches" } ] } } } By the way I'm querying a local Magento 2.3 graphql server. When inspecting the network tab this is the response i get from the graphql endpoint. So no url typo are issue in the response { "data":{ "category":{ "id":3, "children":[ { "id":4, "name":"Bags", "__typename":"CategoryTree" }, { "id":5, "name":"Fitness Equipment", "__typename":"CategoryTree" }, { "id":6, "name":"Watches", "__typename":"CategoryTree" } ], "__typename":"CategoryTree" } } }
Ok, i found it. First issue was that i used no-cors option on the ApolloClient Which prevents it from ready the data thus sending back a empty data object. Second issue was that I needed to set my CORS headers on my GraphQL server properly, just for development accepting all with a * that solved it for the development phase. Third and last issue was that Apollo sends a OPTIONS request to preflight check the CORS headers to see if its all allowed. Magento 2.3 flipped over that because its an empty request thus providing you with a Unable to unserialize value error. What i did to solve that third issue is temporary patching a core file during deployment. The following file needs to be changed: /vendor/magento/module-graph-ql/Controller/GraphQl.php on line 111 the following is needed - $data = $this->jsonSerializer->unserialize($request->getContent()); + $content = ($request->getContent() === '') ? '{}' : $request->getContent(); + $data = $this->jsonSerializer->unserialize($content); I think there are other solutions for this on the React / Apollo side but haven't found that one yet.
Apollo
54,589,989
12
Testing the useSubscription hook I'm finding a bit difficult, since the method is omitted/not documented on the Apollo docs (at time of writing). Presumably, it should be mocked using the <MockedProvider /> from @apollo/react-testing, much like the mutations are in the examples given in that link. Testing the loading state for a subscription I have working: Component: const GET_RUNNING_DATA_SUBSCRIPTION = gql` subscription OnLastPowerUpdate { onLastPowerUpdate { result1, result2, } } `; const Dashboard: React.FC<RouteComponentProps & Props> = props => { const userHasProduct = !!props.user.serialNumber; const [startGetRunningData] = useMutation(START_GET_RUNNING_DATA); const [stopGetRunningData] = useMutation(STOP_GET_RUNNING_DATA); useEffect(() => { startGetRunningData({ variables: { serialNumber: props.user.serialNumber }, }); return () => { stopGetRunningData(); }; }, [startGetRunningData, stopGetRunningData, props]); const SubscriptionData = (): any => { const { data, loading } = useSubscription(GET_RUNNING_DATA_SUBSCRIPTION); if (loading) { return <Heading>Data loading...</Heading>; } const metrics = []; if (data) { console.log('DATA NEVER CALLED IN TEST!'); } return metrics; }; if (!userHasProduct) { return <Redirect to="/enter-serial" />; } return ( <> <Header /> <PageContainer size="midi"> <Panel> <SubscriptionData /> </Panel> </PageContainer> </> ); }; And a successful test of the loading state for the subscription: import React from 'react'; import thunk from 'redux-thunk'; import { createMemoryHistory } from 'history'; import { create } from 'react-test-renderer'; import { Router } from 'react-router-dom'; import wait from 'waait'; import { MockedProvider } from '@apollo/react-testing'; import { Provider } from 'react-redux'; import configureMockStore from 'redux-mock-store'; import Dashboard from './Dashboard'; import { START_GET_RUNNING_DATA, STOP_GET_RUNNING_DATA, GET_RUNNING_DATA_SUBSCRIPTION, } from './queries'; const mockStore = configureMockStore([thunk]); const serialNumber = 'AL3286wefnnsf'; describe('Dashboard page', () => { let store: any; const fakeHistory = createMemoryHistory(); const mocks = [ { request: { query: START_GET_RUNNING_DATA, variables: { serialNumber, }, }, result: { data: { startFetchingRunningData: { startedFetch: true, }, }, }, }, { request: { query: GET_RUNNING_DATA_SUBSCRIPTION, }, result: { data: { onLastPowerUpdate: { result1: 'string', result2: 'string' }, }, }, }, { request: { query: STOP_GET_RUNNING_DATA, }, result: { data: { startFetchingRunningData: { startedFetch: false, }, }, }, }, ]; afterEach(() => { jest.resetAllMocks(); }); describe('when initialising', () => { beforeEach(() => { store = mockStore({ user: { serialNumber, token: 'some.token.yeah', hydrated: true, }, }); store.dispatch = jest.fn(); }); it('should show a loading state', async () => { const component = create( <Provider store={store}> <MockedProvider mocks={mocks} addTypename={false}> <Router history={fakeHistory}> <Dashboard /> </Router> </MockedProvider> </Provider>, ); expect(component.root.findAllByType(Heading)[0].props.children).toBe( 'Data loading...', ); }); }); }); Adding another test to wait until the data has been resolved from the mocks passed in, as per the instructions on the last example from the docs for testing useMutation, you have to wait for it. Broken test: it('should run the data', async () => { const component = create( <Provider store={store}> <MockedProvider mocks={mocks} addTypename={false}> <Router history={fakeHistory}> <Dashboard /> </Router> </MockedProvider> </Provider>, ); await wait(0); }); Error the broken test throws: No more mocked responses for the query: subscription OnLastPowerUpdate { Dependencies: "@apollo/react-common": "^3.1.3", "@apollo/react-hooks": "^3.1.3", "@apollo/react-testing": "^3.1.3", Things I've tried already: react-test-renderer / enzyme / @testing-library/react awaiting next tick initialising the client in the test differently Github repo with example: https://github.com/harrylincoln/apollo-subs-testing-issue Anyone out there able to help?
The problem I can see here is that you're declaring the SubscriptionData component inside the Dashboard component so the next time the Dashboard component is re-rendered, the SubscriptionData component will be re-created and you'll see the error message: No more mocked responses for the query: subscription OnLastPowerUpdate I suggest that you take the SubscriptionData component out of the Dashboard component so it will be created only once const SubscriptionData = (): any => { const { data, loading } = useSubscription(GET_RUNNING_DATA_SUBSCRIPTION); if (loading) { return <Heading>Data loading...</Heading>; } const metrics = []; if (data) { console.log('DATA NEVER CALLED IN TEST!'); } return metrics; }; const Dashboard: React.FC<RouteComponentProps & Props> = props => { const userHasProduct = !!props.user.serialNumber; const [startGetRunningData] = useMutation(START_GET_RUNNING_DATA); const [stopGetRunningData] = useMutation(STOP_GET_RUNNING_DATA); useEffect(() => { startGetRunningData({ variables: { serialNumber: props.user.serialNumber }, }); return () => { stopGetRunningData(); }; }, [startGetRunningData, stopGetRunningData, props]); if (!userHasProduct) { return <Redirect to="/enter-serial" />; } return ( <> <Header /> <PageContainer size="midi"> <Panel> <SubscriptionData /> </Panel> </PageContainer> </> ); }; And for the tests you can try something like this: let component; it('should show a loading state', async () => { component = create( <Provider store={store}> <MockedProvider mocks={mocks} addTypename={false}> <Router history={fakeHistory}> <Dashboard /> </Router> </MockedProvider> </Provider>, ); expect(component.root.findAllByType(Heading)[0].props.children).toBe( 'Data loading...', ); await wait(0); }); it('should run the data', async () => { expect( // another test here component.root... ).toBe(); });
Apollo
61,504,500
12
I'm trying to set up a graphcool subscription / websockets as per this tutorial at How To GraphQL but I'm getting the following message: WebSocket connection to 'wss://subscriptions.graph.cool/v1/###' failed: WebSocket is closed before the connection is established. I'm seem to have everything as per the tutorial. Do you have any idea why the websockets connection is not being established? index.js import React from 'react' import ReactDOM from 'react-dom' import App from './components/App' import registerServiceWorker from './registerServiceWorker' import './styles/index.css' import { ApolloProvider, createNetworkInterface, ApolloClient } from 'react-apollo' import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws' import { BrowserRouter } from 'react-router-dom' import { GC_AUTH_TOKEN } from './constants' const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/###' }) const wsClient = new SubscriptionClient('wss://subscriptions.graph.cool/v1/###', { reconnect: true, connectionParams: { authToken: localStorage.getItem(GC_AUTH_TOKEN), } }) const networkInterfaceWithSubscriptions = addGraphQLSubscriptions( networkInterface, wsClient ) networkInterface.use([{ applyMiddleware(req, next) { if (!req.options.headers) { req.options.headers = {} } const token = localStorage.getItem(GC_AUTH_TOKEN) req.options.headers.authorization = token ? `Bearer ${token}` : null next() } }]) const client = new ApolloClient({ networkInterface: networkInterfaceWithSubscriptions }) ReactDOM.render( <BrowserRouter> <ApolloProvider client={client}> <App /> </ApolloProvider> </BrowserRouter> , document.getElementById('root') ) registerServiceWorker() App.js import React, { Component } from 'react' import LinkList from './LinkList' import CreateLink from './CreateLink' import Header from './Header' import Login from './Login' import Search from './Search' import { Switch, Route, Redirect } from 'react-router-dom' class App extends Component { render() { return ( <div className='center w85'> <Header /> <div className='ph3 pv1 background-gray'> <Switch> <Route exact path='/search' component={Search}/> <Route exact path='/' component={LinkList}/> <Route exact path='/create' component={CreateLink}/> <Route exact path='/login' component={Login}/> </Switch> </div> </div> ) } } export default App LinkList.js import React, { Component } from 'react' import Link from './Link' import { graphql, gql } from 'react-apollo' class LinkList extends Component { _updateCacheAfterVote = (store, createVote, linkId) => { const data = store.readQuery({ query: ALL_LINKS_QUERY }) const votedLink = data.allLinks.find(link => link.id === linkId) votedLink.votes = createVote.link.votes store.writeQuery({ query: ALL_LINKS_QUERY, data }) } componentDidMount() { this._subscribeToNewLinks() this._subscribeToNewVotes() } render() { if (this.props.allLinksQuery && this.props.allLinksQuery.loading) { return <div>Loading</div> } if (this.props.allLinksQuery && this.props.allLinksQuery.error) { return <div>Error</div> } const linksToRender = this.props.allLinksQuery.allLinks return ( <div> {linksToRender.map((link, index) => ( <Link key={link.id} updateStoreAfterVote={this._updateCacheAfterVote} index={index} link={link}/> ))} </div> ) } _subscribeToNewLinks = () => { this.props.allLinksQuery.subscribeToMore({ document: gql` subscription { Link(filter: { mutation_in: [CREATED] }) { node { id url description createdAt postedBy { id name } votes { id user { id } } } } } `, updateQuery: (previous, { subscriptionData }) => { const newAllLinks = [ subscriptionData.data.Link.node, ...previous.allLinks ] const result = { ...previous, allLinks: newAllLinks } return result } }) } _subscribeToNewVotes = () => { this.props.allLinksQuery.subscribeToMore({ document: gql` subscription { Vote(filter: { mutation_in: [CREATED] }) { node { id link { id url description createdAt postedBy { id name } votes { id user { id } } } user { id } } } } `, updateQuery: (previous, { subscriptionData }) => { const votedLinkIndex = previous.allLinks.findIndex(link => link.id === subscriptionData.data.Vote.node.link.id) const link = subscriptionData.data.Vote.node.link const newAllLinks = previous.allLinks.slice() newAllLinks[votedLinkIndex] = link const result = { ...previous, allLinks: newAllLinks } return result } }) } } export const ALL_LINKS_QUERY = gql` query AllLinksQuery { allLinks { id createdAt url description postedBy { id name } votes { id user { id } } } } ` export default graphql(ALL_LINKS_QUERY, { name: 'allLinksQuery' }) (LinkList)
Can you add the timeout parameter to your client configuration like this: const wsClient = new SubscriptionClient('wss://subscriptions.graph.cool/v1/###', { reconnect: true, timeout: 30000, connectionParams: { authToken: localStorage.getItem(GC_AUTH_TOKEN), } }) There's a slight mismatch between the subscription-transport-ws client implementation and the Graphcool subscription server implementation how keep-alives are handled, and the long timeout period fixes it. Read this issue on GitHub and this Graphcool feature request for more background information.
Apollo
45,399,751
11
When I call a mutation on my client I get the following warning: writeToStore.js:111 Missing field updateLocale in {} This is my stateLink: const stateLink = withClientState({ cache, resolvers: { Mutation: { updateLocale: (root, { locale }, context) => { context.cache.writeData({ data: { language: { __typename: 'Language', locale, }, }, }); }, }, }, defaults: { language: { __typename: 'Language', locale: 'nl', }, }, }); And this is my component: export default graphql(gql` mutation updateLocale($locale: String) { updateLocale(locale: $locale) @client } `, { props: ({ mutate }) => ({ updateLocale: locale => mutate({ variables: { locale }, }), }), })(LanguagePicker); What am I missing?
I was getting the same warning and solved it by returning the data from the mutation method. updateLocale: (root, { locale }, context) => { const data = { language: { __typename: 'Language', locale, } }; context.cache.writeData({ data }); return data; };
Apollo
48,005,732
11
Is there any reason to use IntrospectionFragmentMatcher to determine concrete types of values returned from interface and union fields? I'm talking about apollo-client. I'm using InMemoryCache with addTypename: true, so the type is known the moment the client gets the response. Meanwhile my console is plagued with warnings like these: The only reason I see the documentation hint at is response validation. But why validate the server-sent response at all? If the server is not worth trusting, validation is useless anyway.
The warnings seem to be a bug in apollo. https://github.com/apollographql/apollo-client/issues/3397
Apollo
50,451,732
11
In 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. Since we can't access such cookie via javascript to know if it is present or not, how does one handle this in react app? My 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. But 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. Is there a common way to handle this authentication process with set up above?
httpOnly just means that the value can't be read by JavaScript. So you make an HTTP request to the server and it will return a response with a Set-Cookie header. Then any future requests will automatically include the cookie. (Just make sure that you set withCredentials or the equivalent.)
Apollo
51,442,150
11
I'm trying Apollo and using the following relevant code: const withQuery = graphql(gql` query ApolloQuery { apolloQuery { data } } `); export default withQuery(props => { const { data: { refetch, loading, apolloQuery }, } = props; return ( <p> <Button variant="contained" color="primary" onClick={async () => { await refetch(); }} > Refresh </Button> {loading ? 'Loading...' : apolloQuery.data} </p> ); }); The 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. According 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? The 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.
I think that you need to specify notifyOnNetworkStatusChange: true in the query options (it's false by default).
Apollo
55,341,558
11
I have a mutation that fires the channel event 'countIncr', but I don't see the active corresponding subscription fire with the event payload. UPDATE: I've made several updates to this posting and now I'm changing the title to be more representative of where I am. I'm getting a graphqlPlayground error "Subscription field must return Async Iterable. Received: undefined" TGRstack reproduction i'm having trouble with: https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/ Working Reproduction without TGRstack: https://github.com/Falieson/fullstack-apollo-subscription-example Frontend: https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/blob/master/counter-ui/src/app/routes/Home/HomePage.tsx const COUNTER_SUBSCRIPTION = gql` subscription onCountIncr { count } ` const Counter = () => ( <Subscription subscription={COUNTER_SUBSCRIPTION} > {({ data, loading }) => { console.log({loading, data}) return loading ? <h1>Loading ...</h1> : data.count ? <h2>Counter: {data.count}</h2> : <h1>Counter Subscription Not Available</h1> }} </Subscription> ) BE Resolvers: https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/blob/master/counter-service/src/gql/Resolvers.ts BE Schema: https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/blob/master/counter-service/src/gql/Schema.ts BE Controller: https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/blob/master/counter-service/src/gql/Counter.ts const count = { resolve: data => { console.log('CounterSub>', {data}) return data }, subscribe: () => pubsub.asyncIterator(['countIncr']) } const CounterSubscriptions = { count } async function countIncr(root: any, args: any, context: any) { const count = Counter.increment() await pubsub.publish('countIncr', count ) console.log('countIncr', '>>>', { count }) return count } Here is the service log after you've run through the #getting started instructions in the Readme.md [FE] GET /favicon.ico 200 2.465 ms - 1551 # WEBCLIENT LOADED [BE] CounterSub> { data: undefined } # SUBSCRIPTION REQUEST [BE] { data: [Object: null prototype] { count: null } } # SUBSCRIPTION RESULT [BE] POST / 200 21.254 ms - 24 [BE] 2019-05-10 11:37:20 [info]: HELLO # APOLLO CLIENT CONNECTED AGAIN (why always 2?) [BE] countIncr >>> { count: 1 } # MUTATION REQUEST [BE] { data: [Object: null prototype] { countIncr: 1 } } # MUTATION RESPONSE [BE] POST / 200 13.159 ms - 25 [BE] countIncr >>> { count: 2 } # MUTATION REQUEST [BE] { data: [Object: null prototype] { countIncr: 2 } } # MUTATION RESPONSE [BE] POST / 200 4.380 ms - 25 UPDATE Incase 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. UPDATE 2 updated code and links in question per latest commit UPDATE 3 Some people have suggested that pubsub should be a single import. I've updated the code but this creates a new error: Error: Apollo Server requires either an existing schema, modules or typeDefs UPDATE 4 numerous 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). "message": "Subscription field must return Async Iterable. Received: undefined" Working Reproduction without TGRstack: https://github.com/Falieson/fullstack-apollo-subscription-example Update 5 I demodularized/decomposed a bunch of things to make it easier to trace whats going on but still getting the same error
I solved this issue in 2 places ApolloServer.installSubscriptionHandler() TEMPORARILY replacing middleware.apolloSubscriptions() . I configure the subscriptions middleware following this guide: https://www.apollographql.com/docs/graphql-subscriptions/express so I'm going to guess there's something messed up w/ the version of one of those packages or the guide itself. ApolloServer.installSubscriptionHandlers(ws) const listener = ws.listen({port: config.PORT}, () => { middleware.apolloSubscriptions(ws) // middleware.apolloSubscriptions(ws) terminatingLink and getMainDefinition are necessary for the client https://github.com/TGRstack/tgr-apollo-subscription-example-microservice/commit/75b6165f2dc1d035a41f1129f7386a1e18c7ba53#diff-2c47ef33b8ed0e4c893cbc161bcf7814R37 private _terminatingLink = split( ({ query }) => { const { kind, operation } = getMainDefinition(query) return ( kind === 'OperationDefinition' && operation === 'subscription' ) }, this._wsLink, this._httpLink, )
Apollo
56,083,422
11
I use the useQuery Hook like this: function Foo() { const { data, error, loading } = useQuery(MY_QUERY, { pollInterval: 1000 }); return ( <> <Bar/> <Baz/> {data} </> ); } Now, both Bar and Baz use the same query. Baz is a sidebar and I'd like to disable the polling while it is active. I have a global reducer for handling the state of Baz and I modified it like this: if (isSidebarOpen === false) { ... apolloClient.stop(); } else { // TODO } This stops the polling, but I don't know how to reactivate it when the sidebar gets closed (that is, in the else block above). Am I doing this correctly? Is there a different way to toggle the polling of a GraphQL query with Apollo?
You can start and stop polling dynamically with the startPolling and stopPolling functions that are returned by the useQuery hook. For more information, you can see the docs here.
Apollo
58,673,815
11
I have loop - forEach - which find productId for every element of array. I want to fetch my database by productId using apollo query. How to do it? products.forEach(({ productId, quantity }) => // fetch by 'productId' );
From the rules of hooks: Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. Hooks cannot be used inside a loop, so you can't use them inside a forEach callback. You should create a separate component for each product that only uses the useQuery hook once. You can then map over the products and return the component for each one: const YourComponent = () => { ... return products.map(({ productId, quantity }) => ( <Product key={productId} productId={productId} quantity={quantity} /> )) } const Product = () => { const { data, error, loading } = useQuery(...) // render your data accordingly }
Apollo
60,830,193
11
I am struggling to understand the added value of Express (or Koa, Hapi, etc) integration with Apollo GraphQL server. I see it can work in stand alone mode very well (an example: https://medium.com/codingthesmartway-com-blog/apollo-server-2-introduction-efc4026f5654). In which case should we use it with (or without) integration? What should drive this decision?
If all you need is a GraphQL endpoint, then using the standalone library (apollo-server) is generally preferred because there will be less boilerplate to write (features like subscriptions, file uploads, etc. just work without additional configuration). However, many applications require additional functionality beyond just exposing a single API endpoint. Examples include: Webhooks OAuth callbacks Session management Cookie parsing CSRF protection Monitoring or logging requests Rate limiting Geofencing Serving static content Server-side rendering If you need this sort of functionality for your application, then you'll want to utilize an HTTP framework like Express and then use the appropriate integration library (i.e. apollo-server-express). Apollo Server also includes integrations for serverless solutions AWS Lambda. If you want to go serverless to, for example, get better scalability or eliminate system admin costs, then you would also need to use one of these integrations.
Apollo
61,615,755
11
I'm working on testing an Apollo Server RESTDataSource using Jest. My app is written in TypeScript. My class, CDCDataSource extends the abstract class RESTDataSource which itself extends the abstract class DataSource. RESTDataSource has the method get which allows you to pull data from an external REST data source. It is this method I wish to mock, since I wish to mock the external data source. protected async get<TResult = any>( path: string, params?: URLSearchParamsInit, init?: RequestInit, ): Promise<TResult> { return this.fetch<TResult>( Object.assign({ method: 'GET', path, params }, init), ); } However, when I try to mock this method using Jest's spyOn -- following the second answer here: Jest: How to mock one specific method of a class -- import CDCDataSource from '../CDCDataSource'; test('Test', () => { let dataSource = new CDCDataSource(); let spy = jest.spyOn(dataSource, 'get').mockImplementation(() => 'Hello'); expect(dataSource.get()).toBe('Hello'); However, I get the TypeScript error TS2768: No overload matches this call over the get in jest.spyOn(dataSource,'get') and I get over the get in expect(dataSource.get()).toBe('Hello'); So it would seem that part of the issue is that this is a protect method -- I'm unclear how to test this method so as to be able to mock the API. My tsconfig.json is { "compilerOptions": { "target": "ES6", "lib": [ "esnext", "dom" ], "skipLibCheck": true, "outDir": "dist", "strict": false, "forceConsistentCasingInFileNames": true, "esModuleInterop": true, "module": "commonjs", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "sourceMap": true, "alwaysStrict": true, }, "exclude": [ "node_modules" ] } This is a Node Apollo Server project (using Node 12.14.0 and TypeScript 3.8.3) Thanks for any clues!
You are trying to access a protected method. If you don't want to or can't rearchitect your class, you can use ts-ignore to suppress the error. // @ts-ignore` let spy = jest.spyOn(dataSource, 'get').mockImplementation(() => 'Hello'); Or you can extend the original class, with a class made only for testing, that will have a public method that will just proxy to the protected method. test('Protected method',()=>{ class Test extends OriginalClass { testProtected(){ super.protectedMethod() } } let dataSource = new Test(); let spy = jest.spyOn(dataSource, 'testProtected').mockImplementation(() => 'Hello'); })
Apollo
62,026,238
11
I have a page that consists of 2 components and each of them has its own request for data for example <MovieInfo movieId={queryParamsId}/> const GET_MOVIE_INFO = `gql query($id: String!){ movie(id: $id){ name description } }` Next component <MovieActors movieId={queryParamsId}/> const GET_MOVIE_ACTORS = `gql query($id: String!){ movie(id: $id){ actors } }` For each of these queries I use apollo hook const { data, loading, error } = useQuery(GET_DATA, {variable: {id: queryParamsId}})) Everything is fine, but I got a warning message: Cache data may be lost when replacing the movie field of a Query object. To 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: { ... } It'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?
Here is the same solution mentioned by Thomas but a bit shorter const cache = new InMemoryCache({ typePolicies: { Query: { fields: { YOUR_FIELD: { // shorthand merge: true, }, }, }, }, }); This is same as the following const cache = new InMemoryCache({ typePolicies: { Query: { fields: { YOUR_FIELD: { merge(existing, incoming, { mergeObjects }) { return mergeObjects(existing, incoming); }, }, }, }, }, });
Apollo
63,123,558
11
I have a need to create a server farm that can handle 5+ million connections, 5+ million topics (one per client), process 300k messages/sec. I tried to see what various message brokers were capable so I am currently using two RHEL EC2 instances (r3.4xlarge) to make lots of available resources. So you do not need to look it up, it has 16vCPU, 122GB RAM. I am nowhere near that limit in usage. I am unable to pass the 600k connections limit. Since there doesn't seem to be any O/S limitation (plenty of RAM/CPU/etc.) on either the client nor the server what is limiting me? I have edited /etc/security/limits.conf as follows: * soft nofile 20000000 * hard nofile 20000000 * soft nproc 20000000 * hard nproc 20000000 root soft nofile 20000000 root hard nofile 20000000 I have edited /etc/sysctl.conf as follows: net.ipv4.ip_local_port_range = 1024 65535 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_mem = 5242880 5242880 5242880 net.ipv4.tcp_tw_recycle = 1 fs.file-max = 20000000 fs.nr_open = 20000000 net.ipv4.tcp_syncookies = 0 net.ipv4.tcp_max_syn_backlog = 10000 net.ipv4.tcp_synack_retries = 3 net.core.somaxconn=65536 net.core.netdev_max_backlog=100000 net.core.optmem_max = 20480000 For Apollo: export APOLLO_ULIMIT=20000000 For ActiveMQ: ACTIVEMQ_OPTS="$ACTIVEMQ_OPTS -Dorg.apache.activemq.UseDedicatedTaskRunner=false" ACTIVEMQ_OPTS_MEMORY="-Xms50G -Xmx115G" I created 20 additional private addresses for eth0 on the client, then assigned them: ip addr add 11.22.33.44/24 dev eth0 I am FULLY aware of the 65k port limits which is why I did the above. For ActiveMQ I got to: 574309 For Apollo I got to: 592891 For Rabbit I got to 90k but logging was awful and couldn't figure out what to do to go higher although I know its possible. For Hive I got to trial limit of 1000. Awaiting a license IBM wants to trade the cost of my house to use them - nah!
ANSWER: While doing this I realized that I had a misspelling in my client setting within /etc/sysctl.conf file for: net.ipv4.ip_local_port_range I am now able to connect 956,591 MQTT clients to my Apollo server in 188sec. More info: Trying to isolate if this is an O/S connection limitation or a Broker, I decided to write a simple Client/Server. The server: Socket client = null; server = new ServerSocket(1884); while (true) { client = server.accept(); clients.add(client); } The Client: while (true) { InetAddress clientIPToBindTo = getNextClientVIP(); Socket client = new Socket(hostname, 1884, clientIPToBindTo, 0); clients.add(client); } With 21 IPs, I would expect 65535-1024*21 = 1354731 to be the boundary. In reality I am able to achieve 1231734 [root@ip ec2-user]# cat /proc/net/sockstat sockets: used 1231734 TCP: inuse 5 orphan 0 tw 0 alloc 1231307 mem 2 UDP: inuse 4 mem 1 UDPLITE: inuse 0 RAW: inuse 0 FRAG: inuse 0 memory 0 So the socket/kernel/io stuff is worked out. I am STILL unable to achieve this using any broker. Again just after my client/server test this is the kernel settings. Client: [root@ip ec2-user]# sysctl -p net.ipv4.ip_local_port_range = 1024 65535 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_mem = 5242880 5242880 15242880 net.ipv4.tcp_tw_recycle = 1 fs.file-max = 20000000 fs.nr_open = 20000000 [root@ip ec2-user]# cat /etc/security/limits.conf * soft nofile 2000000 * hard nofile 2000000 root soft nofile 2000000 root hard nofile 2000000 Server: [root@ ec2-user]# sysctl -p net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_mem = 5242880 5242880 5242880 net.ipv4.tcp_tw_recycle = 1 fs.file-max = 20000000 fs.nr_open = 20000000 net.ipv4.tcp_syncookies = 0 net.ipv4.tcp_max_syn_backlog = 1000000 net.ipv4.tcp_synack_retries = 3 net.core.somaxconn = 65535 net.core.netdev_max_backlog = 1000000 net.core.optmem_max = 20480000
Apollo
29,358,313
10
I'm using the Apollo Stack with graphql-server-express and apollo-client. Because my backend is not perfect errors can appear and therefore I have to respond to a request with an error for that path. Till now my main problem was authentication and therefore I responded with an error. return new Error(`${data.status}: ${data.statusText} @ ${data.url}`) In the frontend I use apollo-client to query data. return apollo .query({query: gql` query { ${query} }`, forceFetch: forceFetch }) .then(result => { debugger; return result.data }) .catch(error => { debugger; console.error(error); }); But if one property of the query responds with an error, only the catch function will be invoked. Even 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. My attempt works fine with GraphiQL where I get the errors and data in the same object. So how can I throw errors for a property without loosing the whole request?
You could manually look for result.error in the then part of your promise and avoid the use of catch. Also I think you could also add a then after the catch call to handle this specific case. In addition to that, you can also use formatError in your GraphQL server to manually filter and format error messages. The body of that function is the following, and you have access to the thrown Error. formatError: (error) => { return { name: error.name, mensaje: error.message } }
Apollo
41,852,880
10
Can 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: query ProductInCartQuery($id: ID!){ Product(id: $id) { id name price } } But I don't think I can just put it in a function and execute it for example three times for three products.
It's common and very useful to offer two kind of queries for every type you have: a query to fetch a single node with an id or other unique fields, that's in your case Product (you already have this). a query to fetch many nodes depending on different filter conditions, let's call it allProducts. Then you have two options to fetch multiple products in one query. First, you can use the Product query multiple times and use GraphQL Aliases to avoid a name clash in the response data: query ProductInCartQuery($firstId: ID!, $secondId: ID!){ firstProduct: Product(id: $firstId) { id ... ProductInfo } secondProduct: Product(id: $secondId) { id ... ProductInfo } fragment ProductInfo on Product { name price } } You could build this query string dynamically depending on the ids you want to query. However, it's probably best to use the allProducts query with the necessary filter setup if the number of differents ids is dynamic: query filteredProducts($ids: [ID!]!) { allProducts(filter: { id_in: $ids }) { ... ProductInfo } } fragment ProductInfo on Product { name price } You can try it out yourself in this GraphQL Playground I prepared for you. More background information can be found in this article.
Apollo
44,435,510
10
I'm using react-apollo to build a client that consumes a GraphQL API, however, I'm very stuck on testing. What I want is to mock the server so I can easily test the application without needing to make network calls. I've found some pointers on how to mock the server: https://dev-blog.apollodata.com/mocking-your-server-with-just-one-line-of-code-692feda6e9cd http://dev.apollodata.com/tools/graphql-tools/mocking.html#addMockFunctionsToSchema But there isn't really an example on how to use this mocked server in my app tests to avoid hitting the server. My goal is to setup integration tests to assert that the app is actually working: describe('Profile feature', () => { beforeAll(() => { store = setupStore(); app = mount( <ApolloProvider store={store} client={apolloClient}> <ConnectedRouter history={history}> <App /> </ConnectedRouter> </ApolloProvider> ); }); }); The store is using Redux and the client is being created like this: const networkInterface = createNetworkInterface({ uri: process.env.REACT_APP_API_URL }); export const apolloClient = new ApolloClient({ networkInterface }); How can I use a mocked server with graphql-tools here instead of the actual API?
I found 2 different ways of creating mocked data for apollo-client queries: The first is to use graphql-tools to create a mocked server based on your backend schema, in order to connect this mocked server with your tests it's possible to create a mockNetworkInterface like this: const { mockServer } = require("graphql-tools"); const { print } = require("graphql/language/printer"); class MockNetworkInterface { constructor(schema, mocks = {}) { if (schema === undefined) { throw new Error('Cannot create Mock Api without specifying a schema'); } this.mockServer = mockServer(schema, mocks); } query(request) { return this.mockServer.query(print(request.query), request.variables); } } You can pass this network interface to the ApolloClient component and it should work just fine! Having this setup requires to have your API schema up to date in your client, so I found it a bit of a pain to do. Another way of doing this is using the mockNetworkInterface provided by apollo-client/test-utils You can use it this way: import App from './App'; import { UserMock, PublicationMock } from '../__mocks__/data'; import { mockNetworkInterface } from 'react-apollo/test-utils'; import ApolloClient from 'apollo-client'; import { ApolloProvider } from 'react-apollo'; // We will be using here the exact same Query defined in our components // We will provide a custom result or a custom error const GraphQLMocks = [ { request: { query: UserProfileQuery, variables: {} }, result: { data: { current_user: UserMock } } } ]; // To set it up we pass the mocks to the mockNetworkInterface const setupTests = () => { const networkInterface = mockNetworkInterface.apply(null, GraphQLMocks); const client = new ApolloClient({ networkInterface, addTypename: false }); const wrapper = mount( <ApolloProvider client={client}> <App /> </ApolloProvider> ); return { store, wrapper }; }; // Then the tests look like this describe('Profile feature', () => { test('Profile view should render User details', async () => { const { wrapper, store } = setupTests(); const waitFor = createWaitForElement('.profile'); await waitFor(wrapper); const tag = wrapper.find('.profile-username'); expect(tag.text()).toEqual(`${UserMock.first_name} ${UserMock.last_name}`); }); }); It is important to pass addTypename: false to the ApolloClient instance, otherwise you will need to add __typename to all your queries manually. You can inspect the implementation of the mockNetworkInterface here: https://github.com/apollographql/apollo-test-utils/blob/master/src/mocks/mockNetworkInterface.ts
Apollo
45,700,550
10
Background We are working on a fairly large Apollo project. A very simplified version of our api looks like this: type Operation { foo: String activity: Activity } type Activity { bar: String # Lots of fields here ... } We'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: type Operation { foo: String bar: String activity: Activity @deprecated } type Activity { bar: String @deprecated(reason: "Use Operation.bar instead") # Lots of fields here ... } Actual question Is 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?
GraphQL schema directives can be customized. So below is a solution that prints a warning on the server (Edit 2023: And here's a plugin that propagates the warning to the client): import { SchemaDirectiveVisitor } from "graphql-tools" import { defaultFieldResolver } from "graphql" import { ApolloServer } from "apollo-server" class DeprecatedDirective extends SchemaDirectiveVisitor { public visitFieldDefinition(field ) { field.isDeprecated = true field.deprecationReason = this.args.reason const { resolve = defaultFieldResolver, } = field field.resolve = async function (...args) { const [_,__,___,info,] = args const { operation, } = info const queryName = operation.name.value // eslint-disable-next-line no-console console.warn( `Deprecation Warning: Query [${queryName}] used field [${field.name}] Deprecation reason: [${field.deprecationReason}]`) return resolve.apply(this, args) } } public visitEnumValue(value) { value.isDeprecated = true value.deprecationReason = this.args.reason } } new ApolloServer({ typeDefs, resolvers, schemaDirectives: { deprecated: DeprecatedDirective, }, }).listen().then(({ url, }) => { console.log(`🚀 Server ready at ${url}`) })
Apollo
47,056,844
10
I have a App component that I am wrapping into a apollo provider: import React, { Component } from "react"; import { observer, Provider } from "mobx-react"; import { BrowserRouter as Router } from "react-router-dom"; import styled from "styled-components"; import { ThemeProvider } from "styled-components"; // graphQL import { ApolloClient } from "apollo-client"; import { createHttpLink } from "apollo-link-http"; import { setContext } from "apollo-link-context"; import { InMemoryCache } from "apollo-cache-inmemory"; import Main from "./components/Main/Main"; import Navigation from "./components/Navigation/Navigation"; import { ApolloProvider } from "react-apollo"; const httpLink = createHttpLink({ uri: "myUri" }); const authLink = setContext((_, { headers }) => { // get the authentication token from local storage if it exists const token = "myToken"; // return the headers to the context so httpLink can read them return { headers: { ...headers, authorization: token ? `Bearer ${token}` : null } }; }); const mozaikClient = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache() }); @observer class App extends Component { render() { return ( <ThemeProvider theme={theme}> <ApolloProvider client={mozaikClient}> <Provider {...this.props.stores}> <Router> <div className="app-container"> <Navigation /> <Main /> </div> </Router> </Provider> </ApolloProvider> </ThemeProvider> ); } } export default App; Then I have the About component that I want to consume the provider data: import React, { Component } from "react"; import { gql, graphql } from "react-apollo"; class About extends Component { render() { return <div>About component.</div>; } } const landingPageQuery = gql` query landingPage { documents(types: [LANDING]) { items { id ... on LandingDocument { landingPortrait { id url } greeting content } } } } `; export default graphql(landingPageQuery)(About); I am getting the following error: About.js:10 Uncaught TypeError: Object(...) is not a function at Object../src/components/About/About.js (About.js:10) at webpack_require (bootstrap 9e0e85e19ef23447e3e2:669) at fn (bootstrap 9e0e85e19ef23447e3e2:87) at Object../src/components/Main/routes.js (routes.js:1) at webpack_require (bootstrap 9e0e85e19ef23447e3e2:669) at fn (bootstrap 9e0e85e19ef23447e3e2:87) at Object../src/components/Main/Main.js (Contact.js:4) at webpack_require (bootstrap 9e0e85e19ef23447e3e2:669) at fn (bootstrap 9e0e85e19ef23447e3e2:87) at Object../src/App.js (zen-observable.js:498) at webpack_require (bootstrap 9e0e85e19ef23447e3e2:669) at fn (bootstrap 9e0e85e19ef23447e3e2:87) at Object../src/index.js (Skills.js:4) at webpack_require (bootstrap 9e0e85e19ef23447e3e2:669) at fn (bootstrap 9e0e85e19ef23447e3e2:87) at Object.0 (styleVariables.js:17) at webpack_require (bootstrap 9e0e85e19ef23447e3e2:669) at bootstrap 9e0e85e19ef23447e3e2:715 at bundle.js:719 Where and why is this error coming from, and what does it mean? It is pointing to the line where I am defining my query using gql
This seems like a known issue - see here. Try installing graphql-tag and importing gql from this library.
Apollo
47,367,601
10
I have this code: https://codesandbox.io/s/507w9qxrrl I don't understand: 1) How to re-render() Menu component after: this.props.client.query({ query: CURRENT_USER_QUERY, fetchPolicy: "network-only" }); If I login() I expect my Menu component to re-render() itself. But nothing. Only if I click on the Home link it re-render() itself. I suspect because I'm using this to render it: <Route component={Menu} /> for embrace it in react-router props. Is it wrong? Plus, if inspect this.props of Menu after login() I see loading: true forever. Why? 2) 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: export default graphql(CURRENT_USER_QUERY)(Menu); 3) Is this the right way to go?
First, let me answer your second question: You can skip an operation using the skip query option. export default graphql(CURRENT_USER_QUERY, { skip: () => !localStorage.get("auth_token"), })(Menu); The problem now is how to re-render this component when the local storage changes. Usually react does not listen on the local storage to trigger a re-render, instead a re-render is done using one of this three methods: The component's state changes The parent of the component re-renders (usually with new props for the child) forceUpdate is called on the component (Note that also a change of a subscribed context will trigger a re-render but we don't want to mess around with context ;-)) You might want to go with a combination of 2. and 3. or 1. and 2. In your case it can be enough to change the route (as you do in the login function). If this does not work you can call this.forceUpdate() on the App component after Login using a callback property on <Login onLogin={() => this.forceUpdate() } />.
Apollo
47,655,399
10
I'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. I 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 follow the parent/child theme where parent queries include children fragments. Also in large projects you end up traversing long file paths when importing. I 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. This works: class CommentListItem extends Component { static fragments = { comment: gql` #... `, } } class CommentList extends Component { static fragments = { comment: gql` #... ${CommentListItem.fragments.comment} `, } } class CommentsPage extends Component { static fragments = { comment: gql` #... ${CommentList.fragments.comment} `, } } graphql(gql` query Comments { comments { ...CommentsListItemComment } } ${CommentsPage.fragments.comment} `) However, if I want a mutation in a descendent of CommentsPage I can't reference the fragment composition from CommentsPage.fragments.comment. Is there a preferred method or best practice for this type of thing?
Structuring Queries How to structure your code is always a matter of a personal taste but I think the collocation of queries and components is a big strength of GraphQL. For queries I took a lot of inspiration from Relay Modern and the solution looks very close to what you described in the code. Right now as the project becomes bigger and we want to generate Flow type definitions for our queries, putting them into separate files next to the component files is also an option. This will be very similar to CSS-modules. Structuring Mutations When it comes to mutations it often gets much harder to find a good place for them. Mutations need to be called on events far down the component tree and often change the state of the application in multiple states of the app. In this case you want the caller to be unaware of the data consumers. Using fragments might seem like an easy answer. The mutation would just include all fragments that are defined for a specific type. While the mutation now does not need to know which fields are required it needs to know who requires fields on the type. I want to point out two slightly different approaches that you can use to base your design on. Global Mutations: The Relay Approach In Relay Modern Mutations are basically global operations, that can be triggered by any component. This approach is not to bad since most mutations are only written once and thanks to variables are very reusable. They operate on one global state and don't care about which UI part consumes the update. When defining a mutation result you should usually query the properties that might have changed by the mutation instead of all the properties that are required by other components (through fragments). E.g. the mutation likeComment(id: ID!) should probably query for the likeCount and likes field on comment and not care much if any component uses the field at all or what other fields components require on Comment. This approach gets a bit more difficult when you have to update other queries or fields. the mutation createComment(comment: CreateCommentInput) might want to write to the root query object's comments field. This is where Relays structure of nodes and edges comes in handy. You can learn more about Relay updates here. # A reusable likeComment mutation mutation likeComment($id: ID!) { likeComment(id: $id) { comment { id likeCount likes { id liker { id name } } } } } Unfortunately we cannot answer one question: How far should we go? Do I need the names of the people liking the comments or does the component simply display a number of likes? Mutations in Query Container Not all GraphQL APIs are structured the Relay way. Furthermore Apollo binds mutations to the store similar to Redux action creators. My current approach is to have mutations on the same level as queries and then passing them down. This way you can access the children's fragments and use them in the mutations if needed. In your example the CommentListItem component might display a like button. It would define a fragment for the data dependencies, prop types according to the fragment and a function prop type likeComment: (id: string) => Promise<any>. This prop type would be passed through to the query container that wraps the CommentsPage in a query and mutation. Summary You can use both approaches with Apollo. A global mutations folder can contain mutations that can be used anywhere. You can then directly bind the mutations to the components that need them. One benefit is that e.g. in the likeComment example the variable id can be directly derived from the components props and does not need to be bound within the component itself. Alternatively you can pass mutations through from you query components. This gives you a broader overview of the consumers of data. In the CommentsPage it can be easier to decide what needs to be updated when a mutation completed. Let me know what you think in the comments!
Apollo
48,017,187
10
Let's imagine I have a createPost mutation that inserts a new post. In a typical app, that mutation can either: Succeed, returning a Post. Fail, throwing an error (I use apollo-errors to handle this). What 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). What 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? (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)
All my mutations return a wrapping payload type rather than a single value type (e.g. Post in your case), I also don't ever throw in GraphQL unless it's a real system error -- if it's the consequence of user input or is an otherwise expected case, I model it into the return type. Returning a wrapping payload is generally considered a best practice because a) your mutation should return entry points for everything in the graph that may have changed (not just the new post), and b) it gives you the easy ability to add new fields to the return type at a later time. Remember, a mutation is essentially a function that takes in some input data and the current graph, and returns a new graph. It's generally a mistake to think in terms of REST-like CRUD operations. type CreatePostError = { // Whatever you want } type CreatePostSuccess = { post: Post! warning: String } union CreatePostPayload = CreatePostSuccess | CreatePostError mutation { // Other mutations createPost(/* args /*): CreatePostPayload }
Apollo
49,868,843
10
Reaching 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 follow (I'll copy just a part): type Calculation { _id: String! userId: String! data: CalculationData lastUpdated: Int name: String } type CalculationData { Loads: [Load] validated: Boolean x: Float y: Float z: Float Inputs: [Input] metric: Boolean } Then Inputs and Loads are defined, and so on... For this I want a mutation to save the "Calculation", so in the same file I have this: type Mutation { saveCalculation(data: CalculationData!, name: String!): Calculation } My resolver is as follow: export default resolvers = { Mutation: { saveCalculation(obj, args, context) { if(context.user && context.user._id){ const calculationId = Calculations.insert({ userId: context.user._id, data: args.data, name: args.name }) return Calculations.findOne({ _id: calculationId}) } throw new Error('Need an account to save a calculation') } } } Then my mutation is the following : import gql from 'graphql-tag'; export const SAVE_CALCULATION = gql` mutation saveCalculation($data: CalculationData!, $name: String!){ saveCalculation(data: $data, name: $name){ _id } } ` Finally I am using the Mutation component to try to save the data: <Mutation mutation={SAVE_CALCULATION}> {(saveCalculation, { data }) => ( <div onClick={() => saveCalculation({ variables : { data: this.state, name:'name calcul' }})}>SAVE</div> }} </Mutation> Now I get the following error : [GraphQL error]: Message: The type of Mutation.saveCalculation(data:) must be Input Type but got: CalculationData!., Location: undefined, Path: undefined From 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.
From the spec: Fields may accept arguments to configure their behavior. These inputs are often scalars or enums, but they sometimes need to represent more complex values. A GraphQL Input Object defines a set of input fields; the input fields are either scalars, enums, or other input objects. This allows arguments to accept arbitrarily complex structs. In other words, you can't use regular GraphQLObjectTypes as the type for an GraphQLInputObjectType field -- you must use another GraphQLInputObjectType. When you write out your schema using SDL, it may seem redundant to have to create a Load type and a LoadInput input, especially if they have the same fields. However, under the hood, the types and inputs you define are turned into very different classes of object, each with different properties and methods. There is functionality that is specific to a GraphQLObjectType (like accepting arguments) that doesn't exist on an GraphQLInputObjectType -- and vice versa. Trying to use in place of another is kind of like trying to put a square peg in a round hole. "I don't know why I need a circle. I have a square. They both have a diameter. Why do I need both?" Outside of that, there's a good practical reason to keep types and inputs separate. That's because in plenty of scenarios, you will expose plenty of fields on the type that you won't expose on the input. For example, your type might include derived fields that are actually a combination of the underlying data. Or it might include fields to relationships with other data (like a friends field on a User). In both these case, it wouldn't make sense to make these fields part of the data that's submitted as as argument for some field. Likewise, you might have some input field that you wouldn't want to expose on its type counterpart (a password field comes to mind).
Apollo
52,744,900
10
In a react login component, I'd like to refetch and update the navbar component once login is successful. const loginUser = () => { props.mutate({ variables: { input: { email, password }, }, refetchQueries: [{ query: GET_ME }], }); }; I can see the login and re-fetch in network tab, and both return 200 with proper status. But the navbar still displays the old data. Here is my navbar component. export const Header = props => { return <div>Header {JSON.stringify(props.data)}</div>; }; export default graphql(GET_ME)(Header); And apolloClient: export const client = new ApolloClient({ link: createHttpLink({ credentials: 'include', uri: 'http://localhost:8080/api/graphql', }), cache: new InMemoryCache(), });
Try adding options: { awaitRefetchQueries: true }, to your props.mutate next to refetchQueries and variables. Queries refetched using options.refetchQueries are handled asynchronously, which means by default they are not necessarily completed before the mutation has completed. Setting options.awaitRefetchQueries to true will make sure refetched queries are completed before the mutation is considered done (or resolved). options.awaitRefetchQueries is false by default.
Apollo
53,474,637
10
Getting this error from Apollo: core.js:14576 ERROR Error: Network error: Error writing result to store for query: {"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}} Store 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: {"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"}}]}} at new ApolloError (ApolloError.js:25) at QueryManager.js:276 at QueryManager.js:638 at Array.forEach (<anonymous>) at QueryManager.js:637 at Map.forEach (<anonymous>) at QueryManager.push../node_modules/apollo-client/core/QueryManager.js.QueryManager.broadcastQueries (QueryManager.js:632) at QueryManager.js:226 at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391) at Object.onInvoke (core.js:16135) This is the code that makes this happen: this.restaurantID$.pipe( takeUntil(this._ngOnDestroy) ) .subscribe((restaurantID) => { this.additionalServicesQuery$.next(this._apollo .watchQuery<AdditionalServices>({ query: AdditionalServicesQuery, variables: { vendorID: restaurantID } })); }); const loadAdditionalServicesData = this.additionalServicesQuery$ .pipe( takeUntil(this._ngOnDestroy), filter((query) => !!query), switchMap((query) => query.valueChanges), // This is the switchMap that makes it happen takeUntil(this._ngOnDestroy), map((response) => response.data.vendor.services.nodes) ); There is a SwitchMap that I commented if that is removed, the error does not happen. I can't understand what is going on. query: export const AdditionalServicesQuery = gql` query AdditionalServices( $vendorID: ID! ) { vendor( id: $vendorID ) { services: products (productTypes: service) { nodes { id isActive cartSection { id name } description imageUrl shortDescription name } } } } `; Update: Added ID to query, still, same issue export const AdditionalServicesQuery = gql` query AdditionalServices( $vendorID: ID! ) { vendor( id: $vendorID ) { services: products (productTypes: service) { id nodes { id isActive cartSection { id name } description imageUrl shortDescription name } } } } `;
According to that error, you need to add an id field (or _id field, whichever exists) to the selection set for the vendor field. Sounds like you already have another query that returns objects of the type Restaurant, that query included the id and was normalized properly. Apollo won't be able to combine the individual Restaurant objects from both queries unless an id is included. export const AdditionalServicesQuery = gql` query AdditionalServices( $vendorID: ID! ) { vendor( id: $vendorID ) { id # <----------------------------------------- ADD ME services: products (productTypes: service) { nodes { id isActive cartSection { id name } description imageUrl shortDescription name } } } } `;
Apollo
55,008,651
10
I am using Strapi with Nuxt.js to implement my first Headless CMS. I am using Apollo and GraphQL. I am running into the current error and I've had no luck to figure this out for days. If I write: query Page($id: ID!) { page(id: $id) { id slug title } } And pass the following variable: { "id" : "1" } I received the correct expected result: { "data": { "page": { "id": "1", "slug": "/", "title": "Homepage" } } } HOWEVER, I would like to get the content not via ID, but via a field that I created in Strapi, called "slug". Looking around, it seems like I should be able to do something like: query Page($slug: String!) { page(slug: $slug) { id slug title } } With variable: { "slug" : "/" } but I receive this error: { "error": { "errors": [ { "message": "Unknown argument \"slug\" on field \"page\" of type \"Query\".", "locations": [ { "line": 2, "column": 8 } ], "extensions": { "code": "GRAPHQL_VALIDATION_FAILED", "exception": { "stacktrace": [ ... the error continues.... [UPDATE] After Italo replied, I changed it into: query Pages($slug: String!) { page(where: {slug: $slug}) { id slug title } } But I now get the following error: { "error": { "errors": [ { "message": "Unknown argument \"where\" on field \"page\" of type \"Query\".", I also noticed that I get a query if I change "page" into "pages", but it shows all of the pages... What am I missing? Thanks!
To query one item using something other than the primary key (and using just the default built-in queries from Strapi), you need to use the filters avaiable as a where clause: query Pages($slug: String!) { pages(where: {slug: $slug}) { id slug title } } Notice I'm using the endpoint Pages instead of Page, so this will return an array. Check the filters section here: https://strapi.io/documentation/3.0.0-alpha.x/guides/graphql.html#configurations Tip: use the Graphql interface avaiable in http://localhost:1337/graphql to test that. (if you are not already)
Apollo
59,738,496
10
I'm making unit tests for React components using apollo hooks (useQuery, useMutation), and in the tests I mock the actual queries with apollo's MockedProvider. The problem is that sometimes, my mock doesn't match the query actually made by the component (either a typo when creating the mock, or the component evolves and changes some query variables). When this happens, MockedProvided returns a NetworkError to the component. However in the test suite, no warning is displayed. This is frustrating, because sometimes my components do nothing with the error returned by useQuery. This cause my tests, which used to pass, to suddenly fail silently, and gives me a hard time to find the cause. This is an example of component using useQuery : import React from 'react'; import {gql} from 'apollo-boost'; import {useQuery} from '@apollo/react-hooks'; export const gqlArticle = gql` query Article($id: ID){ article(id: $id){ title content } } `; export function MyArticleComponent(props) { const {data} = useQuery(gqlArticle, { variables: { id: 5 } }); if (data) { return ( <div className="article"> <h1>{data.article.title}</h1> <p>{data.article.content}</p> </div> ); } else { return null; } } And this is a unit test, in which I made a mistake, because the variables object for the mock is {id: 6} instead of {id: 5} which will be requested by the component. it('the missing mock fails silently, which makes it hard to debug', async () => { let gqlMocks = [{ request:{ query: gqlArticle, variables: { /* Here, the component calls with {"id": 5}, so the mock won't work */ "id": 6, } }, result: { "data": { "article": { "title": "This is an article", "content": "It talks about many things", "__typename": "Article" } } } }]; const {container, findByText} = render( <MockedProvider mocks={gqlMocks}> <MyArticleComponent /> </MockedProvider> ); /* * The test will fail here, because the mock doesn't match the request made by MyArticleComponent, which * in turns renders nothing. However, no explicit warning or error is displayed by default on the console, * which makes it hard to debug */ let titleElement = await findByText("This is an article"); expect(titleElement).toBeDefined(); }); How can I display an explicit warning in the console ?
I have submitted a Github issue to the apollo team, in order to suggest a built-in way to do this. Meanwhile, this is my homemade solution. The idea is to give the MockedProvider a custom apollo link. By default, it uses MockLink initialized with the given mocks. Instead of this, I make a custom link, which is a chain formed of a MockLink that I create the same way MockedProvider would make it, followed by an apollo error link, which intercepts errors that may be returned by the request, and log them in the console. For this I create a custom provider MyMockedProvider. MyMockedProvider.js import React from 'react'; import {MockedProvider} from '@apollo/react-testing'; import {MockLink} from '@apollo/react-testing'; import {onError} from "apollo-link-error"; import {ApolloLink} from 'apollo-link'; export function MyMockedProvider(props) { let {mocks, ...otherProps} = props; let mockLink = new MockLink(mocks); let errorLoggingLink = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) graphQLErrors.map(({ message, locations, path }) => console.log( `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`, ), ); if (networkError) console.log(`[Network error]: ${networkError}`); }); let link = ApolloLink.from([errorLoggingLink, mockLink]); return <MockedProvider {...otherProps} link={link} />; } MyArticleComponent.test.js import React from 'react'; import {render, cleanup} from '@testing-library/react'; import {MyMockedProvider} from './MyMockedProvider'; import {MyArticleComponent, gqlArticle} from './MyArticleComponent'; afterEach(cleanup); it('logs MockedProvider warning about the missing mock to the console', async () => { let gqlMocks = [{ request:{ query: gqlArticle, variables: { /* Here, the component calls with {"id": 5}, so the mock won't work */ "id": 6, } }, result: { "data": { "article": { "title": "This is an article", "content": "It talks about many things", "__typename": "Article" } } } }]; let consoleLogSpy = jest.spyOn(console, 'log'); const {container, findByText} = render( <MyMockedProvider mocks={gqlMocks}> <MyArticleComponent /> </MyMockedProvider> ); let expectedConsoleLog = '[Network error]: Error: No more mocked responses for the query: query Article($id: ID) {\n' + ' article(id: $id) {\n' + ' title\n' + ' content\n' + ' __typename\n' + ' }\n' + '}\n' + ', variables: {"id":5}'; await findByText('{"loading":false}'); expect(consoleLogSpy.mock.calls[0][0]).toEqual(expectedConsoleLog); });
Apollo
60,100,062
10
I'm trying to test a data source in my Apollo Server that based on Apollo Server's RESTDataSource (https://www.apollographql.com/docs/apollo-server/data/data-sources/#rest-data-source). I'm trying to test it using Jest. The class has methods that pull in data from an external REST API, as well as from another module that calls a second API (so this RESTDataSource ultimately depends on two external APIs, one of which is called directly here, and one of which is called indirectly). I'm not an expert on testing, and I'm unclear how to mock the external APIs. GraphQL Tools has some tools that allow you to mock your server, but I'm not sure that's what I want. Or should I use Jest's methods for mocking ES6 classes, forgetting that this is a GraphQL server? If so, since I'm working with a class, do I just mock the methods using something like MyClass.myMethod as the mocked method? Does anything change in how I do this if I'm using TypeScript (which I am), other than setting up Jest to work with TypeScript? Obviously the correct route is to pick one of the options above, but I'm a bit 'not seeing the forest for the trees', that is, due to my inexperience with testing, I don't know which of these is the correct route to follow. Thanks for any clues.
Unit testing You can unit test your data source by mocking the RESTDataSource in apollo-datasource-rest as suggested in apollo-datasource-rest + Typescript + Jest in the Apollo Spectrum chat. For this data source: import { RESTDataSource } from 'apollo-datasource-rest' export class MyRestDataSource extends RESTDataSource { async getStackoverflow(): Promise<string> { return this.get('https://stackoverflow.com/') } } You could write an unit test like this: import { MyRestDataSource } from './MyRestDataSource' const mockGet = jest.fn() jest.mock('apollo-datasource-rest', () => { class MockRESTDataSource { baseUrl = '' get = mockGet } return { RESTDataSource: MockRESTDataSource, } }) describe('MyRestDataSource', () => { it('getStackoverflow gets data from correct URL', async () => { const datasource = new MyRestDataSource() await datasource.getStackoverflow() expect(mockGet).toBeCalledWith('https://stackoverflow.com/') }) }) Integration testing Rather than unit testing the data sources, I'd in most cases prefer integration testing with e.g. apollo-server-testing: you run GraphQL against the server and test the entire path from the resolver to the data source. If you do so, consider using e.g. nock to mock the HTTP requests the data sources make. TypeScript The general approaches should be the same regardless of whether you're using TypeScript or JavaScript with just some minor differences. E.g. with JavaScript, your unit test could directly replace the get in the data source: const MyRestDataSource = require('./MyRestDataSource') describe('MyRestDataSource', () => { it('getStackoverflow gets data from correct URL', async () => { const datasource = new MyRestDataSource() datasource.get = jest.fn() await datasource.getStackoverflow() expect(datasource.get).toBeCalledWith('https://stackoverflow.com/') }) }) but with TypeScript that would cause a compiler error as get is protected: MyRestDataSource.test.ts:6:16 - error TS2445: Property 'get' is protected and only accessible within class 'RESTDataSource' and its subclasses.
Apollo
62,022,436
10
I 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: const [addDrone, { error }] = useMutation(ADD_DRONE) So 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. So my question is, is there a way to "reset" a useMutation hook back to it's original state?
UPDATE 12/22/2021: As of version 3.5.0 of @apollo/client the useMutation hook now provides a reset method. You can use this method to reset the hook back to its initial state. E.g.: const [addDrone, { error, reset }] = useMutation(ADD_DRONE) Below are some notes from the official documentation on this method. Call reset to reset the mutation's result to its initial state (i.e., before the mutate function was called). You can use this to enable users to dismiss mutation result data or errors in the UI. Calling reset does not remove any cached data returned by the mutation's execution. It only affects the state associated with the useMutation hook, causing the corresponding component to rerender. Old answer, kept for those who use an older version of @apollo/client: As of 12/26/2020 there's no way to reset a useMutation, however there are two feature requests #157 #170 on the Apollo Feature Request repo asking for one, so this may change in the future. The easiest way to implement this behavior right now is to drop the error variable and use the onError handler instead. This is a callback provided by useMutation which uses the same error object. You can then wire that to your own stateful variable, which gives you the exact same error variable and the ability to use setError to clear it. See this example below: const [error, setError] = React.useState(null) const [addDrone] = useMutation(ADD_DRONE, { onError: setError, }) If you're looking to reset the data object as well you can introduce another stateful tuple [data, setData] and wire the setData to the onCompleted callback.
Apollo
65,457,513
10
Is 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? Schema: type Item { id: ID! name: String! } type Query { items: [Item!]! itemById(id: ID!): Item! } Query1: query HomepageList { items { id name } } Query2: query ItemDetail($id: ID!) { itemById(id: $id) { id name } } Given 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. However, 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. Any help greatly appreciated.
This functionality exists, but it's hard to find if you don't know what you're looking for. In Apollo Client v2 you're looking for cache redirect functionality, in Apollo Client v3 this is replaced by type policies / field read policies (v3 docs). Apollo doesn't 'know' your GraphQL schema and that makes it easy to set up and work with in day-to-day usage. However, this implies that given some query (e.g. getBooks) it doesn't know what the result type is going to be upfront. It does know it afterwards, as long as the __typename's are enabled. This is the default behaviour and is needed for normalized caching. Let's assume you have a getBooks query that fetches a list of Books. If you inspect the cache after this request is finished using Apollo devtools, you should find the books in the cache using the Book:123 key in which Book is the typename and 123 is the id. If it exists (and is queried!) the id field is used as identifier for the cache. If your id field has another name, you can use the typePolicies of the cache to inform Apollo InMemoryCache about this field. If you've set this up and you run a getBook query afterwards, using some id as input, you will not get any cached data. The reason is as described before: Apollo doesn't know upfront which type this query is going to return. So in Apollo v2 you would use a cacheRedirect to 'redirect' Apollo to the right cache: cacheRedirects: { Query: { getBook(_, args, { getCacheKey }) { return getCacheKey({ __typename: 'Book', id: args.id, }); } }, }, (args.id should be replaced by another identifier if you have specified another key in the typePolicy) When using Apollo v3, you need a typepolicy / field read policy: typePolicies: { Query: { fields: { getBook(_, { args, toReference }) { return toReference({ __typename: 'Book', id: args.id, }); } } } }
Apollo
65,842,596
10
Some background: I've got a component that immediately calls a useQuery hook upon loading. While that query is running, I spin a loading spinner. Once it completes I render stuff based on the data. I've added a useEffect hook that watches the result of the query and logs the data, which is how I observed this issue. To simplify things, it works like this: export default function MyComponent(props: ???) { const result = useQuery(INITIAL_DATA_QUERY, { variables: { id: 1 } }); React.useEffect(() => console.log(JSON.stringify({ loading: result.loading, data: result.data, error: result.error, })), [result]); if (result.loading) return <LoadingScreen message="Fetching data..."/>; else if (result.error) return <ErrorPage/> else return <Stuff info={result.data}> // omitted because it's unimportant to the issue } When I run this component in the wild, everything works exactly as expected. It hits the endpoint with GraphQL through Apollo, makes rendering decisions based on the result, etc. When I try to mock the request out though, the result.data and result.error fields never change, even though the result.loading field does. I am using react-testing-library to run the tests. My tests look like this: it("should load the data then render the page", () => { const mocks = [{ request: { query: INITIAL_DATA_QUERY, variables: { id: 1 }, }, newData: jest.fn(() => ({ data: { firstName: "Joe", lastName: "Random", } })) }]; const mockSpy = mocks[0].newData; render( <MockedProvider mocks={mocks} addTypename={false}> <MyComponent/> </MockedProvider> ) // Is it a loading view expect(result.asFragment()).toMatchSnapshot(); // Passes just fine, and matches expectations // Wait until the mock has been called once await waitFor(() => expect(mockSpy).toHaveBeenCalled(1)) // Also passes, meaning the mock was called // Has the page rendered once the loading mock has finished expect(result.asFragment()).toMatchSnapshot(); // Passes, but the page has rendered without any of the data }) The problem is this: when I run this test, all three of those tests pass as expected, but in the final fragment the data in my rendered component is missing. I am sure the mock is being called because I've added some logger statements to check. The really confusing part are the loading, data, and error values as the mock is called. I have a useEffect statement logging their values when any of them change, and when I run the test, the output looks like this: { loading: true, data: undefined, error: undefined } { loading: false, data: undefined, error: undefined } This means that the hook is being called and loading begins, but once loading ends whatever happened during loading neither returned any data nor generated any errors. Does anybody know what my problem here might be? I've looked at it eight ways to Sunday and can't figure it out.
I mocked the result using the result field. the result field can be a function that returns a mocked response after performing arbitrary logic It works fine for me. MyComponent.test.tsx: import { gql, useQuery } from '@apollo/client'; import { useEffect } from 'react'; export const INITIAL_DATA_QUERY = gql` query GetUser($id: ID!) { user(id: $id) { firstName lastName } } `; export default function MyComponent(props) { const result = useQuery(INITIAL_DATA_QUERY, { variables: { id: 1 } }); useEffect( () => console.log( JSON.stringify({ loading: result.loading, data: result.data, error: result.error, }), ), [result], ); if (result.loading) return <p>Fetching data...</p>; else if (result.error) return <p>{result.error}</p>; else return <p>{result.data.user.firstName}</p>; } MyComponent.test.tsx: import { render, waitFor } from '@testing-library/react'; import MyComponent, { INITIAL_DATA_QUERY } from './MyComponent'; import { MockedProvider } from '@apollo/client/testing'; describe('68732957', () => { it('should load the data then render the page', async () => { const mocks = [ { request: { query: INITIAL_DATA_QUERY, variables: { id: 1 }, }, result: jest.fn().mockReturnValue({ data: { user: { lastName: 'Random', firstName: 'Joe', }, }, }), }, ]; const mockSpy = mocks[0].result; const result = render( <MockedProvider mocks={mocks} addTypename={false}> <MyComponent /> </MockedProvider>, ); expect(result.asFragment()).toMatchSnapshot(); await waitFor(() => expect(mockSpy).toBeCalledTimes(1)); expect(result.asFragment()).toMatchSnapshot(); }); }); test result: PASS src/stackoverflow/68732957/MyComponent.test.tsx 68732957 ✓ should load the data then render the page (58 ms) console.log {"loading":true} at src/stackoverflow/68732957/MyComponent.tsx:18:15 console.log {"loading":false,"data":{"user":{"firstName":"Joe","lastName":"Random"}}} at src/stackoverflow/68732957/MyComponent.tsx:18:15 Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 2 passed, 2 total Time: 0.736 s, estimated 1 s MyComponent.test.tsx.snap: // Jest Snapshot v1 exports[`68732957 should load the data then render the page 1`] = ` <DocumentFragment> <p> Fetching data... </p> </DocumentFragment> `; exports[`68732957 should load the data then render the page 2`] = ` <DocumentFragment> <p> Joe </p> </DocumentFragment> `; package versions: "@testing-library/react": "^11.1.0", "react": "^17.0.1", "@apollo/client": "^3.4.7", "graphql": "^15.4.0"
Apollo
68,732,957
10