File size: 769 Bytes
d605f27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import path from "path";
import serveHandler from "serve-handler";



const createHandler = (publicDir: string, apiPath: string) => (req, res) => {
	req.url = "/" + path.relative(`${apiPath}/`, req.baseUrl);

	// modify link URL origin
	const responseProxy = new Proxy(res, {
		get (res, prop) {
			//console.log("proxy.get:", prop);
			switch (prop) {
			case "end":
				return (content) => {
					//console.log("end with:", content);
					const html = content && content.replace(/href="/g, `href="${apiPath}`);

					res.end(html);
				};
			}

			if (typeof res[prop] === "function")
				return res[prop].bind(res);

			return res[prop];
		},
	});

	serveHandler(req, responseProxy, {
		public: publicDir,
		//symlinks: true,
	});
};



export {
	createHandler,
};