apollo-link-http#HttpLink JavaScript Examples

The following examples show how to use apollo-link-http#HttpLink. 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: render.js    From tunnel-tool with MIT License 7 votes vote down vote up
configureGraph = ({ url, req }) => ({
  graph: new ApolloClient({
    ssrMode: true,
    link: new HttpLink({
      uri: url,
      onError: e => {
        console.log("APOLLO_CLIENT_ERROR");
        console.log(e.graphQLErrors);
      },
      credentials: "include",
      fetch: fetch,
      headers: {
        cookie: req.header("Cookie")
      }
    }),
    cache: new InMemoryCache()
  })
})
Example #2
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 #3
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 #4
Source File: example1.js    From graphql-sample-apps with Apache License 2.0 7 votes vote down vote up
createRemoteExecutableSchemas = async () => {
  let schemas = [];
  for (const api of graphqlApis) {
    const link = new HttpLink({
      uri: api.uri,
      fetch,
    });
    const remoteSchema = await introspectSchema(link);
    const remoteExecutableSchema = makeRemoteExecutableSchema({
      schema: remoteSchema,
      link,
    });
    schemas.push(remoteExecutableSchema);
  }
  return schemas;
}
Example #5
Source File: example2.js    From graphql-sample-apps with Apache License 2.0 7 votes vote down vote up
createUserSchema = async () => {
  const link = new HttpLink({
    uri: `http://localhost:8080/graphql`,
    fetch,
  });

  const remoteUserSchema = await introspectSchema(link);
  return makeRemoteExecutableSchema({
    schema: remoteUserSchema,
    link,
  });
}
Example #6
Source File: _app.jsx    From teach-yourself-code with MIT License 6 votes vote down vote up
createApolloClient = () => {
  return new ApolloClient({
    link: new HttpLink({
      uri: `${hasuraEndpoint}`,
      headers: {
        authorization: `Bearer ${authToken}`,
        "x-hasura-admin-secret": `${adminSecret}`,
      },
    }),
    cache: new InMemoryCache(),
  });
}
Example #7
Source File: App.js    From project-avocado-web with MIT License 6 votes vote down vote up
link = new HttpLink({
  uri: 'https://cors-anywhere.herokuapp.com/project-avocado-8b3e1.uc.r.appspot.com/graphql'
})
Example #8
Source File: render.js    From tunnel-tool with MIT License 5 votes vote down vote up
configureGraph = ({ url, initState }) => {
  return new ApolloClient({
    cache: new InMemoryCache().restore(window.__APOLLO_STATE__),
    link: new HttpLink({ uri: url })
  });
}
Example #9
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 #10
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 #11
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 #12
Source File: seed-db.js    From willow-grandstack with Apache License 2.0 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({ uri, fetch }),
  cache: new InMemoryCache(),
})
Example #13
Source File: example3.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
link = new HttpLink({
  uri: "http://localhost:8080/graphql",
  fetch,
})
Example #14
Source File: App.js    From spells-fyi with MIT License 5 votes vote down vote up
httpLink = new HttpLink({
  uri: 'https://api.thegraph.com/subgraphs/name/blocklytics/spells'
})
Example #15
Source File: index.js    From Lambda with MIT License 5 votes vote down vote up
httpLink = new HttpLink({ uri: Meteor.absoluteUrl("graphql") })
Example #16
Source File: index.js    From desktop with GNU General Public License v3.0 5 votes vote down vote up
httpLink = new HttpLink({
  uri: isDev ? "http://localhost:8080/graphql" : "https://my.vpn.ht/graphql"
})
Example #17
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 #18
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 #19
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 #20
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 #21
Source File: AppCache.js    From trashpanda-fe with MIT License 5 votes vote down vote up
AppCache = props => {
  const [client, setClient] = useState(undefined);

  useEffect(() => {
    const link = new HttpLink({ uri: "https://trashpanda-be.herokuapp.com" });

    const cache = new InMemoryCache({
      dataIdFromObject: object => {
        switch (object.__typename) {
          case "Material":
            return `Material: ${object.material_id}`;
          case "Family":
            return `Family: ${object.family_id}`;
          case "GPS":
            return `GPS`;
          case "PostalCode":
            return `PostalCode: ${object.postal_code}`;
          case "Location":
            return `Location: ${object.address}`;
          case "Permission":
            return `Permission`;
          default:
            return defaultDataIdFromObject(object);
        }
      }
    });

    // TODO: Monkey-patching in a fix for an open issue suggesting that
    // `readQuery` should return null or undefined if the query is not yet in the
    // cache: https://github.com/apollographql/apollo-feature-requests/issues/1
    cache.originalReadQuery = cache.readQuery;
    cache.readQuery = (...args) => {
      try {
        return cache.originalReadQuery(...args);
      } catch (err) {
        return undefined;
      }
    };

    const client = new ApolloClient({
      link,
      cache,
      typeDefs,
      resolvers
    });

    // set client immediately (replaces cache persist)
    setClient(client);

    return () => {};
  }, []);

  if (client === undefined) return <Spinner />;
  return <ApolloProvider client={client}>{props.children}</ApolloProvider>;
}
Example #22
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>
  );
}