diff --git a/cloudflare-workers/src/administration.ts b/cloudflare-workers/src/administration.ts index 32765485..a69bff58 100644 --- a/cloudflare-workers/src/administration.ts +++ b/cloudflare-workers/src/administration.ts @@ -1,4 +1,4 @@ -import { getComment, getMeta, getPaths, setMeta, setPath, updateCommentOffsets } from './db'; +import { getComment, getMeta, getPaths, isPathExists, setMeta, setPath, updateCommentOffsets } from './db'; import { ModifiedCommentBody } from './types'; type Replacement = { @@ -49,11 +49,11 @@ export async function renameComments(env: Env, oldPath: string, newPath: string) throw new Error('The path you want to rename from and to are the same'); } - const paths = await getPaths(env); - if (!paths.includes(oldPath)) { + const [oldPathExists, newPathExists] = await isPathExists(env, oldPath, newPath); + if (!oldPathExists) { return; } - if (paths.includes(newPath)) { + if (newPathExists) { throw new Error('The path you want to rename to already exists'); } @@ -61,8 +61,7 @@ export async function renameComments(env: Env, oldPath: string, newPath: string) } export async function modifyComments(env: Env, path: string, diff: ModifiedCommentBody['diff']) { - const paths = await getPaths(env); - if (!paths.includes(path)) { + if (!(await isPathExists(env, path))) { throw new Error('The path you want to modify does not exist'); } diff --git a/cloudflare-workers/src/db.ts b/cloudflare-workers/src/db.ts index 98f0e6f4..93866c49 100644 --- a/cloudflare-workers/src/db.ts +++ b/cloudflare-workers/src/db.ts @@ -86,6 +86,27 @@ export async function setPath(env: Env, oldPath: string, newPath: string) { await db.prepare('UPDATE pages SET path = ? WHERE path = ?').bind(newPath, oldPath).run(); } +export async function isPathExists(env: Env, path: string): Promise; +export async function isPathExists(env: Env, ...path: string[]): Promise; +export async function isPathExists(env: Env, ...path: string[]): Promise { + if (typeof path === 'string') { + path = [path]; + } + + const db = env.DB; + + const res = await db + .prepare(`SELECT path FROM pages WHERE path IN (${new Array(path.length).fill('?').join(',')})`) + .bind(...path) + .all>(); + + if (path.length === 1) { + return res.results.length > 0; + } + + return path.map((p) => res.results.some((r) => r.path === p)); +} + export async function updateCommentOffsets( env: Env, path: string,