Skip to content

Commit 097b3ee

Browse files
committed
refactor: enhance version middleware with error handling and redirect logic
1 parent 642036f commit 097b3ee

File tree

1 file changed

+31
-22
lines changed

1 file changed

+31
-22
lines changed

src/middlewares/version.ts

+31-22
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1+
import type { Context } from "hono";
12
import type { HonoEnv } from "../types";
23
import { createMiddleware } from "hono/factory";
34
import { createError } from "../utils";
45

56
const DEFAULT_FALLBACK_VERSION = "15.1";
67

8+
function redirectLatest(c: Context, path: string, latestVersion: string | null) {
9+
return c.redirect(path.replace("latest", latestVersion ?? DEFAULT_FALLBACK_VERSION));
10+
}
11+
712
export const versionMiddleware = createMiddleware<HonoEnv>(async (c, next) => {
813
const version = c.req.param("version");
914
const fullPath = c.req.path;
@@ -12,33 +17,37 @@ export const versionMiddleware = createMiddleware<HonoEnv>(async (c, next) => {
1217
return createError(c, 400, "missing version");
1318
}
1419

15-
const res = await c.env.EMOJI_DATA.get("versions.json");
20+
try {
21+
const res = await c.env.EMOJI_DATA.get("versions.json");
1622

17-
if (res == null) {
18-
return await next();
19-
}
23+
if (res == null) {
24+
return await next();
25+
}
2026

21-
const payload = await res.json<{
22-
latest_version: string;
23-
versions: {
24-
emoji_version: string;
25-
unicode_version: string;
26-
draft: boolean;
27-
}[];
28-
}>();
27+
const payload = await res.json<{
28+
latest_version: string;
29+
versions: {
30+
emoji_version: string;
31+
unicode_version: string;
32+
draft: boolean;
33+
}[];
34+
}>();
2935

30-
const versions = payload.versions;
31-
const latestVersion = payload.latest_version;
36+
const versions = payload.versions;
37+
const latestVersion = payload.latest_version;
3238

33-
if (version !== "latest" && !versions.some((v) => v.emoji_version === version)) {
34-
return createError(c, 404, "version not found");
35-
}
39+
if (version !== "latest" && !versions.some((v) => v.emoji_version === version)) {
40+
return createError(c, 404, "version not found");
41+
}
3642

37-
if (version === "latest") {
38-
const path = fullPath.replace("latest", latestVersion ?? DEFAULT_FALLBACK_VERSION);
43+
if (version === "latest") {
44+
return redirectLatest(c, fullPath, latestVersion);
45+
}
3946

40-
return c.redirect(path);
41-
}
47+
return await next();
48+
} catch (err) {
49+
console.error(err);
4250

43-
await next();
51+
return redirectLatest(c, fullPath, null);
52+
}
4453
});

0 commit comments

Comments
 (0)