0.6 rust重构01

This commit is contained in:
lix-2026
2026-04-14 13:22:29 +08:00
parent 71fb1aee7e
commit 84a8454fa9
401 changed files with 5841 additions and 1512 deletions
+25
View File
@@ -0,0 +1,25 @@
import { getAuthUserId } from "@convex-dev/auth/server";
function readEnv(key: string): string | undefined {
const raw = process.env[key];
if (!raw) return undefined;
const trimmed = raw.trim();
return trimmed ? trimmed : undefined;
}
function isDevAuthEnabled(): boolean {
return readEnv("MNOTE_DEV_AUTH") === "1" || readEnv("NEXT_PUBLIC_MNOTE_DEV_AUTH") === "1";
}
export async function requireUserId(ctx: any): Promise<string> {
const userId = await getAuthUserId(ctx);
if (userId !== null) {
return String(userId);
}
if (isDevAuthEnabled()) {
return readEnv("DEV_USER_ID") ?? "dev-user";
}
throw new Error("未登录");
}
@@ -0,0 +1,73 @@
type DocumentRecordLike = {
_id: unknown;
id?: string | null;
user_id?: string | null;
parent_id?: string | null;
deleted_at?: string | null;
created_at?: string | null;
updated_at?: string | null;
};
export function compareDocumentCanonicalOrder(a: DocumentRecordLike, b: DocumentRecordLike): number {
const aDeleted = a?.deleted_at != null;
const bDeleted = b?.deleted_at != null;
if (aDeleted !== bDeleted) {
return aDeleted ? 1 : -1;
}
const updatedA = String(a?.updated_at ?? "");
const updatedB = String(b?.updated_at ?? "");
if (updatedA !== updatedB) {
return updatedB.localeCompare(updatedA);
}
const createdA = String(a?.created_at ?? "");
const createdB = String(b?.created_at ?? "");
if (createdA !== createdB) {
return createdB.localeCompare(createdA);
}
return String(a?._id ?? "").localeCompare(String(b?._id ?? ""));
}
export function pickCanonicalDocumentRecord<T extends DocumentRecordLike>(records: T[]): T | null {
if (records.length === 0) return null;
return [...records].sort(compareDocumentCanonicalOrder)[0] ?? null;
}
export async function getCanonicalDocumentByBusinessId<T extends DocumentRecordLike>(
ctx: any,
documentId: string,
): Promise<T | null> {
const records = await ctx.db
.query("documents")
.withIndex("by_document_id", (q: any) => q.eq("id", documentId))
.collect();
return pickCanonicalDocumentRecord(records) as T | null;
}
export async function getCanonicalParentDocumentId(
ctx: any,
documentId: string | null | undefined,
): Promise<string | null> {
const normalizedId = String(documentId ?? "").trim();
if (!normalizedId) return null;
const doc = await getCanonicalDocumentByBusinessId<DocumentRecordLike>(ctx, normalizedId);
return doc?.parent_id ?? null;
}
export async function requireCanonicalOwnedDocument<T extends DocumentRecordLike & { user_id?: string | null }>(
ctx: any,
documentId: string,
userId: string,
): Promise<T> {
const doc = await getCanonicalDocumentByBusinessId<T>(ctx, documentId);
if (!doc) {
throw new Error("页面不存在");
}
if (String(doc.user_id ?? "") !== String(userId)) {
throw new Error("无权限");
}
return doc;
}