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: add onRequest hook to createAPIClient #1469

Closed
wants to merge 6 commits into from
Closed
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
5 changes: 5 additions & 0 deletions .changeset/bright-rivers-explain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@shopware/api-client": minor
---

Added onRequest interceptor as option to ApiClientHooks in API Client
10 changes: 10 additions & 0 deletions packages/api-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,16 @@ apiClient.hook("onDefaultHeaderChanged", (key, value) => {

calling `apiClient.hook` will autocomplete the list of available hooks.

#### onResponse

Using the onRequest hook, you can modify the request before it is sent. This is particularly useful for adding custom headers.

```typescript
client.hook("onRequest", (_request, options) => {
options.headers.append("x-custom-header", "value");
});
```

## Links

- [🧑‍🎓 Tutorial](https://api-client-tutorial-composable-frontends.pages.dev)
Expand Down
9 changes: 9 additions & 0 deletions packages/api-client/src/createAPIClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import defu from "defu";
import { createHooks } from "hookable";
import {
type FetchOptions,
type FetchRequest,
type FetchResponse,
type ResolvedFetchOptions,
type ResponseType,
ofetch,
} from "ofetch";
Expand Down Expand Up @@ -68,6 +70,10 @@ export type ApiClientHooks = {
onResponseError: (response: FetchResponse<ResponseType>) => void;
onSuccessResponse: <T>(response: FetchResponse<T>) => void;
onDefaultHeaderChanged: <T>(headerName: string, value?: T) => void;
onRequest: (
request: FetchRequest,
options: ResolvedFetchOptions<ResponseType>,
) => void;
};

export function createAPIClient<
Expand Down Expand Up @@ -121,6 +127,9 @@ export function createAPIClient<
apiClientHooks.callHook("onResponseError", response);
errorInterceptor(response);
},
async onRequest({ request, options }) {
await apiClientHooks.callHook("onRequest", request, options);
},
});
/**
* Invoke API request based on provided path definition.
Expand Down
118 changes: 118 additions & 0 deletions packages/api-client/src/createApiClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,124 @@ describe("createAPIClient", () => {
expect(contextChangedMock).not.toHaveBeenCalled();
});

it("should invoke onRequest hook once", async () => {
const app = createApp().use(
"/context",
eventHandler(async () => {
return {};
}),
);

const baseURL = await createPortAndGetUrl(app);

const onRequestMock = vi.fn();

const client = createAPIClient({
baseURL,
accessToken: "123",
contextToken: "456",
});

client.hook("onRequest", onRequestMock);

await client.invoke("readContext get /context");

expect(onRequestMock).toHaveBeenCalledOnce();
});

it("should allow onRequest hook to modify request options", async () => {
const requestHeadersSpy = vi.fn();

const app = createApp().use(
"/context",
eventHandler(async (event) => {
const requestHeaders = getHeaders(event);
requestHeadersSpy(requestHeaders);
return {};
}),
);

const baseURL = await createPortAndGetUrl(app);

const client = createAPIClient({ baseURL });

client.hook("onRequest", (_request, options) => {
options.headers.append("x-custom-header", "modified-header");
});

await client.invoke("readContext get /context");

expect(requestHeadersSpy).toHaveBeenCalledWith(
expect.objectContaining({
"x-custom-header": "modified-header",
}),
);
});

it("should invoke all onRequest hooks independently", async () => {
const requestHeadersSpy = vi.fn();

const app = createApp().use(
"/context",
eventHandler(async (event) => {
const requestHeaders = getHeaders(event);
requestHeadersSpy(requestHeaders); // Capture request headers
return {};
}),
);

const baseURL = await createPortAndGetUrl(app);

const client = createAPIClient({ baseURL });

client.hook("onRequest", (_request, options) => {
options.headers.append("x-hook1", "value1");
});

client.hook("onRequest", (_request, options) => {
options.headers.append("x-hook2", "value2");
});

await client.invoke("readContext get /context");

expect(requestHeadersSpy).toHaveBeenCalledWith(
expect.objectContaining({
"x-hook1": "value1",
"x-hook2": "value2",
}),
);
});

it("should not interfere with normal request execution", async () => {
const requestHeadersSpy = vi.fn();

const app = createApp().use(
"/context",
eventHandler(async (event) => {
const requestHeaders = getHeaders(event);
requestHeadersSpy(requestHeaders);
return { success: true };
}),
);

const baseURL = await createPortAndGetUrl(app);

const client = createAPIClient({ baseURL });

client.hook("onRequest", () => {
// Perform a no-op
});

const response = await client.invoke("readContext get /context");

expect(response.data).toEqual({ success: true });
expect(requestHeadersSpy).toHaveBeenCalledWith(
expect.objectContaining({
accept: "application/json",
}),
);
});

it("should throw error when there is a problem with request", async () => {
const app = createApp().use(
"/checkout/cart",
Expand Down
Loading