@apollo/client#InMemoryCache JavaScript Examples

The following examples show how to use @apollo/client#InMemoryCache. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: client.js    From nextjs-boilerplate with MIT License 7 votes vote down vote up
client = () =>
  new ApolloClient({
    credentials: "include",
    link: ApolloLink.from([
      new HttpLink({
        uri: settings.graphql.uri,
        credentials: "include",
      }),
    ]),
    cache: new InMemoryCache(),
    defaultOptions: {
      watchQuery: {
        errorPolicy: "all",
        fetchPolicy: "network-only",
      },
      query: {
        errorPolicy: "all",
        fetchPolicy: "network-only",
      },
      mutate: {
        errorPolicy: "all",
      },
    },
  })
Example #2
Source File: ApolloClient.js    From nextjs-woocommerce with GNU General Public License v3.0 6 votes vote down vote up
client = new ApolloClient({
  ssrMode: clientSide,
  link: middleware.concat(
    afterware.concat(
      createHttpLink({
        uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,
        fetch,
      })
    )
  ),
  cache: new InMemoryCache(),
})
Example #3
Source File: ssrApollo.js    From stacker.news with MIT License 6 votes vote down vote up
export default async function getSSRApolloClient (req, me = null) {
  const session = req && await getSession({ req })
  return new ApolloClient({
    ssrMode: true,
    link: new SchemaLink({
      schema: mergeSchemas({
        schemas: typeDefs,
        resolvers: resolvers
      }),
      context: {
        models,
        me: session
          ? session.user
          : me,
        lnd,
        search
      }
    }),
    cache: new InMemoryCache()
  })
}
Example #4
Source File: client.js    From bedav with GNU General Public License v3.0 6 votes vote down vote up
export default async function getClient() {
  const cache = new InMemoryCache();

  await persistCache({
    cache,
    storage: new LocalForageWrapper(localForage),
  });

  const client = new ApolloClient({
    cache,
    uri: "/graphql",
  });

  return client;
}
Example #5
Source File: client.js    From jamstack-ecommerce with MIT License 6 votes vote down vote up
client = new ApolloClient({
    link: new HttpLink({
        uri: "https://shanstore2.myshopify.com/api/graphql",
        fetch,
        headers: {
            "X-Shopify-Storefront-Access-Token": "a9da41bccc9eb31891047c268e893226"
        }
    }),
    cache: new InMemoryCache()
})
Example #6
Source File: API.js    From Dashboard with MIT License 6 votes vote down vote up
client = new ApolloClient({
  uri: 'http://localhost:3100/graphql',
  cache: new InMemoryCache(),
  defaultOptions: {
    query: {
      fetchPolicy: 'no-cache',
      errorPolicy: 'all',
    }
  }
})
Example #7
Source File: ApolloConfig.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
function createApolloClient(getIdTokenClaims) {
  const GRAPHQL_ENDPOINT = process.env.REACT_APP_GRAPHQL_ENDPOINT;

  if (getIdTokenClaims == null) {
    return new ApolloClient({
      uri: GRAPHQL_ENDPOINT,
      cache: new InMemoryCache(),
    });
  }

  const httpLink = createHttpLink({
    uri: GRAPHQL_ENDPOINT,
  });

  const authLink = setContext(async (request, {headers}) => {
    const idTokenClaims = await getIdTokenClaims();
    // return the header to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        'X-Auth-Token': idTokenClaims.__raw,
      },
    };
  });

  return new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
  });
}
Example #8
Source File: App.js    From react-sample-projects with MIT License 6 votes vote down vote up
function App() {
  const client = new ApolloClient({
    uri: 'https://graphql-pokemon2.vercel.app/',
    cache: new InMemoryCache(),
  });

  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        <Router hashType="slash">
          <Routes>
            <Route exact path="/" element={<Home />}></Route>
            <Route
              exact
              path="/pokemon/:id"
              element={<PokemonDetail />}
            ></Route>
          </Routes>
        </Router>
      </Provider>
    </ApolloProvider>
  );
}
Example #9
Source File: cache.js    From ReactNativeApolloOnlineStore with MIT License 6 votes vote down vote up
cache = new InMemoryCache({
  typePolicies: {
    Product: {
      fields: {
        favorite: {
          read(favorite = false) {
            return favorite;
          },
        },
        price(price) {
          return `${convertDollarValueToMAD(price)} MAD`;
        },
      },
    },
    Query: {
      fields: {
        product(_, {args, toReference}) {
          return toReference({
            __typename: 'Product',
            id: args.id,
          });
        },
      },
    },
  },
})
Example #10
Source File: app.js    From x-admin-device-donation with MIT License 6 votes vote down vote up
App = () => {
  const [dataProvider, setDataProvider] = useState(null);
  const [apolloClient, setApolloClient] = useState(null);
  const [session] = useSession();

  useEffect(() => {
    const hasuraHeaders = {};
    hasuraHeaders.Authorization = `Bearer ${session.jwt}`;
    if (session.role) hasuraHeaders["x-hasura-role"] = session.role;

    let tempClient = new ApolloClient({
      uri: process.env.NEXT_PUBLIC_HASURA_URL,
      cache: new InMemoryCache(),
      headers: hasuraHeaders,
    });
    async function buildDataProvider() {
      const hasuraProvider = await buildHasuraProvider(
        { client: tempClient },
        {
          buildFields: customFields,
        },
        customVariables
      );
      setDataProvider(() => hasuraProvider);
      setApolloClient(tempClient);
    }
    buildDataProvider();
  }, [session]);

  if (!dataProvider || !apolloClient) return null;
  return (
    <AdminContext dataProvider={dataProvider}>
      <AsyncResources client={apolloClient} />
    </AdminContext>
  );
}
Example #11
Source File: cache.js    From malware-detection-frontend with Apache License 2.0 6 votes vote down vote up
cache = new InMemoryCache({
    typePolicies: {
        Query: {
            fields: {
                // rulesList: { ...offsetLimitPagination(),
                //     read(existing, { variables }) {

                //         need to have the variables stored/updated as cache var, then we can compare exisitng to what we see in the read

                //         console.error(existing, variables);
                //         if (!existing) {return;} //We have no data at all

                //         if (existing.length < (variables.offset + variables.limit)) {return;} //We don't have enough data

                //         const sliced = existing.slice(variables.offset, variables.offset + variables.limit);

                //         if (sliced.includes(undefined)) {return;} //Some of our data is null

                //         return sliced;
                //     }
                // }
            }
        }
    }
})
Example #12
Source File: cache.js    From next-ecommerce with MIT License 6 votes vote down vote up
cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        isDrawerOpen: {
          read() {
            return isDrawerOpenVar();
          },
        },
        sortProductSection: {
          read() {
            return sortProductSectionVar();
          },
        },
        cart: {
          read() {
            return {
              products: cartProductsVar(),
              cartCount: cartProductsVar().length,
            };
          },
        },
        wishlist: {
          read() {
            return {
              products: wishlistProductsVar(),
              wishlistCount: wishlistProductsVar().length,
            };
          },
        },
      },
    },
  },
})
Example #13
Source File: client.js    From gatsby-apollo-wpgraphql-jwt-starter with MIT License 6 votes vote down vote up
client = new ApolloClient({
  link: from([
    authMiddleware,
    onErrorLink,
    refreshTokenLink,
    httpLink
  ]),
  cache: new InMemoryCache({ possibleTypes }),
})
Example #14
Source File: dataProvider.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export function useGraph(querySource, { subgraph = null, subgraphUrl = null, chainName = "arbitrum" } = {}) {
  const query = gql(querySource)

  if (!subgraphUrl) {
    if (!subgraph) {
      subgraph = getChainSubgraph(chainName)
    }
    subgraphUrl = `https://api.thegraph.com/subgraphs/name/${subgraph}`;
  }

  const client = new ApolloClient({
    link: new HttpLink({ uri: subgraphUrl, fetch }),
    cache: new InMemoryCache()
  })
  const [data, setData] = useState()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  useEffect(() => {
    setLoading(true)
  }, [querySource, setLoading])

  useEffect(() => {
    client.query({query}).then(res => {
      setData(res.data)
      setLoading(false)
    }).catch(ex => {
      console.warn('Subgraph request failed error: %s subgraphUrl: %s', ex.message, subgraphUrl)
      setError(ex)
      setLoading(false)
    })
  }, [querySource, setData, setError, setLoading])

  return [data, loading, error]
}
Example #15
Source File: App.js    From ReactCookbook-source with MIT License 5 votes vote down vote up
client = new ApolloClient({
  uri: 'http://localhost:5000',
  cache: new InMemoryCache(),
})
Example #16
Source File: common.js    From acy-dex-interface with MIT License 5 votes vote down vote up
chainlinkClient = new ApolloClient({
  uri: CHAINLINK_GRAPH_API_URL,
  cache: new InMemoryCache()
})
Example #17
Source File: client.js    From horondi_admin with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: authLink.concat(createUploadLink({ uri: REACT_APP_API_URL })),
  cache: new InMemoryCache({
    addTypename: false,
    fragmentMatcher
  })
})
Example #18
Source File: client.js    From acy-dex-interface with MIT License 5 votes vote down vote up
marketClient = new ApolloClient({
    uri: "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2",
    cache: new InMemoryCache()
})
Example #19
Source File: seed-db.js    From grandcast.fm with Apache License 2.0 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({ uri, fetch }),
  cache: new InMemoryCache(),
})
Example #20
Source File: server.js    From react-workshop with MIT License 5 votes vote down vote up
server
  .disable('x-powered-by')
  .use(express.static(process.env.RAZZLE_PUBLIC_DIR))
  .get('/*', (req, res) => {
    const apolloClient = new ApolloClient({
      ssrMode: true,
      cache: new InMemoryCache(),
      link: createHttpLink({
        uri: 'https://asia-southeast2-minitokopedia.cloudfunctions.net/graphql',
      }),
    });

    const context = {};
    const markup = (
      <ApolloProvider client={apolloClient}>
        <StaticRouter context={context} location={req.url}>
          <App />
        </StaticRouter>
      </ApolloProvider>
    );

    if (context.url) {
      res.redirect(context.url);
    } else {
      getDataFromTree(markup).then((content) => {
        const initialState = apolloClient.extract();

        const html = renderToString(
          <html lang="en">
            <head>
              <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
              <meta charset="utf-8" />
              <title>Welcome to Razzle</title>
              <meta name="viewport" content="width=device-width, initial-scale=1" />
              {cssLinksFromAssets(razzleAssets, 'client')}
            </head>
            <body>
              <div id="root" dangerouslySetInnerHTML={{ __html: content }} />
              <script
                dangerouslySetInnerHTML={{
                  __html: `window.__APOLLO_STATE__=${JSON.stringify(initialState).replace(/</g, '\\u003c')};`,
                }}
              />
              {jsScriptTagsFromAssets(razzleAssets, 'client')}
            </body>
          </html>,
        );

        res.status(200).header('Content-Type', 'text/html').send(`<!doctype html>\n${html}`);
      });
    }
  });
