UNPKG

1.24 kBJavaScriptView Raw
1import _fetch, { Response, FetchError } from "node-fetch";
2import { resolve } from 'path';
3import { promises as fsp } from 'fs';
4import { readDir } from "../utils/fs.js";
5const cwd = import.meta.url.slice('file:/'.length).split('microsite')[0].slice(0, -1);
6async function fetch(url, init) {
7 if (typeof url === 'string' && !url.startsWith('http')) {
8 url = resolve(cwd, `../.${url}`);
9 try {
10 const stat = await fsp.stat(url);
11 if (stat.isFile()) {
12 const content = await fsp.readFile(url, 'utf-8');
13 return new Response(content);
14 }
15 else if (stat.isDirectory()) {
16 let contents = await readDir(url);
17 contents = contents.map(path => path.slice(url.length));
18 const res = new Response(JSON.stringify(contents));
19 res.headers.set('Content-Type', 'application/json');
20 return res;
21 }
22 }
23 catch (e) {
24 const err = new FetchError(`Unable to fetch ${url}. ${e.message}`);
25 err.code = 'ERR_NOT_FOUND';
26 err.errno = '404';
27 throw err;
28 }
29 }
30 return _fetch(url, init);
31}
32export default fetch;