Skip to content

Commit

Permalink
Add onRequest option
Browse files Browse the repository at this point in the history
  • Loading branch information
darthmaim committed Jul 26, 2024
1 parent b8bcc35 commit 0f5f1be
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/new-apes-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@gw2api/fetch": minor
---

Add `onRequest` option to modify requests
25 changes: 24 additions & 1 deletion packages/fetch/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,28 @@ export async function fetchGw2Api<
url.searchParams.set('access_token', options.accessToken);
}

// build request
let request = new Request(url, {
// The GW2 API never uses redirects, so we want to error if we encounter one.
// We use `manual` instead of `error` here so we can throw our own `Gw2ApiError` with the response attached
redirect: 'manual',

// set signal and cache from options
signal: options.signal,
cache: options.cache
});

// if there is a onRequest handler registered, let it modify the request
if(options.onRequest) {
request = await options.onRequest(request);

if(!(request instanceof Request)) {
throw new Error(`onRequest has to return a Request`);
}
}

// call the API
const response = await fetch(url, { redirect: 'manual', signal: options.signal, cache: options.cache });
const response = await fetch(request);

// call onResponse handler
await options.onResponse?.(response);
Expand Down Expand Up @@ -72,6 +92,9 @@ export type FetchGw2ApiOptions<Schema extends SchemaVersion> = {
/** The schema to use when making the API request */
schema?: Schema;

/** onRequest handler allows to modify the request made to the Guild Wars 2 API. */
onRequest?: (request: Request) => Request | Promise<Request>;

/**
* onResponse handler. Called for all responses, successful or not.
* Make sure to clone the response in case of consuming the body.
Expand Down

0 comments on commit 0f5f1be

Please sign in to comment.