commit e8c46ebaf672873b4464e75a1a7e5e1d08e65e2d
parent 9ccc6f75653a2354254ef78d2cb2696c3ea4298f
Author: Yongbin Kim <iam@yongbin.kim>
Date: Mon, 23 Jan 2023 10:05:57 +0900
feat: wiki page model 추가
Signed-off-by: Yongbin Kim <iam@yongbin.kim>
Diffstat:
3 files changed, 98 insertions(+), 0 deletions(-)
diff --git a/lib/db.ts b/lib/db.ts
@@ -11,3 +11,4 @@ const db: PromisePool = mysql.createPool({
})
export default db
+export * from 'mysql2/promise'
diff --git a/lib/model_helpers.ts b/lib/model_helpers.ts
@@ -0,0 +1,31 @@
+import db from '@/lib/db'
+import { Connection, PoolConnection } from 'mysql2/promise'
+
+export async function withConnection <T> (
+ conn: PoolConnection | null,
+ fn: (conn: Connection) => Promise<T>
+): Promise<T> {
+ if (conn == null) {
+ conn = await db.getConnection()
+ }
+ try {
+ return await fn(conn)
+ } finally {
+ conn.release()
+ }
+}
+
+export type ModelBehaviour<TArgs, TResult> =
+ ((conn: PoolConnection, args: TArgs) => Promise<TResult>) &
+ ((args: TArgs) => Promise<TResult>)
+
+export function modelBehaviour <TArgs, TResult> (
+ fn: (conn: Connection, args: TArgs) => Promise<TResult>,
+): ModelBehaviour<TArgs, TResult> {
+ return (connOrArgs: PoolConnection | TArgs, args?: TArgs): Promise<TResult> => {
+ if (args != null) {
+ return fn(connOrArgs as PoolConnection, args)
+ }
+ return withConnection(null, (conn) => fn(conn, connOrArgs as TArgs))
+ }
+}
diff --git a/lib/models/wiki_page.ts b/lib/models/wiki_page.ts
@@ -0,0 +1,66 @@
+import db, { Connection } from '@/lib/db'
+import { modelBehaviour } from '@/lib/model_helpers'
+import { OkPacket, RowDataPacket } from 'mysql2'
+
+export interface WikiPage {
+ wikiId: number
+ path: string
+ content: string
+ html: string
+ createdAt: Date
+ updatedAt?: Date
+}
+
+const SQL_PUT_WIKI_PAGE = `
+ insert into wiki_pages (wiki_id, path, content, html)
+ values (?, ?, ?, ?)
+ on duplicate key update content = values(content),
+ html = values(html)
+`
+
+export const putWikiPage = modelBehaviour(async (
+ conn: Connection,
+ args: [
+ wikiId: number,
+ path: string,
+ content: string,
+ html: string,
+ ],
+) => {
+ await conn.query<OkPacket>({
+ sql: SQL_PUT_WIKI_PAGE,
+ }, args)
+})
+
+const SQL_GET_WIKI_PAGE = `
+ select wiki_id, path, content, html, created_at, updated_at
+ from wiki_pages
+ where wiki_id = ?
+ and path = ?
+`
+
+export const getWikiPage = modelBehaviour(async (
+ conn: Connection,
+ args: [
+ wikiId: number,
+ path: string,
+ ],
+) => {
+ const [rows] = await conn.query<RowDataPacket[]>({
+ sql: SQL_GET_WIKI_PAGE,
+ }, args)
+
+ if (rows.length === 0) {
+ return null
+ }
+
+ const row = rows[0]
+ return {
+ wikiId: row[0],
+ path: row[1],
+ content: row[2],
+ html: row[3],
+ createdAt: row[4],
+ updatedAt: row[5],
+ }
+})