|
| 1 | +/* eslint-disable no-sync */ |
| 2 | + |
| 3 | +// Import Node.js Dependencies |
| 4 | +import fs from "fs"; |
| 5 | + |
| 6 | +// Import Third-party Dependencies |
| 7 | +import kleur from "kleur"; |
| 8 | +import polka from "polka"; |
| 9 | +import open from "open"; |
| 10 | +import * as i18n from "@nodesecure/i18n"; |
| 11 | + |
| 12 | +// Import Internal Dependencies |
| 13 | +import * as root from "./root.js"; |
| 14 | +import * as data from "./data.js"; |
| 15 | +import * as flags from "./flags.js"; |
| 16 | +import * as middleware from "./middleware.js"; |
| 17 | + |
| 18 | +export function buildServer(dataFilePath, options = {}) { |
| 19 | + const httpConfigPort = typeof options.port === "number" ? options.port : 0; |
| 20 | + const openLink = typeof options.openLink === "boolean" ? options.openLink : true; |
| 21 | + |
| 22 | + fs.accessSync(dataFilePath, fs.constants.R_OK | fs.constants.W_OK); |
| 23 | + |
| 24 | + const httpServer = polka(); |
| 25 | + |
| 26 | + httpServer.use(middleware.buildContextMiddleware(dataFilePath)); |
| 27 | + httpServer.use(middleware.addStaticFiles); |
| 28 | + httpServer.get("/", root.get); |
| 29 | + httpServer.get("/data", data.get); |
| 30 | + httpServer.get("/flags", flags.getAll); |
| 31 | + httpServer.get("/flags/description/:title", flags.get); |
| 32 | + |
| 33 | + httpServer.listen(httpConfigPort, () => { |
| 34 | + const link = `http://localhost:${httpServer.server.address().port}`; |
| 35 | + console.log(kleur.magenta().bold(i18n.getToken("cli.http_server_started")), kleur.cyan().bold(link)); |
| 36 | + |
| 37 | + if (openLink) { |
| 38 | + open(link); |
| 39 | + } |
| 40 | + }); |
| 41 | + |
| 42 | + return httpServer; |
| 43 | +} |
0 commit comments