Skip to content

Instantly share code, notes, and snippets.

@j
Last active October 27, 2017 22:48
Show Gist options
  • Save j/5a904125f7c5b45c36e0e56212757c2b to your computer and use it in GitHub Desktop.
Save j/5a904125f7c5b45c36e0e56212757c2b to your computer and use it in GitHub Desktop.
Link Switching Alternative
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import HttpLinkSwitcher from './HttpLinkSwitcher';
let _client; // browser cache
export default (initialState = {}) => {
if (_client) {
return _client;
}
const client = new ApolloClient({
ssrMode: !process.browser,
link: new HttpLinkSwitcher([{
name: 'blog',
isDefault: true,
opts: { uri: 'https://myblog.com/graphql' }
}, {
name: 'github',
opts: { uri: 'https://api.github.com.com/graphql' }
}]),
cache: (new InMemoryCache()).restore(initialState)
});
if (process.browser) {
_client = client;
}
return client;
}
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
// uses HttpLinkSwitcher
export const getBlogPosts = graphql(gql`
query {
posts() {
id
title
message
}
}`
);
// uses alternate client
export const getRepositories = graphql(gql`
query {
repositories() {
id
name
}
}`,
{
options: {
return {
context: {
useClient: 'github'
}
}
}
}
);
import { ApolloLink } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
export default class HttpLinkSwitcher extends ApolloLink {
constructor(clientOpts) {
super();
this.defaultClient = null;
this.clients = {};
clientOpts.forEach(({ name, isDefault, opts }) => {
this.clients[name] = new HttpLink(opts);
if (isDefault) {
this.defaultClient = this.clients[name]
}
});
if (!this.defaultClient) {
throw new Error('missing default client');
}
}
request(operation, forward) {
const { useClient } = operation.getContext();
if (!useClient) {
return this.defaultClient.request(operation);
}
if (typeof this.clients[useClient] === 'undefined') {
console.warn(`client "${useClient}" does not exist`);
return Observable.of();
}
return this.clients[useClient].request(operation);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment