Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'apollo-link-ws' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
import { version } from '../../package.json'
import { GET_CHANNELS } from '../queries'
// Create an http link:
const httpLink = new HttpLink({
uri: process.env.REACT_APP_SERVER || 'http://localhost:4000',
includeExtensions: true,
headers: {
authorization: localStorage.getItem('token'),
'client-name': 'Together [web]',
'client-version': version,
},
})
// Create a WebSocket link:
const wsLink = new WebSocketLink({
uri:
process.env.REACT_APP_SUBSCRIPTION_SERVER || 'ws://localhost:4000/graphql',
options: {
reconnect: true,
timeout: 30000,
connectionParams: {
authToken: localStorage.getItem('token'),
},
},
})
// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
// split based on operation type
({ query }) => {
const WebSocketApolloClient = ({
url,
subscriptionsUrl,
}: IApolloServerUrlInfo) => {
const httpLink = createHttpLink({
fetch: async (input, init) => {
const response = await fetch(input, init);
return response;
},
uri: url,
});
const wsLink = new WebSocketLink({
options: {
reconnect: true,
timeout: 999999999,
},
uri: subscriptionsUrl,
webSocketImpl: WebSocket,
});
const link = split(
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
function create(initialState, native) {
const httpLink = new HttpLink({
uri: 'https://api.graph.cool/simple/v1/cjh2g1fxn6gsw0108o6ud01ms', // Server URL (must be absolute)
credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
});
const wsLink =
(process.browser || native) &&
new WebSocketLink({
uri: 'wss://subscriptions.graph.cool/v1/cjh2g1fxn6gsw0108o6ud01ms',
options: {
reconnect: true,
},
});
const link =
!process.browser && !native
? httpLink
: split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return (
kind === 'OperationDefinition' && operation === 'subscription'
);
},
wsLink,
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { split } from 'apollo-link'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'
// Create an http link:
const httpLink = new HttpLink({
uri: `http://localhost:${process.env.REACT_APP_SERVER_PORT}`,
})
// Create a WebSocket link:
const wsLink = new WebSocketLink({
uri: `ws://localhost:${process.env.REACT_APP_SERVER_PORT}/`,
options: {
reconnect: true,
},
})
// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
// split based on operation type
({ query }) => {
const { kind, operation } = getMainDefinition(query)
return kind === 'OperationDefinition' && operation === 'subscription'
},
wsLink,
httpLink
}
return createHttpLink(config);
})();
const authLink = setContext((_, {headers: extraHeaders}) => {
const token = getToken();
const headers = {...extraHeaders};
if (token) {
headers.authorization = `Bearer ${token}`;
}
return {headers};
});
const wsLink = new WebSocketLink({
uri: WEBSOCKET_URL,
options: {
reconnect: true,
connectionParams: {
authToken: getToken(),
},
}
});
// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
// split based on operation type
({ query }) => {
const {kind, operation} = getMainDefinition(query);
/* Initialize Apollo Client for GraphQL */
// You might want to set these manually if you're running your server somewhere else
const httpUri = Meteor.absoluteUrl('graphql'); // http://localhost:3000/graphql
const wsUri = Meteor.absoluteUrl('subscriptions').replace(/^http/, 'ws'); // ws://localhost:3000/subscriptions
// Apollo 2.0 now uses the extensible "ApolloLink" (the following does not rely on Meteor)
const link = ApolloLink.split(
operation => {
const operationAST = getOperationAST(operation.query, operation.operationName);
return !!operationAST && operationAST.operation === 'subscription';
},
new WebSocketLink({
uri: wsUri,
options: {
reconnect: true, // tells client to reconnect websocket after being disconnected (which will happen after a hot-reload)
// // might be helpful if you want to carry login state from client
// // it is recommended you use the secure version of websockets (wss) when transporting sensitive login information
// connectionParams: {
// authToken: localStorage.getItem("Meteor.loginToken")
// }
}
}),
new HttpLink({ uri: httpUri })
);
const cache = new InMemoryCache(window.__APOLLO_STATE);
const client = new ApolloClient({
});
const hasSubscriptionOperation = operation =>
operation.query.definitions.reduce(
(result, definition) => result || definition.operation === 'subscription',
false
);
// http://localhost:8080 is put behind a proxy by webpack (cors)
const uri = '/graphql';
const link = ApolloLink.from([
errorLink,
authLink.split(
hasSubscriptionOperation,
new WsLink({
uri: 'ws://localhost:8081/graphql',
options: { reconnect: true },
}),
new HttpLink({ uri })
),
]);
const cache = new Cache();
const client = new ApolloClient({
link,
cache: cache.restore(window.__APOLLO_STATE__ || {}),
});
export default () => (
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { ApolloProvider } from 'react-apollo'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { split } from 'apollo-link';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
const httpLink = new HttpLink({ uri: 'http://localhost:4000/graphql' });
const wsLink = new WebSocketLink({
uri: `ws://localhost:4000/subscriptions`,
options: {
reconnect: true
}
});
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink,
);
const client = new ApolloClient({
uri: session.endpoint,
headers,
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,
}
}
const authHeader = token ? `Bearer ${token}` : null;
operation.setContext({
headers: {
authorization: authHeader
}
});
return forward(operation);
});
const httpLink = new HttpLink({
uri: GRAPHQL_ENDPOINT
});
const httpLinkWithToken = apolloLinkWithToken.concat(httpLink);
const wsLink = new WebSocketLink({
uri: SUBSCRIPTIONS_ENDPOINT,
options: {
reconnect: true
}
});
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLinkWithToken
);
const client = new ApolloClient({