Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,13 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14):
- 搬分类时若同时给了 `sortOrder` 则以它为准;未给 `sortOrder` 时落到目标分类末尾(全表 `MAX(sort_order)+1`,与分类跨场景搬家同一口径),不会与现有排序撞号;`categoryId` 传的是原分类(未变)时不动顺序。
- `DELETE /api/admin/links/:id` → `{success:true}`
- `POST /api/admin/links/reorder` body `{ids:[…]}` → `{success:true}`
- `POST /api/admin/links/move` body `{linkId, categoryId, ids}` → `{success:true}`(跨分类拖动的原子保存,nav #28 冻结)
- 语义:在**同一个 `db.batch` 事务**里把 `linkId` 的 `category_id` 改成 `categoryId`,并把 `ids` 的**下标**写成各自的 `sort_order`。两者一起生效或一起回滚,不存在「分组已改、顺序没跟上」而接口返回成功的中间态;整批失败时一行都没写。
- `ids` 是客户端重建后的**全局**链接顺序(链接 `sort_order` 是跨分类、跨场景的一条全局序列)。落点 = `linkId` 在 `ids` 里的下标,**不是**目标分类末尾——这是它与 `PUT /api/admin/links/:id` 追加规则的差别:**跨分类拖动只走本端点**,不要再「先 PUT 改 categoryId 再补一次 reorder」。
- `ids` 只触碰其中出现的行(库中不存在的 id 静默忽略,与 `/links/reorder` 同口径);客户端应提交它当前可见的**全部**链接 id,否则未提交的行保留旧 `sort_order`,可能与新序号撞号。`ids` 里 `linkId` 必须恰好出现一次。
- `categoryId` 可与 `linkId` 当前分类相同(等价纯排序),不报错。
- 校验与错误按此顺序:`linkId` 非空字符串,否则 400 `{"error":"linkId is required"}`;`ids` 必须是字符串数组,否则 400 `{"error":"ids must be an array of link ids"}`;`ids` 里 `linkId` 出现 0 次或多次 → 400 `{"error":"ids must contain linkId exactly once"}`;`linkId` 不存在 → 404 `{"error":"not found"}`;`categoryId` 查不到(含缺失/非字符串,与 `PUT /links/:id` 同口径先 `String()` 再查库)→ 400 `{"error":"categoryId does not exist"}`;写库整批失败 → 500 `{"error":"move failed"}` 且无任何写入。未登录 → 401 `{"error":"unauthorized"}`(与其他 `/api/admin/*` 同口径)。
- 成功响应只回 `{success:true}`(不回整条链接):成功以客户端乐观状态为准、不整表重拉,`sortOrder` 即它提交的下标。

### 搜索引擎

Expand Down
34 changes: 34 additions & 0 deletions worker/src/db/queries/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,40 @@ export async function insertLink(
.run();
}

/**
* Moves one link to another category **and** rewrites the global sort order in a
* single D1 transaction (nav #28: cross-category drag is one atomic save). The
* category write and every `sort_order` write are in the same `db.batch`, so a
* failure leaves neither half behind — no "group changed, order did not" state.
*
* Position comes from the index in `ids` (the client's rebuilt global order),
* **not** from the append-at-the-end rule of `PUT /api/admin/links/:id`. Ids not
* present in the table are ignored, same as `POST /api/admin/links/reorder`.
*/
export async function moveLinkWithOrder(
db: D1Database,
prefix: string,
linkId: string,
categoryId: string,
ids: string[],
): Promise<void> {
const now = nowIso();
await db.batch([
db
.prepare(
`UPDATE ${prefix}links SET category_id = ?, updated_at = ? WHERE id = ?`,
)
.bind(categoryId, now, linkId),
...ids.map((id, index) =>
db
.prepare(
`UPDATE ${prefix}links SET sort_order = ?, updated_at = ? WHERE id = ?`,
)
.bind(index, now, id),
),
]);
}

export async function updateLink(
db: D1Database,
prefix: string,
Expand Down
44 changes: 44 additions & 0 deletions worker/src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
listLinks,
listScenes,
listSearchEngines,
moveLinkWithOrder,
nextCategorySortOrder,
nextLinkSortOrder,
nextSceneSortOrder,
Expand Down Expand Up @@ -600,6 +601,49 @@ adminRoutes.post("/links/reorder", async (c) => {
return c.json({ success: true });
});

// Cross-category drag (nav #28): category and global order are saved by one
// `db.batch` transaction, so they land together or not at all. The position is
// the index of `linkId` inside `ids` — deliberately *not* the append-at-the-end
// rule of `PUT /links/:id`, which stays as the admin dialog's behaviour.
// Error order below is the frozen contract (docs/api-contract.md §链接).
adminRoutes.post("/links/move", async (c) => {
const prefix = getTablePrefix(c.env);
const body = await c.req.json().catch(() => ({}));

const linkId = typeof body.linkId === "string" ? body.linkId.trim() : "";
if (!linkId) return badRequest("linkId is required");

if (!Array.isArray(body.ids))
return badRequest("ids must be an array of link ids");
const ids: string[] = [];
for (const id of body.ids) {
if (typeof id !== "string")
return badRequest("ids must be an array of link ids");
ids.push(id);
}
if (ids.filter((id) => id === linkId).length !== 1)
return badRequest("ids must contain linkId exactly once");

const existing = await findLink(c.env.DB, prefix, linkId);
if (!existing) return c.json({ error: "not found" }, 404);

// Same reading as `PUT /links/:id`: a missing/invalid categoryId never
// matches a row and is reported as a non-existent category.
const categoryId = String(body.categoryId);
const category = await findCategory(c.env.DB, prefix, categoryId);
if (!category) return badRequest("categoryId does not exist");

try {
await moveLinkWithOrder(c.env.DB, prefix, linkId, categoryId, ids);
} catch (error) {
// The batch is all-or-nothing: nothing was written. Report it in a shape the
// client can act on instead of the generic 500 from app.onError.
console.error("link move failed:", error);
return c.json({ error: "move failed" }, 500);
}
return c.json({ success: true });
});

adminRoutes.post("/search-engines/reorder", async (c) => {
const prefix = getTablePrefix(c.env);
const body = await c.req.json().catch(() => ({}));
Expand Down
248 changes: 248 additions & 0 deletions worker/test/api-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,18 @@ describe("public/private surface isolation", () => {
env,
);
expect(write.status).toBe(401);
// 跨分类原子保存端点同口径(nav #28)
const move = await app.request(
"/api/admin/links/move",
{
method: "POST",
body: JSON.stringify({ linkId: "x", categoryId: "y", ids: ["x"] }),
headers: { "content-type": "application/json" },
},
env,
);
expect(move.status).toBe(401);
expect(await readJson(move)).toEqual({ error: "unauthorized" });
});
});

Expand Down Expand Up @@ -535,3 +547,239 @@ describe("link edit: moving a link to another category (nav #17 move rule)", ()
});
});
});

