Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
59 lines (47 loc) · 1.8 KB
/
Copy pathapp.js
File metadata and controls
59 lines (47 loc) · 1.8 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
48
49
50
51
52
53
54
55
56
57
58
59
"use strict";
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { generateExam, writePDF, books, fetchFont } from "./index.js";
const app = new Hono();
app.onError((err, c) => {
console.error(err);
return c.text("Internal Server Error", 500);
});
app.use("*", serveStatic({ root: "./static" }));
app.get("/api/books", async (c) => {
return c.json(
Object.entries(books).map(([bookId, book]) => ({
id: bookId,
name: book.name,
amazon: book.asin && `https://www.amazon.co.jp/dp/${book.asin}`,
})),
);
});
app.get("/api/pdf/:bookId", async (c) => {
const bookId = c.req.param("bookId")?.toLowerCase();
const range0 = parseInt(c.req.query("l")) || Infinity;
const range1 = parseInt(c.req.query("r")) || 1;
const num = parseInt(c.req.query("n")) || 50;
const seed = parseInt(c.req.query("s"), 16) || null;
if (!books.hasOwnProperty(bookId)) return c.json({ error: `${bookId} は存在しません。` }, 404);
const book = books[bookId];
const words = await book.fetch();
const exam = await generateExam(words, bookId, book.name, range0, range1, num, seed);
const doc = await writePDF(exam);
console.log(`Generated ${exam.defaultFileName}`);
c.header("Content-Type", "application/pdf");
c.header("Content-Disposition", `inline; filename="${exam.defaultFileName}"`);
c.header("Cache-Control", "no-cache, no-store, must-revalidate");
return c.body(doc);
});
await fetchFont();
serve({ fetch: app.fetch, port: 3000 }, (info) => {
console.log(`Listening on http://localhost:${info.port}`);
console.table(
Object.entries(books).reduce(
(table, [bookId, book]) => ({ ...table, [book.name]: `http://localhost:${info.port}/api/pdf/${bookId}` }),
{},
),
);
});