codogo-react-widgets
Version:
Provides a unified way to access the styling of commonly used widgets across different apps
78 lines (61 loc) • 1.99 kB
JavaScript
import ApolloClient from "apollo-client";
import { HttpLink } from "apollo-link-http";
import { split } from "apollo-link";
import { InMemoryCache } from "apollo-cache-inmemory";
import { WebSocketLink } from "apollo-link-ws";
import { getMainDefinition } from "apollo-utilities";
import { setContext } from "apollo-link-context";
import getJWT from "./getJWT";
import { graphcoolURL, graphcoolSubURL } from "./consts";
//------------------------------
//http
var rawHTTPLink = new HttpLink({ uri: graphcoolURL });
var authMiddleware = setContext(function (operation, oldContext) {
return getJWT().then(function (jwt) {
return R.assocPath(["headers", "authorization"], jwt ? "Bearer " + jwt : undefined, oldContext);
});
});
var httpLink = authMiddleware.concat(rawHTTPLink);
//------------------------------
//subscription
//the JWT is fetched asyncnsly, but the WebSocketLink needs it sync
//we define a varible here that will be populated with the JWT as fast as possible.
//then `connectionParams` below uses a getter to provide the most up to date version
//of `asyncAuthToken`.
var asyncAuthToken = undefined;
getJWT().then(function (jwt) {
asyncAuthToken = jwt;
});
var connectionParams = {
get Authorization() {
return "Bearer " + asyncAuthToken;
}
};
var wsLink = new WebSocketLink({
uri: graphcoolSubURL,
options: {
reconnect: true,
timeout: 20000,
connectionParams: connectionParams
}
});
//------------------------------
//join
var link = split(
// split based on operation type
function (_ref) {
var query = _ref.query;
var _getMainDefinition = getMainDefinition(query),
kind = _getMainDefinition.kind,
operation = _getMainDefinition.operation;
return kind === "OperationDefinition" && operation === "subscription";
}, wsLink, httpLink);
//------------------------------
//cache
var cache = new InMemoryCache({});
//------------------------------
//client
export var client = new ApolloClient({
cache: cache,
link: link
});