-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
84 lines (72 loc) · 1.97 KB
/
main.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
74
75
76
77
78
79
80
81
82
83
84
import { Hono, HTTPException } from "hono/mod.ts";
import { contentType } from "std/media_types/mod.ts";
import { Status } from "std/http/http_status.ts";
import { serve } from "std/http/mod.ts";
import Qrcode from "qrcode";
const app = new Hono();
app.get("/", (ctx) => {
return ctx.text(
"このサービスはDeno Deployでホスティングされ、Honoとnode-qrcodeによって構築されています。",
);
});
type Extention = "png" | "svg";
const generateQrcode = async (
url: string,
options: Qrcode.QRCodeToBufferOptions | Qrcode.QRCodeToStringOptions,
) => {
if (options.type === "png") return await Qrcode.toBuffer(url, options);
else if (options.type === "svg") return await Qrcode.toString(url, options);
throw new HTTPException(Status.BadRequest, {
message: "`type`でpngかsvgを設定してください",
});
};
app.get("/api", async (ctx) => {
const {
type = "png",
url,
width,
qrcolor = "000000ff",
bgcolor = "ffffffff",
} = ctx.req.query();
const extention = type as Extention;
if (!url) {
throw new HTTPException(Status.BadRequest, {
message: "クエリパラメータに`url`を設定してください",
});
}
const qrcode = await generateQrcode(url, {
type: extention,
width: Number(width),
color: {
dark: `#${qrcolor}`,
light: `#${bgcolor}`,
},
});
return ctx.body(qrcode, Status.OK, {
"Content-Type": contentType(extention),
});
});
app.all("*", () => {
throw new HTTPException(Status.NotFound, {
message: "お探しのページは存在しません",
});
});
app.onError((err, ctx) => {
if (err instanceof HTTPException) {
return ctx.json(
{
status: err.status,
message: err.message,
},
err.status,
);
}
return ctx.json(
{
status: Status.InternalServerError,
message: "不明なエラーが発生しました",
},
Status.InternalServerError,
);
});
serve(app.fetch, { port: 8080 });