How to use the apollo-link.split function in apollo-link

To help you get started, we’ve selected a few apollo-link examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github arkhn / pyrog / client / src / app.tsx View on Github external
}
  }
});

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 coreLink = split(
  // Split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === "OperationDefinition" &&
      definition.operation === "subscription"
    );
  },
  wsLink,
  httpLinkAuth
);

// Aggregate all links
const links = [];
if (process.env.NODE_ENV === "development") {
  links.push(errorLink);
github hasura / custom-resolvers-boilerplate / src / utils.js View on Github external
// Create a WebSocket link:
  const wsLink = new WebSocketLink(new SubscriptionClient(
    uri,
    {
      reconnect: true,
      connectionParams: {
        headers
      }
    },
    ws
  ));

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


  return link;
};
github graphql-boilerplates / react-fullstack-graphql / subscriptions-with-apollo-worldchat / src / components / App.js View on Github external
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'

// Paste your own service ID here
const serviceId = ``

const httpLink = createHttpLink({ uri: `https://api.graph.cool/simple/v1/${serviceId}` })

const wsLink = new WebSocketLink({
  uri: `wss://subscriptions.graph.cool/v1/${serviceId}`,
  options: {
    reconnect: true
  }
})

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

const client = new ApolloClient({
  link,
  cache: new InMemoryCache().restore(window.__APOLLO_STATE__),
})

const WORLDCHAT_USERNAME_KEY = 'WORLDCHAT_USERNAME'

class App extends Component {
github creatorsdaily / client.creatorsdaily.com / libs / init-apollo.js View on Github external
const wsLink = new WebSocketLink({
      uri: process.env.GRAPHQL_WS,
      options: {
        reconnect: true,
        connectionParams: () => {
          if (!getToken) return {}
          const token = getToken()
          return {
            headers: {
              authorization: token ? `Bearer ${token}` : ''
            }
          }
        }
      }
    })
    link = split(
      // split based on operation type
      ({ query }) => {
        const definition = getMainDefinition(query)
        return (
          definition.kind === 'OperationDefinition' &&
          definition.operation === 'subscription'
        )
      },
      wsLink,
      link
    )
  }
  const cache = new InMemoryCache().restore(initialState)
  // if (isBrowser) persistCache({ cache, storage: localStorage })
  return new ApolloClient({
    connectToDevTools: isBrowser,
github realm / realm-graphql / src / GraphqlConfig.ts View on Github external
initial: 100,
        max: 5000,
      },
      attempts: {
        max: 3,
        retryIf: async (error) => {
          if (error && error.result && error.result.status === 401) {
            await this.refreshToken(0, /* shouldRetry */ false);
          }

          return true;
        },
      },
    });

    const link = split(({ query }) => {
        const { kind, operation } = getMainDefinition(query);
        return kind === "OperationDefinition" && operation === "subscription";
      },
      subscriptionLink,
      from([retryLink, this.authLink, httpLink]));

    return new ApolloClient({
      link,
      cache,
    });
  }
github erxes / erxes / src / apolloClient.ts View on Github external
// Subscription config
export const wsLink = new WebSocketLink({
  uri: REACT_APP_API_SUBSCRIPTION_URL || '',
  options: {
    reconnect: true,
    timeout: 30000
  }
});

type Definintion = {
  kind: string;
  operation?: string;
};

// Setting up subscription with link
const link = split(
  // split based on operation type
  ({ query }) => {
    const { kind, operation }: Definintion = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  wsLink,
  httpLinkWithMiddleware
);

// Creating Apollo-client
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link
});

export default client;
github Urigo / WhatsApp-Clone-Client-React / src / apollo-client.ts View on Github external
}),
  },
})

const authLink = setContext((_, { headers }) => {
  const auth = getAuthHeader()

  return {
    headers: {
      ...headers,
      Authorization: auth,
    },
  }
})

const terminatingLink = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query) as OperationDefinitionNode
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  authLink.concat(httpLink),
)

const link = ApolloLink.from([terminatingLink])
const cache = new InMemoryCache()

export default new ApolloClient({
  link,
  cache,
})
github hasura / graphql-engine / community / sample-apps / svelte-apollo / src / apollo.js View on Github external
uri: "ws://localhost:8080/v1/graphql",
  options: {
    reconnect: true,
    lazy: true,
    connectionParams: () => {
      return { headers: getHeaders() };
    },
  },
});

const httpLink = new HttpLink({
  uri: "http://localhost:8080/v1/graphql",
  headers: getHeaders()
});

const link = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query);
    return kind === "OperationDefinition" && operation === "subscription";
  },
  wsLink,
  httpLink
);

export const client = new ApolloClient({
  link,
  cache
});
github BrenoMazieiro / the-god-stack / spa / src / apolloConfig.js View on Github external
const httpLink = authLink.concat(createUploadLink({ uri }))

const wsLink = new WebSocketLink({
  uri: WS_URL,
  options: {
    reconnect: true,
    timeout: 10000,
    connectionParams: () => ({
      Authorization: localStorage.getItem('token'),
    }),
  },
})

export const client = new ApolloClient({
  link: split(
    ({ query }) => {
      const definition = getMainDefinition(query)
      return (definition.kind === 'OperationDefinition' && definition.operation === 'subscription')
    },
    wsLink,
    httpLink,
  ),
  cache: new InMemoryCache(),
})

/*
cache.writeData({
  data: {
    pessoas: [],
  },
})