Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: refactor to avoid client loading race condition #10

Merged
merged 1 commit into from
Feb 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions src/client/browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {
createClient,
dedupExchange,
cacheExchange,
fetchExchange,
ssrExchange,
type ClientOptions,
type Client,
} from "@urql/core";

let client: Client;
let ssr: ReturnType<typeof ssrExchange>;

export function getClient() {
assertConfigured();
return client;
}

export function configureClient(config: ClientOptions) {
ssr = ssrExchange({ isClient: true });
const exchanges = [dedupExchange, cacheExchange, ssr, fetchExchange];
if (process.env.NODE_ENV !== "production") {
// eslint-disable-next-line @typescript-eslint/no-var-requires
exchanges.push(require("@urql/devtools").devtoolsExchange);
}

client = createClient({
exchanges,
fetch,
...config,
});
}

export function hydrateQuery(opKey: string, data: any, error: any) {
assertConfigured();
ssr.restoreData({
[opKey]: {
data: data ? JSON.stringify(data) : undefined,
error,
},
});
}

function assertConfigured() {
if (!client) throw new Error("<gql-client> not configured.");
}
43 changes: 0 additions & 43 deletions src/client/index.ts

This file was deleted.

61 changes: 61 additions & 0 deletions src/client/node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import fetchImpl from "make-fetch-happen";
import {
createClient,
dedupExchange,
cacheExchange,
fetchExchange,
ssrExchange,
type ClientOptions,
type Client,
} from "@urql/core";

const kClient = Symbol("client");
const strictSSL = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0";

export function getClient(out: any): Client {
const client = out.global[kClient];
if (!client) throw new Error("<gql-client> not configured.");
return out.global[kClient];
}

export function configureClient(config: ClientOptions, out: any) {
out.global[kClient] = createClient({
exchanges: [
dedupExchange,
cacheExchange,
ssrExchange({ isClient: false }),
fetchExchange,
],
fetch: ((url: string, options: fetchImpl.FetchOptions) => {
const incomingMessage =
(out.stream && (out.stream.req || out.stream.request)) ||
out.global.req ||
out.global.request;
if (!incomingMessage) return fetchImpl(url, options);

return fetchImpl(
new URL(
url,
`${incomingMessage.protocol}://${incomingMessage.headers.host}`
).toString(),
{
...options,
strictSSL,
headers: {
...incomingMessage.headers,
...options.headers,
},
}
);
}) as any,
...config,
});
}

export function whenConfigured() {
throw new Error("Cannot be called on the server.");
}

export function hydrateQuery() {
throw new Error("Cannot be called on the server.");
}
4 changes: 4 additions & 0 deletions src/client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"main": "./node",
"browser": "./browser"
}
6 changes: 3 additions & 3 deletions src/components/gql-client/index.marko
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import lookup from "../../client/lookup";
import { configureClient } from "../../client";
class {
onCreate(input) {
lookup.config = input;
onCreate(input, out) {
configureClient(input, out);
}
}

Expand Down
5 changes: 2 additions & 3 deletions src/components/gql-mutation/index.marko
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createClient } from "../../client";
import { getClient } from "../../client";
class {
onCreate() {
this.state = { results: {}, fetching: false };
Expand All @@ -8,9 +8,8 @@ $ const { renderBody, mutation, requestPolicy } = input;

<${renderBody}(
(variables, options) => {
const { client } = window.$$GQL || (window.$$GQL = createClient({}));
component.setState("fetching", true);
return client
return getClient()
.mutation(mutation, variables, { requestPolicy, ...options })
.toPromise()
.then((results) => {
Expand Down
71 changes: 36 additions & 35 deletions src/components/gql-query/components/gql-query-client/index.marko
Original file line number Diff line number Diff line change
@@ -1,57 +1,58 @@
import { pipe, subscribe } from "wonka";
import { getClient, hydrateQuery } from "../../../../client";
import readyLookup from "../../ready-lookup";
static function doQuery(
component,
{ query, variables, requestPolicy },
options
) {
if (component.unsubscribe) {
component.unsubscribe();
component.unsubscribe = null;
}

component.state.fetching = true;
component.unsubscribe = pipe(
window.$$GQL.client.query(query, variables, {
requestPolicy,
...options,
}),
subscribe(({ data, error }) => {
component.state.data = data;
component.state.error = error;
component.state.fetching = false;
})
).unsubscribe;
}
class {
onCreate({ data, error, opKey }) {
this.state = { data, error, fetching: false };
this.mounted = false;

if (typeof document !== "undefined" && opKey) {
window.$$GQL.ssr.restoreData({
[opKey]: {
data: data ? JSON.stringify(data) : undefined,
error,
},
});
hydrateQuery(opKey, data, error);
readyLookup[this.id]();
}
}
onInput(input) {
if (!input.opKey) doQuery(this, input);
if (!input.opKey) {
if (this.mounted) {
this.doQuery();
} else {
this.once("mounted", () => this.doQuery());
}
}
}
onMount() {
this.mounted = true;
}
onDestroy() {
this.stopQuery();
}
stopQuery() {
this.unsubscribe && this.unsubscribe();
this.unsubscribe = undefined;
}
doQuery(options) {
this.stopQuery();
this.state.fetching = true;
this.unsubscribe = pipe(
getClient().query(this.input.query, this.input.variables, {
requestPolicy: this.input.requestPolicy,
...options,
}),
subscribe(({ data, error }) => {
this.state.data = data;
this.state.error = error;
this.state.fetching = false;
})
).unsubscribe;
}
}

<if(state.data || state.error)>
<${input.then}(
state,
(options) =>
doQuery(component, input, { requestPolicy: "network-only", ...options }),
(options) => {
component.doQuery({ requestPolicy: "network-only", ...options });
},
)/>
</if>
<else>
<${input.placeholder}/>
</else>
<else><${input.placeholder}/></else>
2 changes: 0 additions & 2 deletions src/components/gql-query/impl/browser.marko
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import readyLookup from "../ready-lookup";
import { createClient } from "../../../client";
$ window.$$GQL || (window.$$GQL = createClient({}));

<div key="root" no-update-if(!component.ready)>
$ component.ready = true;
Expand Down
35 changes: 2 additions & 33 deletions src/components/gql-query/impl/server.marko
Original file line number Diff line number Diff line change
@@ -1,38 +1,7 @@
import fetchImpl from "make-fetch-happen";
import { createClient } from "../../../client";
static const strictSSL = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0";
import { getClient } from "../../../client";

$ {
const store =
out.global.$$GQL ||
(out.global.$$GQL = createClient({
isServer: true,
fetch(url, options) {
const incomingMessage =
(out.stream && (out.stream.req || out.stream.request)) ||
out.global.req ||
out.global.request;
if (!incomingMessage) return fetchImpl(url, options);

return fetchImpl(
new URL(
url,
`${incomingMessage.protocol}://${incomingMessage.headers.host}`
).toString(),
{
...options,
strictSSL,
headers: {
...incomingMessage.headers,
...options.headers,
},
}
);
},
}));
}
<div key="root" no-update>
<await(store.client.query(input.query, input.variables).toPromise())
<await(getClient(out).query(input.query, input.variables).toPromise())
client-reorder
placeholder=input.placeholder
>
Expand Down