|
1 | | -import { Hono } from 'hono' |
| 1 | +import { createClient, Client } from "@libsql/client"; |
| 2 | +import { Hono } from "hono"; |
| 3 | +import { cors } from "hono/cors"; |
2 | 4 |
|
3 | | -const app = new Hono() |
| 5 | +const app = new Hono(); |
4 | 6 |
|
5 | | -app.get('/', (c) => { |
6 | | - return c.text('Hello Hono!') |
7 | | -}) |
| 7 | +// Define global typing for Turso client |
| 8 | +declare global { |
| 9 | + var tursoClient: Client | undefined; |
| 10 | +} |
8 | 11 |
|
9 | | -export default app |
| 12 | +app.use( |
| 13 | + cors({ |
| 14 | + origin: ["https://keshav.is-a.dev"], |
| 15 | + allowMethods: ["POST"], |
| 16 | + }), |
| 17 | +); |
| 18 | + |
| 19 | +app.get("*", async ({ env }, next) => { |
| 20 | + if (!globalThis.tursoClient) { |
| 21 | + if (!env.TURSO_AUTH_TOKEN || !env.TURSO_DATABASE_URL) { |
| 22 | + throw new Error("Turso API Keys Required"); |
| 23 | + } |
| 24 | + globalThis.tursoClient = createClient({ |
| 25 | + url: env.TURSO_DATABASE_URL, |
| 26 | + authToken: env.TURSO_AUTH_TOKEN, |
| 27 | + }); |
| 28 | + } |
| 29 | + await next(); |
| 30 | +}); |
| 31 | + |
| 32 | +app.get("/track", async (c) => { |
| 33 | + try { |
| 34 | + const turso = globalThis.tursoClient; |
| 35 | + if (!turso) throw new Error("Turso Client is not Initialized"); |
| 36 | + await turso.execute(` |
| 37 | + UPDATE Analytics |
| 38 | + SET views = views + 1 |
| 39 | + WHERE rowid = 1; |
| 40 | + `); |
| 41 | + } catch (error) { |
| 42 | + console.error("Database error:", error); |
| 43 | + return c.text("Database query failed", 500); |
| 44 | + } |
| 45 | + return c.text("Succesfully Incremented"); |
| 46 | +}); |
| 47 | + |
| 48 | +export default app; |
0 commit comments