-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfetch.js
60 lines (52 loc) · 1.74 KB
/
fetch.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import fs from 'fs';
import fsPromises from 'fs/promises';
import path from 'path';
import mime from 'mime-types';
globalThis.oldFetch = fetch;
export default function createFetch(gameDir) {
let resourcePath = gameDir;
// Check if gameDir has a public/ folder in it
const publicDir = path.join(gameDir, 'public');
if (fs.existsSync(publicDir)) {
resourcePath = publicDir;
}
// console.log('resourcePath', resourcePath);
async function localFetch(url, options = {}) {
// console.log('localFetch', url, options);
const { method } = options;
const lcUrl = String(url).toLowerCase();
// For non-local files or non-GET methods, fall back to global fetch
if (lcUrl.startsWith('http') || lcUrl.startsWith('//') || (method && (method !== 'GET'))) {
return globalThis.oldFetch(url, options);
}
// Construct the file path
const filePath = path.join(resourcePath, url);
// const resp = new Response();
try {
// Read the file content
const fileBuffer = await fsPromises.readFile(filePath);
// Guess the MIME type based on file extension
const mimeType = mime.lookup(filePath) || 'application/octet-stream';
console.log('MIME TYPE', mimeType, filePath);
const resp = new Response(fileBuffer, {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': mimeType,
},
});
resp.headers.set('Content-Type', mimeType);
return resp;
} catch (err) {
// Handle file not found or other errors
console.error('Error fetching file', filePath);
const resp = new Response(null, {
ok: false,
status: 404,
statusText: 'Not Found',
});
return resp;
}
}
return localFetch;
}