Skip to content

Commit

Permalink
refactor: getOffsets func
Browse files Browse the repository at this point in the history
  • Loading branch information
shaokeyibb committed Aug 22, 2024
1 parent fd024a3 commit bf0870d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 13 deletions.
15 changes: 3 additions & 12 deletions cloudflare-workers/src/administration.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getComment, getMeta, getPaths, isPathExists, setMeta, setPath, updateCommentOffsets } from './db';
import { ModifiedCommentBody } from './types';
import { getComment, getMeta, getOffsets, getPaths, isPathExists, setMeta, setPath, updateCommentOffsets } from './db';
import { ModifiedCommentBody, Offset } from './types';

type Replacement = {
from: {
Expand All @@ -12,11 +12,6 @@ type Replacement = {
};
};

type Offset = {
start: number;
end: number;
};

type OffsetDiff = {
len: number;
diff: number;
Expand Down Expand Up @@ -175,11 +170,7 @@ export async function modifyComments(env: Env, path: string, diff: ModifiedComme
}

// Distinct offsets
const offsets = [
...new Map((await getComment(env, { path })).map((comment) => comment.offset).map((offset) => [offset.start, offset.end])).entries(),
]
.map(([start, end]) => ({ start, end }))
.sort((a, b) => a.start - b.start);
const offsets = (await getOffsets(env, path)).sort((a, b) => a.start - b.start);

if (offsets.length === 0) {
return;
Expand Down
17 changes: 16 additions & 1 deletion cloudflare-workers/src/db.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GetComment, GetCommentRespBody, PostComment } from './types';
import { GetComment, GetCommentRespBody, Offset, PostComment } from './types';

export async function postComment(env: Env, req: PostComment) {
const db = env.DB;
Expand Down Expand Up @@ -107,6 +107,21 @@ export async function isPathExists(env: Env, ...path: string[]): Promise<boolean
return path.map((p) => res.results.some((r) => r.path === p));
}

export async function getOffsets(env: Env, path: string): Promise<Offset[]> {
const db = env.DB;

const page = await db.prepare('SELECT * FROM pages WHERE path = ?').bind(path).first();

if (!page) {
return [];
}

return (await db.prepare('SELECT * FROM offsets WHERE page_id = ?').bind(page.id).all()).results.map((offset) => ({
start: offset.start as number,
end: offset.end as number,
}));
}

export async function updateCommentOffsets(
env: Env,
path: string,
Expand Down
5 changes: 5 additions & 0 deletions cloudflare-workers/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,8 @@ export type ResponseBody<T = {}> = {
status: 200;
data?: T;
};

export type Offset = {
start: number;
end: number;
};

0 comments on commit bf0870d

Please sign in to comment.