Wire up Drizzle (MySQL), Redis, and Swagger docs for coursework

This commit is contained in:
2026-09-06 10:55:57 +02:00
parent 87e6ef0d15
commit b494da9fa4
11 changed files with 431 additions and 15 deletions
+14
View File
@@ -0,0 +1,14 @@
import { drizzle } from "drizzle-orm/mysql2";
import * as schema from "./schema";
export const db = drizzle({
connection: {
host: process.env.MYSQL_HOST ?? "localhost",
port: Number(process.env.MYSQL_PORT ?? 3306),
database: process.env.MYSQL_DATABASE,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
},
schema,
mode: "default",
});
+8
View File
@@ -0,0 +1,8 @@
import { mysqlTable, int, varchar, timestamp } from "drizzle-orm/mysql-core";
export const notes = mysqlTable("notes", {
id: int("id").primaryKey().autoincrement(),
title: varchar("title", { length: 255 }).notNull(),
body: varchar("body", { length: 2000 }).notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
});
+35 -3
View File
@@ -1,7 +1,39 @@
import { Elysia } from "elysia";
import { Elysia, t } from "elysia";
import { swagger } from "@elysiajs/swagger";
import { db } from "./db";
import { notes } from "./db/schema";
import { redis } from "./redis";
const app = new Elysia().get("/", () => "Hello Elysia").listen(3000);
const app = new Elysia()
.use(swagger())
.get("/", () => "Hello Elysia")
// Example: MySQL via Drizzle ORM. Run `bun run db:push` once to create the
// table before trying these.
.get("/notes", () => db.select().from(notes))
.post(
"/notes",
async ({ body }) => {
await db.insert(notes).values(body);
return { ok: true };
},
{ body: t.Object({ title: t.String(), body: t.String() }) },
)
// Example: Redis, namespaced per student so everyone can share the same
// instance without colliding (see REDIS_USERNAME's ACL restriction).
.get("/cache/:key", async ({ params }) => {
const value = await redis.get(`student:${process.env.REDIS_USERNAME}:${params.key}`);
return { key: params.key, value };
})
.put(
"/cache/:key",
async ({ params, body }) => {
await redis.set(`student:${process.env.REDIS_USERNAME}:${params.key}`, body.value);
return { ok: true };
},
{ body: t.Object({ value: t.String() }) },
)
.listen(3000);
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port} - docs at /swagger`,
);
+10
View File
@@ -0,0 +1,10 @@
import { Redis } from "ioredis";
export const redis = new Redis({
host: process.env.REDIS_HOST ?? "localhost",
port: Number(process.env.REDIS_PORT ?? 6379),
username: process.env.REDIS_USERNAME,
password: process.env.REDIS_PASSWORD,
lazyConnect: true,
maxRetriesPerRequest: 2,
});