Skip to content

Commit

Permalink
feat: use ofetch to improve http error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Sep 27, 2023
1 parent 9826cda commit ac30512
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 16 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -46,7 +46,7 @@
"h3": "^1.8.2",
"image-meta": "^0.1.1",
"listhen": "^1.5.5",
"node-fetch-native": "^1.4.0",
"ofetch": "^1.3.3",
"pathe": "^1.1.1",
"sharp": "^0.32.6",
"ufo": "^1.3.0",
Expand Down
11 changes: 8 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 11 additions & 12 deletions src/storage/http.ts
@@ -1,4 +1,4 @@
import { fetch } from "node-fetch-native";
import { ofetch } from "ofetch";
import { createError } from "h3";
import { getEnv } from "../utils";
import type { IPXStorage } from "../types";
Expand Down Expand Up @@ -58,14 +58,6 @@ export function ipxHttpStorage(_options: HTTPStorageOptions = {}): IPXStorage {

// eslint-disable-next-line unicorn/consistent-function-scoping
function parseResponse(response: Response) {
if (!response.ok) {
throw createError({
statusCode: response.status || 500,
statusText: response.statusText || `IPX_FETCH_ERROR`,
message: `Fetch error: [${response.status}] [${response.statusText}]`,
});
}

let maxAge = defaultMaxAge;
const _cacheControl = response.headers.get("cache-control");
if (_cacheControl) {
Expand All @@ -89,7 +81,10 @@ export function ipxHttpStorage(_options: HTTPStorageOptions = {}): IPXStorage {
async getMeta(id) {
const url = validateId(id);
try {
const response = await fetch(url, { ...fetchOptions, method: "HEAD" });
const response = await ofetch.raw(url, {
...fetchOptions,
method: "HEAD",
});
const { maxAge, mtime } = parseResponse(response);
return { mtime, maxAge };
} catch {
Expand All @@ -98,8 +93,12 @@ export function ipxHttpStorage(_options: HTTPStorageOptions = {}): IPXStorage {
},
async getData(id) {
const url = validateId(id);
const response = await fetch(url, { ...fetchOptions, method: "GET" });
return response.arrayBuffer();
const response = await ofetch(url, {
...fetchOptions,
method: "GET",
responseType: "arrayBuffer",
});
return response;
},
};
}

0 comments on commit ac30512

Please sign in to comment.