Example #21
Source File: index.js    From openeew-dashboard with Apache License 2.0 5 votes vote down vote up
client = new ApolloClient({
  uri: 'api/graphql',
  cache: new InMemoryCache(),
  credentials: 'include',
})
Example #22
Source File: common.js    From acy-dex-interface with MIT License 5 votes vote down vote up
nissohGraphClient = new ApolloClient({
  uri: NISSOH_GRAPH_API_URL,
  cache: new InMemoryCache()
})
Example #23
Source File: client.js    From jamstack-serverless with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: 'http://localhost:8888/.netlify/functions/graphql_hello',
    fetch,
  }),
  cache: new InMemoryCache()
})
Example #24
Source File: uniswapClient.js    From SimpleFi with GNU General Public License v3.0 5 votes vote down vote up
uniswapClient = new ApolloClient({
  uri: 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2',
  cache: new InMemoryCache()
})
Example #25
Source File: index.js    From readr-coverages with MIT License 5 votes vote down vote up
export async function getStaticProps() {
  const client = new ApolloClient({
    uri: process.env.NEXT_PUBLIC_CMS_ENDPOINT,
    cache: new InMemoryCache(),
  });

  const POST_ID = 2641;

  const { contentApiData, ...meta } = (
    await client.query({
      query: gql`
        query posts {
          Post(where: { id: ${POST_ID} }) {
            contentApiData

            title: name
            ogTitle
            ogDescription
            ogImage {
              urlOriginal
            }
            tags {
              name
            }
            publishTime
            updatedAt
          }
        }
      `,
    })
  ).data.Post;

  const story = archieml.load(
    JSON.parse(contentApiData)
      .filter((item) => item.type === 'unstyled' || item.type === 'annotation')
      .map((item) => item.content)
      // .flatMap(function (item) {
      //   if (item.type === 'unstyled') {
      //     return item.content;
      //   }

      //   const text = '{"text":"';
      //   return item.content.map((str) =>
      //     str
      //       .split(/<!--__ANNOTATION__=|-->/gm)
      //       .filter((str) => str && !str.startsWith('<!--'))
      //       .map((str) =>
      //         str.includes(text)
      //           ? str.slice(text.length, str.indexOf('","annotation"'))
      //           : str
      //       )
      //       .join('')
      //   );
      // })
      .join('\n')
  );

  // console.log(
  //   JSON.parse(contentApiData)
  //     .filter((item) => item.type === 'unstyled')
  //     .flatMap((item) => item.content)
  //     .join('\n')
  // );

  return {
    props: {
      meta,
      story,
    },
  };
}
Example #26
Source File: common.js    From acy-dex-interface with MIT License 5 votes vote down vote up
avalancheGraphClient = new ApolloClient({
  uri: AVALANCHE_GRAPH_API_URL,
  cache: new InMemoryCache()
})
Example #27
Source File: _app.js    From redis-examples with MIT License 5 votes vote down vote up
client = new ApolloClient({
  uri: "https://graphql-us-east-1.upstash.io/",
  cache: new InMemoryCache(),
  link,
})
Example #28
Source File: App.js    From Simplify-Testing-with-React-Testing-Library with MIT License 5 votes vote down vote up
client = new ApolloClient({
  // uri: 'production url',
  uri: 'http://localhost:4000',
  cache: new InMemoryCache()
})
Example #29
Source File: index.jsx    From moonshot with MIT License 5 votes vote down vote up
client = new ApolloClient({
  uri: subgraphUri,
  cache: new InMemoryCache(),
})