Skip to content

Add custom fetch injection to FetchHttpClient for Next.js caching #5101

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
14 changes: 10 additions & 4 deletions packages/platform/src/FetchHttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,28 @@
import * as Context from "effect/Context"
import type * as Layer from "effect/Layer"
import type { HttpClient } from "./HttpClient.js"
import * as internal from "./internal/fetchHttpClient.js"
import { layer, layerWithFetch } from "./internal/fetchHttpClient.js"

/**
* @since 1.0.0
* @category tags
*/
export class Fetch extends Context.Tag(internal.fetchTagKey)<Fetch, typeof globalThis.fetch>() {}
export class Fetch extends Context.Tag("@effect/platform/FetchHttpClient/Fetch")<Fetch, typeof globalThis.fetch>() {}

/**
* @since 1.0.0
* @category tags
*/
export class RequestInit extends Context.Tag(internal.requestInitTagKey)<RequestInit, globalThis.RequestInit>() {}
export class RequestInit extends Context.Tag("@effect/platform/FetchHttpClient/FetchOptions")<RequestInit, globalThis.RequestInit>() {}

/**
* @since 1.0.0
* @category layers
* Default FetchHttpClient Layer using global fetch.
*
* @example
* import { FetchHttpClient } from "@effect/platform/FetchHttpClient"
*
* const defaultLayer = FetchHttpClient.layer
*/
export const layer: Layer.Layer<HttpClient> = internal.layer
export { layer, layerWithFetch }
59 changes: 56 additions & 3 deletions packages/platform/src/internal/fetchHttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import type * as Client from "../HttpClient.js"
import * as Error from "../HttpClientError.js"
import * as client from "./httpClient.js"
import * as internalResponse from "./httpClientResponse.js"
import * as Layer from "effect/Layer"
import * as Context from "effect/Context"

/** @internal */
export const fetchTagKey = "@effect/platform/FetchHttpClient/Fetch"
Expand All @@ -29,14 +31,14 @@ const fetch: Client.HttpClient = client.make((request, url, signal, fiber) => {
duplex: request.body._tag === "Stream" ? "half" : undefined,
signal
} as any),
catch: (cause) =>
catch: (cause: unknown) =>
new Error.RequestError({
request,
reason: "Transport",
cause
})
}),
(response) => internalResponse.fromWeb(request, response)
(response: Response) => internalResponse.fromWeb(request, response)
)
switch (request.body._tag) {
case "Raw":
Expand All @@ -50,5 +52,56 @@ const fetch: Client.HttpClient = client.make((request, url, signal, fiber) => {
return send(undefined)
})

/** @internal */
/**
* @internal
* Default FetchHttpClient Layer using global fetch.
*/
export const layer = client.layerMergedContext(Effect.succeed(fetch))

/**
* @internal
* Creates a FetchHttpClient Layer using a custom fetch implementation (e.g., Next.js's fetch).
*/
export function layerWithFetch(customFetch: typeof globalThis.fetch) {
return client.layerMergedContext(
Effect.sync(() =>
client.make((request, url, signal, fiber) => {
const context = fiber.getFiberRef(FiberRef.currentContext)
const fetch: typeof globalThis.fetch = customFetch
const options: RequestInit = context.unsafeMap.get(requestInitTagKey) ?? {}
const headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers
const send = (body: BodyInit | undefined) =>
Effect.map(
Effect.tryPromise({
try: () =>
fetch(url, {
...options,
method: request.method,
headers,
body,
duplex: request.body._tag === "Stream" ? "half" : undefined,
signal
} as any),
catch: (cause: unknown) =>
new Error.RequestError({
request,
reason: "Transport",
cause
})
}),
(response: Response) => internalResponse.fromWeb(request, response)
)
switch (request.body._tag) {
case "Raw":
case "Uint8Array":
return send(request.body.body as any)
case "FormData":
return send(request.body.formData)
case "Stream":
return Effect.flatMap(Stream.toReadableStreamEffect(request.body.stream), send)
}
return send(undefined)
})
)
)
}
24 changes: 24 additions & 0 deletions packages/platform/test/HttpClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,27 @@ describe("HttpClient", () => {
Effect.runPromise
))
})

describe("FetchHttpClient.layerWithFetch", () => {
it.effect("uses the injected fetch implementation", () =>
Effect.gen(function*() {
let called = false;
// Mock fetch implementation
const mockFetch: typeof globalThis.fetch = (input, init) => {
called = true;
// Return a minimal Response object
return Promise.resolve(new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { "Content-Type": "application/json" }
}));
};
const client = yield* HttpClient.HttpClient;
const response = yield* pipe(
HttpClient.get("https://mocked-url.com/"),
Effect.flatMap((_) => _.json)
).pipe(Effect.provide(FetchHttpClient.layerWithFetch(mockFetch)));
deepStrictEqual(response, { ok: true });
strictEqual(called, true);
})
);
});