Skip to content

Commit

Permalink
add custom properties to request object (#1653)
Browse files Browse the repository at this point in the history
* add custom properties to request object

* fix typing for accept custom properties

* added unit test

* add changeset

* fix unused types
  • Loading branch information
FreeAoi committed May 8, 2024
1 parent 37885c2 commit 4f4253a
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/red-pants-cover.md
@@ -0,0 +1,5 @@
---
"openapi-fetch": patch
---

Let request object have custom properties
2 changes: 1 addition & 1 deletion packages/openapi-fetch/src/index.d.ts
Expand Up @@ -166,7 +166,7 @@ export type ClientMethod<Paths extends Record<string, PathMethods>, M extends Ht
I extends MaybeOptionalInit<Paths[P], M>,
>(
url: P,
...init: HasRequiredKeys<I> extends never ? [I?] : [I]
...init: HasRequiredKeys<I> extends never ? [(I & { [key: string]: unknown })?] : [I]
) => Promise<FetchResponse<Paths[P][M], I, Media>>;

export default function createClient<Paths extends {}, Media extends MediaType = MediaType>(
Expand Down
18 changes: 17 additions & 1 deletion packages/openapi-fetch/src/index.js
Expand Up @@ -5,6 +5,22 @@ const DEFAULT_HEADERS = {

const PATH_PARAM_RE = /\{[^{}]+\}/g;

/**
* Add custom parameters to Request object
*/
class CustomRequest extends Request {
constructor(input, init) {
super(input, init);

// add custom parameters
for (const key in init) {
if (!this[key]) {
this[key] = init[key];
}
}
}
}

/**
* Create an openapi-fetch client.
* @type {import("./index.js").default}
Expand Down Expand Up @@ -67,7 +83,7 @@ export default function createClient(clientOptions) {
if (requestInit.body instanceof FormData) {
requestInit.headers.delete("Content-Type");
}
let request = new Request(createFinalURL(url, { baseUrl, params, querySerializer }), requestInit);
let request = new CustomRequest(createFinalURL(url, { baseUrl, params, querySerializer }), requestInit);
// middleware (request)
const mergedOptions = {
baseUrl,
Expand Down
23 changes: 23 additions & 0 deletions packages/openapi-fetch/test/index.test.ts
Expand Up @@ -854,6 +854,29 @@ describe("client", () => {
expect(req.headers.get("foo")).toBe("bar");
});

it("can attach custom properties to request", async () => {
function createCustomFetch(data: any) {
const response = {
clone: () => ({ ...response }),
headers: new Headers(),
json: async () => data,
status: 200,
ok: true,
} as Response;
return async (input: Request) => {
expect(input).toHaveProperty("customProperty", "value");
return Promise.resolve(response);
};
}

const customFetch = createCustomFetch({});
const client = createClient<paths>({ fetch: customFetch, baseUrl });

client.GET("/self", {
customProperty: "value",
});
});

it("can modify response", async () => {
const toUnix = (date: string) => new Date(date).getTime();

Expand Down

0 comments on commit 4f4253a

Please sign in to comment.