describe("link move: cross-category atomic save (nav #28 frozen contract)", () => {
let env: Env;
let app: Hono;
let cookie: string;
let devCat: string;
let readCat: string;

const adminFetch = (path: string, init: RequestInit = {}) =>
app.request(
path,
{
...init,
headers: { "content-type": "application/json", cookie },
},
env,
);

async function createCategory(name: string): Promise<string> {
const res = await adminFetch("/api/admin/categories", {
method: "POST",
body: JSON.stringify({ name }),
});
return (await readJson(res)).id;
}

async function createLink(body: Record<string, unknown>): Promise<string> {
const res = await adminFetch("/api/admin/links", {
method: "POST",
body: JSON.stringify({
url: `https://example.com/${String(body.title)}`,
...body,
}),
});
return (await readJson(res)).id;
}

/** 全量链接(后端按 sort_order, created_at 排序)。 */
async function listLinks(): Promise<
{ id: string; categoryId: string; title: string; sortOrder: number }[]
> {
return (await readJson(await adminFetch("/api/admin/links"))).links;
}

function sqlite(): SqliteD1["db"] {
return (env.DB as unknown as SqliteD1).db;
}

/** 绕过接口直接读库:断言「什么都没写」时用。 */
function rawLinks(): { id: string; categoryId: string; sortOrder: number }[] {
return sqlite()
.prepare(
"SELECT id, category_id AS categoryId, sort_order AS sortOrder FROM links ORDER BY sort_order, created_at",
)
.all() as { id: string; categoryId: string; sortOrder: number }[];
}

const move = (body: unknown) =>
adminFetch("/api/admin/links/move", {
method: "POST",
body: JSON.stringify(body),
});

beforeEach(async () => {
env = makeEnv();
app = makeApp();
await runMigrations(env);
cookie = (await setupRequest(app, env)).headers.get("set-cookie") ?? "";
devCat = await createCategory("开发");
readCat = await createCategory("阅读");
});

it("writes category and global order together, landing on the drop index", async () => {
const a = await createLink({
title: "A",
categoryId: devCat,
sortOrder: 0,
});
const b = await createLink({
title: "B",
categoryId: devCat,
sortOrder: 1,
});
const c = await createLink({
title: "C",
categoryId: devCat,
sortOrder: 2,
});
const d = await createLink({
title: "D",
categoryId: readCat,
sortOrder: 3,
});
const e = await createLink({
title: "E",
categoryId: readCat,
sortOrder: 4,
});

// 把 B 拖进「阅读」并落在 D 之后(下标 3),不是目标分类末尾。
const ids = [a, c, d, b, e];
const res = await move({ linkId: b, categoryId: readCat, ids });

expect(res.status).toBe(200);
expect(await readJson(res)).toEqual({ success: true });

const links = await listLinks();
expect(links.map((l) => l.id)).toEqual(ids);
expect(links.map((l) => l.sortOrder)).toEqual([0, 1, 2, 3, 4]);
expect(links.find((l) => l.id === b)?.categoryId).toBe(readCat);
// 目标分类内次序来自 ids(落点即下标):[D, B, E],而非追加到末尾的 [D, E, B]
expect(
links.filter((l) => l.categoryId === readCat).map((l) => l.title),
).toEqual(["D", "B", "E"]);
expect(
links.filter((l) => l.categoryId === devCat).map((l) => l.title),
).toEqual(["A", "C"]);
});

it("also saves a pure reorder when categoryId is unchanged", async () => {
const a = await createLink({
title: "A",
categoryId: devCat,
sortOrder: 0,
});
const b = await createLink({
title: "B",
categoryId: devCat,
sortOrder: 1,
});
const c = await createLink({
title: "C",
categoryId: devCat,
sortOrder: 2,
});

const res = await move({ linkId: c, categoryId: devCat, ids: [c, a, b] });
expect(res.status).toBe(200);

const links = await listLinks();
expect(links.map((l) => l.id)).toEqual([c, a, b]);
expect(links.map((l) => l.sortOrder)).toEqual([0, 1, 2]);
expect(links.every((l) => l.categoryId === devCat)).toBe(true);
});

it("rolls the whole batch back when any statement fails (no half save)", async () => {
const a = await createLink({
title: "A",
categoryId: devCat,
sortOrder: 0,
});
const b = await createLink({
title: "B",
categoryId: devCat,
sortOrder: 1,
});
const c = await createLink({
title: "C",
categoryId: devCat,
sortOrder: 2,
});
const d = await createLink({
title: "D",
categoryId: readCat,
sortOrder: 3,
});

const before = rawLinks();
// 让 C 的 sort_order 写入失败:分组那一句先跑过,也必须跟着回滚。
sqlite().exec(
`CREATE TRIGGER abort_link_order BEFORE UPDATE ON links
WHEN NEW.id = '${c}' AND OLD.sort_order <> NEW.sort_order
BEGIN SELECT RAISE(ABORT, 'boom'); END;`,
);

const res = await move({
linkId: b,
categoryId: readCat,
ids: [a, c, d, b],
});
expect(res.status).toBe(500);
expect(await readJson(res)).toEqual({ error: "move failed" });

expect(rawLinks()).toEqual(before);
});

it("rejects malformed payloads in the frozen order and writes nothing", async () => {
const a = await createLink({
title: "A",
categoryId: devCat,
sortOrder: 0,
});
const b = await createLink({
title: "B",
categoryId: devCat,
sortOrder: 1,
});
const before = rawLinks();

const cases: [unknown, number, string][] = [
[{ categoryId: readCat, ids: [a] }, 400, "linkId is required"],
[
{ linkId: " ", categoryId: readCat, ids: [a] },
400,
"linkId is required",
],
[{ linkId: a }, 400, "ids must be an array of link ids"],
[{ linkId: a, ids: "nope" }, 400, "ids must be an array of link ids"],
[{ linkId: a, ids: [a, 7] }, 400, "ids must be an array of link ids"],
[{ linkId: a, ids: [b] }, 400, "ids must contain linkId exactly once"],
[
{ linkId: a, ids: [a, b, a] },
400,
"ids must contain linkId exactly once",
],
[
{ linkId: "ghost", categoryId: readCat, ids: ["ghost", a] },
404,
"not found",
],
[
{ linkId: a, categoryId: "ghost", ids: [a, b] },
400,
"categoryId does not exist",
],
[{ linkId: a, ids: [a, b] }, 400, "categoryId does not exist"],
];

for (const [payload, status, error] of cases) {
const res = await move(payload);
expect(res.status, JSON.stringify(payload)).toBe(status);
expect(await readJson(res)).toEqual({ error });
expect(rawLinks()).toEqual(before);
}
});
});
Loading