Skip to content

Commit

Permalink
feat: add fetch imp as third param in custom fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
bill-min authored and DylanPiercey committed May 7, 2024
1 parent 95dccc0 commit 003c769
Show file tree
Hide file tree
Showing 9 changed files with 112 additions and 25 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,12 @@ This attribute allows you to pass a custom `fetch` implementation.

In the following example we'll add a token to each fetch request that our Client sends to our GraphQL API.

> Note: fetchImp as third parameter is the default implementation based on environment. It is `fetch` API in browser and `make-fetch-happen` in node.
```marko
<gql-client
url="http://localhost:3000/graphql"
fetch=((resource, options) => {
fetch=((resource, options, fetchImp) => {
const token = getToken();
return fetch(resource, {
...options,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<div>
<noscript
id="GENERATED-0"
/>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<div>
<noscript
id="GENERATED-0"
/>
</div>
<div
id="GENERATED-1"
style="display:none"
>
<span>
Hello world!
</span>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<div>
<span>
Hello world!
</span>
</div>
<div
id="GENERATED-0"
style="display:none"
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { gql } from "../../../../../../index";
static const QUERY = gql`
{
hello
}
`;

class {}

<gql-query query=QUERY>
<@then|{ data }|><span>${data.hello}</span></@then>
</gql-query>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Example</title>
<esbuild-assets/>
</head>
<body>
<gql-client url=input.graphqlURL fetch=((resource, options, fetchImp) => fetchImp(resource, options)) />
<app />
</body>
</html>
4 changes: 4 additions & 0 deletions src/components/gql-query/__tests__/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ describe(
);

describe("isomorphic", fixture(path.join(__dirname, "fixtures/isomorphic")));
describe(
"isomorphic-fetch-imp",
fixture(path.join(__dirname, "fixtures/isomorphic-fetch-imp")),
);
describe(
"isomorphic-placeholder",
fixture(path.join(__dirname, "fixtures/isomorphic-placeholder")),
Expand Down
12 changes: 10 additions & 2 deletions src/node_modules/@internal/client/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ export function getClient() {
return client;
}

export function configureClient(config: ClientOptions) {
export function configureClient(
config: ClientOptions & {
fetch?: (
...params: [...Parameters<typeof fetch>, typeof fetch]
) => ReturnType<typeof fetch>;
},
) {
ssr = ssrExchange({ isClient: true });
let exchanges = [dedupExchange, cacheExchange, ssr, fetchExchange];
if (process.env.NODE_ENV !== "production" && devtoolsExchange) {
Expand All @@ -34,7 +40,9 @@ export function configureClient(config: ClientOptions) {
client = createClient({
...config,
exchanges,
fetch: config.fetch || fetch,
fetch: config.fetch
? (...params: Parameters<typeof fetch>) => config.fetch!(...params, fetch)
: fetch,
});
}

Expand Down
65 changes: 43 additions & 22 deletions src/node_modules/@internal/client/node.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fetchImpl from "make-fetch-happen";
import fetchImpl, { FetchOptions } from "make-fetch-happen";
import https from "https";
import {
createClient,
dedupExchange,
Expand All @@ -9,8 +10,17 @@ import {
type Client,
} from "@urql/core";

type FetchFn = (
uriOrRequest: string | Request,
opts?: FetchOptions,
) => ReturnType<typeof fetchImpl>;

const kClient = Symbol("client");
const { ca } = https.globalAgent.options;
const strictSSL = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0";
function internalFetch(url, options) {
return fetchImpl(url, { ...options, ca, strictSSL });
}

export const readyLookup = {};

Expand All @@ -20,7 +30,14 @@ export function getClient(out: any): Client {
return out.global[kClient];
}

export function configureClient(config: ClientOptions, out: any) {
export function configureClient(
config: ClientOptions & {
fetch?: (
...params: [...Parameters<FetchFn>, FetchFn]
) => ReturnType<FetchFn>;
},
out: any,
) {
let exchanges = [
dedupExchange,
cacheExchange,
Expand All @@ -35,30 +52,34 @@ export function configureClient(config: ClientOptions, out: any) {
out.global[kClient] = createClient({
...config,
exchanges,
fetch:
config.fetch ||
(async (url, options) => {
const incomingMessage =
(out.stream && (out.stream.req || out.stream.request)) ||
out.global.req ||
out.global.request;
if (typeof url !== "string") throw new Error("Expected a string.");
if (!incomingMessage) return fetchImpl(url, options as any) as any;
const protocol =
incomingMessage.headers["x-forwarded-proto"] ||
incomingMessage.protocol;
const host =
incomingMessage.headers["x-forwarded-host"] ||
incomingMessage.headers.host;
return fetchImpl(new URL(url, `${protocol}://${host}`).toString(), {
...(options as any),
strictSSL,
fetch: async (url, options: any) => {
const fetchImplOverride = config.fetch
? (...params: Parameters<FetchFn>) =>
config.fetch!(...params, internalFetch)
: internalFetch;
const incomingMessage =
(out.stream && (out.stream.req || out.stream.request)) ||
out.global.req ||
out.global.request;
if (typeof url !== "string") throw new Error("Expected a string.");
if (!incomingMessage) return fetchImplOverride(url, options) as any;
const protocol =
incomingMessage.headers["x-forwarded-proto"] ||
incomingMessage.protocol;
const host =
incomingMessage.headers["x-forwarded-host"] ||
incomingMessage.headers.host;
return fetchImplOverride(
new URL(url, `${protocol}://${host}`).toString(),
{
...options,
headers: {
...incomingMessage.headers,
...options?.headers,
},
}) as any;
}),
},
) as any;
},
});
}

Expand Down

0 comments on commit 003c769

Please sign in to comment.