summaryrefslogtreecommitdiff
path: root/src/index.ts
blob: 82eaad9a36045ea055dfb2bd330359cfd3b2cef1 (plain)
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
85
86
87
88
89
90
91
92
93
import { logger } from "hono/logger";
import { prettyJSON } from "hono/pretty-json";
import { swaggerUI } from "@hono/swagger-ui";
import { OpenAPIHono, createRoute } from "@hono/zod-openapi";
import { VERSION } from "./consts";
import { Bindings, Variables } from "./env";
import {
	ListTeawiesParams,
	ListTeawiesResponse,
	RandomTeawiesResponse,
} from "./schemas";
import { imageUrls } from "./teawie";

const app = new OpenAPIHono<{ Bindings: Bindings; Variables: Variables }>();

app.use("*", logger());
app.use("*", prettyJSON());

app.get("/", (c) =>
	c.redirect(c.env.REDIRECT_ROOT ?? "https://github.com/getchoo/teawieAPI"),
);

app.get("/swagger", swaggerUI({ url: "/doc" }));

app.doc("/doc", {
	openapi: "3.0.0",
	info: {
		version: VERSION,
		title: "teawieAPI",
	},
});

app.openapi(
	createRoute({
		method: "get",
		path: "/list_teawies",
		request: {
			params: ListTeawiesParams,
		},
		responses: {
			200: {
				content: {
					"application/json": {
						schema: ListTeawiesResponse,
					},
				},
				description: "List known Teawie URLS",
			},
		},
	}),
	async (c) => {
		const { limit } = c.req.query();
		const urls = await imageUrls(c.env.TEAWIE_API);

		return c.json(
			{
				urls: urls.splice(0, parseInt(limit ?? "5")),
			},
			200,
		);
	},
);

app.openapi(
	createRoute({
		method: "get",
		path: "/random_teawie",
		responses: {
			200: {
				content: {
					"application/json": {
						schema: RandomTeawiesResponse,
					},
				},
				description: "A random URL to a picture of Teawie",
			},
		},
	}),
	async (c) =>
		imageUrls(c.env.TEAWIE_API).then((urls) =>
			c.json({
				url: urls[Math.floor(Math.random() * urls.length)],
			}),
		),
);

app.onError((error, c) => {
	console.error(error);

	return c.json({ error: error.message }, 500);
});

export default app;