diff --git a/src/fetch.ts b/src/fetch.ts index cd9ebf5..d3f30c3 100644 --- a/src/fetch.ts +++ b/src/fetch.ts @@ -170,16 +170,18 @@ export function createFetch(globalOptions: CreateFetchOptions): $Fetch { } } - context.response = await fetch( - context.request, - context.options as RequestInit - ).catch(async (error) => { - context.error = error; + try { + context.response = await fetch( + context.request, + context.options as RequestInit + ); + } catch (error) { + context.error = error as Error; if (context.options.onRequestError) { await context.options.onRequestError(context as any); } - return onError(context); - }); + return await onError(context); + } const responseType = (context.options.parseResponse ? "json" : context.options.responseType) || @@ -205,14 +207,15 @@ export function createFetch(globalOptions: CreateFetchOptions): $Fetch { await context.options.onResponseError(context as any); } - return onError(context); + return await onError(context); } return context.response; }; - const $fetch = function $fetch(request, options) { - return $fetchRaw(request, options).then((r) => r._data); + const $fetch = async function $fetch(request, options) { + const r = await $fetchRaw(request, options); + return r._data; } as $Fetch; $fetch.raw = $fetchRaw; diff --git a/test/index.test.ts b/test/index.test.ts index a64cddd..f0ff0af 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -9,14 +9,14 @@ import { } from "h3"; import { Blob } from "fetch-blob"; import { FormData } from "formdata-polyfill/esm.min.js"; -import { describe, beforeEach, afterEach, it, expect } from "vitest"; +import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { Headers, $fetch } from "../src/node"; describe("ofetch", () => { let listener; const getURL = (url) => joinURL(listener.url, url); - beforeEach(async () => { + beforeAll(async () => { const app = createApp() .use( "/ok", @@ -24,23 +24,23 @@ describe("ofetch", () => { ) .use( "/params", - eventHandler((event) => getQuery(event.req.url || "")) + eventHandler((event) => getQuery(event.node.req.url || "")) ) .use( "/url", - eventHandler((event) => event.req.url) + eventHandler((event) => event.node.req.url) ) .use( "/post", eventHandler(async (event) => ({ body: await readBody(event), - headers: event.req.headers, + headers: event.node.req.headers, })) ) .use( "/binary", eventHandler((event) => { - event.res.setHeader("Content-Type", "application/octet-stream"); + event.node.res.setHeader("Content-Type", "application/octet-stream"); return new Blob(["binary"]); }) ) @@ -51,7 +51,7 @@ describe("ofetch", () => { listener = await listen(toNodeListener(app)); }); - afterEach(async () => { + afterAll(async () => { await listener.close(); });