Skip to content

Commit

Permalink
refactor: isPathExists
Browse files Browse the repository at this point in the history
  • Loading branch information
shaokeyibb committed Aug 20, 2024
1 parent 9c67173 commit 48f2684
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
11 changes: 5 additions & 6 deletions cloudflare-workers/src/administration.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand Down Expand Up @@ -49,20 +49,19 @@ 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');
}

await setPath(env, oldPath, newPath);
}

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');
}

Expand Down
21 changes: 21 additions & 0 deletions cloudflare-workers/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>;
export async function isPathExists(env: Env, ...path: string[]): Promise<boolean[]>;
export async function isPathExists(env: Env, ...path: string[]): Promise<boolean | boolean[]> {
if (typeof path === 'string') {
path = [path];
}

const db = env.DB;

const res = await db
.prepare(`SELECT path FROM pages WHERE path IN (${new Array<string>(path.length).fill('?').join(',')})`)
.bind(...path)
.all<Record<string, string>>();

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,
Expand Down

0 comments on commit 48f2684

Please sign in to comment.