-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
73 lines (69 loc) · 1.98 KB
/
index.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { IncomingMessage, ServerResponse } from "http";
import axios from "axios";
import * as qs from "querystring";
import * as url from "url";
/**
* Group 1: scope
* Group 2: repo
* Group 3: @
* Group 4: branch
* Group 5: rest
*/
export const MATCHER = /^\/([^\/]+)\/([^\/@]+)(@)?([^\/]*)(.*)/;
export default (req: IncomingMessage, resp: ServerResponse) => {
try {
if (req.url.startsWith("/badge")) {
const query = url.parse(req.url).query;
const { scope, repo, style } = qs.parse(query);
if (!scope || !repo) {
throw new InvalidUrlException();
}
const styleParameter = style ? `&style=${style}` : '';
resp.statusCode = 301;
resp.setHeader(
"Location",
`https://img.shields.io/badge/dynamic/json.svg?label=DenoLib&query=$.name${styleParameter}&url=https://raw.githubusercontent.com/${scope}/${repo}/master/denolib.json`
);
resp.end();
}
if (req.url === "/") {
resp.statusCode = 301;
resp.setHeader("Location", "https://github.com/denolib/denolib.com");
resp.end();
}
if (!MATCHER.test(req.url)) {
throw new InvalidUrlException();
}
const [, scope, repo, versionSpecified, branch, rest] = MATCHER.exec(
req.url
);
if (!scope || !repo) {
throw new InvalidUrlException();
}
axios
.get(
`https://raw.githubusercontent.com/${scope}/${repo}/${
versionSpecified ? branch : "master"
}${rest}`
)
.then(body => {
resp.setHeader("Content-Type", "text/plain");
resp.statusCode = 200;
resp.end(body.data);
})
.catch(err => {
resp.statusCode = 404;
resp.end("Not Found");
if (rest.endsWith(".js")) {
// TODO: https://github.com/denoland/registry/issues/39
}
});
} catch (err) {
resp.statusCode = err.status;
resp.end(err.message);
}
};
class InvalidUrlException extends Error {
message = "Invalid URL";
status = 500;
}