feat: implement lazy singleton pattern for repository instances and update related imports

This commit is contained in:
2026-06-29 17:25:41 +08:00
parent 96612da5c0
commit 0bae53bfba
14 changed files with 69 additions and 74 deletions
+4 -1
View File
@@ -6,11 +6,11 @@ import { fromPromise, fromCallback } from "xstate";
import { MessageQueue } from "@/core/net/message-queue";
import type { ChatSendResponse } from "@/data/dto/chat";
import { getChatRepository } from "@/data/repositories/chat_repository";
import { Result, Logger } from "@/utils";
import {
PAGE_SIZE,
chatRepo,
localMessagesToUi,
readAndSyncHistory,
sendResponseToUiMessage,
@@ -60,6 +60,7 @@ export const loadMoreHistoryActor = fromPromise<
{ messages: UiMessage[]; hasMore: boolean; newOffset: number },
{ offset: number }
>(async ({ input }) => {
const chatRepo = getChatRepository();
const result = await chatRepo.getHistory(PAGE_SIZE, input.offset);
if (Result.isErr(result)) {
log.error("[chat-machine] loadMoreHistoryActor failed", { error: result.error });
@@ -81,6 +82,7 @@ export const unlockHistoryActor = fromPromise<{
hasMore: boolean;
newOffset: number;
}>(async () => {
const chatRepo = getChatRepository();
const unlockResult = await chatRepo.unlockHistory();
if (Result.isErr(unlockResult)) {
log.error("[chat-machine] unlockHistoryActor failed", {
@@ -148,6 +150,7 @@ async function sendMessageViaHttp(content: string): Promise<{
response: ChatSendResponse;
reply: UiMessage | null;
}> {
const chatRepo = getChatRepository();
const result = await chatRepo.sendMessage(content);
if (Result.isErr(result)) {
log.error("[chat-machine] sendMessageHttpActor failed", { error: result.error });
+2 -8
View File
@@ -1,6 +1,5 @@
import type { UiMessage } from "@/data/dto/chat";
import { chatRepository } from "@/data/repositories/chat_repository";
import type { IChatRepository } from "@/data/repositories/interfaces";
import { getChatRepository } from "@/data/repositories/chat_repository";
import { ChatSendResponse } from "@/data/dto/chat/chat_send_response";
import { todayString, Result, Logger } from "@/utils";
@@ -14,12 +13,6 @@ const log = new Logger("StoresChatChatMachineHelpers");
/** 翻历史每页大小(仅 `loadMoreHistoryActor` 用) */
export const PAGE_SIZE = 50;
// ============================================================
// Repository injection
// ============================================================
// 仓库以接口类型注入:调用面只看接口,运行时仍是同一单例
export const chatRepo: IChatRepository = chatRepository;
// ============================================================
// DTO ↔ UiMessage 映射
// ============================================================
@@ -279,6 +272,7 @@ export async function readAndSyncHistory(): Promise<{
* - 用户从未发过消息就关掉 app 再开,仍然没 network 消息 → 会再次显示本条
* ("每次冷启动给个温暖的起点" —— 若要"只显示一次",需额外存 local
*/
const chatRepo = getChatRepository();
const greetingMessage: UiMessage = {
content:
"You're here! Facebook is so restrictive, " +