feat: allow throwing error with .response prop in upgrade (#113)

Co-authored-by: Pooya Parsa <pooya@pi0.io>
This commit is contained in:
Luke Hagar
2025-01-24 15:06:21 -06:00
committed by GitHub
parent fdba8ed6ce
commit 3bb5269b6f
2 changed files with 17 additions and 7 deletions

View File

@@ -66,8 +66,12 @@ export class AdapterHookable {
};
}
} catch (error) {
if (error instanceof Response) {
return { context, endResponse: error };
const errResponse = (error as { response: Response }).response || error;
if (errResponse instanceof Response) {
return {
context,
endResponse: errResponse,
};
}
throw error;
}
@@ -96,6 +100,8 @@ export type UpgradeRequest =
headers: Headers;
};
export type UpgradeError = Response | { readonly response: Response };
export interface Hooks {
/** Upgrading */
/**

View File

@@ -58,11 +58,15 @@ export function createDemo<T extends Adapter<any, any>>(
},
upgrade(req) {
if (req.url.endsWith("?unauthorized")) {
return new Response("unauthorized", {
status: 401,
statusText: "Unauthorized",
headers: { "x-error": "unauthorized" },
});
throw {
get response() {
return new Response("unauthorized", {
status: 401,
statusText: "Unauthorized",
headers: { "x-error": "unauthorized" },
});
},
};
}
req.context.test = "1";
return {