UNPKG

@coko/client

Version:

Client side common code for coko apps

61 lines (60 loc) 1.98 kB
import { serverUrl as e } from "./getUrl.js"; import { ApolloClient as t, ApolloLink as n, InMemoryCache as r } from "@apollo/client"; import { getMainDefinition as i } from "@apollo/client/utilities"; import { GraphQLWsLink as a } from "@apollo/client/link/subscriptions"; import { SetContextLink as o } from "@apollo/client/link/context"; import s from "apollo-upload-client/UploadHttpLink.mjs"; import { createClient as c } from "graphql-ws"; //#region src/helpers/makeApolloClient.ts var l = (e) => { if (!e) return null; let t = e.replace(/^http:/, "ws:"); return t = t.replace(/^https:/, "wss:"), t; }; function u(e) { return Object.keys(e).forEach((t) => { let n = e[t]; typeof n == "object" && n && !(n instanceof File) ? (delete e.property, e[t] = u(n)) : t === "__typename" && delete e[t]; }), e; } var d = (d) => { let f = `${l(e)}/subscriptions`, p = new s({ uri: `${e}/graphql`, headers: { "Apollo-Require-Preflight": "true" } }), m = new o((e) => { let t = localStorage.getItem("token"); return { headers: { ...e.headers, authorization: t ? `Bearer ${t}` : "" } }; }), h = new n((e, t) => (e.variables &&= u(e.variables), t(e))), g = n.from([ h, m, p ]), _ = "[subscriptions-ws]", v = new a(c({ url: f, retryAttempts: Infinity, connectionParams: { authToken: localStorage.getItem("token") }, shouldRetry: () => (console.log(`${_} Attempting to reconnect...`), !0), on: { connecting: () => { console.log(`${_} Connecting...`); }, connected: (e) => { console.log(`${_} Connected.`); }, closed: (e) => { e instanceof CloseEvent && e.wasClean ? console.log(`${_} Disconnected:`, e) : console.error(`${_} Disconnected unexpectedly:`, e); } } })), y = { link: n.split(({ query: e }) => { let t = i(e); return t.kind === "OperationDefinition" && t.operation === "subscription"; }, v, g), cache: new r() }; return new t(d ? d(y) : y); }; //#endregion export { d as makeApolloClient };