How to use the apollo-link.ApolloLink.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 cdmbase / fullstack-pro / servers / frontend-server / src / config / apollo-client.ts View on Github external
lazy: true,
            connectionParams,
            connectionCallback: async (error) => {
                if (error) {
                    logger.trace('[connectionCallback error] %j', error);
                    // error.message has to match what the server returns.
                    if ((error as any).message === 'TokenExpired') {
                        console.log('onTokenError about to call');
                        // Reset the WS connection for it to carry the new JWT.
                        (wsLink as any).subscriptionClient.close(false, false);
                    }
                }
            },
        },
    });
    link = ApolloLink.split(
        ({ query, operationName }) => {
            if (operationName.endsWith('_WS')) {
                return true;
            } else {
                const operationAST = getOperationAST(query as any, operationName);
                return !!operationAST && operationAST.operation === 'subscription';
            }
        },
        wsLink,
        new HttpLink({
            uri: PUBLIC_SETTINGS.GRAPHQL_URL,
        }),
    );
} else {
    link = new BatchHttpLink({ uri: PUBLIC_SETTINGS.LOCAL_GRAPHQL_URL });
}
github sysgears / apollo-universal-starter-kit / src / client / app / Main.jsx View on Github external
for (const afterware of modules.afterwares) {
      afterware(response, options);
    }
  } catch (e) {
    console.error(e);
  }
  next();
});

let connectionParams = {};
for (const connectionParam of modules.connectionParams) {
  Object.assign(connectionParams, connectionParam());
}

const wsUri = apiUri.replace(/^http/, 'ws');
let link = ApolloLink.split(
  operation => {
    const operationAST = getOperationAST(operation.query, operation.operationName);
    return !!operationAST && operationAST.operation === 'subscription';
  },
  new WebSocketLink({
    uri: wsUri,
    options: {
      reconnect: true,
      connectionParams: connectionParams
    }
  }),
  new BatchHttpLink({ fetch })
);

// if (__PERSIST_GQL__) {
//   networkInterface = addPersistedQueries(networkInterface, queryMap);
github akeating / pespa / src / client / vue / src / api / client.js View on Github external
export default function newClient(opts) {
  // eslint-disable-next-line new-cap
  const link = new ApolloLink.split(
    operation => hasSubscription(operation.query),
    absintheSocketLink(opts),
    createHttpLink({uri: '/api/graphql'})
  );

  const client = new ApolloClient({
    link,
    cache: new InMemoryCache()
  });
  return client;
}
github reactioncommerce / example-storefront / src / lib / apollo / initApollo.js View on Github external
const httpLink = new HttpLink({ uri: graphqlUrl, credentials: "same-origin" });
  let link = httpLink;

  if (process.browser) {
    // If we are in the browser, try to split the request between wsLink and httpLink.
    const wsLink = new WebSocketLink({
      uri: wsGraphqlUrl,
      options: {
        reconnect: true, // auto-reconnect
        connectionParams: {
          authToken: options.accessToken
        }
      }
    });

    link = ApolloLink.split(
      (operation) => {
        const operationAST = getOperationAST(operation.query, operation.operationName);
        return !!operationAST && operationAST.operation === "subscription";
      },
      wsLink,
      httpLink
    );
  }

  return new ApolloClient({
    ssrMode: !process.browser,
    link: ApolloLink.from([omitTypenameLink, authLink, errorLink, link]),
    cache: new InMemoryCache().restore(initialState || {})
  });
};
github prisma-labs / graphql-playground / packages / graphql-playground-react / src / state / sessions / fetchingSagas.ts View on Github external
credentials,
  })

  if (!subscriptionEndpoint) {
    return { link: httpLink }
  }

  const subscriptionClient = new SubscriptionClient(subscriptionEndpoint, {
    timeout: 20000,
    lazy: true,
    connectionParams,
  })

  const webSocketLink = new WebSocketLink(subscriptionClient)
  return {
    link: ApolloLink.split(
      operation => isSubscription(operation),
      webSocketLink as any,
      httpLink,
    ),
    subscriptionClient,
  }
}
github sysgears / apollo-universal-starter-kit / modules / upload / client-react / netLink.js View on Github external
export default uri =>
  ApolloLink.split(
    ({ variables }) => extractFiles(cloneDeep(variables)).length > 0,
    createUploadLink({ uri, credentials: 'include' }),
    new BatchHttpLink({
      uri,
      credentials: 'include'
    })
  );
github awslabs / aws-mobile-appsync-sdk-js / packages / aws-appsync-subscription-link / src / index.ts View on Github external
observer.next({ [CONTROL_EVENTS_KEY]: controlEvents });

              return () => {};
            })
        )
      }),
      new NonTerminatingLink("subsInfo", { link: resultsFetcherLink }),
      new SubscriptionHandshakeLink("subsInfo")
    ]);
  } else {
    const { url } = infoOrUrl;
    resultsFetcherLink = theResultsFetcherLink || createHttpLink({ uri: url });
    subscriptionLinks = new AppSyncRealTimeSubscriptionHandshakeLink(infoOrUrl);
  }

  return ApolloLink.split(
    operation => {
      const { query } = operation;
      const { kind, operation: graphqlOperation } = getMainDefinition(
        query
      ) as OperationDefinitionNode;
      const isSubscription =
        kind === "OperationDefinition" && graphqlOperation === "subscription";

      return isSubscription;
    },
    subscriptionLinks,
    resultsFetcherLink
  );
}
github beeman / kikstart-graphql-client / src / kikstart-apollo-client.ts View on Github external
const wsOperations: string[] = [];

  if (mutationLink === 'ws') {
    wsOperations.push('mutation');
  }

  if (queryLink === 'ws') {
    wsOperations.push('query');
  }

  if (subscriptionLink === 'ws') {
    wsOperations.push('subscription');
  }

  return wsOperations.length
    ? ApolloLink.split(
        ({ query }) =>
          (({ kind, operation }: any) =>
            kind === 'OperationDefinition' && wsOperations.includes(operation))(
            getMainDefinition(query),
          ),
        wsLink,
        httpLink,
      )
    : httpLink;
};
github orbiting / publikator-frontend / lib / apollo / initApollo.js View on Github external
function create (initialState = {}, headers = {}) {
  const http = new HttpLink({
    uri: API_URL,
    credentials: 'include',
    headers: {
      cookie: headers.cookie,
      accept: headers.accept,
      Authorization: API_AUTHORIZATION_HEADER
    }
  })

  const link = process.browser
    ? ApolloLink.split(
      hasSubscriptionOperation,
      new WebSocketLink({
        uri: API_WS_URL,
        options: {
          reconnect: true,
          timeout: 50000
        }
      }),
      http
    )
    : http

  return new ApolloClient({
    connectToDevTools: process.browser,
    cache: new InMemoryCache({
      fragmentMatcher,