Skip to content

Commit 592684d

Browse files
committed
fix: update category fetching to use environment variable and improve error handling
1 parent 05e5477 commit 592684d

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/routes/v1_categories.ts

+16-7
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import type { HonoContext } from "../types";
22
import { OpenAPIHono, z } from "@hono/zod-openapi";
3+
import { HTTPException } from "hono/http-exception";
34
import { versionMiddleware } from "../middlewares/version";
45
import { EmojiCategorySchema } from "../schemas";
5-
import { createError } from "../utils";
6+
import { cache, createError } from "../utils";
67
import { ALL_CATEGORIES_ROUTE, GET_CATEGORY_ROUTE } from "./v1_categories.openapi";
78

89
export const V1_CATEGORIES_ROUTER = new OpenAPIHono<HonoContext>().basePath("/api/v1/categories/:version");
@@ -12,10 +13,12 @@ V1_CATEGORIES_ROUTER.use(versionMiddleware);
1213
V1_CATEGORIES_ROUTER.openapi(ALL_CATEGORIES_ROUTE, async (c) => {
1314
const version = c.req.param("version");
1415

15-
const res = await fetch(`https://raw.githubusercontent.com/mojisdev/emoji-data/refs/heads/main/data/v${version}/groups.json`);
16+
const res = await c.env.EMOJI_DATA.get(`v${version}/groups.json`);
1617

17-
if (!res.ok) {
18-
return createError(c, 500, "failed to fetch categories");
18+
if (res == null) {
19+
throw new HTTPException(500, {
20+
message: "failed to fetch categories",
21+
});
1922
}
2023

2124
const data = await res.json();
@@ -28,6 +31,8 @@ V1_CATEGORIES_ROUTER.openapi(ALL_CATEGORIES_ROUTE, async (c) => {
2831

2932
const categories = result.data;
3033

34+
cache(c, 3600, true);
35+
3136
return c.json(
3237
categories,
3338
200,
@@ -38,10 +43,12 @@ V1_CATEGORIES_ROUTER.openapi(GET_CATEGORY_ROUTE, async (c) => {
3843
const version = c.req.param("version");
3944
const categorySlug = c.req.param("category");
4045

41-
const res = await fetch(`https://raw.githubusercontent.com/mojisdev/emoji-data/refs/heads/main/data/v${version}/groups.json`);
46+
const res = await c.env.EMOJI_DATA.get(`v${version}/groups.json`);
4247

43-
if (!res.ok) {
44-
return createError(c, 500, "failed to fetch categories");
48+
if (res == null) {
49+
throw new HTTPException(500, {
50+
message: "failed to fetch categories",
51+
});
4552
}
4653

4754
const data = await res.json();
@@ -54,6 +61,8 @@ V1_CATEGORIES_ROUTER.openapi(GET_CATEGORY_ROUTE, async (c) => {
5461

5562
const category = result.data.find((c) => c.slug === categorySlug);
5663

64+
cache(c, 3600, true);
65+
5766
return c.json(
5867
category,
5968
200,

0 commit comments

Comments
 (0)