iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📜

Building a Message Board with Hono and Cloudflare D1

に公開

Introduction

Happy New Year!
I'm taisan11.
In this post, I'd like to introduce/explain a bulletin board I created.
Here is the finished product (it's probably faster to just look at this):
https://github.com/taisan11/hono-d1-kejiban
The repository name is just a placeholder...

Tech Stack

  • Hono
  • drizzleorm
  • cloudflare D1
  • cloudflare workers

Features

As of January 2024, the following features are implemented:

  • View thread list (latest 20 only) (GET)
  • View inside a thread (GET)
  • Create a thread (POST)
  • Post a response (POST)
    Everything is in API format, and there is no UI.

Code Breakdown

I'll just introduce them briefly.

DB

DB Design

import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
// Thread
export const threads = sqliteTable("threads", {
	id: integer("id").primaryKey().notNull(), // Thread ID (Timestamp)
	title: text("title").notNull(), // Thread title
	createdAt: text("created_at").notNull(), // Posting date and time
	ip_addr: text("ip_addr").notNull(), // Poster's IP address
	isDelete: integer("isDelete", { mode: "boolean" }).notNull().default(false), // Deletion flag
});
// Response
export const post = sqliteTable("post", {
	ex_id: integer("ex_id").primaryKey().notNull(), // Posting ID (Private) (Thread ID + Response Number + Random Number)
	id: integer("id").notNull().references(() => threads.id), // Thread ID (Timestamp)
	res_id: integer("res_id").notNull(), // Response number (from 0001 to 1000)
	name: text("name").notNull(), // Poster name
	mail: text("mail"), // Optional!! Poster email (Cap/Tripcode allowed)
	message: text("message").notNull(), // Post content
	createdAt: text("created_at").notNull(), // Posting date and time
	ip_addr: text("ip_addr").notNull(), // Poster's IP address
	isDelete: integer("isDelete", { mode: "boolean" }).notNull().default(false), // Deletion flag
});

Viewing the Thread List

app.get("/api/threads", async (c) => {
	const db = drizzle(c.env.DB, { schema });
	const result = await db.select().from(threads).limit(10).execute(); // Retrieve here
	return c.json(result.map((record) => ({ [record.id]: record.title })));
});

Regenerating only the necessary parts in JSON using the map function.

Viewing Inside a Thread

app.get("/api/threads/:threadid", async (c) => {
	const threadidIn = c.req.param("threadid");
	const threadidDate = parseInt(threadidIn);

	const db = drizzle(c.env.DB);
	const result2 = await db.select().from(post).where(eq(post.id, threadidDate));
	return c.json(result2);
});

Logic for adding a response to a thread (Function?)

I wanted to organize this into a function, but I couldn't.

// Add a response to the thread
console.debug(body.id);
let resulta = await db.query.post.findFirst({
	where: (post, { eq }) => eq(post.id, body.id),
	orderBy: (post, { desc }) => [desc(post.res_id)],
});
if (!resulta) {
	//@ts-ignore
	resulta = { res_id: 1 }; // Assign a new object if resulta is undefined
}
console.debug(resulta);
if (!resulta) {
	// Handle the case where the record doesn't exist
	return c.text("The record for the specified ID does not exist");
}
const record = resulta; // Get the first record
const ex_id = Number(`${record.res_id + 1}${body.id}${Math.floor(Math.random() * 88) + 10}`,);
const res_id = Number(`${record.res_id + 1}`);
const id = Number(`${body.id}`);
console.debug(body.mail);
//@ts-ignore
let kextuka;
if (!body.mail) {
	console.debug("No mail");
	kextuka = await db
		.insert(post)
		.values({
			ex_id: ex_id,
			id: id,
			res_id: res_id,
			name: body.name,
			message: body.message,
			createdAt: new Date().toISOString(),
			ip_addr: body.ip_addr,
			// user_id: body.user_id,
	})
	.execute();
} else {
	console.debug("Mail exists");
	kextuka = await db
		.insert(post)
		.values({
			ex_id: ex_id,
			id: body.id,
			res_id: record.res_id + 1,
			name: body.name,
			mail: body.mail,
			message: body.message,
			createdAt: new Date().toISOString(),
			ip_addr: body.ip_addr,
			// user_id: body.user_id,
			).execute();
	})

Adding a Response

app.post("/api/post/:threadid", async (c) => {
	// Check data
	if (await dataConfirmation(c, true)) {
		return dataConfirmation(c, true);
	}
	const body = await c.req.json();
	const db = drizzle(c.env.DB, { schema });
	if (!body.id) {
		return c.text("No thread ID");
	}
	// Add response to thread (omitted)
	return c.text(String(kextuka.success));
});

I wanted to make this a function... if I had, it could have been simplified this much... I'll think about it someday.

Creating a Thread

app.post("/api/newThread", async (c) => {
	if (await dataConfirmation(c, false)) {
		return dataConfirmation(c, false);
	}
	const body = await c.req.json();
	const db = drizzle(c.env.DB, { schema });
	if (!body.title) {
		return c.text("No thread title");
	}
	const date = new Date();
	const UnixTime = date.getTime();
	// Add thread to thread list
	const result = await db
		.insert(threads)
		.values({
			id: UnixTime,
			title: body.title,
			createdAt: new Date().toISOString(),
			ip_addr: body.ip_addr,
		})
		.returning({ insertedId: threads.id })
		.execute();
	// Add response to thread (omitted) (it's slightly different, but oh well)
	return c.json(result);
});

Conclusion

I'll aim to create a UI someday.
Next time -> planned (UI edition)

Discussion