|
| 1 | +import { Hono } from "hono"; |
| 2 | +import { getCookie } from "hono/cookie"; |
| 3 | +import { createClient } from "redis"; |
| 4 | + |
| 5 | +const client = createClient(); |
| 6 | +client.on("error", (err) => console.log("Redis Client Error", err)); |
| 7 | +await client.connect(); |
| 8 | + |
| 9 | +type TModel = { |
| 10 | + path: string; |
| 11 | + method: string; |
| 12 | + data: object; |
| 13 | + status: number; |
| 14 | +}; |
| 15 | + |
| 16 | +const app = new Hono(); |
| 17 | + |
| 18 | +const create = (userId: string, value: TModel) => { |
| 19 | + client.set( |
| 20 | + `${userId}:${value.method}:${value.path}`, |
| 21 | + JSON.stringify({ status: value.status, data: value.data }), |
| 22 | + ); |
| 23 | +}; |
| 24 | + |
| 25 | +const clear = async (userId: string) => { |
| 26 | + for await (const key of client.scanIterator({ |
| 27 | + TYPE: "string", |
| 28 | + MATCH: `${userId}:*`, |
| 29 | + })) { |
| 30 | + client.del(key); |
| 31 | + } |
| 32 | +}; |
| 33 | + |
| 34 | +const get = ( |
| 35 | + userId: string, |
| 36 | + method: string, |
| 37 | + path: string, |
| 38 | +): ReturnType<typeof client.get> => { |
| 39 | + return client.get(`${userId}:${method}:${path}`); |
| 40 | +}; |
| 41 | + |
| 42 | +app.post("/create", async (c) => { |
| 43 | + const userIdCookie = getCookie(c, "userId"); |
| 44 | + if (!userIdCookie) return c.json({}); |
| 45 | + const data = await c.req.json<TModel>(); |
| 46 | + create(userIdCookie, data); |
| 47 | + return c.json({ |
| 48 | + user: userIdCookie, |
| 49 | + ...data, |
| 50 | + }); |
| 51 | +}); |
| 52 | + |
| 53 | +app.post("/clear", (c) => { |
| 54 | + const userIdCookie = getCookie(c, "userId"); |
| 55 | + if (!userIdCookie) return c.json({}); |
| 56 | + clear(userIdCookie); |
| 57 | + return c.json({ cookie: userIdCookie }); |
| 58 | +}); |
| 59 | + |
| 60 | +app.all("/api/*", async (c) => { |
| 61 | + const userIdCookie = getCookie(c, "userId"); |
| 62 | + if (!userIdCookie) return c.json({}); |
| 63 | + const path = c.req.path.replace("/api", ""); |
| 64 | + const redisData = await get(userIdCookie, c.req.method, path); |
| 65 | + if (!redisData) return c.json({}); |
| 66 | + const { status, data } = JSON.parse(redisData); |
| 67 | + c.status = status; |
| 68 | + return c.json(data); |
| 69 | +}); |
| 70 | + |
| 71 | +export default app; |
0 commit comments