You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.4 KiB
56 lines
1.4 KiB
import type {
|
|
AfterResponseHook,
|
|
BeforeErrorHook,
|
|
BeforeRequestHook,
|
|
BeforeRetryHook,
|
|
HookContext
|
|
} from './types.ts';
|
|
|
|
export async function runBeforeRequest(
|
|
hooks: ReadonlyArray<BeforeRequestHook>,
|
|
ctx: HookContext
|
|
): Promise<Response | undefined> {
|
|
for (const hook of hooks) {
|
|
const result = await hook(ctx);
|
|
if (result instanceof Response) return result;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
export async function runBeforeRetry(
|
|
hooks: ReadonlyArray<BeforeRetryHook>,
|
|
ctx: HookContext & { error: unknown; retryDelay: number }
|
|
): Promise<void> {
|
|
for (const hook of hooks) {
|
|
await hook(ctx);
|
|
}
|
|
}
|
|
|
|
export async function runAfterResponse(
|
|
hooks: ReadonlyArray<AfterResponseHook>,
|
|
ctx: HookContext,
|
|
response: Response
|
|
): Promise<Response> {
|
|
let current = response;
|
|
for (const hook of hooks) {
|
|
const result = await hook({ ...ctx, response: current });
|
|
if (result instanceof Response) current = result;
|
|
}
|
|
return current;
|
|
}
|
|
|
|
export async function runBeforeError(
|
|
hooks: ReadonlyArray<BeforeErrorHook>,
|
|
ctx: HookContext & { response?: Response },
|
|
error: unknown
|
|
): Promise<Response | undefined> {
|
|
let current: Response | undefined = ctx.response;
|
|
for (const hook of hooks) {
|
|
const result = await hook({ ...ctx, response: current, error });
|
|
if (result instanceof Response) current = result;
|
|
}
|
|
// Only return when the hook actually swapped in a fresh response.
|
|
if (current !== undefined && current !== ctx.response) return current;
|
|
return undefined;
|
|
}
|