-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
50 lines (42 loc) · 1.46 KB
/
server.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
const express = require("express");
const fs = require("fs");
const path = require("path");
const SCHEMA = "http://json-schema.org/draft-07/schema";
const HOST = "https://raw.githubusercontent.com";
const PREFIX = /bettyblocks\/json-schema\/\w+\//g;
const PORT = 9797;
const app = express();
const serve = (request, response, file) => {
console.log("Request for: ", request.url);
console.log("Serving: ", file);
fs.readFile(file, function (error, content) {
if (error) {
if (error.code == "ENOENT") {
response.status(404).send("Not Found");
} else {
response.status(500).send("Internal Error: " + error.code + " ..\n");
}
} else {
const protocol = request.headers.host.includes("localhost")
? request.protocol
: "https";
const hostname = `${protocol}://${request.headers.host}`;
console.log({ protocol: protocol, host: request.headers.host });
const json = content
.toString()
.replaceAll(HOST, hostname)
.replace(PREFIX, "")
.replaceAll(SCHEMA, `${hostname}/schema`);
response.status(200).contentType("application/json").send(json);
}
});
};
app.get("/schema", (request, response) =>
serve(request, response, path.join(process.cwd(), "schema.json"))
);
app.get("*", (request, response) => {
serve(request, response, path.join(process.cwd(), request.url));
});
app.listen(PORT, () =>
console.log(`JSON Schema Server running at 127.0.0.1:${PORT}`)
);