-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
47 lines (35 loc) · 1.23 KB
/
app.js
File metadata and controls
47 lines (35 loc) · 1.23 KB
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
import fs from "node:fs";
import path from "node:path";
import express from "express";
import swaggerUi from "swagger-ui-express";
import cors from 'cors';
import swagger from "./swagger.json" assert { type: "json" };
import quotes from "./resources/quotes.json" assert { type: "json" };
async function sleep(ms) {
return new Promise((resolve) => setTimeout(() => resolve(), ms));
}
const PORT = process.env.PORT || 3000;
const app = express();
const BASE_PATH = path.join(process.cwd(), "resources");
const IMAGE_PATH = path.join(BASE_PATH, "images");
const pictures = fs.readdirSync(path.join(IMAGE_PATH));
app.use(express.static("resources/images"));
app.use(cors());
app.use("/docs", swaggerUi.serve, swaggerUi.setup(swagger));
app.get("/api/random", (_, res) => {
res.json({ message: quotes[~~(Math.random() * quotes.length)] });
});
app.get("/api/cat", (request, res) => {
const picture = pictures[~~(Math.random() * pictures.length)];
res.send({ image: request.url + picture });
});
app.get("/api/rocket/async", async (_, res) => {
await sleep(5000);
res.send({ message: "Hello, world! 🚀" });
});
app.all("*", (_, res) => {
res.redirect("/docs");
});
app.listen(PORT, () => {
console.log("Listening on port %s", PORT);
});