apollo-client#ApolloClient JavaScript Examples

The following examples show how to use apollo-client#ApolloClient. 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: apolloClient.js    From dineforward with MIT License 7 votes vote down vote up
export default function createApolloClient(initialState, ctx) {
  const linkOpts = {
    uri: apiUrl, // Server URL (must be absolute)
    credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
    fetch,
  };

  // The `ctx` (NextPageContext) will only be present on the server.
  // use it to extract auth headers (ctx.req) or similar.
  // The Keystone session ID cookie will be present here if this is SSR and
  // the user has a session.
  const sid = ctx && ctx['keystone.sid'];
  if (sid) linkOpts.headers = { 'keystone.sid': ctx['keystone.sid'] };

  return new ApolloClient({
    ssrMode: Boolean(ctx),
    link: new HttpLink(linkOpts),
    cache: new InMemoryCache().restore(initialState),
  });
}
Example #2
Source File: newApolloClient.js    From pods-frontend with MIT License 6 votes vote down vote up
export function newApolloClient({ provider }) {
  const tb = new Tightbeam({
    providerSource: () => provider,
    abiMapping: newAbiMapping()
  })
  const cache = new InMemoryCache()
  cache.writeData(tb.defaultCacheData())
  const client = new ApolloClient({
    cache,
    resolvers: tb.resolvers(),
    typeDefs: typeDefs
  });

  client.watchQuery({
    query: gql`query {
      network @client {
        id
        chainId
        name
      }
    }`,
    pollInterval: 2000,
    fetchPolicy: 'network-only'
  }).subscribe()

  client.watchQuery({
    query: gql`query { account @client }`,
    pollInterval: 2000,
    fetchPolicy: 'network-only'
  }).subscribe()

  return client
}
Example #3
Source File: client.js    From mailmask with GNU Affero General Public License v3.0 6 votes vote down vote up
createApolloClient = ({ endpoint, name, initialState = {} }) => {
  const cache = new InMemoryCache({ fragmentMatcher }).restore(initialState)

  const client = new ApolloClient({
    name,
    cache,
    typeDefs: getTypeDefs(),
    link: createLinks({ cache, endpoint }),
  })

  return client
}
Example #4
Source File: index.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
client = new ApolloClient({
  link: trackMetrics.concat(httpLink),
  cache: new InMemoryCache(),
  request: (operation) => {
    operation.setContext({
      fetchOptions: {
        mode: "no-cors",
      },
    });
  },
  defaultOptions: {
    query: {
      fetchPolicy: "network-only",
      errorPolicy: "all",
    },
  },
})
Example #5
Source File: main.js    From minimal-portfolio with GNU General Public License v3.0 5 votes vote down vote up
apolloClient = new ApolloClient({
  link: httpLink,
  cache,
})
Example #6
Source File: client.js    From pancake-info-v1 with GNU General Public License v3.0 5 votes vote down vote up
blockClient = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.thegraph.com/subgraphs/name/pancakeswap/blocks',
  }),
  cache: new InMemoryCache(),
})
Example #7
Source File: client.js    From pancake-info-v1 with GNU General Public License v3.0 5 votes vote down vote up
healthClient = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.thegraph.com/index-node/graphql',
  }),
  cache: new InMemoryCache(),
  shouldBatch: true,
})
Example #8
Source File: client.js    From pancake-info-v1 with GNU General Public License v3.0 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.thegraph.com/subgraphs/name/pancakeswap/exchange',
  }),
  cache: new InMemoryCache(),
  shouldBatch: true,
})
Example #9
Source File: graphql.js    From lifebank with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link,
  cache: new InMemoryCache()
})
Example #10
Source File: App.js    From project-avocado-web with MIT License 5 votes vote down vote up
client = new ApolloClient({
  cache,
  link
})
Example #11
Source File: index.js    From reactnative-best-practice with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: createHttpLink({uri: 'http://devcloud3.digihcs.com:14047/graphqlhrm'}),
  cache: new InMemoryCache(),
  // link: ApolloLink.from([errorLink, authLink, terminalLink]),
})
Example #12
Source File: App.js    From spells-fyi with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: split(
    operation => operation.getContext().clientName === "github", // Routes the query to the proper client
    githubLink,
    thegraphLink
  ),
  cache: new InMemoryCache()
})
Example #13
Source File: index.js    From Lambda with MIT License 5 votes vote down vote up
client = new ApolloClient({ link: httpLink, cache })
Example #14
Source File: client.js    From spooky-info with GNU General Public License v3.0 5 votes vote down vote up
blockClient = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.fura.org/subgraphs/name/spookyswap',
  }),
  cache: new InMemoryCache(),
})
Example #15
Source File: client.js    From spooky-info with GNU General Public License v3.0 5 votes vote down vote up
stakingClient = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.thegraph.com/subgraphs/name/way2rach/talisman',
  }),
  cache: new InMemoryCache(),
  shouldBatch: true,
})
Example #16
Source File: client.js    From spooky-info with GNU General Public License v3.0 5 votes vote down vote up
healthClient = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.fura.org/subgraphs/name/spookyswap',
  }),
  cache: new InMemoryCache(),
  shouldBatch: true,
})
Example #17
Source File: client.js    From spooky-info with GNU General Public License v3.0 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.fura.org/subgraphs/name/spookyswap'
    ,
  }),
  cache: new InMemoryCache(),
  shouldBatch: true,
})
Example #18
Source File: apollo.js    From saasgear with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: ApolloLink.from([
    networkStatusNotifierLink,
    authLink,
    onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors)
        graphQLErrors.forEach(({ message, path }) =>
          console.error(`[GraphQL error]: Message: ${message}, Path: ${path}`),
        );

      if (networkError) console.error(`[Network error]: ${networkError}`);

      if (graphQLErrors && graphQLErrors[0]) {
        const errors = graphQLErrors[0];
        switch (errors.extensions.code) {
          case 'UNAUTHENTICATED':
            if (!window.location.pathname.startsWith('/auth')) {
              window.location.href = '/auth/signin';
            }
            break;
          case 'ANOTHER_ERROR_CODE':
            break;
          default:
        }
      }
    }),
    createUploadLink({
      uri: process.env.REACT_APP_GRAPHQL_URL,
      credentials: 'include',
    }),
  ]),
  cache: new InMemoryCache(),
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'no-cache',
    },
    query: {
      fetchPolicy: 'no-cache',
    },
    mutate: {
      errorPolicy: 'all',
    },
  },
  credentials: "include"
})
Example #19
Source File: App.js    From AdaptivApps-fe with MIT License 4 votes vote down vote up
function App() {
  const { getIdTokenClaims } = useAuth0();
  const [authToken, setAuthToken] = useState();

  const request = async operation => {
    const token = await getIdTokenClaims();
    setAuthToken(token.__raw);
    operation.setContext(context => ({
      headers: {
        ...context.headers,
        Authorization: token.__raw,
      },
    }));
  };

  const requestLink = new ApolloLink(
    (operation, forward) =>
      new Observable(observer => {
        let handle;
        Promise.resolve(operation)
          .then(oper => {
            request(oper)
          })
          .then(() => {
            handle = forward(operation).subscribe({
              next: observer.next.bind(observer),
              error: observer.error.bind(observer),
              complete: observer.complete.bind(observer),
            });
          })
          .catch(observer.error.bind(observer));
        return () => {
          if (handle) handle.unsubscribe();
        };
      })
  );

  const httpLink = new HttpLink({ 
    uri: process.env.REACT_APP_API_URL,
    credentials: "same-origin", 
  });

  var location = window.location, new_uri;

  location.protocol === "https:" ? new_uri = "wss://" : new_uri = "ws://";

  const wsLink = new WebSocketLink({
    uri: `${new_uri}${process.env.REACT_APP_WS_URL}`,
    options: {
      reconnect: true,
      connectionParams: {
        authToken: authToken,
      }
    }
  });

  const link = split(
    // split based on operation type
    ({ query }) => {
      const { kind, operation } = getMainDefinition(query);
      return (
        kind === 'OperationDefinition' &&
        operation === 'subscription'
      );
    },
    wsLink,
    httpLink,
  );

  const client = new ApolloClient({
    link: ApolloLink.from([
      onError(({ graphQLErrors, networkError }) => {
        if (graphQLErrors)
          graphQLErrors.forEach(({ message, locations, path }) =>
            console.log(
              `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
            )
          );
        if (networkError) console.log(`[Network error]: ${networkError}`);
      }),
      requestLink,
      link
    ]),
    cache: new InMemoryCache(),
  });

  return (
    <ApolloProvider client={client}>
      <div className="App">
        <Router>
          <Accessibility path="/accessibility" />
          <PrivacyPolicy path="/privacy-policy" />
          <PrivateRoute path="/" component={DashRouter}>
            <UserProfile path="/" />
            <EventsCalendar path="calendar" />
            <ActivityList path="calendar/:eventId" />
            <MyEvents path="myevents" />
            <MyEventDetails path="myevents/:eventId" />
            <ManageEvents path="manage" />
            <ManageUsers path="users" />
            <ChatFeature path="chats" />
          </PrivateRoute>
        </Router>
      </div>
    </ApolloProvider>
  );
}