-
Notifications
You must be signed in to change notification settings - Fork 380
/
buffy.js
35 lines (32 loc) · 1.01 KB
/
buffy.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
// https://github.com/retronbv/buffy
import axios from "axios";
export default class Buffy {
constructor(opts) {
this.url = new URL(opts.url).toString();
if(this.url.endsWith("/")) this.url = this.url.slice(0, this.url.length - 1);
this.validateStatus = opts.validateStatus ? opts.validateStatus : (status) => status >= 200 && status < 300;
}
/**
* Proxy a Request
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async request(req, res, next) {
try {
// Get the asset from the website as a Stream
const response = await axios({
method: req.method,
url: this.url + req.url,
responseType: "stream",
validateStatus: this.validateStatus
});
// Send the HTTP status code and the MIME type
res.writeHead(response.status, { "Content-Type": response.headers.get("content-type").split(";")[0] });
// Pipe the asset to the response
response.data.pipe(res);
} catch(error) {
next();
}
}
}