forked from withastro/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil-server.ts
46 lines (41 loc) · 1.11 KB
/
util-server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
This file contains server-side utilities using features that don't work in a browser.
Do not import this file from a hydrated client-side component.
*/
// @ts-expect-error Package without types we can’t do anything about.
import EleventyFetch from '@11ty/eleventy-fetch';
export type CachedFetchOptions = {
duration?: string;
verbose?: boolean;
};
export async function cachedFetch(
url: string,
fetchOptions = {},
{ duration = '5m', verbose = false }: CachedFetchOptions = {}
) {
let status = 200;
let statusText = 'OK';
let buffer: Buffer | undefined;
try {
buffer = await EleventyFetch(url, {
duration,
verbose,
type: 'buffer',
fetchOptions,
});
} catch (e: unknown) {
const error = e as Error;
const msg: string = error?.message || error.toString();
const matches = msg.match(/^Bad response for (.*) \(.*?\): (.*)$/);
status = parseInt(matches?.[2] || '') || 404;
statusText = matches?.[3] || msg;
}
return {
ok: status >= 200 && status <= 299,
status,
statusText,
body: buffer,
json: () => buffer && JSON.parse(buffer.toString()),
text: () => buffer?.toString(),
};
}